I. Input Handling
    A. Introduction: Figure 3.1 in Olsen
        1. Essential geometry is geometry the controller needs to use in
	   order to translate input events into commands issued to the model
    B. Three main issues in event handling
        1. Dispatching events to correct window-responsibility of OS
	2. Associating event with event-handling code
	3. Notifying view and windowing system of model changes so presentation
	   can be redrawn (you should already have handled this part in
	   earlier lectures)
    C. Window Systems
        1. Input event dispatch
	    a. First determine if event should be consumed for window
		     	handling purposes (e.g., moving, resizing, passing
			an event to a function designated by an icon)

 	    b. If not, there are three dispatch strategies
	        i. bottom-up, frontmost: dispatch event to bottommost window
		   in window hierarchy. If it doesn't want the event it passes
		   it up the hierarchy to its parent.
		ii. top-down, frontmost: event first passed to root window,
		    which passes it to top-most child that contains the event
	       iii. focus: event passed to whichever window has the current 
		    Advantage of top-down over bottom-up: Can implement
		      flexible management policies. For example, if the
		      bottommost window should be view-only, then a container
		      can be wrapped around it that dispatches only output
		      events, like redraw or resize events to the window, while
		      discarding input events
	2. Key Focus
	    a. Key focus: keyboard events immediately forwarded to window
	       with the key focus. Handling the focus involves
	       i. requesting the focus
	       ii. losing the focus
	       iii. receiving the focus
	       iv. tab order
	    b. RequestFocus/ReceiveFocus: Provide feedback, such as flashing
	       caret or highlighted button, to indicate that you have focus
	    c. Lose Focus 
		i. Remove feedback, such as hiding the caret
		ii. Possibly generate an action event with changed text
	    d. Tab Order/Tab Stop: Order in which focus cycles among widgets and
	       whether or not a widget can receive the focus
	       i. default is typically left-to-right, top-to-bottom
	       ii. sometimes you can provide either a tabindex or a pointer
	           to a widget in order to indicate tab order
	3. Mouse Focus: Useful for narrow windows, such as slider, or for
	   drawing windows when user is operating near an edge
	4. Event Queue: Most modern systems put everything into an event
	   queue, including events generated by devices, by an application,
	   or by the window system. This provides a uniform way for
	   handling asynchronously generated events without making the
	   application worry about writing interrupt handlers

II. Input Events: Typically mouse or keyboard (tell students to read this
    part--it's too boring to handle in class. Just focus on difference
    between physical events, like mouse and keyboard, and semantic
    events, like actionEvents or itemChangedEvents)
    A. Event information
        1. Event type
	2. Mouse/pen location
	3. Modifier information: which button pressed, which keyboard keys
	   pressed, which modifier keys (e.g., ctrl, shift) pressed
    B. Event types
        1. Button events: 
	    a. Mouse down
	    b. Mouse up
	    c. click/double click: software generated events
	    d. mouse enter: useful for detecting hovering (e.g., for tool
	       tips) or requesting focus
	    e. mouse exit
	2. Mouse movement
	    a. mouse move: moving a mouse with no buttons pressed
	    b. mouse drag: moving a mouse with a button pressed
	    c. often ignore mouse moves because every pixel move will be
	3. Keyboard events
	    a. KeyInput: reports a character and is software generated
	    b. KeyPressed/KeyReleased 
		i. sometimes you want to know the individual key pressed 
		    (e.g., Shift followed by 'a' produces a capital 'A' 
		    KeyInput event, but you might want to know about the two 
		    individual key presses 
		ii. you want to have something happen as soon as a key is 
			pressed (e.g., vi might want to immediately move the
			cursor when an arrow key is pressed)
	4. Window events
	    a. visibility--new, iconified, de-iconified
	    b. exposure--a part of a window that was previously
				covered becomes visible
            c. configuration--a window was moved or resized
	    d. stacking--stacking order of windows changed
	 5. Application defined events--application specific events
		such as ChangeEvent for a slider, Action Event for
		a button, packet arrived/dispatched (in a network),
		or particle created/destroyed (in a physics simulation).

III. Main Event Loop

    A. General Form
	while (not time to quit)
	   { Get next event E
	     Dispatch event E

IV. Event/code binding: different ways to implement main event loop.
    Here is a tree that illustrates the evolution of event handling:
      	      	   	Mac Main Event Loop
              Windows /                    \ Unix
                  WindowProc          EventTables
                     \                 /       \                   |
                     Inheritance-Based      Interpreted (HTML)  Delegates

    A. Main event loop written by user and placed in main: early Macs plus 
       small devices with limited speed and space for code. Events typically 
       labeled with a window so application knows where to dispatch them

    B. Window event tables: Each window has a table indexed by event types
        1. Each entry either has a function pointer or a forwarding procedure
	   that passes the event to the enclosing window
	2. Binding of procedure pointers to windows must be done dynamically
	   at run-time by code
	3. Every window must have union of all possible event types
    C. Callbacks: Windows have named properties and function pointers are
        assigned to named properties
	1. Window systems can match property names to entries in table and
	   bind procedure pointers to appropriate entries when window is
	2. Widgets only need to handle events they are interested in
    D. Microsoft WindowProc: Each window has a main event loop with switch
        statements--slightly more compartmentalized then a Mac
    E. Inheritance Event Handling: Each widget defines methods associated
        with particular events. There is a single base widget from which
	all other widgets are derived
	1. Root class defines methods along with empty bodies
	2. Subclasses override methods whose events they want to handle
	3. Event loop identifies object that should handle the event and
	   invokes the appropriate method
   	4. Implementation of method invocation
	   a. Smalltalk: Object checks class definition to see if method
	      exists. If not, then superclass pointers followed until
	      method found. This traversal is inefficient.
	   b. Modern languages starting with C++: Virtual tables
	       i. Each subclass tacks on its additional methods to the end of 
	          the table
	       ii. Each entry in the table points to a subclass method, if the
	           subclass overrode the method or if it's a new subclass
		   declared method, or to a superclass method if the subclass
		   chooses to accept the superclass's implementation of the
	5. Drawback: Large applications have thousands of events so widgets
	   may have enormous virtual tables (all events will typically be
	   declared in the top-level widget since the event queue wants a
	   pointer to a top-level widget)
    F. Listeners
        1. Widgets use interfaces to specify exactly the set of events they
	   are interested in handling (listeners subdivide the universe
	   of events into more manageable subsets)
	2. Each class that implements an interface has a virtual table for
	   that interface
	3. When a variable is declared as an interface, then it has two
	   pointers--one to the object and one to the virtual table provided
	   by that object for that interface
	4. Listener class structure
	   a. Objects that produce events are called generators
	   b. Objects that consume events are called listeners
	   c. Generators define interfaces of methods that listeners then
    G. Delegation: C#'s way of providing pseudo-function pointers (use the
        example in Olsen--it's excellent). 
	1. General style: C#'s delegation mechanism is more procedural than
	   inheritance-based. C# provides a set of pre-defined functions,
	   such as processMouseEvent, which it calls when a certain type
	   of event occurs. You then switch on the event type and invoke the
	   appropriate set of callback methods using C#'s delegation mechanism
        2. Mechanics
	    a. You can declare a delegate type using the syntax:

	       public delegate return-type typename(parameters)

	       For example:
	       public delegate void ActionEventHandler(ActionEvent e);

	       declares a delegate type named ActionEventHandler.
	       ActionEventHandler is essentially a function pointer to
	       a function that returns a void and takes an ActionEvent
	       object as a parameter.
	    b. In the same class as your event handling function
	       (e.g., processMouseEvent), declare a variable to be of
	       your delegate type. For example:

	       public ActionEventHandler actionPerformed;

	       i. A delegate type can actually be a list of function 
	       	  pointers. Much like the listener model, you can register
		  one or more function pointers with the type.

	    c. Inside your event handling function, you can call your
	        delegate variable as though it were a function:

		actionPerformed(new ActionEvent(args));
		C# will iterate through each of the function pointers in
		actionPerformed's list, and call each of them

	    d. Create your callback methods. For example:

	       void myDeleteAction(ActionEvent e) {
	       	    perform the delete action }

	       void beepAction(ActionEvent e) {
	            beep(); }

	    e. Register the callback method with the appropriate
	       delegate variable:

	       Button myDelete = new Button("Delete");
	       myDelete.actionPerformed = this.myDeleteAction
	       myDelete.actionPerformed += this.beepAction

	       The += operator tells C# that you are registering
	       multiple callbacks with this delegate variable

	    f. Explanation of Fig 3.30: MouseEventHandler is a delegate
		type that you do not declare directly but is instead
		pre-declared by C# and is associated with several
		event generators (MouseDown, MouseMove, and MouseUp).
		When you add a method that has the same function prototype
		as MouseEventHandler to the appropriate event handler,
		then that method will get called when the event gets
		fired. This delegation technique is
		different from the one shown earlier in the textbook, 
		because the earlier example did not use the event
		keyword to associate an ActionPerformed delegate with an
		i. MouseDown, MouseMove, and MouseUp are the events that
			a C# Panel defines for handling a mouse
		ii. You add the MouseEventHandler delegate object to the
			appropriate event in order to register that delegate
			to handle the event
		iii. MouseDown, MouseMove, and MouseUp are declared as
			public event MouseEventHandler MouseDown;

			Presumably event declares MouseDown as an event
			generator and MouseEventHandler as the delegate
			that handles MouseDown events
    H. Interpreted expressions: Used by scripting languages, like Javascript.
        For example:

	<input type="radio" name="beginner" value="beginner" 

IV. Examples of Java Event Listeners (see sample programs)

V. Essential Geometry--essential geometry represents information that will 
   map mouse position into some meaningful concept in the model or the behavior 
   of the controller
    A. Examples
        1. Minesweeper: map mouse location to row and column
	2. Scroll bar: map mouse location to a region (e.g., page up, page
	   down, step left, step right, drag region) and to a value
	3. Gauge: compute an angle
    B. If controller separated from view, then view should hide calculation
        of essential geometry and only provide an interface
	1. Example: scroll bar

	enum ScrollRegion { stepLeft, pageLeft, drag, pageRight, stepRight } 
	ScrollRegion mouseRegion( Point mouseLocation) { . . . } 
	int mouseToCurValue( Point mouseLocation) { . . . } 

	Now you can re-use the controller with multiple scroll bars, as long
	as each returns an appropriate ScrollRegion to the controller.

    C. Converting a mouse point to an angle in an oval gauge:
     The difficult part about moving an arrow in a gauge view is figuring
     out how to compute the arrow's angle based on the current mouse points.
     The obvious solution is to compute the angle from the center of the gauge
     to the mouse point, but this works only if the guage is circular. An
     elliptical gauge skews the calculations because the angle the ellipse
     uses to calculate the position of the arrow line will not coincide with
     the angle of the mouse. For example, suppose that the width of the arc
     is 100 pixels, the height is 50 pixels, 
     and that the mouse angle is 45 degrees. If you naively plug in 45 as
     the angle for the ellipse, you obtain the coordinates

       (x,y) = (100 cos 45, 50 sin 45) = (70.7, 35.4)

     for where the arrow intersects the boundary of the ellipse. You will note
     that the angle of this line is not 45 degrees. Mathematically, the ellipse
     is an affine transform of a circle and hence the angle has been transformed
     as well. There are multiple ways to figure out how to make the arrow line
     actually be 45 degrees and to figure out what angle to feed the ellipse
     equation to get the line to appear at 45 degrees. One way is to recognize
     that the ellipse is an elongated circle that has been scaled by a factor
     of 2 in the x direction, and hence a correction factor of 2 must be
     applied to the argument provided to the arctangent function. 
     Another way to view it is to use similar triangles:

       let dy = mouse.y - gauge_center.y
           dx = mouse.x - gauge_center.x
           dy / dx = gauge_height * sin(angle) / gauge_width * cos(angle)

      Since gauge_height / gauge_width is 1/2 we have:

          dy / dx = 1/2 * sin(angle)/cos(angle)
	  2 * dy / dx = sin(angle)/cos(angle)
	  arctan(2*dy/dx) = angle

     You can now plug in this angle to the ellipse equation to obtain the
     point where the arrow intersects the ellipse boundary.

VI. Controller Implementation: Go through the books example of creating
    new lines: It has a complete example with the model which your sample
    programs do not

VII. Event Handling Summary: Go through the book's event handling summary as
     it presents a good review of all the ideas presented in the chapter.

VIII. Polling
     A. Polling is an alternative event-handling paradigm (as opposed to
	interrupt-driven handling) that combines event-handling with redrawing
	1. Redraw is called a predetermined number of times per second
	2. Each time redraw is called, the canvas polls all devices to see
		whether or not one of them has generated an event. 
	3. The canvas processes all events and updates state information
		before drawing itself.
	4. Often the model and the view are combined for speed purposes
     B. Polling is often used in games or applications devoted to animation
	(e.g., a scientific modeling application)