Developer Documentation
PATH  Mac OS X Documentation > Application Kit Reference: Java


[Previous] [Class List] [Next]

NSResponder


Inherits from: NSObject
Package: com.apple.yellow.application


Class Description


NSResponder is an abstract class that forms the basis of event and command processing in the Application Kit. The core classes-NSApplication, NSWindow, and NSView-inherit from NSResponder, as must any class that handles events. The responder model is built around three components: event messages, action messages, and the responder chain. An event message is a message corresponding directly to an input event, and includes as its sole argument an NSEvent object describing the event; a mouse down or keypress, for example. An action message is a higher-level message indicating a command to be performed, which includes as an argument the object requesting the action. Some examples of action messages are the standard cut:, copy:, and paste:.

The responder chain is a series of responder objects to which an event or action message is applied. When a given responder object doesn't handle a particular message, the message is passed to its successor in the chain. This allows responder objects to delegate responsibility to other, typically higher-level objects. The responder chain is constructed automatically as described below, but you can insert custom objects into it using the setNextResponder method and examine it with nextResponder.

An application can contain any number of responder chains, but only one is active at any given time. It begins with the first responder in some NSWindow and proceeds to the NSWindow itself. The first responder is typically the "selected" NSView within the NSWindow, and its next responder is its containing NSView (also called its superview), and so on up to the NSWindow itself. You can safely inject other responders between NSViews, but you can't add responders past the NSWindow. Nearly all event messages apply to a single window's responder chain.

For action messages, a more elaborate responder chain is used, constructed from the individual responder chains of two NSWindows and the application object itself. The NSWindows are the key window, whose responder chain gets first crack at action messages, and the main window, which follows. The main window is sometimes identical to the key window; the two are typically distinguished when an auxiliary window or panel related to a primary window-such as a Find Panel-is opened. In this case the primary window, which was the key window, becomes the main window, and the Find Panel becomes key. The two windows and the NSApplication object also give their delegates a chance to handle action messages as though they were responders, even though a delegate isn't formally in the responder chain (a nextResponder message to a window or application object doesn't return the delegate). Given all these components, then, the full responder chain comprises these objects:

Selecting the First Responder

The first responder is typically chosen by the user, with the mouse or keyboard. The mechanism by which one object loses its first responder status and another gains it is public though, and you can programmatically change the first responder if necessary. The method that changes the first responder is NSWindow's makeFirstResponder. An NSWindow's first responder is initially itself, though you can set which object will be first responder when the NSWindow is first placed on-screen using the setInitialFirstResponder method.

makeFirstResponder always asks the current first responder if it is ready to resign its status, using resignFirstResponder. If the current first responder returns false when sent this message, makeFirstResponder fails and likewise returns false. If the current first responder returns true then the new one is sent a becomeFirstResponder message to inform it that it can be the first responder. This object can return false to reject the assignment, in which case the NSWindow itself becomes the first responder.

When an NSWindow that's the key window receives a mouse-down event, it automatically tries to make first responder the NSView under the event. It does so by asking the NSView whether it wants to become first responder, using the acceptsFirstResponder method defined by this class, with the mouse-down event as the argument. This method normally returns false; responder subclasses that need to be first responder must override it to return true. This method is also used when the user changes the first responder using the keyboard.

Normally a mouse-down event in a non-key window simply brings the window forward and makes it key, and isn't sent to the NSView over which it occurs. The NSView can claim an initial mouse-down, however, by implementing acceptsFirstMouse to return true. The argument is the mouse-down event, which the NSView can examine to determine whether it wants to receive the mouse event and potentially become first responder.

An additional consideration for responders that manage selections is of course to set the selection. An NSView that handles mouse events should set this itself. However, objects can also define methods for setting their selection that automatically make the receiver first responder as well. NSTextField's selectText, for example, does something quite like this.

Event and Action Messages in the Responder Chain

The main purpose of the responder chain is to route events and action messages to an appropriate target. Event and action methods are dispatched in different ways, by different methods. Nearly all events enter an application from the Window Server, and are handled automatically by NSApplication's sendEvent method. Action messages are instigated by objects, who use NSApplication's sendActionToTargetFromSender method to route them to their proper destinations.

NSApplication's sendEvent analyzes the event and handles some things specially-key equivalents, for example. Most events, however, it passes to the appropriate window for dispatch up its responder chain using NSWindow's sendEvent method. NSResponder's default implementations of all event methods simply pass the message to the next responder, so if no object in the responder chain does anything with the event it's simply lost. As mentioned before, an NSView's next responder is nearly always its superview, so if, for example, the NSView that receives a mouseDown message doesn't handle it, its superview gets a chance, and so on up to the NSWindow. If no object is found to handle the event, the last responder in the chain invokes noResponderFor:, which for a key-down event simply beeps. Event-handling objects (subclasses of NSWindow and NSView) can override this method to perform additional steps as needed.

Event messages form a well-known set, so NSResponder provides implementations for all of them. Action messages, however, are defined by custom classes and can't be predicted. For this reason they're dispatched in different manner from events. To instigate an action message, an object invokes NSApplication'ssendActionToTargetFromSender. The first argument is the selector for the action method to invoke. The second is the intended recipient of the message, often called the target. The final argument is usually the object invoking sendActionToTargetFromSender, thus indicating which object instigated the action message. If the intended target isn't null, the action is simply sent directly to that object; this is called a targeted action message. In the case of an untargeted action message, where the target is null, sendActionToTargetFromSender searches the full responder chain for an object that implements the action method specified. If it finds one, it sends the message to that object with the instigator of the action message as the sole argument. The receiver of the action message can then use the argument directly as input or query it for additional information. You can find the recipient of an untargeted action message without actually sending the message using targetForAction.

A more general mechanism, which applies to the shorter form of the responder chain, is provided by NSResponder's tryToPerform. This method checks the receiver to see if it responds to the selector provided, if so invoking the message. If not, it sends tryToPerform to its next responder. NSWindow and NSApplication override this method to include their delegates, but they don't link individual responder chains in the way that NSApplication's sendActionToTargetFromSender does. Similar to tryToPerform is doCommandBySelector:, which takes a method selector and tries to find a responder that implements it. If none is found, the method beeps.

WARNING

NSResponder declares a number of action messages, but doesn't actually implement them. You should never send an action message directly to a responder object of an unknown class. Always use NSApplication's sendActionToTargetFromSender, NSResponder's tryToPerform or doCommandBySelector:, or check that the target responds using the NSObject method respondsToSelector:.

Implementing Event and Action Methods

Implementing event methods is fairly straightforward. If your subclass handles a particular event, it overrides the method- keyDown, for example-usurping the implementation of its superclass. If your subclass needs to handle particular events some of the time-only some typed characters, perhaps-then it must override the event method to handle the cases it's interested in and to invoke super's implementation otherwise. This allows a superclass to catch the cases it's interested in, and ultimately allows the event to continue on its way along the responder chain if it isn't handled. "Key Events" below describes how to handle keyboard events in your application. See the NSView class specification for information on handling mouse events.

Action methods don't have default implementations, so responder subclasses shouldn't blindly forward action messages to super. Passing of action messages is predicated merely on whether an object responds to the method, unlike with the passing of event messages. Of course, if you know that a superclass does in fact implement the method, you can pass it on up from your subclass.

Key Events

Processing keyboard input is by far the most complex part of event handling. The Application Kit goes to great lengths to ease this process for you, and in fact handling the key events that get to your custom objects is fairly straightforward. However, a lot happens to those events on their way from the hardware to the responder chain. The sections below attempt to explain how events are handled through the operating system and the Application Kit, so you can understand what your objects receive and don't receive.

The Path of a Key Event

Physical keyboard events must pass through the operating system before becoming NSEvent objects in the Application Kit. Depending on the operating system, some of these "raw" events might be trapped before they ever become NSEvent objects. Reserved key combinations are often handled in this way. Key events that arrive at the Application Kit are processed by NSApplication's sendEvent method as indicated before. The application object filters out key equivalents (also known as "Command key events") and sends them out as described under "Key Equivalents and Mnemonics" below. All other key events are passed to the key window's sendEvent method.

The key window first checks the event to see if the Control key is pressed. If it is, the window treats the event as a forced control event, which is blocked from the responder chain and is processed immediately as a potential mnemonic or keyboard interface control event. If this doesn't apply, the event is passed to the window's first responder in a keyDown message, which is how your custom responders receive uninterpreted key events. "Keyboard Input" describes how you can handle these events.

If no view object in the key window accepts the key event, NSWindow's keyDown attempts to handle the key event itself. It tries to interpret the key event as each of the following, in order, beeping if it fails to match any of them to let the user know the typing couldn't be processed:

Key Equivalents and Mnemonics

A key equivalent is a character bound to some view in a window, which causes that view to perform a specified action when the user types that character, usually while pressing the Command key (the Control key on Microsoft Windows). A mnemonic works similarly, using the Alternate key as its cue to action. If both modifier keys are pressed, the key event is interpreted only as a mnemonic. A key equivalent or mnemonic must be a character that can be typed with no modifier keys, or with Shift only. Each is sent down the view hierarchy of a window instead of up the responder chain, but at different times.

Key equivalents are dispatched by the NSApplication object's sendEvent method. On the Mach operating system, this results in a performKeyEquivalent message being sent to every NSWindow in the application until one of them returns true. On the Microsoft Windows operating system, it results in a performKeyEquivalent message being sent to the menu of the key window, and of the main window if the key window's menu doesn't handle it. This difference in handling means that, among other things, NSWindow subclasses shouldn't override performKeyEquivalent. Also, objects other than menu items shouldn't be assigned key equivalents; they should instead be assigned mnemonics. Key equivalents sent to a window on Mach are passed down the view hierarchy through NSView's abstract implementation of performKeyEquivalent, which forwards the message to each of its subviews until one responds true, returning false if none does.

Mnemonics, on the other hand, are dispatched by the key window. If the user presses the Control key as well as the mnemonic's key combination, NSWindow's sendEvent immediately treats that event as a mnemonic to be performed, without sending the event up the responder chain. If the user doesn't press the Control key, the event passes through the window's responder chain, possibly being handled by a responder, before arriving as a keyDown message to the window. In either case, a mnemonic for a top-level menu on Microsoft Windows is sent back to the operating system, and eventually results in the Application Kit invoking a menu item's action. Any other mnemonic is handled by sending a performMnemonic: message down the window's view hierarchy, in the same manner as for a performKeyEquivalent message.



Keyboard Interface Control

Mnemonics are actually part of a more general means of controlling the user interface via the keyboard. An NSWindow treats certain key events specially, as commands to move control to a different interface object, to simulate a mouse click on it, and so on. In brief, pressing Tab moves control to the next object, whether a button, a text field, or some other kind of control object. Shift-Tab moves control to the previous one. Pressing Space simulates a mouse click for many kinds of control objects, causing a push button to click, a radio button to toggle its state, and so on. In selection lists, pressing Space selects or deselects the highlighted item; the user can also press Alternate or Shift to extend the selection, not affecting other selected items. Some interface controls also accept arrow-key input.

Each window can be assigned a default button, which is triggered by the Return or Enter key. Also, in modal windows or panels the user can press the Escape key to dismiss the window or panel. If interface control moves to another button, the default button temporarily loses this ability as the user's focus shifts to the button where control resides. However, if control then moves to a different kind of interface object, the default button resumes its normal ability.

The interface objects that are connected together within a window make up the window's key view loop. You normally set up the key view loop using Interface Builder, establishing connections to each interface object's nextKeyView outlet. You can also set the object that's initially selected when a window is first opened by setting the window's initialFirstResponder outlet in Interface Builder. If you do not set this outlet, the window will set a key loop (not necessarily the same as the one you may have specified!) and pick a default initial outlet for you. NSView and NSWindow also define a number of methods for manipulating the key view loop programmatically; see their class specifications for more information.

Keyboard Input

A normal key event eventually makes its way to the responder chain as a keyDown message, which the receiver can handle in any way it sees fit. A text object typically interprets the message as a request to insert text, while a drawing object might only be interested in a few keys, such as Delete and the arrow keys to delete and move selected items. The receiver of a keyDown message can extract the event's characters directly using NSEvent's characters or charactersIgnoringModifiers methods, or it can pass the key event to the Application Kit's input manager for interpretation according to the user's key bindings. Input management allows key events to be interpreted as text not directly available on the keyboard, such as Kanji and some accented characters, and as commands that affect the content of the responder object handling the event. See the NSInputManager and NSTextInput class and protocol specifications for more information on input management and key binding.

To invoke the input manager, simply invoke NSResponder's interpretKeyEvents message in your implementation of keyDown. This method sends an NSArray of events to the input manager, which interprets the events as text or commands and responds by sending insertText: or doCommandBySelector: to your responder object. The section "Standard Action Methods for Selecting and Editing" below describes the messages that might be sent to your object.

Other Uses

The responder chain is utilized by two other mechanisms in the Application Kit. In enabling and disabling a menu item, the application object consults the full responder chain for an object that implements the menu item's action method, as described in the NSMenuActionResponder protocol specification. Similarly, the Services facility passes validRequestorForTypes messages along the full responder chain to check for objects that are eligible for services offered by other applications. The Services validation process is described fully in "Services" in OPENSTEP Programming Topics.


Adopted Protocols


NSCoding
- encodeWithCoder:
- initWithCoder:

Method Types


Changing the first responder
acceptsFirstResponder
becomeFirstResponder
resignFirstResponder
Setting the next responder
setNextResponder
nextResponder
Event methods
mouseDown
mouseDragged
mouseUp
mouseMoved
mouseEntered
mouseExited:
rightMouseDown
rightMouseDragged
rightMouseUp
keyDown
keyUp
flagsChanged
helpRequested
Special key event methods
interpretKeyEvents
performKeyEquivalent
performMnemonic:
Clearing key events
flushBufferedKeyEvents
Action methods
capitalizeWord:
centerSelectionInVisibleArea:
changeCaseOfLetter:
complete:
deleteBackward:
deleteForward:
deleteToBeginningOfLine:
deleteToBeginningOfParagraph:
deleteToEndOfLine:
deleteToEndOfParagraph:
deleteToMark:
deleteWordBackward:
deleteWordForward:
indent:
insertBacktab:
insertNewline:
insertNewlineIgnoringFieldEditor:
insertParagraphSeparator:
insertTab:
insertTabIgnoringFieldEditor:
insertText:
lowercaseWord:
moveBackward:
moveBackwardAndModifySelection:
moveDown:
moveDownAndModifySelection:
moveForward:
moveForwardAndModifySelection:
moveLeft:
moveRight:
moveToBeginningOfDocument:
moveToBeginningOfLine:
moveToBeginningOfParagraph:
moveToEndOfDocument:
moveToEndOfLine:
moveToEndOfParagraph:
moveUp:
moveUpAndModifySelection:
moveWordBackward:
moveWordBackwardAndModifySelection:
moveWordForward:
moveWordForwardAndModifySelection:
pageDown:
pageUp:
scrollLineDown:
scrollLineUp:
scrollPageDown:
scrollPageUp:
selectAll:
selectLine:
selectParagraph:
selectToMark:
selectWord:
setMark:
showContextHelp
swapWithMark:
transpose:
transposeWords:
uppercaseWord:
yank:
Dispatch methods
doCommandBySelector:
tryToPerform
Terminating the responder chain
noResponderFor:
Services menu updating
validRequestorForTypes
Setting the menu
setMenu
menu
Setting the interface style
setInterfaceStyle
interfaceStyle


Instance Methods



acceptsFirstResponder

public boolean acceptsFirstResponder()

Overridden by subclasses to return true if the receiver can handle key events and action messages sent up the responder chain. NSResponder's implementation returns false, indicating that by default a responder object doesn't agree to become first responder. Objects that aren't first responder can receive mouse event messages, but no other event or action messages.

See Also: becomeFirstResponder, resignFirstResponder, - needsPanelToBecomeKey (NSView)



becomeFirstResponder

public boolean becomeFirstResponder()

Notifies the receiver that it's about to become first responder in its NSWindow. NSResponder's implementation returns true, accepting first responder status. Subclasses can override this method to update state or perform some action such as highlighting the selection, or to return false, refusing first responder status.

Use NSWindow's makeFirstResponder:, not this method, to make an object the first responder. Never invoke this method directly.

See Also: resignFirstResponder, acceptsFirstResponder



flagsChanged

public void flagsChanged(NSEvent theEvent)

Informs the receiver that the user has pressed or released a modifier key (Shift, Control, and so on). NSResponder's implementation simply passes this message to the next responder.

flushBufferedKeyEvents

public void flushBufferedKeyEvents()

Overridden by subclasses to clear any unprocessed key events.

helpRequested

public void helpRequested(NSEvent theEvent)

Displays context-sensitive help for the receiver if such exists, otherwise passes this message to the next responder. NSWindow invokes this method automatically when the user clicks for help. Subclasses need not override this method, and application code shouldn't directly invoke it.

See Also: showContextHelp



interfaceStyle

public int interfaceStyle()

Returns the receiver's interface style. interfaceStyle is an abstract method in NSResponder and just returns NoInterfaceStyle. It is overridden in classes such as NSWindow and NSView to return the interface style, such as MacintoshInterfaceStyle or Windows95InterfaceStyle. A responder's style (if other than NoInterfaceStyle) overrides all other settings, such as those established by the defaults system.

See Also: setInterfaceStyle



interpretKeyEvents

public void interpretKeyEvents(NSArray eventArray)

Invoked by subclasses from their keyDown method to handle a series of key events. This method sends the character input in eventArray to the system input manager for interpretation as text to insert or commands to perform. The input manager responds to the request by sending insertText: and doCommandBySelector: messages back to the invoker of this method. Subclasses shouldn't override this method.

See the NSInputManager and NSTextInput class and protocol specifications for more information on input management.



keyDown

public void keyDown(NSEvent theEvent)

Informs the receiver that the user has pressed a key. The receiver can interpret theEvent itself, or pass it to the system input manager using interpretKeyEvents. NSResponder's implementation simply passes this message to the next responder.

keyUp

public void keyUp(NSEvent theEvent)

Informs the receiver that the user has released a key. NSResponder's implementation simply passes this message to the next responder.

menu

public NSMenu menu()

Returns the receiver's menu. For NSApplication this is the same as the menu returned by its mainMenu method.

See Also: setMenu, - menuForEvent: (NSView) + defaultMenu (NSView)



mouseDown

public void mouseDown(NSEvent theEvent)

Informs the receiver that the user has pressed the left mouse button. NSResponder's implementation simply passes this message to the next responder.

mouseDragged

public void mouseDragged(NSEvent theEvent)

Informs the receiver that the user has moved the mouse with the left button pressed. NSResponder's implementation simply passes this message to the next responder.

mouseEntered

public void mouseEntered(NSEvent theEvent)

Informs the receiver that the mouse has entered a tracking rectangle. NSResponder's implementation simply passes this message to the next responder.

mouseExited:

public void mouseExited(NSEvent theEvent)

Informs the receiver that the mouse has exited a tracking rectangle. NSResponder's implementation simply passes this message to the next responder.

mouseMoved

public void mouseMoved(NSEvent theEvent)

Informs the receiver that the mouse has moved. NSResponder's implementation simply passes this message to the next responder.

See Also: - setAcceptsMouseMovedEvents: (NSWindow)



mouseUp

public void mouseUp(NSEvent theEvent)

Informs the receiver that the user has released the left mouse button. NSResponder's implementation simply passes this message to the next responder.

nextResponder

public NSResponder nextResponder()

Returns the receiver's next responder, or null if it has none.

See Also: setNextResponder, noResponderFor:



noResponderFor:

public void noResponderForSelector(NSSelector eventSelector)

Handles the case where an event or action message falls off the end of the responder chain. NSResponder's implementation beeps if eventSelector is keyDown.

performKeyEquivalent

public boolean performKeyEquivalent(NSEvent theEvent)

Overridden by subclasses to handle a key equivalent. If the character code or codes in theEvent match the receiver's key equivalent, the receiver should respond to the event and return true. NSResponder's implementation does nothing and returns false.
performKeyEquivalent takes an NSEvent as its argument, while performMnemonic: takes an NSString containing the uninterpreted characters of the key event. You should extract the characters for a key equivalent using NSEvent's charactersIgnoringModifiers method.

See Also: - performKeyEquivalent: (NSView) - performKeyEquivalent: (NSButton)



performMnemonic:

public boolean performMnemonic(String aString)

Overridden by subclasses to handle a mnemonic. If the character code or codes in aString match the receiver's mnemonic, the receiver should perform the mnemonic and return true. NSResponder's implementation does nothing and returns false.

See Also: - performMnemonic: (NSView)



resignFirstResponder

public boolean resignFirstResponder()

Notifies the receiver that it's been asked to relinquish its status as first responder in its NSWindow. NSResponder's implementation returns true, resigning first responder status. Subclasses can override this method to update state or perform some action such as unhighlighting the selection, or to return false, refusing to relinquish first responder status.

Use NSWindow's makeFirstResponder:, not this method, to make an object the first responder. Never invoke this method directly.

See Also: becomeFirstResponder, acceptsFirstResponder



rightMouseDown

public void rightMouseDown(NSEvent theEvent)

Informs the receiver that the user has pressed the right mouse button. NSResponder's implementation simply passes this message to the next responder.

rightMouseDragged

public void rightMouseDragged(NSEvent theEvent)

Informs the receiver that the user has moved the mouse with the right button pressed. NSResponder's implementation simply passes this message to the next responder.

rightMouseUp

public void rightMouseUp(NSEvent theEvent)

Informs the receiver that the user has released the right mouse button. NSResponder's implementation simply passes this message to the next responder.

setInterfaceStyle

public void setInterfaceStyle(int interfaceStyle)

Sets the receiver's style to the style specified by interfaceStyle, such as MacintoshInterfaceStyle or Windows95InterfaceStyle. setInterfaceStyle: is an abstract method in NSResponder, but is overridden in classes such as NSWindow and NSView to actually set the interface style. You should almost never need to invoke or override this method, but if you do override it, your version should always invoke the implementation in super.

See Also: interfaceStyle



setMenu

public void setMenu(NSMenu aMenu)

Sets the receiver's menu to aMenu. For NSApplication this is the same as the main menu, typically set using setMainMenu:.

See Also: menu



setNextResponder

public void setNextResponder(NSResponder aResponder)

Sets the receiver's next responder to aResponder.

See Also: nextResponder



showContextHelp

public void showContextHelp(Object sender)

Implemented by subclasses to invoke the host platform's help system, displaying information relevant to the receiver and its current state.

See Also: helpRequested



tryToPerform

public boolean tryToPerform(NSSelector anAction, Object anObject)

Attempts to perform the action method indicated by anAction. The method should take a single argument of type Object and return void. If the receiver responds to anAction, it invokes the method with anObject as the argument and returns true. If the receiver doesn't respond, it sends this message to its next responder with the same selector and object. Returns false if no responder is found that responds to anAction.

See Also: doCommandBySelector: - sendAction:to:from: (NSApplication)



undoManager

public NSUndoManager undoManager()

<<Documentation Forthcoming>>

validRequestorForTypes

public Object validRequestorForTypes(String sendType, String returnType)

Overridden by subclasses to determine what services are available. With each event, and for each service in the Services menu, the application object sends this message up the responder chain with the send and return type for the service being checked. This method is therefore invoked many times per event. If the receiver can place data of sendType on the pasteboard and receive data of returnType, it should return this; otherwise it should return null. NSResponder's implementation simply forwards this message to the next responder, ultimately returning null.

Either sendType or returnType-but not both-may be empty. If sendType is empty, the service doesn't require input from the application requesting the service. If returnType is empty, the service doesn't return data.

See "Services" in OPENSTEP Programming Topics for more information.

See Also: - registerServicesMenuSendTypes:returnTypes: (NSApplication), - writeSelectionToPasteboard:types: (NSServicesRequests, protocol), - readSelectionFromPasteboard: (NSServicesRequests protocol)




[Previous][Next]
performKeyEquivalent takes an NSEvent as its argument, while performMnemonic: takes an NSString containing the uninterpreted characters of the key event. You should extract the characters for a key equivalent using NSEvent's charactersIgnoringModifiers method.