EventSensor >> processEvent:
processEvent: evt 
	"Process a single event. This method is run at high priority."
	| type buttons window |
	type := evt at: 1.
	lastEventTime := evt at: 2.

	"Only process main window events, forward others to host window proxies"
	window := evt at: 8.
	(window isNil or: [window isZero]) ifTrue: 
		[window := 1. 
		evt at: 8 put: window].
	window = 1 ifFalse: [
		^Smalltalk at: #HostWindowProxy ifPresent: [:w | w processEvent: evt]].

	"Tackle mouse events and mouse wheel events first"
	(type = EventTypeMouse or: [type = EventTypeMouseWheel])
		ifTrue: [buttons := (ButtonDecodeTable at: (evt at: 5) + 1). 
				evt at: 5 put: (Smalltalk platformName = 'Mac OS'
							ifTrue: [ buttons ]
							ifFalse: [ self mapButtons: buttons modifiers: (evt at: 6) ]).
				self queueEvent: evt.
				type = EventTypeMouseWheel
					ifTrue: [^ self processMouseWheelEvent: evt].				
				type = EventTypeMouse
					ifTrue: [^ self processMouseEvent: evt]].
	
	"Store the event in the queue if there's any"
	type = EventTypeKeyboard
		ifTrue: [ "Check if the event is a user interrupt"
			((evt at: 4) = EventKeyChar
				and: [((evt at: 3)
						bitOr: (((evt at: 5)
							bitAnd: 8)
							bitShift: 8))
							= interruptKey])
					ifTrue: ["interrupt key is meta - not reported as event"
							^ interruptSemaphore signal].
			"Decode keys for characters (e.g., map ctrl -> cmd)."
			(evt at: 4) = EventKeyChar
				ifTrue: [ | unicode ascii |
					"Copy lookup key first in case of key swap."
					unicode := {evt at: 6. evt at: 5}.
					ascii := {evt at: 3. evt at: 5}.
					KeyDecodeTable "Unicode character first"
						at: unicode
						ifPresent: [:a | evt at: 6 put: a first;
								 at: 5 put: a second]. 
					KeyDecodeTable "ASCII character second"
						at: ascii
						ifPresent: [:a | evt at: 3 put: a first;
								 at: 5 put: a second]]
				ifFalse: ["Replace modifiers for virtual keys. (keyUp/keyDown)"
					(evt at: 5) > 0 "Any modifier pressed?" ifTrue: [
						VirtualKeyTable
							at: ((evt at: 5) bitShift: 8)
							ifPresent: [:a | evt at: 5 put: a]]].
			self queueEvent: evt. 
			self processKeyboardEvent: evt . 
			^self ].
				
	"Handle all events other than Keyboard or Mouse."
	self queueEvent: evt.
	

EventSensor >> processKeyboardEvent:
processKeyboardEvent: evt
	"process a keyboard event, updating EventSensor state"
	"Never update keyboardBuffer if we have an eventQueue active"
	mouseButtons := (mouseButtons bitAnd: EventSensor anyMouseButtonMask) bitOr: ((evt at: 5) bitShift: EventSensor numMouseButtons).
	
	(evt at: 3) ifNotNil: "extra characters not handled in MVC"
		[:charCode| | pressCode |
		 (pressCode := evt at: 4) = EventKeyChar ifTrue: "key down/up not handled in MVC"
			["mix in modifiers"
			keyboardBuffer nextPut: (charCode bitOr: ((evt at: 5) bitShift: 8))]]

EventSensor >> initialize
initialize

	mouseButtons := 0.
	mousePosition := 0@0.
	mouseWheelDelta := 0@0.
	keyboardBuffer := SharedQueue new.
	
	interruptKey := $. asciiValue bitOr: 16r0800. 	"cmd-."
	interruptSemaphore := Semaphore new.
	
	eventQueue := SharedQueue new.
	
	inputSemaphore := Semaphore new.
	hasInputSemaphore := false.

EventSensor class >> initialize
initialize
	
	Smalltalk addToStartUpList: self before: ProcessorScheduler.
	Smalltalk addToShutDownList: self.
	
	KeyDecodePreferences := Dictionary new.
	
	self installKeyDecodeTable.
	self installMouseDecodeTable.
	self installVirtualKeyTable.

TextEditor >> dispatchOnKeyboardEvent:
dispatchOnKeyboardEvent: aKeyboardEvent 
	"Carry out the action associated with this character, if any. Type-ahead is passed so some routines can flush or use it."
	
	| honorCommandKeys typedChar |
	typedChar := aKeyboardEvent keyCharacter.
	
	"Handle one-line input fields."
	(typedChar == Character cr and: [morph acceptOnCR])
		ifTrue: [^ true].
	
	"Clear highlight for last opened parenthesis."
	self clearParens.
	
	"Handle line breaks and auto indent."
	typedChar == Character cr ifTrue: [
		aKeyboardEvent controlKeyPressed
			ifTrue: [^ self normalCharacter: aKeyboardEvent].
		aKeyboardEvent shiftPressed
			ifTrue: [^ self lf: aKeyboardEvent].
		aKeyboardEvent commandKeyPressed
			ifTrue: [^ self crlf: aKeyboardEvent].
		^ self crWithIndent: aKeyboardEvent].

	"Handle indent/outdent with selected text block."
	typedChar == Character tab ifTrue: [
		aKeyboardEvent shiftPressed
			ifTrue: [self outdent: aKeyboardEvent. ^ true]
			ifFalse: [self hasMultipleLinesSelected
				ifTrue: [self indent: aKeyboardEvent. ^ true]]].

	honorCommandKeys := Preferences cmdKeysInText.

	(honorCommandKeys and: [typedChar == Character enter])
		ifTrue: [^ self dispatchOnEnterWith: aKeyboardEvent].
	
	"Special keys overwrite crtl+key combinations - at least on Windows. To resolve this
	conflict, assume that keys other than cursor keys aren't used together with Crtl."
	((self class specialShiftCmdKeys includes: aKeyboardEvent keyValue)
		and: [aKeyboardEvent keyValue < 27])
			ifTrue: [^ aKeyboardEvent controlKeyPressed
				ifTrue: [self
							perform: (self class shiftCmdActions at: aKeyboardEvent keyValue + 1)
							with: aKeyboardEvent]
				ifFalse: [self
							perform: (self class cmdActions at: aKeyboardEvent keyValue + 1)
							with: aKeyboardEvent]].
			
	"backspace, and escape keys (ascii 8 and 27) are command keys"
	((honorCommandKeys and: [aKeyboardEvent commandKeyPressed])
		or: [self class specialShiftCmdKeys includes: aKeyboardEvent keyValue])
			ifTrue: [ ^ aKeyboardEvent shiftPressed
				ifTrue: [self
							perform: (self class shiftCmdActions at: aKeyboardEvent keyValue + 1)
							with: aKeyboardEvent]
				ifFalse: [self
							perform: (self class cmdActions at: aKeyboardEvent keyValue + 1)
							with: aKeyboardEvent]].

	"the control key can be used to invoke shift-cmd shortcuts"
	(honorCommandKeys and: [ aKeyboardEvent controlKeyPressed ])
		ifTrue: [^ self
					perform: (self class shiftCmdActions at: aKeyboardEvent keyValue + 1)
					with: aKeyboardEvent].

	"Enclose selection with brackets etc."
	((self class encloseSelection and: [self hasSelection]) and: [self enclose: aKeyboardEvent])
		ifTrue: [^ true].

	"Automatically enclose paired characters such as brackets."
	(self class autoEnclose and: [self autoEncloseFor: typedChar])
		ifTrue: [^ true].
		
	"Even if no enclosing feature was used, highlight the matching bracket when closing one."
	(')]}' includes: typedChar)
		ifTrue: [self blinkPrevParen: typedChar].
					
	self normalCharacter: aKeyboardEvent.
	^ false

SmalltalkEditor >> save:
save: aKeyboardEvent
	"Submit the current text.  Equivalent to 'accept' 1/18/96 sw"

	self insertAndCloseTypeIn.
	self accept.
	^ true

TextEditor >> undo:
undo: aKeyboardEvent 
	"Undo the last edit."

	self insertAndCloseTypeIn.
	self undo.
	^true

SmalltalkEditor >> doIt:
doIt: aKeyboardEvent
	"Called when user hits cmd-d.  Select the current line, if relevant, then evaluate and execute.  2/1/96 sw.
	2/29/96 sw: don't call selectLine; it's done by doIt now"

	self doIt.
	^ true

SmalltalkEditor >> printIt:
printIt: aKeyboardEvent
	"Print the results of evaluting the selection -- invoked via cmd-p.  If there is no current selection, use the current line.  1/17/96 sw
	 2/29/96 sw: don't call selectLine now, since it's called by doIt"

	self printIt.
	^ true

SmalltalkEditor >> inspectIt:
inspectIt: aKeyboardEvent
	"Inspect the selection -- invoked via cmd-i.  If there is no current selection, use the current line.  1/17/96 sw
	 2/29/96 sw: don't call selectLine; it's done by inspectIt now"

	self inspectIt.
	^ true

SmalltalkEditor >> browseIt:
browseIt: aKeyboardEvent
	"Triggered by Cmd-B; browse the thing represented by the current selection, if plausible.  1/18/96 sw"

	self browseIt.
	^ true

StandardToolSet class >> handleUserInterruptRequest:
handleUserInterruptRequest: aString
	"Double dispatch. Let the current project manage processes, which usually calls back here eventually into #debugProcess..."
	
	Preferences cmdDotEnabled ifFalse: [^ self].
	^ Project current interruptName: aString

Current mapControlKeysToCommandKeys: true
Sensor instance vars: #('mouseButtons' 'mousePosition' 'mouseWheelDelta' 'keyboardBuffer' 'interruptKey' 'interruptSemaphore' 'eventQueue' 'inputSemaphore' 'lastEventPoll' 'hasInputSemaphore' 'lastEventTime')
EventSensor class vars: #(#KeyDecodePreferences #ButtonDecodeTable #EventTicklerProcess #VirtualKeyTable #KeyDecodeTable #InterruptWatcherProcess #EventPollPeriod)
