Copyright: Copyright ©


Classes

NSActionCell

NSApplication

NSAttributedString Class Cluster Additions

NSBitmapImageRep

NSBox

NSBrowser

NSBrowserCell

NSBundleAdditions

NSButton

NSButtonCell

NSCachedImageRep

NSCell

NSClipView

NSCoderAdditions

NSColor

NSColorList

NSColorPanel

NSColorPicker

NSColorWell

NSControl

NSCursor

NSCustomImageRep

NSDataLink

NSDataLinkManager

NSDataLinkPanel

NSDPSContext

NSEPSImageRep

NSEvent

NSFileWrapper

NSFont

NSFontManager

NSFontPanel

NSForm

NSFormCell

NSHelpManager

NSImage

NSImageCell

NSImageRep

NSImageView

NSLayoutManager

NSMatrix

NSMenu

NSMenuItem

NSMutableParagraphStyle

NSOpenPanel

NSPageLayout

NSPanel

NSParagraphStyle

NSPasteboard

NSPopUpButton

NSPrinter

NSPrintInfo

NSPrintOperation

NSPrintPanel

NSResponder

NSRulerMarker

NSRulerView

NSSavePanel

NSScreen

NSScrollView

NSScroller

NSSecureTextField

NSSecureTextFieldCell

NSSelection

NSSlider

NSSliderCell

NSSpellChecker

NSSpellServer

NSSplitView

NSString Additions

NSTableColumn

NSTableHeaderCell

NSTableHeaderView

NSTableView

NSText

NSTextAttachment

NSTextAttachmentCell

NSTextContainer

NSTextField

NSTextFieldCell

NSTextStorage

NSTextTab

NSTextView

NSView

NSWindow

NSWorkspace


Client Library Functions

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

DPSAddFD(), DPSRemoveFD()

SUMMARY	Monitor a file descriptor

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	void DPSAddFD(int fd, DPSFDProc handler, void *userData, int priority)

void DPSRemoveFD(int fd)

DESCRIPTION	DPSAddFD() registers the function handler to be called each time there is activity with the file specified by file descriptor fd.  The function is called provided the following are true:

•	The file descriptor fd must be valid and open; typically fd is generated through a call to open().  There needn’t be any data waiting to be read on fd.

•	priority, an integer from 0 to 30, must be equal to or greater than the application’s current priority threshold.  See DPSAddTimedEntry() for a further explanation.

DPSFDProc, handler’s defined type, takes the form

void *handler(int fd, void *userData)

where fd is the file descriptor that prompted the function call and userData is the same pointer that was passed as the third argument to DPSAddFD().  The userData pointer is provided as a convenience, allowing you to pass arbitrary data to handler.

DPSRemoveFD() removes the specified file descriptor from the list of those that the application will check.

Typically, DPSAddFD() is used to listen to a socket or pipe; it’s rarely used to monitor a common file.

SEE ALSO	DPSAddPort(), DPSAddTimedEntry()

DPSAddNotifyPortProc(), DPSRemoveNotifyPortProc()

SUMMARY	Set the handler function for the notify port

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	void DPSAddNotifyPortProc(DPSPortProc handler, void *userData)

void DPSRemoveNotifyPortProc(DPSPortProc handler)

DESCRIPTION	DPSAddNotifyPortProc() registers handler as the function that’s called when a message arrives on the notify port, the unique port, created through the task_notify() Mach function, on which notifications (such as port death) are sent.  You don’t need to create the notify port yourself; DPSAddNotifyPortProc() creates it for you if it doesn’t already exist.

DPSPortProc, handler’s defined type, takes the form

void ∗handler(msg_header_t *msg, void *userData)

where msg is a pointer to the message that was received at the port and userData is the same pointer that was passed as the second argument to DPSAddNotifyPortProc().  The userData pointer is provided as a convenience, allowing you to pass arbitrary data to handler.

The notify port can have only one handler at a time; adding a handler removes the current one.  You can remove the port’s handler without specifying a new one with the DPSRemoveNotifyPortProc() function.  The function’s argument must match the notify port’s current handler.

SEE ALSO	DPSAddPort(), DPSAddTimedEntry()

DPSAddPort(), DPSRemovePort()

SUMMARY	Monitor a Mach port

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	void DPSAddPort(port_t port, DPSPortProc handler, int maxMsgSize, void *userData, int priority)

void DPSRemovePort(port_t port)

DESCRIPTION	DPSAddPort() registers the function handler to be called each time your application asks for an event or peeks at the event queue.  The function is called provided the following are true:

•	The Mach port port  must be valid and it must hold a message waiting to be read.

•	priority, an integer from 0 to 30, must be equal to or greater than the application’s current priority threshold.  See DPSAddTimedEntry() for a further explanation.

DPSPortProc, handler’s defined type, takes the form

void *handler(msg_header_t *msg, void *userData)

where msg is a pointer to the message that was received at the port and userData is the same pointer that was passed as the fourth argument to DPSAddPort().  The userData pointer is provided as a convenience, allowing you to pass arbitrary data to handler.

If, within handler, you want to call msg_receive() to receive further messages at the port, you must first call DPSRemovePort() to remove the port from the system’s port set.  (This is because your application can’t receive messages from a port that’s in a port set.)  After your application is finished receiving messages directly from the port, it can call DPSAddPort() to have the system continue to monitor the port.

The contents of the message buffer msg, as received by handler, are invalid after the function returns.  If you need to save any of the information that you find.

The maxMsgSize argument is an integer that gives the size, in bytes, of the largest message you expect to receive.

DPSRemovePort() removes the specified Mach port from the list of those that the application will check.

SEE ALSO	DPSAddFD(), DPSAddTimedEntry()

DPSAddTimedEntry(), DPSRemoveTimedEntry()

SUMMARY	Create a timed entry

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	DPSTimedEntry DPSAddTimedEntry(double  period, DPSTimedEntryProc handler, void *userData, int priority)

void DPSRemoveTimedEntry(DPSTimedEntry tag)

DESCRIPTION	DPSAddTimedEntry() registers handler as a “timed entry,” a function that’s called repeatedly at a given time interval.  period determines the number of seconds between calls to the timed entry.  Whenever an application based on the Application Kit attempts to retrieve events from the event queue, it also checks (depending on priority) to determine whether any timed entries are due to be called.  userData is a pointer that you can use to pass some data to the timed entry.

The function registered as handler has the form:

void *handler(DPSTimedEntry tag, double now, void *userData)

where tag is the timed entry identifier returned by DPSAddTimedEntry(), now is the number of seconds since some arbitrary point in the past, and userData is the pointer DPSAddTimedEntry() received when this timed entry was installed.

An application’s priority threshold can be set explicitly as an integer from 0 to 31 through a call to DPSGetEvent() or DPSPeekEvent().  It’s against this threshold that priority is measured (note that priority can be no greater than 30—the additional threshold level, 31, is provided to disallow all inter-event function calls).  However, if you’re using the Application Kit, you should access the event queue through Application class methods such as getNextEvent:.  Although some of these methods let you set the priority threshold explicity, you typically invoke the methods that set it automatically.  Such methods use only three priority levels:

Constant	Meaning

NX_BASETHRESHOLD	Normal execution

NX_RUNMODALTHRESHOLD	An attention panel is being run

NX_MODALRESPTHRESHOLD	A modal event loop is being run

When applicable, you should use these constants as the value for priority.  For example, if you want handler to be called during normal execution, but not if an attention panel or a modal loop is running, then you would set priority to NX_BASETHRESHOLD.

DPSRemoveTimedEntry() removes a previously registered timed entry.

RETURN	DPSAddTimedEntry() returns a number identifying the timed entry or −1 to indicate an error.

DPSAsynchronousWaitContext()

SUMMARY	Procede asynchronously while PostScript code is executed

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	void DPSAsynchronousWaitContext(DPSContext context, DPSPingProc handler,

void *userData)

DESCRIPTION	This function is similar to the more familiar DPSWaitContext() functions, except that rather than wait for all PostScript code to execute, it returns immediately, allowing your application to procede while the PostScript code is executed in the background.  The DPSPingProc function handler is called (with context and userData as its two arguments) when all the PostScript code has been executed.  The DPSPingProc function takes the form

void *handler(DPSContext context, void *userData);

Warning:  Be careful when you use this function; you mustn’t send more PostScript code while waiting for the handler to be called.  In general, it’s best to not make any demands on the Application Kit or the Client Library if you’re waiting for an asynchronous handler to return.

DPSCreateContext(), DPSCreateContextWithTimeoutFromZone(), DPSCreateNonsecureContext(), DPSCreateStreamContext()

SUMMARY	Create a PostScript execution context

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	DPSContext DPSCreateContext(const char *hostName, const char *serverName, DPSTextProc textProc, DPSErrorProc errorProc)

DPSContext DPSCreateContextWithTimeoutFromZone(const char *hostName, const char *serverName, DPSTextProc textProc, DPSErrorProc errorProc, int timeout, NXZone *zone)

DPSContext DPSCreateNonsecureContext(const char *hostName, const char *serverName, DPSTextProc textProc, DPSErrorProc errorProc, int timeout, NXZone *zone)

DPSContext DPSCreateStreamContext(NXStream *stream, int debugging, DPSProgramEncoding progEnc, DPSNameEncoding nameEnc, DPSErrorProc errorProc)

DESCRIPTION	DPSCreateContext() establishes a connection with the Window Server and creates a PostScript execution context in it.  The new context becomes the current context.  The first argument, hostName, identifies the machine that’s running the Window Server; the second argument, serverName, identifies the Window Server that’s running on that machine.  With these two arguments and the help of the Mach network server nmserver, the Mach port for the Window Server can be identified.  If hostName is NULL, the network server on the local machine is queried for the Window Server’s port.  If serverName is NULL, a default name for the Window Server is used.

The last two arguments, textProc and errorProc, refer to call-back functions (defined in the Client Library specification) that handle text returned from the Window Server and errors generated on either side of the connection.

For an application that’s based on the Application Kit, you could create an additional context by making this call:

DPSContext  c;

c = DPSCreateContext(NXGetDefaultValue([NXApp appName], "NXHost"),

                   NXGetDefaultValue([NXApp appName], "NXPSName"),

                   NULL,

                   NULL);

This example queries the application’s default values for the indentity of the host machine and the Window Server.  By doing this, the new context is created in the correct Window Server even if that Server is not on the same machine as the application process.

The context that DPSCreateContext() creates allocates memory from the default allocation zone.  Also, when there’s difficulty creating the context, DPSCreateContext() waits up to 60 seconds before raising an exception.  If you want to change either of these parameters, use DPSCreateContextWithTimeoutFromZone().  Its two additional arguments let you specify the zone for the context to use when allocating context-specific data and a timeout value in milliseconds.

DPSCreateNonsecureContext() creates a “nonsecure” context in which you can use PostScript operators that are normally disallowed.  The most significant of these are operators that let you write files.

DPSCreateStreamContext() is similar to DPSCreateContext(), except that the new context is actually a connection from the client application to a stream.  This connection becomes the current context.  PostScript code that the application generates is sent to the stream rather than to the Window Server.  The first argument, stream, is a pointer to an NXStream structure, as created by NXOpenFile() or NXMapFile().  The debugging argument is intended for debugging purposes but is not currently implemented.  progEnc and nameEnc specify the type of program and user-name encodings to be used for output to the stream.  The last argument, errorProc, identifies the procedure that’s called when errors are generated.

Few programmers will need to call either of these functions directly:  The Application Kit manages contexts for programs based on the Kit.  For example, when an application is launched, its Application object calls DPSCreateContext() to create a context in the Window Server.  Similarly, to print a View the Kit calls DPSCreateStreamContext() to temporarily redirect PostScript code from the View to a stream.

RETURN	Each of these functions returns the newly created DPSContext structure.

EXCEPTIONS	DPSCreateContext() and DPSCreateContextWithTimeoutFromZone() raise a dps_err_outOfMemory exception if they encounter difficulty allocating ports or other resources for the new context.  They raise a dps_err_cantConnect exception if they can’t return a context within the timeout period.

DPSDefineUserObject(), DPSUndefineUserObject()

SUMMARY	Create a user object

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	int DPSDefineUserObject(int index)

void DPSUndefineUserObject(int index)

DESCRIPTION	DPSDefineUserObject() associates index with the PostScript object that’s on the top of the operand stack, thereby creating a user object (as defined by the PostScript language).  If index is 0, the object is assigned the next available index number.  The function returns the new index, which can then be passed to a pswrap-generated function that takes a user object.

Warning:  To avoid coming into conflict with user objects defined by the Client Library or Application Kit, use DPSDefineUserObject() rather than the PostScript operator defineuserobject or the single-operator functions DPSdefineuserobject() and PSdefineuserobject().

DPSUndefineUserObject() removes the association between index and the PostScript object it refers to, thus destroying the user object.  By destroying a user object that’s no longer needed, you can let the garbage collector reclaim the previously associated PostScript object.

RETURN	DPSDefineUserObject(), if successful in assigning an index, returns the index that the object was assigned.  If unsuccessful, it returns 0.

DPSDoUserPath(), DPSDoUserPathWithMatrix()

SUMMARY	Send an encoded PostScript path to the Window Server

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	void DPSDoUserPath(void *coords, int numCoords, DPSNumberFormat numType, unsigned char *ops, int numOps, void *bbox, int action)

void DPSDoUserPathWithMatrix(void *coords, int numCoords, DPSNumberFormat numType, unsigned char *ops, int numOps, void *bbox, int action, float matrix[6])

DESCRIPTION	DPSDoUserPath() and DPSDoUserPathWithMatrix() send an encoded user path to the Window Server and then execute, upon that path, the operator specified by action.  The use of these functions, rather than the analogous step-by-step path construction, is encouraged; rendering an encoded path is much more efficient than executing the individual PostScript operators that would otherwise be needed.

An encoded user path consists of an array of coordinate values, a sequence of PostScript operators, and a bounding box specification.  The values in the coordinate array are used as operands to the operators; the operands are distributed to the operators in the order that they’re given.  The resulting path must fit within the bounding box.

The coordinates, operators, and bounding box are given by the functions’ first five arguments:

•	The array of coordinate values is given by coords.

•	numCoords is the number of elements in coords.

•	 numType specifies the data type of the coordinates, as described below.  All the values in coords must be of the same type.

•	ops is the sequence of PostScript operators, represented by constants as listed below.

•	The  bounding box is defined by the four coordinate values that you pass as an array in the bbox argument.  These are passed as operands to the setbbox operator.  (If you don’t supply a setbbox as part of the ops sequence, one is inserted for you.)

The following integer constants represent the data types that you can pass as the numType argument:

Constant	Meaning

dps_float	single-precision floating-point number

dps_long	32-bit integer

dps_short	8-bit integer

You can also specify 16- and 32-bit fixed-point real numbers.  For 16-bit fixed-point numbers, use dps_short plus the number of bits in the fractional portion.  For 32-bit fixed-point numbers, use dps_long plus the number of bits in the fractional portion.

These constants are provided for ops:

dps_setbbox

dps_moveto

dps_rmoveto

dps_lineto

dps_rlineto

dps_curveto

dps_rcurveto

dps_arc

dps_arcn

dps_arct

dps_closepath

dps_ucache

Once the user path has been constructed, the operator specified by action is executed.  The value of action is an index into Display PostScript’s encoded system names; the following constants, provided as a convenience, represent the most commonly used actions:

dps_uappend

dps_ufill

dps_ueofill

dps_ustroke

dps_ustrokepath

dps_inufill

dps_inueofill

dps_inustroke

dps_def

dps_put

DPSDoUserPathWithMatrix()’s matrix argument represents the transformation matrix operand used by the ustroke, inustroke, and ustrokepath operators.  If matrix is NULL, the argument is ignored.

The following program fragment demonstrates the use of DPSDoUserPath() as it creates and strokes a user path (an isosceles triangle) within a bounding rectangle whose lower left corner is located at (0, 0) and whose width and height are 200.

short   coords[6] = {0, 0, 200, 0, 100, 200};

char    ops[4] = {dps_moveto, dps_lineto,dps_lineto,

                    dps_closepath};

short   bbox[4] = {0, 0, 200, 200};

DPSDoUserPath(coords, 6, dps_short, ops, 4, bbox, dps_ustroke);

Note:  If an application calls DPSDoUserPath() with large values (~10,000-20,000) of numCoords and/or numOps, it may generate a Display PostScript error.

DPSFlush(), DPSSendEOF()

SUMMARY	Send PostScript data to the Window Server

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	void DPSFlush()

void DPSSendEOF(DPSContext context)

DESCRIPTION	DPSFlush() flushes the application’s output buffer, forcing any buffered PostScript code or data to the Window Server.

DPSSendEOF() sends a PostScript end-of-file marker to the given context.  The connection to the context isn’t closed or disturbed in any way by this function.

DPSGetEvent(), DPSPeekEvent(), DPSDiscardEvents()

SUMMARY	Access events from the Window Server

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	int DPSGetEvent(DPSContext context, NXEvent *anEvent, int mask, double timeout, int threshold)

int DPSPeekEvent(DPSContext context, NXEvent *anEvent, int mask, double timeout, int threshold)

void DPSDiscardEvents(DPSContext context, int mask)

DESCRIPTION	DPSGetEvent() and DPSPeekEvent() are macros that access event records in an application’s event queue.  These routines are provided primarily for programs that don’t use the Application Kit.  An application based on the Kit should use the corresponding Application class methods (such as getNextEvent: and peekNextEvent:into:) or the function NXGetOrPeekEvent() so that it can be journaled.  DPSDiscardEvents() removes all event records of a specified type from the queue.

DPSGetEvent() and DPSPeekEvent() differ only in how they treat the accessed event record.  DPSGetEvent() removes the record from the queue after making its data available to the application; DPSPeekEvent() leaves the record in the queue.

DPSGetEvent() and DPSPeekEvent() take the same parameters.  The first, context, represents a PostScript execution context within the Window Server.  Virtually all applications have only one execution context, which can be returned using DPSGetCurrentContext().  Applications having more than one execution context can use the constant DPS_ALLCONTEXTS to access events from all contexts belonging to them.

The second argument, anEvent, is a pointer to an event record.  If DPSGetEvent() or DPSPeekEvent() is successful in accessing an event record, the record’s data is copied into the storage referred to by anEvent.

mask determines the types of events sought.  See the section “Types and Constants” for a list of the constants that represent the event type masks.  To check for more than one type of event, you combine individual constants using the bitwise OR operator.

If an event matching the event mask isn’t available in the queue, DPSGetEvent() or DPSPeekEvent() waits until one arrives or until timeout seconds have elapsed, whichever occurs first.  The value of timeout can be in the range of 0.0 to NX_FOREVER.  If timeout is 0.0, the routine returns an event only if one is waiting in the queue when the routine asks for it.  If timeout is NX_ FOREVER, the routine waits until an appropriate event arrives before returning.

The last argument, threshold, is an integer in the range 0 through 31 that determines which other services may be provided during a call to DPSGetEvent() or DPSPeekEvent().

Requests for services are registered by the functions DPSAddTimedEntry(), DPSAddPort(), and DPSAddFD().  Each of these functions takes an argument specifying a priority level.  If this level is equal to or greater than threshold, the service is provided before DPSGetEvent() or DPSPeekEvent() returns.

DPSDiscardEvents()’s two parameters, context and mask, are the same as those for DPSGetEvent() and DPSPeekEvent().  DPSDiscardEvents() removes from the application’s event queue those records whose event types match mask and whose context matches context.

RETURN	DPSGetEvent() and DPSPeekEvent() return 1 if they are successful in accessing an event record and 0 if they aren’t.

SEE ALSO	DPSAddFD(), DPSAddPort(), DPSAddTimedEntry(), DPSPostEvent(), NXGetOrPeekEvent()

DPSInterruptContext()

Warning:  This function is unimplemented in the NEXTSTEP version of the Client Library.

DPSNameFromTypeAndIndex()

SUMMARY	Access the system and user name tables

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	const char *DPSNameFromTypeAndIndex(short type, int index)

DESCRIPTION	DPSNameFromTypeAndIndex() returns the text associated with index from the system or user name table.  If type is −1, the text is returned from the system name table; if type is 0, it’s returned from the user name table.

The name tables are used primarily by the Client Library and pswrap; few programmers will access them directly.

RETURN	This function returns a read-only character string.

DPSPostEvent()

SUMMARY	Create an event

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	int DPSPostEvent(NXEvent *anEvent, int atStart)

DESCRIPTION	DPSPostEvent() lets you add an event record to your application’s event queue without involving the Window Server.  anEvent is a pointer to the event record to be added.  atStart specifies where the new record will be placed in relation to any other records in the queue.  If atStart is TRUE, the event is posted in front of all others and so will be the next one your application receives.  If atStart is FALSE, the event is posted behind all others and so won’t be returned until events that precede it are processed.

You can free, reuse, or otherwise mangle anEvent after you’ve posted it without fear of corrupting the posted record.  DPSEvent() copies the record it receives and posts the copy.

Note that event records you post using DPSPostEvent() aren’t filtered by an event filter function set with DPSSetEventFunc().

RETURN	DPSPostEvent() returns 0 if successful in posting the event record; it returns −1 if unsuccessful in posting the record because the event queue is full.

SEE ALSO	DPSSetEventFunc()

DPSPrintError(), DPSPrintErrorToStream()

SUMMARY	Print error messages

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	void DPSPrintError(FILE *fp, const DPSBinObjSeq error)

void DPSPrintErrorToStream(NXStream *stream, const DPSBinObjSeq error)

DESCRIPTION	DPSPrintError() and DPSPrintErrorToStream() format and print error messages received from a PostScript execution context in the Window Server.  The error message is extracted from the binary object sequence error.  DPSPrintError() prints the error message to the file identified by fp; DPSPrintErrorToStream() prints the error message to stream.

You rarely need to call these functions directly.  However, if you reset the error handler for a PostScript execution context, the new handler you install could use one of these functions to process errors that it receives.

DPSResetContext()

Warning:  This function is unimplemented in the NEXTSTEP version of the Client Library.

DPSSetDeadKeysEnabled()

SUMMARY	Allow dead key processing for a context’s events

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	void DPSSetDeadKeysEnabled(DPSContext context, int flag)

DESCRIPTION	DPSSetDeadKeysEnabled() turns dead key processing on or off for context.  If flag is 0, dead key processing is turned off; otherwise, it’s turned on (the default).

Dead key processing is a technique for extending the range of characters that can be entered from the keyboard.  In NEXTSTEP, it provides one way for users to enter accented characters.  For example, a user can type Alternate-e followed by the letter “e” to produce the letter “é”.  The first keyboard input, Alternate-e, seems to have no effect—it’s the “dead key”.  However, it signals Client Library routines that it and the following character should be analyzed as a pair.  If, within NEXTSTEP, the pair of characters has been associated with a third character, a keyboard event record representing the third character is placed in the application’s event queue, and the first two event records are discarded.  If there is no such association between the two characters, the two event records are added to the event queue.

See the NeXT User’s Reference manual for a listing of the keys that produce accent characters.

DPSSetEventFunc()

SUMMARY	Set the function that filters events

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	DPSEventFilterFunc DPSSetEventFunc(DPSContext context, DPSEventFilterFunc func)

DESCRIPTION	DPSSetEventFunc() establishes the function func as the function to be called when an event record is returned from the PostScript context context in the Window Server.  The registered function is called before the event record is put in the event queue.  If the registered function returns 0, the record is discarded.  If the registered function returns 1, the record is passed on for further processing.

Only event records coming from the Window Server are filtered by the registered function.  Records that you post to the event queue using DPSPostEvent() aren’t affected.

A DPSEventFilterFunc function takes the following form:

int *func(NXEvent *anEvent)

RETURN	DPSSetEventFunc() returns a pointer to the previously registered event function.  This lets you chain together the current and previous event functions.

SEE ALSO	DPSPostEvent()

DPSSetTracking()

SUMMARY	Coalesce mouse events

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	int DPSSetTracking(int flag)

DESCRIPTION	DPSSetTracking() turns mouse event-coalescing on or off for the current context.  If flag is 0, coalescing is turned off; otherwise, it’s turned on (the default).

Event coalescing is an optimization that’s useful when tracking the mouse.  When the mouse is moved, numerous events flow into the event queue.  To reduce the number of events awaiting removal by the application, adjacent mouse-moved events are replaced by the most recent event of the contiguous group.  The same is done for left and right mouse-dragged events, with the addition that a mouse-up event replaces mouse-dragged events that come before it in the queue.

RETURN	DPSSetTracking() returns the previous state of the event-coalescing switch.

DPSStartWaitCursorTimer()

SUMMARY	Initiate a count down for the wait cursor

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	void DPSStartWaitCursorTimer()

DESCRIPTION	DPSStartWaitCursorTimer() triggers the mechanism that displays a wait cursor when an application is busy and can’t respond to user input.  In most cases, wait cursor support is automatic:  You’ll only need to call this function if your application starts a time-consuming operation that’s not initiated by a user-generated event.

Client Library routines and the Window Server cooperate to display the wait cursor whenever more than a preset amount of time elapses between the time an application takes an event record from the event queue and the time the application is again ready to consume events.  However, when an application starts an operation that isn’t initiated by an event—such as one caused by receiving a Mach message or by processing data from a file (see DPSAddPort() and DPSAddFD())—the wait cursor mechanism is bypassed.  To ensure proper wait cursor behavior in these cases, call DPSStartWaitCursorTimer() before beginning the time-consuming operation.

SEE ALSO	DPSAddFD(), DPSAddPort(), setwaitcursorenabled

DPSSynchronizeContext()

SUMMARY	Synchronize a context with your application

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	int DPSSynchronizeContext(DPSContext context, int flag)

DESCRIPTION	DPSSynchronizeContext() causes DPSWaitContext() to be called after each pswrap function is called, thus synchronizing the PostScript context with your application.

DPSTraceContext(), DPSTraceEvents()

SUMMARY	Trace data and events

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	int DPSTraceContext(DPSContext context, int flag)

void DPSTraceEvents(DPSContext context, int flag)

DESCRIPTION	DPSTraceContext() and DPSTraceEvents() control the tracing of data and events between a PostScript execution context (or contexts) in the Window Server and an application process.

The first argument for both functions, context, specifies the context to be traced.  An application’s single context can be returned with DPSGetCurrentContext().  Applications having more than one execution context can use the constant DPS_ALLCONTEXTS to trace all contexts belonging to them.

The second argument, flag, determines whether tracing is enabled.

When data tracing is enabled (DPSTraceContext()), a copy of the PostScript code generated by an application and the values returned to it by the Window Server is sent to UNIX standard error.  Values returned to the application are marked by the prepended string:

% value returned ==>

When event tracing is enabled (DPSTraceEvents()), information about each event that the application receives is sent to UNIX standard error.  For example, for a left mouse-down event the listing might look like this:

Receiving: LMouseDown at: 343.0,69.0 time: 1271899

            flags: 0x0 win: 6 ctxt: 76128 data: 1111,1

The listing displays the fields of the event record:  type, location, time, flags, local window number, PostScript execution context, and data.  The contents of the data field listing depends on the event type; for instance, in the preceding example the event number and the click count were displayed.

For applications based on the Application Kit, there are two preferable methods for turning on data tracing:  You can use the NXShowPS command-line switch when you launch an application from Terminal.  Alternatively, when you run the application under GDB, you can use the showps and shownops commands to control tracing output.  Similarly, there are more convenient ways to turn on event tracing:  You can use the NXTraceEvents command-line switch when you launch an application from Terminal.  Alternatively, when you run the application under GDB, you can use the traceevents and tracenoevents commands to control event-tracing output.

Only one tracing context can be created for the supplied context.  If you attempt to create additional tracing contexts for a context that’s already being traced, no new context is created and DPSTraceContext() returns −1.

RETURN	DPSTraceContext() returns 0 if successful in creating a tracing context, or −1 if not.

NX_EVENTCODEMASK()

SUMMARY	Generate an event mask for an event type

DECLARED IN	dpsclient/event.h

SYNOPSIS	int NX_EVENTCODEMASK(int type)

DESCRIPTION	This handy utility macro returns an event mask that corresponds to the given (single) event type.


Contents

Classes

Functions

Protocols

Types and Constants


DPSTypes

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Defined Types

DPSContextRec

DECLARED IN	dpsclient/dpsfriends.h

SYNOPSIS	typedef struct _t_DPSContextRec {

char *priv;

DPSSpace space;

DPSProgramEncoding programEncoding;

DPSNameEncoding nameEncoding;

struct _t_DPSProcsRec const * procs;

void (*textProc)();

void (*errorProc)();

DPSResults resultTable;

unsigned int resultTableLength;

struct _t_DPSContextRec *chainParent, *chainChild;

DPSContextType type;

} DPSContextRec, *DPSContext;

DESCRIPTION	The DPSContextRec structure represents a Display PostScript context.

DPSContextType

DECLARED IN	dpsclient/dpsfriends.h

SYNOPSIS	typedef enum {

dps_machServer,

dps_fdServer,

dps_stream

} DPSContextType;

DESCRIPTION	These represent the context types supported by NeXT’s version of Display PostScript, as used in the type field of a DPSContextRec structure.

DPSErrorCode

DECLARED IN	dpsclient/dpsclient.h

SYNOPSIS	typedef enum _DPSErrorCode {

dps_err_ps = DPS_ERROR_BASE,

dps_err_nameTooLong,

dps_err_resultTagCheck,

dps_err_resultTypeCheck,

dps_err_invalidContext,

dps_err_select = DPS_NEXT_ERROR_BASE,

dps_err_connectionClosed,

dps_err_read,

dps_err_write,

dps_err_invalidFD,

dps_err_invalidTE,

dps_err_invalidPort,

dps_err_outOfMemory,

dps_err_cantConnect

} DPSErrorCode;

DESCRIPTION	Error codes passed to a DPSErrorProc() function.

DPSEventFilterFunc

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	typedef int (*DPSEventFilterFunc)(NXEvent *ev );

DESCRIPTION	Call-back function used to filter events.

DPSFDProc

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	typedef void (*DPSFDProc)( int fd, void *userData );

DESCRIPTION	Call-back function used when a file descriptor is registered through DPSAddFD().

DPSNumberFormat

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	typedef enum _DPSNumberFormat {

#ifdef _ _BIG_ENDIAN_ _

dps_float = 48,

dps_long = 0,

dps_short = 32

#else

dps_float = 48+128,

dps_long = 0+128,

dps_short = 32+128

} DPSNumberFormat;

DESCRIPTION	These constants are used by the DPSDoUserPath() function to describe the type of numbers that are being passed.

DPSPingProc

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	typedef void (*DPSPingProc)

(DPSContext ctxt,

void *userData);

DESCRIPTION	Call-back function used by DPSAsynchronousWaitContext().

DPSPortProc

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	typedef void (*DPSPortProc)

( msg_header_t *msg,

void *userData );

DESCRIPTION	Call-back function used when a port is registered through DPSAddPort().

DPSTimedEntry

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	typedef struct _ _DPSTimedEntry *DPSTimedEntry;

DESCRIPTION	The return type for DPSAddTimedEntry().

DPSTimedEntryProc

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	typedef void (*DPSTimedEntryProc)

(DPSTimedEntry timedEntry,

double now,

void *userData );

DESCRIPTION	Call-back function used when a timed entry is registered through DPSAddTimedEntry().

DPSUserPathAction

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	typedef enum _DPSUserPathAction {

dps_uappend,

dps_ufill,

dps_ueofill,

dps_ustroke,

dps_ustrokepath,

dps_inufill,

dps_inueofill,

dps_inustroke,

dps_def,

dps_put

} DPSUserPathAction;

DESCRIPTION	These constants are convenient representations of some of the PostScript operator indices, suitable for enrollment in the action array passed to DPSDoUserPath().

DPSUserPathOp

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	typedef enum _DPSUserPathOp {

dps_setbbox,

dps_moveto,

dps_rmoveto,

dps_lineto,

dps_rlineto,

dps_curveto,

dps_rcurveto,

dps_arc,

dps_arcn,

dps_arct,

dps_closepath,

dps_ucache

} DPSUserPathOp;

DESCRIPTION	These constants represent the PostScript operators that can be passed in DPSDoUserPath()’s operator array.

NXCoord

DECLARED IN	dpsclient/event.h

SYNOPSIS	typedef float NXCoord

DESCRIPTION	Used to represent a single coordinate in a Cartesian coordinate system.

NXEvent

DECLARED IN	dpsclient/event.h

SYNOPSIS	typedef struct _NXEvent {

int type;

NXPoint location;

long time;

int flags;

unsigned int window;

NXEventData data;

DPSContext ctxt;

} NXEvent, *NXEventPtr;

DESCRIPTION	Represents a single event; this structure is also known as the event record.  The fields are:

type	The type of event (see “Event Types,” below)

location	The event’s location in the base coordinate system of its window

time	The time of the event (in hardware-dependent units) since system startup

flags	Mouse-button and modifier-key flags (see “Event Flags,” below)

window	The window number of the window associated with the event

data	Additional type-specific data (see “NXEventData,” below)

ctxt	The PostScript context of the event

NXEventData

DECLARED IN	dpsclient/event.h

SYNOPSIS	typedef union {

struct {

short eventNum;

int click;

unsigned char pressure;

} mouse;

struct {

short repeat;

unsigned short charSet;

unsigned short charCode;

unsigned short keyCode;

short keyData;

} key;

struct {

short eventNum;

int trackingNum;

int userData;

} tracking;

struct {

short subtype;

union {

float F[2];

long L[2];

short S[4];

char C[8];

} misc;

} compound;

} NXEventData;

DESCRIPTION	This structure supplies type-specific information for an event.  It’s a union of four structures, where the type of the event determines which structure is pertinent:

•	mouse is used for mouse events.

•	key is used for keyboard events.

•	tracking is for tracking-rectangle events.

•	compound is for system-, kit-, and application-defined events.

NXPoint

DECLARED IN	dpsclient/event.h

SYNOPSIS	typedef struct _NXPoint {

NXCoord x;

NXCoord y;

} NXPoint;

DESCRIPTION	Represents a point in a Cartesian coordinate system.

NXSize

DECLARED IN	dpsclient/event.h

SYNOPSIS	typedef struct _NXSize {

NXCoord width;

NXCoord height;

} NXSize;

DESCRIPTION	Represents a two-dimensional size.

Symbolic Constants

All Contexts

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	DPS_ALLCONTEXTS

DESCRIPTION	This constant represents all extant contexts.

Alpha Constants

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	NX_DATA

NX_ONES

DESCRIPTION	These constants represent alpha values.

Character Set Values

DECLARED IN	dpsclient/event.h

SYNOPSIS	NX_ASCIISET

NX_SYMBOLSET

NX_DINGBATSSET

DESCRIPTION	These constants represent the values that may occur in the data.key.charSet field of an NXEvent structure.

Compositing Operations

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	NX_CLEAR

NX_COPY

NX_SOVER

NX_SIN

NX_SOUT

NX_SATOP

NX_DOVER

NX_DIN

NX_DOUT

NX_DATOP

NX_XOR

NX_PLUSD

NX_HIGHLIGHT

NX_PLUSL

DESCRIPTION	These represent the compositing operations used by PScomposite() and the NXImage class.

Error Code Bases

DECLARED IN	dpsclient/dpsclient.h

SYNOPSIS	DPS_ERROR_BASE

DPS_NEXT_ERROR_BASE

DESCRIPTION	These constants represent the lowest values for Display PostScript error codes.

Event Types

DECLARED IN	dpsclient/event.h

SYNOPSIS	Type	Meaning

NX_NULLEVENT	A non-event

NX_LMOUSEDOWN	Left mouse-down

NX_LMOUSEUP	Left mouse-up

NX_LMOUSEDRAGGED	left mouse-dragged

NX_MOUSEDOWN	Same as NX_LMOUSEDOWN

NX_MOUSEUP	Same as NX_LMOUSEUP

NX_MOUSEDRAGGED	Same as NX_LMOUSEDRAGGED

NX_RMOUSEDOWN	Right mouse-down

NX_RMOUSEUP	Right mouse-up

NX_RMOUSEDRAGGED	Right mouse-dragged

NX_MOUSEMOVED	Mouse-moved

NX_MOUSEENTERED	Mouse-entered

NX_MOUSEEXITED	Mouse-exited

NX_KEYDOWN	Key-down

NX_KEYUP	Key-up event

NX_FLAGSCHANGED	Flags-changed

NX_KITDEFINED	Application Kit-defined

NX_SYSDEFINED	System-defined

NX_APPDEFINED	Application-defined

NX_TIMER	Timer used for tracking

NX_CURSORUPDATE	Cursor tracking

NX_JOURNALEVENT	Event used by journaling

NX_FIRSTEVENT	The smallest-valued event constant

NX_LASTEVENT	The greatest-valued event constant

NX_ALLEVENTS	A value that includes all event types

DESCRIPTION	These constants represent event types.  They’re passed as the type field of the NXEvent structure that’s created when an event occurs.

Event Type Masks

DECLARED IN	dpsclient/event.h

SYNOPSIS	NX_NULLEVENTMASK

NX_LMOUSEDOWNMASK

NX_LMOUSEUPMASK

NX_RMOUSEDOWNMASK

NX_RMOUSEUPMASK

NX_MOUSEMOVEDMASK

NX_LMOUSEDRAGGEDMASK

NX_RMOUSEDRAGGEDMASK

NX_MOUSEENTEREDMASK

NX_MOUSEEXITEDMASK

NX_KEYDOWNMASK

NX_KEYUPMASK

NX_FLAGSCHANGEDMASK

NX_KITDEFINEDMASK

NX_APPDEFINEDMASK

NX_SYSDEFINEDMASK

NX_TIMERMASK

NX_CURSORUPDATEMASK

NX_MOUSEDOWNMASK

NX_MOUSEUPMASK

NX_MOUSEDRAGGEDMASK

NX_JOURNALEVENTMASK

DESCRIPTION	These masks correspond to the event types defined immediately above.  They let you query the type field of an NXEvent structure for the existence of a particular event type.

Forever

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	NX_FOREVER

DESCRIPTION	A long, long time.  Typically used as the timeout argument to DPSGetEvent().

Keyboard State Flags Masks

DECLARED IN	dpsclient/event.h

SYNOPSIS	Type	Meaning

NX_ALPHASHIFTMASK	Shift lock

NX_SHIFTMASK	Shift key

NX_CONTROLMASK	Control key

NX_ALTERNATEMASK	Alt key

NX_COMMANDMASK	Command key

NX_NUMERICPADMASK	Number pad key

NX_HELPMASK	Help key

NX_NEXTCTRLKEYMASK	Control key

NX_NEXTLSHIFTKEYMASK	Left shift key

NX_NEXTRSHIFTKEYMASK	Right shift key

NX_NEXTLCMDKEYMASK	Left command key

NX_NEXTRCMDKEYMASK	Right command key

NX_NEXTLALTKEYMASK	Left alt key

NX_NEXTRALTKEYMASK	Right alt key

DESCRIPTION	These masks correspond to keyboard states that might be included in an NXEvent structure’s flags mask.  The masks are grouped as device-independent (NX_ALPHASHIFTMASK through NX_HELPMASK) and device-dependent (all others).

Miscellaneous Event Flags Masks

DECLARED IN	dpsclient/event.h

SYNOPSIS	Type	Meaning

NX_STYLUSPROXIMITYMASK	Stylus is in proximity (for tablets)

NX_NONCOALSESCEDMASK	Event coalescing disabled

DESCRIPTION	These masks correspond to miscellaneous states that might be included in an NXEvent structure’s flags mask.

Window Backing Types

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	NX_RETAINED

NX_NONRETAINED

NX_BUFFERED

DESCRIPTION	These represent the three backing types provided by window devices (and used by the Application Kit’s Window objects).

Window Screen List Placement

DECLARED IN	dpsclient/dpsNeXT.h

SYNOPSIS	NX_ABOVE

NX_BELOW

NX_OUT

DESCRIPTION	These represent the placement of a window device in the screen list.


Functions

DPSClientLibraryFunctions

DPSSingleOpFunctions

PSOperators


NSActionCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSCell : NSObject

Conforms To:	NSCoding, NSCopying (NSCell)

NSObject (NSObject)

Declared In:	 AppKit/NSActionCell.h

Class Description

An NSActionCell defines an active area inside a control (an instance of NSControl or one of its subclasses). As an NSControl’s active area, an NSActionCell does three things: it usually performs display of text or an icon; it provides the NSControl with a target and an action; and it handles mouse (cursor) tracking by properly highlighting its area and sending action messages to its target based on cursor movement. The only way to specify the NSControl for a particular NSActionCell is to send the NSActionCell a drawWithFrame:inView: message, passing the NSControl as the argument for the inView: keyword of the method.

NSActionCell implements the target object and action method as defined by its superclass, NSCell. As a user manipulates an NSControl, NSActionCell’s trackMouse:inRect:ofView:untilMouseUp: method (inherited from NSCell) updates its appearance and sends the action message to the target object with the NSControl object as the only argument. See "Target and Action" below more more on this paradigm.

Usually, the responsibility for an NSControl’s appearance and behavior is completely given over to a corresponding NSActionCell. (NSMatrix, and its subclass NSForm, are NSControls that don’t follow this rule.)

A single NSControl may have more than one NSActionCell. To help identify it in this case, every NSActionCell has an integer tag. Note, however, that no checking is done by the NSActionCell object itself to ensure that the tag is unique. See the NSMatrix class for an example of a subclass of NSControl that contains multiple NSActionCells.

Many of the methods that define the contents and look of an NSActionCell, such as setFont: and setBordered:, are reimplementations of methods inherited from NSCell. They’re overriden to ensure that the NSActionCell is redisplayed when "visual" attributes change.

Target and Action

Target objects and action methods (or messages) are part of the mechanism by which NSControls respond to user actions and enable users to communicate their intentions to an application. A target is an object that an NSControl uses as the receiver of action messages. The target’s class defines an action method to enable its instances to respond to these messages, which are sent as users click or otherwise manipulate the NSControl. NSControl’s sendAction:to: asks the NSApplication object, NSApp, to send an action message to the NSControl’s target object.

An action method takes only one argument: the id of the sender. The sender may be either the NSControl that sends the action message or, on occassion, another object that the target should treat as the sender. When it receives an action message, a target can return messages to the sender requesting additional information about its status.

You can also set the target to nil and allow it to be determined at run time. When the target is nil, the NSApplication object must look for an appropriate receiver. It conducts its search in a prescribed order, by following the responder chain until it finds an object that can respond to the message:

•	It begins with the first responder in the key window and follows nextResponder links up the responder chain to the NSWindow’s content view.

•	It tries the NSWindow object and then the NSWindow’s delegate.

•	If the main window is different from the key window, it then starts over with the first responder in the main window and works its way up the main window’s responder chain to the NSWindow object and its delegate.

•	Next, the NSApplication object tries to respond itself. If it can’t respond, it tries its own delegate. NSApp and its delegate are the receivers of last resort.

NSControl provides methods for setting and using the target object and the action method. However, these methods require that an NSControl’s cell (or cells) be NSActionCells or custom cells that hold action and target as instance variables and can respond to the NSControl methods.

Method Types

 Configuring an NSActionCell	− setAlignment:

− setBezeled:

− setBordered:

− setEnabled:

− setFloatingPointFormat:left:right:

− setFont:

− setImage:

Obtaining and setting cell values	− doubleValue

− floatValue

− intValue

− stringValue

− setStringValue:

− setObjectValue:

Displaying the NSActionCell	− drawWithFrame:inView:

− controlView

Assigning target and action	− setAction:

− action

− setTarget:

− target

Assigning a tag	− setTag:

− tag

Instance Methods

action

− (SEL)action

Returns the NSActionCell’s action-message selector.

See also:	− setAction:, − setTarget:, − target

controlView

− (NSView *)controlView

Returns the view (normally an NSControl) in which the NSActionCell was last drawn or nil if the NSActionCell has no control view (as might occur if the control view hasn’t yet been placed in the view hierarchy).

See also:	− drawWithFrame:inView:

doubleValue

− (double)doubleValue

Returns the NSActionCell’s value as a double after validating any editing of cell content. If the receiver is not a text-type cell or the cell value is not scannable, the method returns zero.

See also:	− validateEditing (NSControl)

drawWithFrame:inView:

− (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView

Draws the NSActionCell's regular or bezeled border (if those attributes are set) and then draws the interior of the cell. NSActionCell’s method overrides this method to replace its controlling control with controlView (if they’re different) before invoking NSCell’s drawWithFrame:inView:.

See also:	− controlView

floatValue

− (float)floatValue

Returns the NSActionCell’s value as a float after validating any editing of cell content. If the receiver is not a text-type cell or the cell value is not scannable, the method returns zero.

See also:	− validateEditing (NSControl)

intValue

− (int)intValue

Returns the NSActionCell’s value as a int after validating any editing of cell content. If the receiver is not a text-type cell or the cell value is not scannable, the method returns zero.

See also:	− validateEditing (NSControl)

setAction:

− (void)setAction:(SEL)aSelector

Sets the selector used for the action message to aSelector.

See also:	− action, − setTarget:, − target

setAlignment:

− (void)setAlignment:(NSTextAlignment)mode

Sets the alignment of text in the receiving NSActionCell;  mode is one of five constants: NSLeftTextAlignment, NSRightTextAlignment, NSCenterTextAlignment, NSJustifiedTextAlignment, NSNaturalTextAlignment (the default alignment for the text). The method marks the receiving NSActionCell as needing redisplay after discarding any editing changes that were being made to cell text.

See also:	− alignment (NSCell)

setBezeled:

− (void)setBezeled:(BOOL)flag

Sets whether the NSActionCell draws itself with a bezeled border and marks it as needing redisplay. The setBezeled: and setBordered: methods are mutually exclusive (that is, a border can be only plain or bezeled).

See also:	− isBezeled (NSCell)

setBordered:

− (void)setBordered:(BOOL)flag

Sets whether the receiver draws itself outlined with a plain border and marks it as needing redisplay. The setBezeled: and setBordered: methods are mutually exclusive (that is, a border can be only plain or bezeled).

See also:	− isBordered (NSCell)

setEnabled:

− (void)setEnabled:(BOOL)flag

Sets whether the receiver is enabled or disabled. The text of disabled cells is changed to gray. If a cell is disabled, it cannot be highlighted, does not support mouse tracking (and thus cannot participate in target/action functionality), and cannot be edited. The method marks the receiving NSActionCell as needing redisplay after discarding any editing changes that were being made to cell text.

See also:	− isEnabled (NSCell)

setFloatingPointFormat:left:right:

− (void)setFloatingPointFormat:(BOOL)autoRange

left:(unsigned int)leftDigits

right:(unsigned int)rightDigits

Sets the NSActionCell’s floating point format as described in the NSCell class specification for the setFloatingPointFormat:left:right: method. NSActionCell’s implementation of the method supplements NSCell’s by marking the receiving NSActionCell as needing redisplay after discarding any editing changes that were being made to cell text.

setFont:

− (void)setFont:(NSFont *)fontObj

Sets the font to be used when the NSActionCell displays text. If the receiver is not a text-type cell, the method converts it to that type. If fontObj is nil and the receiver is a text-type cell, the font currently held by the receiver is autoreleased. NSActionCell supplements NSCell’s implementation of this method by marking the updated cell as needing redisplay; if the receiving NSActionCell was converted to a text-type cell and is selected, it also updates the field editor with fontObj.

See also:	− font (NSCell)

setImage:

− (void)setImage:(NSImage *)image

Sets the font to be used when the NSActionCell displays text. If the receiver is not a text-type cell, the method converts it to that type. If fontObj is nil and the receiver is a text-type cell, the font currently held by the receiver is autoreleased. NSActionCell supplements NSCell’s implementation of this method by marking the updated cell as needing redisplay.

See also:	− image (NSCell)

p	setObjectValue:

− (void)setObjectValue:(id)object

Discards any editing of the receiving NSActionCell’s text and sets its object value to object. If the object value is afterwards different from what it was before the method was invoked, the method marks the NSActionCell as needing redisplay.

See also:	− objectValue (NSCell)

setStringValue:

− (void)setStringValue:(NSString *)aString

Discards any editing of the receiving NSActionCell’s text and sets its string value to aString. If the object value is afterwards different from what it was before the method was invoked, the method marks the NSActionCell as needing redisplay.

See also:	− stringValue (NSCell)

setTag:

− (void)setTag:(int)anInt

Sets the receiving NSActionCell’s tag to anInt.

See also:	− tag

setTarget:

− (void)setTarget:(id)anObject

Sets the receiving NSActionCell’s target object to anObject.

See also:	− action, − setAction:, − target

stringValue

− (NSString *)stringValue

Returns the receiving NSActionCell’s value as a string object as converted by the cell’s formatter, if one exists. If no formatter exists and the value is an NSString, returns the value as an plain, attributed or localized formatted string. If the value is not an NSString or can’t be converted to one, returns an empty string. The method supplements NSCell’s implementation by validating and retaining any editing changes being made to cell text.

See also:	− validateEditing (NSControl)

tag

− (int)tag

Returns the receiving NSActionCell’s tag.

See also:	− setTag:

target

− (id)target

Returns the receiving NSActionCell’s target object.

See also:	− action, − setAction:, − setTarget:


NSApplication

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSApplication.h

AppKit/NSColorPanel.h

AppKit/NSDataLinkPanel.h

AppKit/NSHelpManager.h

AppKit/NSPageLayout.h

Purpose

An NSApplication object manages an application’s main event loop in addition to resources used by all of that application’s objects.

Principal Attributes

•	Delegate	•	List of windows

•	Key window	•	Main window

•	DPS context

Creation

Project Builder

+ sharedApplication	Creates the shared application instance

(global variable NSApp).

Commonly Used Methods

− keyWindow	Returns an NSWindow representing the

key window.

− mainWindow	Returns an NSWindow representing the

main window.

− registerServicesMenuSendTypes:returnTypes:	Specifies which services are valid for this

application.

− runModalForWindow:	Runs a modal event loop for the specified

NSWindow.

Class Description

The NSApplication class provides the central framework for your application’s execution. Every application must have exactly one instance of NSApplication (or a subclass of NSApplication). Your program’s main() function should create this instance by invoking the sharedApplication class method. After creating the NSApplication object, the main() function should load your application’s main nib file and then start the event loop by sending the NSApplication object a run message. If you create an Application project in Project Builder, this main() function is created for you. The main() function that Project Builder creates begins by calling a function named NSApplicationMain(), which is functionally similar to the following:

void NSApplicationMain(int argc, char *argv[]) {

[NSApplication sharedApplication];

[NSBundle loadNibNamed:@"myMain" owner:app];

[NSApp run];

}

The sharedApplication class method initializes the PostScript environment and connects your program to the Window Server and the Display PostScript server. The NSApplication object maintains a list of all the NSWindows that the application uses, so it can retrieve any of the application’s NSViews. sharedApplication also initializes the global variable NSApp, which you use to retrieve the NSApplication instance. sharedApplication only performs the initialization once; if you invoke it more than once, it simply returns the NSApplication object that it created previously.

NSApplication’s main purpose is to receive events from the Window Server and distribute them to the proper NSResponders. NSApp translates an event into an NSEvent object, then forwards the NSEvent to the affected NSWindow object. All keyboard and mouse events go directly to the NSWindow associated with the event. The only exception to this rule is if the Command key is pressed when a key-down event occurs; in this case, every NSWindow has an opportunity to respond to the event. When an NSWindow receives an NSEvent from NSApp, it distributes it to the objects in its view hierarchy.

The NSApplication class sets up autorelease pools (instances of the NSAutoreleasePool class) during initialization and inside the event loop—specifically, within its init (or sharedApplication) and run methods. Similarly, the methods that the Application Kit adds to NSBundle employ autorelease pools during the loading of nib files. These autorelease pools aren’t accessible outside the scope of the respective NSApplication and NSBundle methods. Typically, an application creates objects either while the event loop is running or by loading objects from nib files, so this usually isn’t a problem. However, if you do need to use OpenStep classes within the main() function itself (other than to load nib files or to instantiate NSApplication), you should create an autorelease pool before using the classes and then release the pool when you’re done. For more information, see the NSAutoreleasePool class specification in the Foundation Framework Reference.

Subclassing NSApplication

Rarely do you need to create a custom NSApplication subclass. In general, a better design is to separate the code that embodies your program’s functionality into a number of custom objects. Usually, those custom objects are subclasses of NSObject. Methods defined in your custom objects can be invoked from a small dispatcher object without being closely tied to NSApp. The only reason to subclass NSApplication is if you need to provide your own special response to messages that are routinely sent to NSApp. (Even then, NSApp’s delegate is often given a chance to respond to such messages, so it’s more appropriate to implement the delegate methods.) To use a custom subclass of NSApplication, simply send sharedApplication to your custom class rather than directly to NSApplication. If you create your application in Project Builder, set the application class on the Project Attributes inspector, and Project Builder will update the main() function accordingly. As mentioned previously, NSApp uses autorelease pools in its init and run methods; if you override these methods, you’ll need to create your own autorelease pools.

The Delegate and Notifications

You can assign a delegate to NSApp. The delegate responds to certain messages on behalf of NSApp. Some of these messages, such as application:openFile:, ask the delegate to open a file. Another message, applicationShouldTerminate:, lets the delegate determine whether the application should be allowed to quit. The NSApplication class sends these messages directly to its delegate.

NSApp also posts notifications to the application’s default notification center. Any object may register to receive one or more of the notifications posted by NSApp by sending the message addObserver:selector:name:object: to the default notification center (an instance of the NSNotificationCenter class). NSApp’s delegate is automatically registered to receive these notifications if it implements certain delegate methods. For example, NSApp posts notifications when it is about to be done launching the application and when it is done launching the application (NSApplicationWillFinishLaunchingNotification and NSApplicationDidFinishLaunchingNotification). The delegate has an opportunity to respond to these notifications by implementing the methods applicationWillFinishLaunching: and applicationDidFinishLaunching:. If the delegate wants to be informed of both events, it implements both methods. If it only needs to know when the application is finished launching, it implements only applicationDidFinishLaunching:. For more information on notifications, see the NSNotificationCenter class specification in the Foundation Framework Reference.

Method Types

Creating and initializing an NSApplication

+ sharedApplication

− finishLaunching

Changing the active application	− activateIgnoringOtherApps:

− isActive

− deactivate

Running the event loop	− run

− isRunning

− stop:

− runModalForWindow:

− stopModal

− stopModalWithCode:

− abortModal

− beginModalSessionForWindow:

− runModalSession:

− endModalSession:

− sendEvent:

Getting, removing, and posting events

− currentEvent

− nextEventMatchingMask:untilDate:inMode:dequeue:

− discardEventsMatchingMask:beforeEvent:

− postEvent:atStart:

Managing windows	− keyWindow

− mainWindow

− windowWithWindowNumber:

− windows

− makeWindowsPerform:inOrder:

− setWindowsNeedUpdate:

− updateWindows

− miniaturizeAll:

− preventWindowOrdering

Hiding all windows	− hide:

− isHidden

− unhide:

− unhideWithoutActivation

Setting the application’s icon	− setApplicationIconImage:

− applicationIconImage

Getting the main menu	− setMainMenu:

− mainMenu

Managing the Window menu	− setWindowsMenu:

− windowsMenu

− arrangeInFront:

− addWindowsItem:title:filename:

− changeWindowsItem:title:filename:

− removeWindowsItem:

− updateWindowsItem:

Managing the Services menu	− setServicesMenu:

− servicesMenu

− registerServicesMenuSendTypes:returnTypes:

− validRequestorForSendType:returnType:

− setServicesProvider:

− servicesProvider:

Showing standard panels	− orderFrontColorPanel:

− orderFrontDataLinkPanel:

− runPageLayout:

Displaying help	− showHelp:

− activateContextHelpMode:

Sending action messages	− sendAction:to:from:

− tryToPerform:with:

− targetForAction:

Getting the Display PostScript context

− context

Reporting an exception	− reportException:

Terminating the application	− terminate:

Assigning a delegate	− setDelegate:

− delegate

Microsoft Windows®specific methods

− applicationHandle

− windowWithWindowHandle:

+ setApplicationHandle:previousHandle:commandLine:show:

+ useRunningCopyOfApplication

Class Methods

p	setApplicationHandle:previousHandle:commandLine:show:

+ (void)setApplicationHandle:(void *)hInstance

previousHandle:(void *)prevInstance

commandLine:(NSString *)cmdLine

show:(int)cmdShow

On Microsoft Windows platforms, informs the NSApplication class of the values for the arguments passed to the WinMain() function. This message should be sent once, as the first line of the WinMain() function. If you create your application using Project Builder, this is done for you. You only need to invoke this method if you implement your own WinMain() function. Don’t override this method in NSApplication subclasses.

This method is not implemented on the Mach platform.

See also:	− applicationHandle

sharedApplication

+ (NSApplication *)sharedApplication

Returns the NSApplication instance (the global NSApp), creating it if it doesn’t exist yet. This method also makes a connection to the Window Server and completes other initialization. Your program should invoke this method as one of the first statements in main(); this is done for you if you create your application with Project Builder. To retrieve the NSApplication instance after it has been created, you use the global variable NSApp or invoke this method.

See also:	− run, − terminate:

p	useRunningCopyOfApplication

+ (void)useRunningCopyOfApplication

On Microsoft Windows platforms, attempts to find an already running copy of the application at startup. This method is invoked in the WinMain() function. If the command used to start the application contains the option -NSUseRunningCopy YES and the application is already running, this method causes that version of the application to be activated rather than start up a new copy.

The method returns if the -NSUseRunningCopy YES option was not specified, if there was no previously running copy, or if the running copy was unable to be used (for any reason).  If a running copy is successfully found and used, this method exits with a code of 0.

You never need to invoke this method directly. If you need to prevent the system from using an already running copy of the application, write your own WinMain() function, removing this method invocation. NSApplication subclasses should not override this method.

This method is not defined for the Mach platform.

Instance Methods

abortModal

− (void)abortModal

Aborts the event loop started by runModalForWindow: by raising an NSAbortModalException, which is caught by runModalForWindow:. Because this method raises an exception, it never returns; runModalForWindow:, when stopped with this method, returns NSRunAbortedResponse. abortModal is typically sent by objects registered with the default NSRunLoop; for example, by objects that have registered a method to be repeatedly invoked by the NSRunLoop through the use of an NSTimer object.

This method can also abort a modal session created by beginModalSessionForWindow:, provided the loop that runs the modal session (by invoking runModalSession:) catches NSAbortModalException.

See also:	− endModalSession:, − stopModal, − stopModalWithCode:

p	activateContextHelpMode:

− (void)activateContextHelpMode:(id)sender

Places the application in context-sensitive help mode. In this mode, the cursor becomes a question mark, and help appears for any user interface item that the user clicks. This method is typically invoked on Microsoft Windows platforms when the user selects the What’s This menu item. (An application also enters context-sensitive help mode on Microsoft Windows platforms when the user presses Shift-F1.)

On Mach platforms, most applications don’t use this method. Instead, applications enter context-sensitive mode when the user presses the Help key. On either platform, applications exit context-sensitive help mode upon the first event after a help window is displayed.

See also:	− showHelp:

activateIgnoringOtherApps:

− (void)activateIgnoringOtherApps:(BOOL)flag

Makes the receiver the active application. If flag is NO, the application is activated only if no other application is currently active. If flag is YES, the application activates regardless.

On Mach platforms, flag is normally set to NO. When the Workspace Manager launches an application, using a value of NO for flag allows the application to become active if the user waits for it to launch, but the application remains unobtrusive if the user activates another application. Regardless of the setting of flag, there may be a time lag before the application activates; you should not assume that the application will be active immediately after sending this message.

On Microsoft Windows platforms, flag is normally set to YES. Setting flag to NO has no effect.

You rarely need to invoke this method. Under most circumstances, the Application Kit takes care of proper activation. However, you might find this method useful if you implement your own methods for interapplication communication.

You don’t need to send this message to make one of the application’s NSWindows key. When you send a makeKeyWindow message to an NSWindow, you simply ensure that the NSWindow will be the key window when the application is active.

See also:	− deactivate, − isActive

addWindowsItem:title:filename:

− (void)addWindowsItem:(NSWindow *)aWindow

title:(NSString *)aString

filename:(BOOL)isFilename

Adds an item to the Window menu for aWindow. If isFilename is NO, aString appears literally in the menu. If isFilename is YES, aString is assumed to be a converted path name with the name of the file preceding the path (the way NSWindow’s setTitleWithRepresentedFilename: method shows a title). If an item for aWindow already exists in the Window menu, this method has no effect. You rarely invoke this method because an item is placed in the Window menu for you whenever an NSWindow’s title is set.

See also:	− changeWindowsItem:title:filename:, − setTitle: (NSWindow),

− setTitleWithRepresentedFilename: (NSWindow)

p	applicationHandle

- (void *)applicationHandle

On Microsoft Windows platforms, returns the application’s Win32 instance handle, which is a required parameter for some Win32 function calls. This method is not defined for the Mach platform.

See also:	+ setApplicationHandle:previousHandle:commandLine:show:

applicationIconImage

− (NSImage *)applicationIconImage

Returns the NSImage used for the application’s icon, which represents the application in the Workspace Manager on Mach platforms or in the Program Manager on Microsoft Windows platforms.

See also:	− setApplicationIconImage:

arrangeInFront:

− (void)arrangeInFront:(id)sender

Arranges all of the windows listed in the Window menu in front of all other windows. Windows associated with the application but not listed in the Window menu are not ordered to the front.

See also:	− addWindowItem:title:filename:, − removeWindowsItem:,

− makeKeyAndOrderFront: (NSWindow)

beginModalSessionForWindow:

− (NSModalSession)beginModalSessionForWindow:(NSWindow *)aWindow

Sets up a modal session with the NSWindow aWindow and returns an NSModalSession structure representing the session. In a modal session, the application receives mouse events only if they occur in aWindow. The NSWindow is made key and ordered to the front.

beginModalSessionForWindow: only sets up the modal session. To actually run the session, use runModalSession:. beginModalSessionForWindow: should be balanced by endModalSession:. If an exception is raised, beginModalSessionForWindow: arranges for proper cleanup. Do not use NS_DURING constructs to send an endModalSession: message in the event of an exception.

A loop using these methods is similar to a modal event loop run with runModalForWindow:, except that the application can continue processing between method invocations.

changeWindowsItem:title:filename:

− (void)changeWindowsItem:(NSWindow *)aWindow title:(NSString *)aString filename:(BOOL)isFilename

Changes the item for aWindow in the Window menu to aString. If aWindow doesn’t have an item in the Window menu, this method adds the item. If isFilename is NO, aString appears literally in the menu. If isFilename is YES, aString is assumed to be a converted path name with the file’s name preceding the path (the way NSWindow’s setTitleWithRepresentedFilename: places a title).

See also:	 − addWindowsItem:title:filename:, − removeWindowsItem:, − setTitle: (NSWindow), − setTitleWithRepresentedFilename: (NSWindow)

context

− (NSDPSContext *)context

Returns the receiver’s Display PostScript context.

currentEvent

− (NSEvent *)currentEvent

Returns the current event, the last event the receiver retrieved from the event queue. NSApp receives events and forwards the current event to the affected NSWindow object, which then distributes it to the objects in its view hierarchy.

See also:	− discardEventsMatchingMask:beforeEvent:, − postEvent:atStart:, − sendEvent:

deactivate

− (void)deactivate

Deactivates the application. Normally, you shouldn’t invoke this method; the Application Kit is responsible for proper deactivation.

See also:	− activateIgnoringOtherApps:

delegate

− (id)delegate

Returns the receiver’s delegate.

See also:	− setDelegate:

discardEventsMatchingMask:beforeEvent:

− (void)discardEventsMatchingMask:(unsigned int)mask beforeEvent:(NSEvent *)lastEvent

Removes from the event queue all events matching those specified in mask that were generated before lastEvent. Typically, you send this message to an NSWindow rather than to NSApp.

mask can contain these constants:

NSLeftMouseDownMask	The left mouse button was pressed.

NSLeftMouseUpMask	The left mouse button was released.

NSRightMouseDownMask	The right mouse button was pressed.

NSRightMouseUpMask	The right mouse button was released.

NSMouseMovedMask	The user moved the mouse.

NSLeftMouseDraggedMask	The user moved the mouse while the left button was pressed.

NSRightMouseDraggedMask	The user moved the mouse while the right button was pressed.

NSMouseEnteredMask	The mouse entered a tracking rectangle.

NSMouseExitedMask	The mouse exited a tracking rectangle.

NSKeyDownMask	A key on the keyboard was pressed.

NSKeyUpMask	A key on the keyboard was released.

NSFlagsChangedMask	A Shift, Command, Alternate, or Escape key was pressed or

released.

NSPeriodicMask	A periodic event occurred.

NSCursorUpdateMask	Cursor update.

NSAnyEventMask	Any event.

Use this method to ignore certain events that occurred after a particular event. For example, suppose your application has a tracking loop that you exit when the user releases the mouse button, and you want to discard all of the events that occurred during that loop. You use NSAnyEvent as the mask argument and pass the mouse up event as the lastEvent argument. Passing the mouse-up event as lastEvent ensures that any events that might have occurred after the mouse-up event (that is, that appear in the queue after the mouse-up event) don’t get discarded.

See also:	− nextEventMatchingMask:untilDate:inMode:dequeue:

encodeWithCoder:

@protocol NSCoding

− (void)encodeWithCoder:(NSCoder *)aCoder

Raises an NSInvalidArgumentException. You cannot encode an NSApplication instance.

See also:	− initWithCoder:

endModalSession:

− (void)endModalSession:(NSModalSession)session

Finishes a modal session. The argument session should be the return value from a previous invocation of beginModalSessionForWindow:.

See also:	− runModalSession:

finishLaunching

− (void)finishLaunching

Activates the application, opens any files specified by the “NSOpen” user default, and unhighlights the application’s icon. The run method invokes this method before it starts the event loop. When this method begins, it posts an NSApplicationWillFinishLaunchingNotification to the default notification center. When it successfully completes, it posts an NSApplicationDidFinishLaunchingNotification. If you override finishLaunching, the subclass method should invoke the superclass method.

See also:	− applicationWillFinishLaunching: (delegate method),

− applicationDidFinishLaunching: (delegate method)

hide:

− (void)hide:(id)sender

Hides all the application’s windows. This method is usually invoked when the user chooses Hide in the application’s main menu. When this method begins, it posts an NSApplicationWillHideNotification to the default notification center. When it completes successfully, it posts an NSApplicationDidHideNotification.

See also:	− applicationDidHide: (delegate method), − applicationWillHide: (delegate method),

− miniaturizeAll:, − unhide:, − unhideWithoutActivation

initWithCoder:

@protocol NSCoding

− (id)initWithCoder:(NSCoder *)aDecoder

Raises an NSInvalidArgumentException. You cannot encode an NSApplication instance.

See also:	− encodeWithCoder:

isActive

− (BOOL)isActive

Returns YES if this is the active application, NO otherwise.

See also:	− activateIgnoringOtherApps:, − deactivate

isHidden

− (BOOL)isHidden

Returns YES if the application is hidden, NO otherwise.

See also:	− hide:, − unhide:, − unhideWithoutActivation

isRunning

− (BOOL)isRunning

Returns YES if the main event loop is running, NO otherwise. NO means the stop: method was invoked.

See also:	− run, − terminate:

keyWindow

− (NSWindow *)keyWindow

Returns the key window, the NSWindow that receives keyboard events. If there is no key window or if the key window belongs to another application, this method returns nil.

See also:	− mainWindow, − isKeyWindow (NSWindow)

mainMenu

− (NSMenu *)mainMenu

Returns the application’s main menu.

See also:	− setMainMenu:

mainWindow

− (NSWindow *)mainWindow

Returns the main window. If there is no main window, if the main window belongs to another application, or if the application is hidden, this method returns nil.

See also:	− keyWindow, − isMainWindow (NSWindow)

makeWindowsPerform:inOrder:

− (NSWindow *)makeWindowsPerform:(SEL)aSelector inOrder:(BOOL)flag

Sends the aSelector message to each NSWindow in the application in turn until one of them returns a value other than nil. Returns that NSWindow, or nil if all of the NSWindows returned nil for

aSelector.

If flag is YES, the NSWindows receive the aSelector message in the front-to-back order in which they appear in the Window Server’s window list. If flag is NO, NSWindows receive the message in the order they appear in NSApp’s window list. This order is unspecified.

The method designated by aSelector can’t take any arguments.

See also:	− sendAction:to:from:, − tryToPerform:with:, − windows

miniaturizeAll:

− (void)miniaturizeAll:(id)sender

Miniaturizes all the receiver’s windows.

See also:	− hide:

nextEventMatchingMask:untilDate:inMode:dequeue:

− (NSEvent *)nextEventMatchingMask:(unsigned int)mask

untilDate:(NSDate *)expiration

inMode:(NSString *)mode

dequeue:(BOOL)flag

Returns the next event matching mask, or nil if no such event is found before the expiration date. If flag is YES, the event is removed from the queue. See the method description for discardEventsMatchingMask:beforeEvent: for a list of the possible values for mask.

The mode argument names an NSRunLoop mode that determines what other ports are listened to and what timers may fire while NSApp is waiting for the event. The possible modes available in the Application Kit are:

NSDefaultRunLoopMode	Main event loop.

NSEventTrackingRunLoopMode	Modal event loops.

NSModalPanelRunLoopMode	Loops that operate while a modal panel is up.

NSConnectionReplyMode	Loops that operate while NSConnection is waiting for reply.

Events that are skipped are left in the queue.

You can use this method to short circuit normal event dispatching and get your own events. For example, you may want to do this in response to a mouse-down event in order to track the mouse while it’s down. In this case, you would set mask to accept mouse-dragged or mouse-up events and use the NSEventTrackingRunLoopMode.

See also:	− postEvent:atStart:, − run, − runModalForWindow:

orderFrontColorPanel:

− (void)orderFrontColorPanel:(id)sender

Brings up the color panel, an instance of NSColorPanel. If the NSColorPanel does not exist yet, it creates one. This method is typically invoked when the user chooses Colors from a menu.

orderFrontDataLinkPanel:

− (void)orderFrontDataLinkPanel:(id)sender

Brings up the data link panel, an instance of NSDataLinkPanel. If the NSDataLinkPanel does not exist yet, it creates one. This method is typically invoked when the user chooses an appropriate command from the application’s menu. For example, the Edit application invokes this method when the user chooses Link Inspector from the Link menu.

postEvent:atStart:

− (void)postEvent:(NSEvent *)anEvent atStart:(BOOL)flag

Adds anEvent to the application’s event queue. If flag is YES, the event is added to the front of the queue, otherwise the event is added to the back of the queue.

See also:	− currentEvent, − sendEvent:

preventWindowOrdering

− (void)preventWindowOrdering

Suppresses the usual window ordering in handling the most recent mouse-down event. This method is only useful for mouse-down events when you want to prevent the window that receives the event from being ordered to the front.

registerServicesMenuSendTypes:returnTypes:

− (void)registerServicesMenuSendTypes:(NSArray *)sendTypes returnTypes:(NSArray *)returnTypes

Registers the pasteboard types that the application can send and receive in response to service requests. If the application has a Services menu, a menu item is added for each service provider that can accept one of the specified sendTypes or return one of the specified returnTypes. You should typically invoke this method at application start-up time or when an object that can use services is created. You can invoke it more than once; its purpose is to ensure that there is a menu item for every service that the application may use. The event-handling mechanism will dynamically enable the individual items to indicate which services are currently appropriate. All of the NSResponders in your application (typically NSViews) should register every possible type that they can send and receive by sending this message to NSApp.

See also:	− validRequestorForSendType:returnType:, − readSelectionFromPasteboard: (NSServicesRequests protocol), − writeSelectionToPasteboard:types: (NSServicesRequests protocol)

removeWindowsItem:

− (void)removeWindowsItem:(NSWindow *)aWindow

Removes the Window menu item for aWindow. This method doesn’t prevent the item from being automatically added again. Use NSWindow’s setExcludedFromWindowsMenu: method if you want the item to remain excluded from the Window menu.

See also:	− addWindowsItem:title:filename:, − changeWindowsItem:title:filename:

reportException:

− (void)reportException:(NSException *)anException

Logs anException by calling NSLog(). This method does not raise the exception. Use it inside of an exception handler to record that the exception occurred.

run

− (void)run

Starts the main event loop. The loop continues until a stop: or terminate: message is received. Upon each iteration through the loop, the next available event from the Window Server is stored and is then dispatched by sending the event to NSApp using sendEvent:.

Send a run message as the last statement from main(), after the application’s objects have been initialized.

See also:	− applicationDidFinishLaunching: (delegate method), − runModalForWindow:,

− runModalSession:

runModalForWindow:

− (int)runModalForWindow:(NSWindow *)aWindow

Starts a modal event loop for aWindow. Until the loop is broken by a stopModal, stopModalWithCode:, or abortModal message, the application won’t respond to any mouse, keyboard, or window-close events unless they’re associated with aWindow. If stopModalWithCode: is used to stop the modal event loop, this method returns the argument passed to stopModalWithCode:. If stopModal is used, it returns the constant NSRunStoppedResponse. If abortModal is used, it returns the constant NSRunAbortedResponse. This method is functionally similar to the following:

NSModalSession session = [NSApp beginModalSessionforWindow:theWindow];

for (;;) {

 if ([NSApp runModalSession:session] != NSRunContinuesResponse)

  break;

}

[NSApp endModalSession:session];

See also:	− run, − runModalSession:

runModalSession:

− (int)runModalSession:(NSModalSession)session

Runs a modal session represented by session, as defined in a previous invocation of beginModalSessionForWindow:. A loop using this method is similar to a modal event loop run with runModalForWindow:, except that with this method the application can continue processing between method invocations. When you invoke this method, events for the NSWindow of this session are dispatched as normal; this method returns when there are no more events. You must invoke this method frequently enough that the window remains responsive to events.

If the modal session was not stopped, this method returns NSRunContinuesResponse. If stopModal was invoked as the result of event processing, NSRunStoppedResponse is returned. If stopModalWithCode: was invoked, this method returns the value passed to stopModalWithCode:. The NSAbortModalException raised by abortModal isn’t caught, so abortModal will not stop the loop.

See also:	− endModalSession, − run

runPageLayout:

− (void)runPageLayout:(id)sender

Displays the application’s page layout panel, an instance of NSPageLayout. If the NSPageLayout instance does not exist, it creates one. This method is typically invoked when the user selects Page Layout from the application’s menu.

sendAction:to:from:

− (BOOL)sendAction:(SEL)anAction to:(id)aTarget from:(id)sender

Sends the message anAction to aTarget. If aTarget is nil, NSApp looks for an object that can respond to the message—that is, an object that implements a method matching anAction. It begins with the first responder of the key window. If the first responder can’t respond, it tries the first responder’s next responder and continues following next responder links up the responder chain. If none of the objects in the key window’s responder chain can handle the message, NSApp attempts to send the message to the key window’s delegate.

If the delegate doesn’t respond and the main window is different from the key window, NSApp begins again with the first responder in the main window. If objects in the main window can’t respond, NSApp attempts to send the message to the main window’s delegate. If still no object has responded, NSApp tries to handle the message itself. If NSApp can’t respond, it attempts to send the message to its own delegate.

Returns YES if the action is successfully sent; otherwise returns NO.

See also:	− targetForAction:, − tryToPerform:with:, − makeWindowsPerform:inOrder:

sendEvent:

− (void)sendEvent:(NSEvent *)anEvent

Dispatches anEvent to other objects. You rarely invoke sendEvent: directly although you might want to override this method to perform some action on every event. sendEvent: messages are sent from the main event loop (the run method). sendEvent: is the method that dispatches events to the appropriate responders; NSApp handles application events, the NSWindow indicated in the event record handles window related events, and mouse and key events are forwarded to the appropriate NSWindow for further dispatching.

See also:	− currentEvent, − postEvent:atStart:

servicesMenu

− (NSMenu *)servicesMenu

Returns the Services menu or nil if no Services menu has been created.

See also:	− setServicesMenu:

servicesProvider

− (NSMenu *)servicesProvider

Returns the object that provides the services that this application advertises in the Services menu of other applications.

See also:	− setServicesProvider:

setApplicationIconImage:

− (void)setApplicationIconImage:(NSImage *)anImage

Sets the application’s icon to anImage.

See also:	− applicationIconImage

setDelegate:

− (void)setDelegate:(id)anObject

Makes anObject the receiver’s delegate. The messages that a delegate can expect to receive are listed at the end of this specification. The delegate doesn’t need to implement all the methods.

See also:	− delegate

setMainMenu:

− (void)setMainMenu:(NSMenu *)aMenu

Makes aMenu the application’s main menu.

See also:	− mainMenu

setServicesMenu:

− (void)setServicesMenu:(NSMenu *)aMenu

Makes aMenu the application’s Services menu.

See also:	− servicesMenu

setServicesProvider:

− (void)setServicesProvider:(id)aProvider

Registers the object aProvider as the service provider. The service provider is an object that performs all of the services that the application provides to other applications. When another application requests a service from the receiver, it sends the service request to aProvider.

For more information on registering services, see the on-line document /NextLibrary/Documentation/NextDev/TasksAndConcepts/ProgrammingTopics/Services.rtf.

See also:	− servicesProvider

setWindowsMenu:

− (void)setWindowsMenu:(NSMenu *)aMenu

Makes aMenu the application’s Window menu.

See also:	− windowsMenu

setWindowsNeedUpdate:

− (void)setWindowsNeedUpdate:(BOOL)flag

Sets whether the application’s windows need updating when the application has finished processing the current event. This method is especially useful for making sure menus are updated to reflect changes not initiated by user actions, such as messages received from remote objects.

See also:	 − updateWindows

p	showHelp:

− (void)showHelp:(id)sender

Brings up the application’s help file by sending a request to the shared NSWorkspace object to open the file using the default application for the help file’s type. (You set the application’s help file using Project Builder.) This method is typically invoked when the user chooses the Help command or one of the commands from the Help menu.

On Microsoft Windows platforms, the help file is typically an HLP file, so this method brings up Microsoft Windows help. On Mach platforms, the help file is typically an RTF file and is displayed using Edit, but the help file can be anything. For example, Project Builder on Mach brings up a Digital Librarian bookshelf in response to its Help command.

For more information on providing on-line help for your application, see the NSHelpManager class specification.

See also:	− activateContextHelpMode:

stop:

− (void)stop:(id)sender

Stops the main event loop. This method will break the flow of control out of the run method, thereby returning to the main() function. A subsequent run message will restart the loop.

If this method is invoked during a modal event loop, it will break that loop but not the main event loop.

See also:	− runModalForWindow:, − runModalSession:, − terminate:

stopModal

− (void)stopModal

Stops a modal event loop. This method should always be paired with a previous invocation of runModalForWindow: or beginModalSessionForWindow:. When runModalForWindow: is stopped with this method, it returns NSRunStoppedResponse. This method will stop the loop only if it’s executed by code responding to an event. If you need to stop a runModalForWindow: loop from a method registered with the current NSRunLoop (for example, a method repeatedly invoked by an NSTimer object), use the abortModal method.

See also:	− runModalSession:, − stopModalWithCode:

stopModalWithCode:

− (void)stopModalWithCode:(int)returnCode

Like stopModal, except the argument returnCode allows you to specify the value that runModalForWindow: will return.

See also:	− abortModal

targetForAction:

− (id)targetForAction:(SEL)aSelector

Returns the object that receives the action message aSelector.

See also:	− sendAction:to:from:, − tryToPerform:with:

terminate:

− (void)terminate:(id)sender

Terminates the application. This method is typically invoked when the user chooses Quit or Exit from the application’s menu. Each use of terminate: invokes applicationShouldTerminate: to notify the delegate that the application will terminate. If applicationShouldTerminate: returns NO, control is returned to the main event loop, and the application isn’t terminated. Otherwise, this method posts an NSApplicationWillTerminateNotification to the default notification center. Don’t put final cleanup code in your application’s main() function; it will never be executed. If cleanup is necessary, have the delegate respond to applicationWillTerminate: and perform the cleanup in that method.

See also:	− run, − stop:, exit()

tryToPerform:with:

− (BOOL)tryToPerform:(SEL)aSelector with:(id)anObject

Dispatches action messages. The receiver tries to perform the method aSelector using its inherited NSResponder method tryToPerform:with:. If the receiver doesn’t perform aSelector, the delegate is given the opportunity to perform it using its inherited NSObject method perform:withObject:. If either the receiver or its delegate accept aSelector, this method returns YES; otherwise it returns NO.

See also:	− respondsToSelector: (NSObject)

unhide:

− (void)unhide:(id)sender

Restores hidden windows to the screen and makes the application active. Invokes unhideWithoutActivation.

See also:	− activateIgnoringOtherApps:, − hide:

unhideWithoutActivation

− (void)unhideWithoutActivation

Restores hidden windows without activating their owner (the receiver). When this method begins, it posts an NSApplicationWillUnhideNotification to the default notification center. If it completes successfully, it posts an NSApplicationDidUnhideNotification.

See also:	− activateIgnoringOtherApps:, − applicationDidUnhide: (delegate method),

− applicationWillUnhide: (delegate method), − hide:

updateWindows

− (void)updateWindows

Sends an update message to each on-screen NSWindow. This method is invoked automatically in the main event loop after each event. If the NSWindow has automatic updating turned on, its update method will redraw all of the NSWindow’s NSViews that need redrawing. If automatic updating is turned off, the update message does nothing. (You turn automatic updating on and off by sending setAutodisplay: to an NSWindow.)

When this method begins, it posts an NSApplicationWillUpdateNotification to the default notification center. When it successfully completes, it posts an NSApplicationDidUpdateNotification.

See also:	− applicationWillUpdate: (delegate method), − applicationDidUpdate: (delegate method), − setWindowsNeedUpdate:, − setAutodisplay: (NSWindow)

updateWindowsItem:

− (void)updateWindowsItem:(NSWindow *)aWindow

Updates the Window menu item for aWindow to reflect the edited status of aWindow. You rarely need to invoke this method because it is invoked automatically when the edit status of an NSWindow is set.

See also:	− changeWindowsItem:title:filename:, − setDocumentEdited: (NSWindow)

validRequestorForSendType:returnType:

− (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType

Indicates whether the receiver can send and receive the specified pasteboard types. This message is sent to all responders in a responder chain. NSApp is typically the last item in the responder chain, so it usually only receives this message if none of the current responders can send sendType data and accept back returnType data.

The receiver passes this message on to its delegate if the delegate can respond (and isn’t an NSResponder with its own next responder). If the delegate can’t respond or returns nil, this method returns nil. If the delegate can find an object that can send sendType data and accept back returnType data, that object is returned.

See also:	− validRequestorForSendType:returnType: (NSResponder),

− registerServicesMenuSendTypes:andReturnTypes:,

− readSelectionFromPasteboard: (NSServicesRequests protocol),

− writeSelectionToPasteboard:types: (NSServicesRequests protocol)

p	windowWithWindowHandle:

− (NSWindow *)windowWithWindowHandle:(void *)hWnd

On Microsoft Windows platforms, returns the NSWindow object associated with the Win32 window handle hWnd. If the application does not own hWnd or hWnd does not have an NSWindow associated with it, this method returns nil. This method is for Microsoft Windows platforms only. windowWithWindowHandle: is not defined for the Mach platform.

See also:	− windowWithWindowHandle: (NSWindow), − windowHandle (NSWindow)

windowWithWindowNumber:

− (NSWindow *)windowWithWindowNumber:(int)windowNum

Returns the NSWindow object corresponding to windowNum.

windows

− (NSArray *)windows

Returns an NSArray of the application’s NSWindows, including off-screen windows.

windowsMenu

− (NSMenu *)windowsMenu

Returns the Window menu or nil if no Window menu has been created.

See also:	− setWindowsMenu:

Notifications

NSApplicationDidBecomeActiveNotification

Posted immediately after the application becomes active. The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationDidFinishLaunchingNotification

Posted at the end of the finishLaunching method to indicate that the application has completed launching and is ready to run.

The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationDidHideNotification

Posted at the end of the hide: method to indicate that the application is now hidden. The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationDidResignActiveNotification

Posted immediately after the application gives up its active status to another application. The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationDidUnhideNotification

Posted at the end of the unhideWithoutActivation method to indicate that the application is now visible. The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationDidUpdateNotification

Posted at the end of the updateWindows method to indicate that the application has finished updating its windows. The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationWillBecomeActiveNotification

Posted immediately after the application becomes active. The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationWillFinishLaunchingNotification

Posted at the start of the finishLaunching method to indicate that the application has completed its initialization process and is about to finish launching. The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationWillHideNotification

Posted at the start of the hide: method to indicate that the application is about to be hidden. The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationWillResignActiveNotification

Posted immediately before the application gives up its active status to another application. The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationWillTerminateNotification

Posted by the terminate: method to indicate that the application will terminate. Posted only if the delegate method applicationShouldTerminate: returns YES. The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationWillUnhideNotification

Posted at the start of the unhideWithoutActivation method to indicate that the application is about to be visible. The notification contains:

Notification Object	NSApp

Userinfo	None

NSApplicationWillUpdateNotification

Posted at the start of the updateWindows method to indicate that the application is about to update its windows. The notification contains:

Notification Object	NSApp

Userinfo	None

Methods Implemented By the Delegate

application:openFile:

− (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename

Sent directly by theApplication to the delegate. The method should open the file filename, returning YES if the file is successfully opened, and NO otherwise.

Note:	If the user has started up the application by double-clicking a file, the delegate receives the application:openFile: message before receiving applicationDidFinishLaunching:. (applicationWillFinishLaunching: is sent before application:openFile:.)

See also:	− application:openFileWithoutUI:, − application:openTempFile:,

− applicationOpenUntitledFile:

application:openFileWithoutUI:

− (BOOL)application:(NSApplication *)sender openFileWithoutUI:(NSString *)filename

Sent directly by sender to the delegate to request that the file filename be opened as a linked file. The method should open the file without bringing up its application’s user interface; that is, work with the file is under programmatic control of sender, rather than under keyboard control of the user. Returns YES if the file was successfully opened, NO otherwise.

See also:	− application:openFile:, − appliction:openTempFile:, − application:printFile:,

− applicationOpenUntitledFile:

application:openTempFile:

− (BOOL)application:(NSApplication *)theApplication openTempFile:(NSString *)filename

Sent directly by theApplication to the delegate. The method should attempt to open the file filename, returning YES if the file is successfully opened, and NO otherwise.

By design, a file opened through this method is assumed to be temporary; it’s the application’s responsibility to remove the file at the appropriate time.

See also:	− application:openFile:, − application:openFileWithoutUI:,

− applicationOpenUntitledFile:

application:printFile:

− (BOOL)application:(NSApplication *)theApplication printFile:(NSString *)filename

Sent when the user starts up the application on the command line with the -NSPrint option. Sent directly by theApplication to the delegate.

The method should attempt to print the file filename, returning YES if the file was successfully printed, and NO otherwise. The application terminates (using the terminate: method) after this method returns.

If at all possible, this method should print the file without displaying the user interface. For example, if you pass the -NSPrint option to the TextEdit application, TextEdit assumes you want to print the entire contents of the specified file. However, if the application opens more complex documents, you may want to display a panel that lets user choose exactly what they want to print.

See also:	− application:openFileWithoutUI:

applicationDidBecomeActive:

− (void)applicationDidBecomeActive:(NSNotification *)aNotification

Sent by the default notification center immediately after the application becomes active. aNotification is always an NSApplicationDidBecomeActiveNotification. You can retrieve the NSApplication object by sending the object method to aNotification.

See also:	− applicationDidFinishLaunching:, − applicationDidResignActive:,

− applicationWillBecomeActive:

applicationDidFinishLaunching:

− (void)applicationDidFinishLaunching:(NSNotification *)aNotification

Sent by the default notification center after the application has been launched and initialized but before it has received its first event. aNotification is always an NSApplicationDidFinishLaunchingNotification. You can retrieve the NSApplication object in question by sending object to aNotification. The delegate can implement this method to perform further initialization.

Note:	If the user has started up the application by double-clicking a file, the delegate receives the application:openFile: message before receiving applicationDidFinishLaunching:. (applicationWillFinishLaunching: is sent before application:openFile:.)

See also:	− applicationDidBecomeActive:, − applicationWillFinishLaunching:,

− finishLaunching

applicationDidHide:

− (void)applicationDidHide:(NSNotification *)aNotification

Sent by the default notification center immediately after the application is hidden. aNotification is always an NSApplicationDidHideNotification. You can retrieve the NSApplication object in question by sending object to aNotification.

See also:	− applicationWillHide:, − applicationDidUnhide:, − hide:

applicationDidResignActive:

− (void)applicationDidResignActive:(NSNotification *)aNotification

Sent by the default notification center immediately after the application is deactivated. aNotification is always an NSApplicationDidResignActiveNotification. You can retrieve the NSApplication object in question by sending object to aNotification.

See also:	− applicationDidBecomeActive:, − applicationWillResignActive:

applicationDidUnhide

− (void)applicationDidUnhide:(NSNotification *)aNotification

Sent by the default notification center immediately after the application is made visible. aNotification is always an NSApplicationDidUnhideNotification. You can retrieve the NSApplication object in question by sending object to aNotification.

See also:	− applicationDidHide:, − applicationWillUnhide:, − unhide:

applicationDidUpdate:

− (void)applicationDidUpdate:(NSNotification *)aNotification

Sent by the default notification center immediately after the NSApplication object updates its NSWindows. aNotification is always an NSApplicationDidUpdateNotification. You can retrieve the NSApplication object in question by sending object to aNotification.

See also:	− applicationWillUpdate:, − updateWindows

applicationOpenUntitledFile:

− (BOOL)applicationOpenUntitledFile:(NSApplication *)theApplication

Sent directly by theApplication to the delegate to request that a new, untitled file be opened. Returns YES if the file was successfully opened, NO otherwise.

See also:	− application:openFile:, − application:openFileWithoutUI:,

− application:openTempFile:

applicationShouldTerminate:

− (BOOL)applicationShouldTerminate:(NSApplication *)sender

Invoked from within the terminate: method immediately before the application terminates. sender is the NSApplication to be terminated. If this method returns NO, the application is not terminated, and control returns to the main event loop. Return YES to allow the application to terminate.

See also:	− applicationShouldTerminateAfterLastWindowClosed:,

− applicationWillTerminate:, − terminate:

p	applicationShouldTerminateAfterLastWindowClosed:

− (BOOL)applicationShouldTerminateAfterLastWindowsClosed:(NSApplication *)theApplication

Invoked when the user closes the last window that the application has open on.

This method is intended for the Microsoft Windows platform. On Microsoft Windows, the default behavior is to terminate the application if the user closes the last window. Most application use this default behavior; however, you may choose to have applicationShouldTerminateAfterLastWindowClosed: perform some other function, such as display a panel that gives the user a choice of exiting the application or opening a new window.

If this method returns NO, the application is not terminated, and control returns to the main event loop. Return YES to allow the application to terminate. Note that applicationShouldTerminate: is invoked if this method returns YES.

See also:	− terminate:

applicationWillBecomeActive:

− (void)applicationWillBecomeActive:(NSNotification *)aNotification

Sent by the default notification center immediately before the application becomes active. aNotification is always an NSApplicationWillBecomeActiveNotification. You can retrieve the NSApplication object in question by sending object to aNotification.

See also:	− applicationDidBecomeActive:, − applicationWillFinishLaunching:,

− applicationWillResignActive:

applicationWillFinishLaunching:

− (void)applicationWillFinishLaunching:(NSNotification *)aNotification

Sent by the default notification center immediately before the NSApplication object is initialized. aNotification is always an NSApplicationWillFinishLaunchingNotification. You can retrieve the NSApplication object in question by sending object to aNotification.

See also:	− applicationDidFinishLaunching:, − applicationWilBecomeActive:,

− finishLaunching

applicationWillHide:

− (void)applicationWillHide:(NSNotification *)aNotification

Sent by the default notification center immediately after the application is hidden. aNotification is always an NSApplicationWillHideNotification. You can retrieve the NSApplication object in question by sending object to aNotification.

See also:	− applicationDidHide:, − hide:

applicationWillTerminate:

− (void)applicationWillTerminate:(NSNotification *)aNotification

Sent by the default notification center immediately before the application terminates. aNotification is always an NSApplicationWillTerminateNotification. You can retrieve the NSApplication object in question by sending object to aNotification. Put any necessary cleanup code in this method.

See also:	− applicationShouldTerminate:, − terminate:

applicationWillResignActive:

− (void)applicationWillResignActive:(NSNotification *)aNotification

Sent by the default notification center immediately after the application is deactivated. aNotification is always an NSApplicationWillResignActiveNotification. You can retrieve the NSApplication object in question by sending object to aNotification.

See also:	− applicationWillBecomeActive:, − applicationDidResignActive:

applicationWillUnhide

− (void)applicationWillUnhide:(NSNotification *)aNotification

Sent by the default notification center immediately after the application is unhidden. aNotification is always an NSApplicationWillUnhideNotification. You can retrieve the NSApplication object in question by sending object to aNotification.

See also:	− applicationDidUnhide:, − applicationWillHide:, − unhide:

applicationWillUpdate:

− (void)applicationWillUpdate:(NSNotification *)aNotification

Sent by the default notification center immediately before the NSApplication object updates its NSWindows. aNotification is always an NSApplicationWillUpdateNotification. You can retrieve the NSApplication object in question by sending object to aNotification.

See also:	− applicationDidUpdate:, −  updateWindows


NSAttributedString Class Cluster Additions
p c NSAttributedString Class Cluster Additions

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Class Cluster Description

NSAttributedString objects manage character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string. The cluster’s two public classes, NSAttributedString and NSMutableAttributedString, declare the programmatic interface for read-only attributed strings and modifiable attributed strings, respectively. The Foundation Kit defines the basic functionality for attributed strings, while the remainder is defined here in the Application Kit. The Application Kit also uses a subclass of NSMutableAttributedString, called NSTextStorage, to provide the storage for NeXT’s extended text-handling system.

Note:	NSAttributedString is not a subclass of NSString. It contains a string object to which it applies attributes. This protects users of attributed strings from ambiguities caused by the semantic differences between simple and attributed string. For example, equality can’t be simply defined between an NSString and an attributed string.

Because of the nature of class clusters, attributed string objects are not actual instances of the NSAttributedString or NSMutableAttributedString classes, but are instances of one of their private concrete subclasses. Although an attributed string object’s class is private, its interface is public, as declared by these abstract superclasses, NSAttributedString and NSMutableAttributedString. The attributed string classes adopt the NSCopying and NSMutableCopying protocols, making it convenient to convert an attributed string from one type to the other.

You create an NSAttributedString object from scratch by using one of initWithString:, initWithString:attributes:, or initWithAttributedString:. These methods initialize an attributed string with data you provide. You can also create an attributed string from RTF data using initWithRTF:documentAttributes:, initWithRTFD:documentAttributes:, initWithRTFDFileWrapper:documentAttributes:, or initWithPath:documentAttributes:. See “RTF Document Attributes” for more details on reading RTF.

An attributed string provides basic access to its contents with the string and attributesAtIndex:effectiveRange: methods, which yield characters and attributes, respectively. These two primitive methods are used by the other access methods to retrieve attributes individually by name, by functional group (font or ruler attributes, for example), and so on.

Feature Overview

NSAttributedString and NSMutableAttributedString add a number of features to the basic content storage of NSString:

•	Association of arbitrary, programmer-defined attributes with ranges of characters

•	Preservation of attribute-to-character mapping after changes (NSMutableAttributedString)

•	Support for RTF, including file attachments and graphics

•	Drawing in NSView objects (note that the Application Kit adds drawing methods to NSString as well)

•	Linguistic unit (word) and line calculation

An attributed string identifies attributes by name, storing their values as opaque ids in an NSDictionary. For example, the text font is stored as an NSFont object under the name given by NSFontAttributeName. You can associate any object value, by any name, with a given range of characters in the attributed string. The basic attributes defined by NSAttributedString are described below under “Accessing Attributes.”

A mutable attributed string keeps track of the attribute mapping as characters are added to and deleted from it and as attributes are changed. It allows you to group batches of edits with the beginEditing and endEditing methods, and to consolidate changes to the attribute-to-character mapping with the fix... methods. See “Changing a Mutable Attributed String” below for more information.

An attributed string can be created from rich text (RTF) or rich text with attachments (RTFD), and can write its contents as RTF or RTFD data. Three initialization methods, initWithRTF:documentAttributes:, initWithRTFD:documentAttributes:, and initWithRTFDFileWrapper:documentAttributes:, interpret rich text data. The methods for writing rich text are RTFFromRange:documentAttributes: and

RTFDFromRange:documentAttributes:, which return rich text data for any legal range within the attributed string, and RTFDFileWrapperFromRange:documentAttributes:, which returns the attributed string as an NSFileWrapper. NSAttributedString provides limited support for some document-level attributes, as described below under “RTF Document Attributes.” Additional support for rich text is provided by other text-handling classes such as NSTextView.

You can draw an attributed string in a focused NSView by invoking either the drawAtPoint: or drawInRect: method. Note that the Application Kit defines drawing methods for NSString as well, allowing any string object to draw itself. These methods, drawAtPoint:withAttributes: and drawInRect:withAttributes:, are described in the NSString Additions class specification.

An attributed string supports the typical behavior of editors in selecting a word on a double-click with the doubleClickAtIndex: method, and finds word breaks with nextWordFromIndex:forward:. It also calculates line breaks with the lineBreakBeforeIndex:withinRange: method.

Accessing Attributes

An attributed string identifies attributes by name, storing an id value under the attriute name in an NSDictionary, which is in turn associated with an NSRange that indicates the characters to which the dictionary’s attributes apply. You can assign any attribute name/value pair you wish to a range of characters, in addition to these standard attributes:

Attribute Identifier	Value Class	Default Value

NSFontAttributeName	NSFont	Helvetica 12-point

NSForegroundColorAttributeName	NSColor	black

NSBackgroundColorAttributeName	NSColor	none (no background drawn)

NSUnderlineStyleAttributeName	NSNumber, as an int	none (no underline)

NSSuperscriptAttributeName	NSNumber, as an int	0

NSBaselineOffsetAttributeName	NSNumber, as a float	0.0

NSKernAttributeName	NSNumber, as a float	0.0

NSLigatureAttributeName	NSNumber, as an int	1 (standard ligatures)

NSParagraphStyleAttributeName	NSParagraphStyle	(as returned by NSParagraphStyle’s

defaultParagraphStyle method)

NSAttachmentAttributeName	NSTextAttachment	none (no attachment)

The identifiers listed are actually global NSString variables containing the attribute names. The value class is what users of an attributed string should expect the attribute values to be presented as. The default values are what they should assume if no attribute value has been explicitly set for the requested character range.

The natures of several attributes aren’t obvious from name alone:

•	The underline attribute has only one value defined, NSSingleUnderlineStyle. All characters with this attribute value should be drawn with a single line just below the baseline.

•	The superscript attribute indicates an abstract level for both super- and subscripts. The user of the attributed string can interpret this as desired, adjusting the baseline by the same or a different amount for each level, changing the font size, or both.

•	The baseline offset attribute is a literal distance by which the characters should be shifted above the baseline (for positive offsets) or below (for negative offsets).

•	The kerning attribute indicates how much the following character should be shifted from its default offset as defined by the current character’s font; a positive kern indicates a shift farther along and a negative kern indicates a shift closer to the current character.

•	The ligature attribute determines what kinds of ligatures should be used when displaying the string. A value of 0 indicates that only ligatures essential for proper rendering of text should be used, 1 indicates that standard ligatures should be used, and 2 indicates that all available ligatures should be used. Which ligatures are standard depends on the script and possibly the font. Arabic text, for example, requires ligatures for many character sequences, but has a rich set of additional ligatures that combine characters. English text has no essential ligatures, and typically has only two standard ligatures, those for “fi” and “fl”—all others being considered more advanced or fancy.

With an immutable attributed string, you assign all attributes on creating the string using methods such as initWithRTF:documentAttributes:, which interprets attributes from the RTF data, initWithString:attributes:, which explicitly takes an NSDictionary of name/value pairs, or initWithString:, which assigns no attributes. See “Changing a Mutable Attributed String” below for information on assigning attributes with a mutable attributed string.

To retrieve attribute values from either type of attributed string, use any of these methods:

− attributesAtIndex:effectiveRange:

− attributesAtIndex:longestEffectiveRange:inRange:

− attribute:atIndex:effectiveRange:

− attribute:atIndex:longestEffectiveRange:inRange:

− fontAttributesInRange:

− rulerAttributesInRange:

The first two methods return all attributes at a given index, the attribute:... methods return the value of a single named attribute, and fontAttributesInRange: and rulerAttributesInRange: return attributes defined to apply only to characters or to whole paragraphs, respectively (see the individual method descriptions for more information).

The first four methods also return by reference the effective range and the longest effective range of the attributes. These ranges allow you to determine the extent of attributes. Conceptually, each character in an attributed string has its own collection of attributes; however, it’s often useful to know when the attributes and values are the same over a series of characters. This allows a routine to progress through an attributed string in chunks larger than a single character. In retrieving the effective range, an attributed string simply looks up information in its attribute mapping, essentially the dictionary of attributes that apply at the index requested. In retrieving the longest effective range, the attributed string continues checking characters past this basic range as long as the attribute values are the same. This extra comparison increases the execution time for these methods but guarantees a precise maximal range for the attributes requested.The code fragment below progresses through an attributed string in chunks based on the effective range. The fictitious analyzer object here counts the number of characters in each font. The while loop progresses as long as the effective range retrieved doesn’t include the end of the attributed string, retrieving the font in effect just past the latest retrieved range. For each font attribute retrieved, analyzer is asked to tally the number of characters in the effective range. In this example, it’s possible that consecutive invocations of attribute:atIndex:effectiveRange: will return the same value.

NSAttributedString *attrStr;

unsigned int length;

NSRange effectiveRange;

id attributeValue;

length = [attrStr length];

effectiveRange = NSMakeRange(0, 0);

while (NSMaxRange(effectiveRange) < length) {

    attributeValue = [attrStr attribute:NSFontAttributeName

        atIndex:NSMaxRange(effectiveRange) effectiveRange:&effectiveRange];

    [analyzer tallyCharacterRange:effectiveRange font:attributeValue];

}

In contrast, the next code fragment progresses through the attributed string according to the maximum effective range for each font. In this case, analyzer counts font changes, which may not be represented by merely retrieving effective ranges. In this case the while loop is predicated on the length of the limiting range, which begins as the entire length of the attributed string and is whittled down as the loop progresses. After analyzer records the font change, the limit range is adjusted to account for the longest effective range retrieved.

NSAttributedString *attrStr;

NSRange limitRange;

NSRange effectiveRange;

id attributeValue;

limitRange = NSMakeRange(0, [attrStr length]);

while (limitRange.length > 0) {

    attributeValue = [attrStr attribute:NSFontAttributeName

        atIndex:limitRange.location longestEffectiveRange:&effectiveRange

        inRange:limitRange];

    [analyzer recordFontChange:attributeValue];

    limitRange = NSMakeRange(NSMaxRange(effectiveRange),

        NSMaxRange(limitRange) - NSMaxRange(effectiveRange));

}

Note that the second code fragment is more complex. Because of this, and because attribute:atIndex:longestEffectiveRange:inRange: is somewhat slower than attribute:atIndex:effectiveRange:, you should typically use it only when absolutely necessary for the work you’re performing. In most cases working by effective range is enough.

Changing a Mutable Attributed String

NSMutableAttributedString declares a number of methods for changing both characters and attributes, such as the primitive replaceCharactersInRange:withString: and setAttributes:range:, or the more convenient methods addAttribute:value:range:, applyFontTraits:range:, setAlignment:range:, and so on. All of the methods for changing a mutable attributed string properly update the mapping between characters and attributes, but after a change some inconsistencies can develop. Here are some examples of attribute consistency requirements:

•	Paragraph styles must apply to entire paragraphs.

•	Scripts may only be assigned fonts that support them. For example, Kanji and Arabic characters can’t be assigned the Times-Roman font, and must be reassigned fonts that support these scripts.

•	Deleting attachment characters from the string requires the corresponding attachment objects to be released. Similarly, removing attachment objects requires the corresponding attachment characters to be removed from the string.

•	A code editing application that displays all language keywords in boldface can automatically assign this attriute as the user changes the font or edits the text.

NSMutableAttributedString defines methods to fix these inconsistencies as changes are made. This allows the attributes to be cleaned up at a low level, hiding potential problems from higher levels and providing for very clean update of display as attributes change. There are six methods for fixing attributes:

− fixAttributesInRange:

− fixAttachmentAttributeInRange:

− fixFontAttributeInRange:

− fixParagraphStyleAttributeInRange:

− beginEditing

− endEditing

The first method, fixAttributesInRange:, invokes the other three fix... methods to clean up deleted attachment references, font attributes, and paragraph attributes, respectively. The individual method descriptions explain what cleanup entails for each case.

The beginEditing and endEditing methods are provided for subclasses of NSMutableAttributedString to override. Their default implementations do nothing. These methods allow instances of a subclass to record or buffer groups of changes and clean themselves up on receiving an endEditing message. endEditing also allows the receiver to notify any observers that it has been changed. NSTextStorage’s implementation of endEditing, for example, fixes changed attributes and then notifies its NSLayoutManagers that they need to re-lay and redisplay their text.

RTF Document Attributes

Attributed strings keep attribute information for their text only, while RTF allows for more general attributes of a document, especially regarding paper size and layout. To support higher-level objects that use attributed strings, the methods that work with RTF also read and write some RTF directives for document attributes, stored in an NSDictionary under these keys:

Attribute Key	Value Class

PaperSize	NSValue, as an NSSize

LeftMargin	NSNumber, as a float

RightMargin	NSNumber, as a float

TopMargin	NSNumber, as a float

BottomMargin	NSNumber, as a float

The init methods, such as initWithRTF:documentAttributes:, return by reference a dictionary containing the attributes read from the RTF data, which your application can then use to set up its page layout. Similarly, RTF extraction methods such as RTFFromRange:documentAttributes:, accept a dictionary containing those attributes and writes them into the RTF data, thus preserving the page layout information.

Attachments

Attachments, such as embedded images or files, are represented in an attributed string by both a special character and an attribute. The character is identified by the global name NSAttachmentCharacter, and indicates the presence of an attachment at its location in the string. The attribute, identified in the string by the attribute name NSAttachmentAttributeName, is an NSTextAttachment object. An NSTextAttachment contains the data for the attachment itself, as well as an image to display when the string is drawn. You can use NSAttributedString’s attributedStringWithAttachment: class method to construct an attachment string, which you can then add to a mutable attributed string using appendAttributedString: or insertAttributedString:atIndex:.

i NSAttributedString Additions

Inherits From:	NSObject

Declared In:	AppKit/NSAttributedString.h

AppKit/NSStringDrawing.h

AppKit/NSTextAttachment.h

Class Description

The Application Kit extends the Foundation Kit’s NSAttributedString class by adding:

•	Support for RTF, with or without attachments

•	Graphic attributes, including font and ruler attributes

•	Methods for drawing attributed strings

•	Methods for calculating significant linguistic units

Method Types

Creating an NSAttributedString	− initWithRTF:documentAttributes:

− initWithRTFD:documentAttributes:

− initWithRTFDFileWrapper:documentAttributes:

− initWithPath:documentAttributes:

+ attributedStringWithAttachment:

Retrieving attribute information	− fontAttributesInRange:

− rulerAttributesInRange:

− containsAttachments

Calculating linguistic units	− doubleClickAtIndex:

− lineBreakBeforeIndex:withinRange:

− nextWordFromIndex:forward:

Drawing the string	− drawAtPoint:

− drawInRect:

− size

Generating RTF data	− RTFFromRange:documentAttributes:

− RTFDFileWrapperFromRange:documentAttributes:

− RTFDFromRange:documentAttributes:

Class Methods

p	attributedStringWithAttachment:

+ (NSAttributedString *)attributedStringWithAttachment:(NSTextAttachment *)attachment

Returns an NSAttributedString object containing only the attachment marker character (NSAttachmentCharacter), which is assigned an attribute whose name is NSTextAttachmentName and whose value is attachment. Use this method, along with appendAttributedString: or insertAttributedString:atIndex:, to add an attachment to an attributed string.

Instance Methods

p	containsAttachments

− (BOOL)containsAttachments

Returns YES if the receiver contains any attachment attributes, NO otherwise. This method checks only for attachment attributes, not for NSAttachmentCharacter.

p	doubleClickAtIndex:

− (NSRange)doubleClickAtIndex:(unsigned int)index

Returns the range of characters that form a word (or other linguistic unit) surrounding index, taking language characteristics into account. Raises an NSRangeException if index lies beyond the end of the receiver’s characters.

See also:	− nextWordFromIndex:forward:

p	drawAtPoint:

− (void)drawAtPoint:(NSPoint)point

Draws the receiver with its font and other display attributes at point in the currently focused NSView. Text is drawn in such a way that the upper left corner of its bounding box lies at point, regardless of the line sweep direction or whether the NSView is flipped.

Don’t invoke this method while no NSView is focused.

See also:	− lockFocus (NSView), − size, − drawInRect:

p	drawInRect:

− (void)drawInRect:(NSRect)rect

Draws the receiver with its font and other display attributes within rect in the currently focused NSView, clipping the drawing to this rectangle. Text is drawn within rect according to its line sweep direction; for example, Arabic text will begin at the right edge and potentially be clipped on the left.

Don’t invoke this method while no NSView is focused.

See also:	− lockFocus (NSView), − drawAtPoint:

p	fontAttributesInRange:

− (NSDictionary *)fontAttributesInRange:(NSRange)aRange

Returns the font attributes in effect for the character at aRange.location. Font attributes are all those listed under “Accessing Attributes” in the class cluster description except NSParagraphStyleAttributeName and NSAttachmentAttributeName. Use this method to obtain font attributes that are to be copied or pasted with “copy font” operations. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

See also:	− rulerAttributesInRange:

p	initWithPath:documentAttributes:

− (id)initWithPath:(NSString *)path documentAttributes:(NSDictionary **)docAttributes

Initializes a new NSAttributedString from RTF or RTFD data contained in the file at path. Also returns by reference in docAttributes a dictionary containing document-level attributes, as listed in the class cluster description under “RTF Document Attributes.” docAttributes may be NULL, in which case no document attributes are returned. Returns self, or nil if rtfData can’t be decoded.

p	initWithRTF:documentAttributes:

− (id)initWithRTF:(NSData *)rtfData documentAttributes:(NSDictionary **)docAttributes

Initializes a new NSAttributedString by decoding the stream of RTF commands and data contained in rtfData. Also returns by reference in docAttributes a dictionary containing document-level attributes, as listed in the class cluster description under “RTF Document Attributes.” docAttributes may be NULL, in which case no document attributes are returned. Returns self, or nil if rtfData can’t be decoded.

p	initWithRTFD:documentAttributes:

− (id)initWithRTFD:(NSData *)rtfdData documentAttributes:(NSDictionary **)docAttributes

Initializes a new NSAttributedString by decoding the stream of RTFD commands and data contained in rtfdData. Also returns by reference in docAttributes a dictionary containing document-level attributes, as listed in the class cluster description under “RTF Document Attributes.” docAttributes may be NULL, in which case no document attributes are returned. Returns self, or nil if rtfData can’t be decoded.

p	initWithRTFDFileWrapper:documentAttributes:

− (id)initWithRTFDFileWrapper:(NSFileWrapper *)wrapper documentAttributes:(NSDictionary **)docAttributes

Initializes a new NSAttributedString from wrapper an NSFileWrapper object containing an RTFD document. Also returns by reference in docAttributes a dictionary containing document-level attributes, as listed in the class cluster description under “RTF Document Attributes.” docAttributes may be NULL, in which case no document attributes are returned. Returns self, or nil if wrapper can’t be interpreted as an RTFD document.

p	lineBreakBeforeIndex:withinRange:

− (unsigned int)lineBreakBeforeIndex:(unsigned int)index withinRange:(NSRange)aRange

Returns the index of the closest character before index and within aRange that can be placed on a new line when laying out text. In other words, finds the appropriate line break when the character at index won’t fit on the same line as the character at the beginning of aRange. Returns NSNotFound if no line break is possible before index.

Raises an NSRangeException if index or any part of aRange lies beyond the end of the receiver’s characters.

See also:	− nextWordFromIndex:forward:

p	nextWordFromIndex:forward:

− (unsigned int)nextWordFromIndex:(unsigned int)index forward:(BOOL)flag

Returns the index of the first character of the word after or before index. If flag is YES, this is the first character after index that begins a word; if flag is NO, it’s the first character before index that begins a word, whether index is located within a word or not. If index lies at either end of the string and the search direction would progress past that end, it’s returned unchanged. This method is intended for moving the insertion point during editing, not for linguistic analysis or parsing of text.

Raises an NSRangeException if index lies beyond the end of the receiver’s characters.

See also:	− lineBreakBeforeIndex:withinRange:

p	RTFDFileWrapperFromRange:documentAttributes:

− (NSFileWrapper *)RTFDFileWrapperFromRagne:(NSRange)aRange documentAttributes:(NSDictionary *)docAttributes

Returns an NSFileWrapper object that contains an RTFD document corresponding to the characters and attributes within aRange. The file wrapper also includes the document-level attributes in docAttributes, as explained in the class cluster description under “RTF Document Attributes.” If there are no document-level attributes, docAttributes can be nil. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

You can save the file wrapper using NSFileWrapper’s writeToFile:atomically:updateFilenames: method.

See also:	− RTFDFromRange:documentAttributes:, − RTFFromRange:documentAttributes:

p	RTFDFromRange:documentAttributes:

− (NSData *)RTFDFromRange:(NSRange)aRange documentAttributes:(NSDictionary *)docAttributes

Returns an NSData object that contains an RTFD stream corresponding to the characters and attributes within aRange. Also writes the document-level attributes in docAttributes, as explained in the class cluster description under “RTF Document Attributes.” If there are no document-level attributes, docAttributes can be nil. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

When writing data to the pasteboard, you can use the NSData object as the first argument to NSPasteboard’s setData:forType: method, with a second argument of NSRTFDPboardType.

See also:	− RTFFromRange:documentAttributes:,

− RTFDFileWrapperFromRange:documentAttributes:

p	RTFFromRange:documentAttributes:

− (NSData *)RTFFromRange:(NSRange)aRange documentAttributes:(NSDictionary *)docAttributes

Returns an NSData object that contains an RTF stream corresponding to the characters and attributes within aRange, omitting all attachment attributes. Also writes the document-level attributes in docAttributes, as explained in the class cluster description under “RTF Document Attributes.” If there are no document-level attributes, docAttributes can be nil. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

When writing data to the pasteboard, you can use the NSData object as the first argument to NSPasteboard’s setData:forType: method, with a second argument of NSRTFPboardType.

Although this method strips attachments, it leaves the attachment characters in the text itself. NSText’s RTFFromRange: method, on the other hand, does strip attachment characters when extracting RTF.

See also:	− RTFDFromRange:documentAttributes:,

− RTFDFileWrapperFromRange:documentAttributes:

p	rulerAttributesInRange:

− (NSDictionary *)rulerAttributesInRange:(NSRange)aRange

Returns the ruler (paragraph) attributes in effect for the characters within aRange. The only ruler attribute currently defined is that named by NSParagraphStyleAttributeName. Use this method to obtain attributes that are to be copied or pasted with “copy ruler” operations. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

See also:	− fontAttributesInRange:

p	size

− (NSSize)size

Returns the bounding box of the marks that the receiver draws.

See also:	− drawAtPoint:, − drawInRect:

i NSMutableAttributedString

Inherits From:	NSAttributedString : NSObject

Declared In:	AppKit/NSAttributedString.h

AppKit/NSStringDrawing.h

AppKit/NSTextAttachment.h

Class Description

Additions to the NSMutableAttributedString class primarily involve setting graphical attributes, such as font, super- or subscripting, and alignment, and making these attributes consistent after changes. See the class cluster description for more information.

Method Types

Changing attributes	− applyFontTraits:range:

− setAlignment:range:

− subscriptRange:

− superscriptRange:

− unscriptRange:

Updating attachment contents	− updateAttachmentsFromPath:

Fixing attributes after changes	− fixAttributesInRange:

− fixAttachmentAttributeInRange:

− fixFontAttributeInRange:

− fixParagraphStyleAttributeInRange:

Instance Methods

p	applyFontTraits:range:

− (void)applyFontTraits:(NSFontTraitMask)mask range:(NSRange)aRange

Apply the font attributes specified by mask to the characters in aRange. See the NSFontManager class specification for a description of the font traits available. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

See also:	− setAlignment:range:, − setAttributes:range:

p	fixAttachmentAttributeInRange:

− (void)fixAttachmentAttributeInRange:(NSRange)aRange

Cleans up attachment attributes in aRange, removing all attachment attributes assigned to characters other than NSAttachmentCharacter. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

See also:	− fixFontAttributeInRange:, − fixParagraphStyleAttributeInRange:,

− fixAttributesInRange:

p	fixAttributesInRange:

− (void)fixAttributesInRange:(NSRange)aRange

Invokes the other fix... methods, allowing you to clean up an attributed string with a single message. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

See also:	− fixAttachmentAttributeInRange:, − fixFontAttributeInRange:,

− fixParagraphStyleAttributeInRange:

p	fixFontAttributeInRange:

− (void)fixFontAttributeInRange:(NSRange)aRange

Fixes the font attribute in aRange, assigning default fonts to characters with illegal fonts for their scripts and otherwise correcting font attribute assignments. For example, Kanji characters in assigned a Latin font are reassigned an appropriate Kanji font. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

See also:	− fixParagraphStyleAttributeInRange:, − fixAttachmentAttributeInRange:,

− fixAttributesInRange:

p	fixParagraphStyleAttributeInRange:

− (void)fixParagraphStyleAttributeInRange:(NSRange)aRange

Fixes the paragraph style attributes in aRange, assigning the first paragraph style attribute value in each paragraph to all characters of the paragraph. This method extends the range as needed to cover the last paragraph partially contained. A paragraph is delimited by any of these characters, the longest possible sequence being preferred to any shorter:

U+000D (\r or CR)	U+2028 (Unicode line separator)

U+000A (\n or LF)	U+2029 (Unicode paragraph separator)

\r\n, in that order (also known as CRLF)

Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

See also:	− fixFontAttributeInRange:, − fixAttachmentAttributeInRange:,

− fixAttributesInRange:

p	setAlignment:range:

− (void)setAlignment:(NSTextAlignment)alignment range:(NSRange)aRange

Sets the alignment characteristic of the paragraph style attribute for the characters in aRange to alignment. When attribute fixing takes place, this change will only affect paragraphs whose first character was included in aRange. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

See also:	− addAttributes:range:, − applyFontTraits:range:,

− fixParagraphStyleAttributeInRange:

p	subscriptRange:

− (void)subscriptRange:(NSRange)aRange

Decrements the value of the superscript attribute for characters in aRange by 1. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

See also:	− superscriptRange:, − unscriptRange:

p	superscriptRange:

− (void)superscriptRange:(NSRange)aRange

Increments the value of the superscript attribute for characters in aRange by 1. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

See also:	− subscriptRange:, − unscriptRange:

p	unscriptRange:

− (void)unscriptRange:(NSRange)aRange

Removes the superscript attribute from the characters in aRange. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

See also:	− subscriptRange:, − superscriptRange:

p	updateAttachmentsFromPath:

− (void)updateAttachmentsFromPath:(NSString *)path

Updates all attachments based on files contained in the RTFD file package at path.

See also:	− updateFromPath: (NSFileWrapper)


NSBitmapImageRep

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSImageRep : NSObject

Conforms To:	NSCoding (from NSImageRep)

NSCopying (from NSImageRep)

NSObject (from NSObject)

Declared In:	AppKit/NSImage.h

Class Description

An NSBitmapImageRep is an object that can render an image from bitmap data. The data can be in Tag Image File Format (TIFF), Windows bitmap format (BMP), or it can be raw image data. If it’s raw data, the object must be informed about the structure of the image—its size, the number of color components, the number of bits per sample, and so on—when it’s first initialized. If it’s TIFF or BMP data, the object can get this information from the various fields included with the data.

Although NSBitmapImageReps are often used indirectly, through instances of the NSImage class, they can also be used directly—for example to manipulate the bits of an image as you might need to do in a paint program.

Setting Up an NSBitmapImageRep

You pass bitmap data for an image to a new NSBitmapImageRep when you first initialize it. You can also create an NSBitmapImageRep from bitmap data that’s read from a specified rectangle of a focused NSView.

Although the NSBitmapImageRep class inherits NSImageRep methods that set image attributes, these methods shouldn’t be used. Instead, you should either allow the object to find out about the image from the fields included with the bitmap data, or use methods defined in this class to supply this information when the object is initialized.

TIFF Compression

TIFF data can be read and rendered after it has been compressed using any one of the four schemes briefly described below:

LZW	Compresses and decompresses without information loss, achieving compression ratios up to 5:1. It may be somewhat slower to compress and decompress than the PackBits scheme.

PackBits	Compresses and decompresses without information loss, but may not achieve the same compression ratios as LZW.

JPEG	Compresses and decompresses with some information loss, but can achieve compression ratios anywhere from 10:1 to 100:1. The ratio is determined by a user-settable factor ranging from 1.0 to 255.0, with higher factors yielding greater compression. More information is lost with greater compression, but 15:1 compression is safe for publication quality. Some images can be compressed even more. JPEG compression can be used only for images that specify at least 4 bits per sample.

CCITTFAX	Compresses and decompresses 1 bit gray-scale images using international fax compression standards CCITT3 and CCITT4.

An NSBitmapImageRep can also produce compressed TIFF data for its image using any of these schemes.

Method Types

Creating an NSBitmapImageRep	+ imageRepsWithData:

+ imageRepWithData:

− initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:

samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:

bytesPerRow:bitsPerPixel:

− initWithBitmapHandle:

− initWithData:

− initWithFocusedViewRect:

− initWithIconHandle:

Getting information about the image

− bitsPerPixel

− bytesPerPlane

− bytesPerRow

− isPlanar

− numberOfPlanes

− samplesPerPixel

Getting image data	− bitmapData

− getBitmapDataPlanes:

Producing a TIFF representation of the image

+ TIFFRepresentationOfImageRepsInArray:

+ TIFFRepresentationOfImageRepsInArray:

usingCompression:factor:

− TIFFRepresentation

− TIFFRepresentationUsingCompression:factor:

Setting and checking compression types

+ getTIFFCompressionTypes:count:

+ localizedNameForTIFFCompressionType:

− canBeCompressedUsing:

− getCompression:factor:

− setCompression:factor:

Class Methods

getTIFFCompressionTypes:count:

+ (void)getTIFFCompressionTypes:(const NSTIFFCompression **)list count:(int *)numTypes

Returns, by reference, an array of NSTIFFCompressions representing all available compression types that can be used when writing a TIFF image. The number of elements in list is represented by numTypes. list belongs to the NSBitmapImageRep class; it shouldn’t be freed or altered.

The following compression types are supported:

Constant	Value	Usage

NSTIFFCompressionNone	1

NSTIFFCompressionCCITTFAX3	3	1 bps images only

NSTIFFCompressionCCITTFAX4	4	1 bps images only

NSTIFFCompressionLZW	5

NSTIFFCompressionJPEG	6

NSTIFFCompressionNEXT	32766	Input only

NSTIFFCompressionPackBits	32773

NSTIFFCompressionOldJPEG	32865	Input only

Note that not all compression types can be used for all images: NSTIFFCompressionNEXT can be used only to retrieve image data. Because future releases of OpenStep may include other compression types, always use this method to get the available compression types—for example, when you implement a user interface for selecting compression types.

See also:	+ localizedNameForTIFFCompressionType:, − canBeCompressedUsing:

imageRepsWithData:

+ (NSArray *)imageRepsWithData:(NSData *)bitmapData

Creates and returns an array of initialized NSBitmapImageRep objects corresponding to the images in bitmapData. If NSBitmapImageRep is unable to interpret bitmapData, the returned array is empty. bitmapData can contain data in any supported bitmap format.

imageRepWithData:

+ (id)imageRepWithData:(NSData *)bitmapData

Creates and returns an initialized NSBitmapImageRep corresponding to the first image in bitmapData, or nil if NSBitmapImageRep is unable to interpret bitmapData. bitmapData can contain data in any supported bitmap format.

localizedNameForTIFFCompressionType:

+ (NSString *)localizedNameForTIFFCompressionType:(NSTIFFCompression)compression

Returns an autoreleased string containing the localized name for the compression type represented by compression, or nil if compression is unrecognized. Compression types are listed in the getTIFFCompressionTypes:count: class method description. When implementing a user interface for selecting TIFF compression types, use getTIFFCompressionTypes:count: to get the list of supported compression types, then use this method to get the localized names for each compression type.

See also:	+ getTIFFCompressionTypes:count:

TIFFRepresentationOfImageRepsInArray:

+ (NSData *)TIFFRepresentationOfImageRepsInArray:(NSArray *)array

Returns a TIFF representation of the images in array, using the compression that’s returned by getCompression:factor: (if applicable).

If a problem is encountered during generation of the TIFF, TIFFRepresentationOfImageRepsInArray raises an NSTIFFException or an NSBadBitmapParametersException.

See also:	− TIFFRepresentation

TIFFRepresentationOfImageRepsInArray:usingCompression:factor:

+ (NSData *)TIFFRepresentationOfImageRepsInArray:(NSArray *)array usingCompression:(NSTIFFCompression)compression factor:(float)factor

Returns a TIFF representation of the images in array, which are compressed using the specified compression type and factor. Legal values for compression can be found in NSBitmapImageRep.h, and are described in “Tiff Compression” in NSBitmapImageRep’s class description. factor provides a hint for those compression types that implement variable compression ratios; currently only JPEG compression uses a compression factor. If your compression type doesn’t implement variable compression ratios, or if it does and you don’t want the image to be compressed, specify a compression factor of 0.0.

If the specified compression isn’t applicable, no compression is used. If a problem is encountered during generation of the TIFF, TIFFRepresentationOfImageRepsInArray:usingCompression:factor: raises an NSTIFFException or an NSBadBitmapParametersException.

See also:	− TIFFRepresentationUsingCompression:factor:

Instance Methods

bitmapData

− (unsigned char *)bitmapData

Returns a pointer to the bitmap data. If the data is planar, returns a pointer to the first plane.

See also:	− getBitmapDataPlanes:

bitsPerPixel

− (int)bitsPerPixel

Returns the number of bits allocated for each pixel in each plane of data. This is normally equal to the number of bits per sample or, if the data is in meshed configuration, the number of bits per sample times the number of samples per pixel. It can be explicitly set to another value (in the initWithBitmapDataPlanes:pixelsWide:pixelsHigh:... method) in case extra memory is allocated for each pixel. This may be the case, for example, if pixel data is aligned on byte boundaries.

bytesPerPlane

− (int)bytesPerPlane

Returns the number of bytes in each plane or channel of data. This is calculated from the number of bytes per row and the height of the image.

See also:	− bytesPerRow

bytesPerRow

− (int)bytesPerRow

Returns the minimum number of bytes required to specify a scan line (a single row of pixels spanning the width of the image) in each data plane. If not explicitly set to another value (in the initWithBitmapDataPlanes:pixelsWide:pixelsHigh:... method), this will be figured from the width of the image, the number of bits per sample, and, if the data is in a meshed configuration, the number of samples per pixel. It can be set to another value to indicate that each row of data is aligned on word or other boundaries.

See also:	− bytesPerPlane

canBeCompressedUsing:

− (BOOL)canBeCompressedUsing:(NSTIFFCompression)compression

Tests whether the receiver can be compressed by compression type. Legal values for compression can be found in NSBitmapImageRep.h, and are described in “Tiff Compression” in the class description. This method returns YES if the receiver’s data matches compression; for example, if compression is NSTIFFCompressionCCITTFAX3, then the data must be one bit-per-sample and one sample-per-pixel. It returns NO if the data doesn’t match compression or if compression is unsupported.

See also:	+ getTIFFCompressionTypes:count:

getBitmapDataPlanes:

− (void)getBitmapDataPlanes:(unsigned char **)data

Provides access to bitmap data for the image separated into planes. data should be an array of five character pointers. If the bitmap data is in planar configuration, each pointer will be initialized to point to one of the data planes. If there are less than five planes, the remaining pointers will be set to NULL. If the bitmap data is in meshed configuration, only the first pointer will be initialized; the others will be NULL.

Color components in planar configuration are arranged in the expected order—for example, red before green before blue for RGB color. All color planes precede the coverage plane.

See also:	− data, − isPlanar

getCompression:factor:

− (void)getCompression:(NSTIFFCompression *)compression factor:(float *)factor

Returns by reference the receiver’s compression type and compression factor. Use this method to get information on the compression type for the source image data. compression represents the compression type used on the data, and corresponds to one of the values returned by the class method getTIFFCompressionTypes:count:. factor is a value that is specific to the compression type; many types of compression don’t support varying degrees of compression, and thus ignore factor. JPEG compression allows a compression factor ranging from 0.0 to 255.0, with 0.0 representing minimal compression.

initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bytesPerRow:bitsPerPixel:

− (id)initWithBitmapDataPlanes:(unsigned char **)planes pixelsWide:(int)width pixelsHigh:(int)height bitsPerSample:(int)bps samplesPerPixel:(int)spp hasAlpha:(BOOL)alpha isPlanar:(BOOL)isPlanar colorSpaceName:(NSString *)colorSpaceName bytesPerRow:(int)rowBytes bitsPerPixel:(int)pixelBits

Initializes the receiver, a newly allocated NSBitmapImageRep object, so that it can render the image specified in planes and described by the other arguments. If the object can’t be initialized, this method frees it and returns nil. Otherwise, it returns the object (self).

planes is an array of character pointers, each of which points to a buffer containing raw image data. If the data is in planar configuration, each buffer holds one component—one plane—of the data. Color planes are arranged in the standard order—for example, red before green before blue for RGB color. All color planes precede the coverage plane.

If the data is in meshed configuration (isPlanar is NO), only the first buffer is read.

If planes is NULL or if it’s an array of NULL pointers, this method allocates enough memory to hold the image described by the other arguments. You can then obtain pointers to this memory (with the getBitmapDataPlanes: or bitmapData method) and fill in the image data. In this case, the allocated memory will belong to the object and will be freed when it’s freed.

If planes is not NULL and the array contains at least one data pointer, the object will only reference the image data; it won’t copy it. The buffers won’t be freed when the object is freed.

Each of the other arguments (besides planes) informs the NSBitmapImageRep object about the image. They’re explained below:

•	width and height specify the size of the image in pixels. The size in each direction must be greater than 0.

•	bps (bits per sample) is the number of bits used to specify one pixel in a single component of the data. All components are assumed to have the same bits per sample.

•	spp (samples per pixel) is the number of data components. It includes both color components and the coverage component (alpha), if present. Meaningful values range from 1 through 5. An image with cyan, magenta, yellow, and black (CMYK) color components plus a coverage component would have an spp of 5; a gray-scale image that lacks a coverage component would have an spp of 1.

•	alpha should be YES if one of the components counted in the number of samples per pixel (spp) is a coverage component, and NO if there is no coverage component.

•	isPlanar should be YES if the data components are laid out in a series of separate “planes” or channels (“planar configuration”), and NO if component values are interwoven in a single channel (“meshed configuration”).

For example, in meshed configuration, the red, green, blue, and coverage values for the first pixel of an image would precede the red, green, blue, and coverage values for the second pixel, and so on. In planar configuration, red values for all the pixels in the image would precede all green values, which would precede all blue values, which would precede all coverage values.

•	colorSpaceName indicates how data values are to be interpreted. It should be one of the following enumerated values:

NSCalibratedWhiteColorSpace

NSCalibratedBlackColorSpace

NSCalibratedRGBColorSpace

NSDeviceWhiteColorSpace

NSDeviceBlackColorSpace

NSDeviceRGBColorSpace

NSDeviceCMYKColorSpace

NSNamedColorSpace

NSCustomColorSpace

•	rowBytes is the number of bytes that are allocated for each scan line in each plane of data. A scan line is a single row of pixels spanning the width of the image.

Normally, rowBytes can be figured from the width of the image, the number of bits per pixel in each sample (bps), and, if the data is in a meshed configuration, the number of samples per pixel (spp). However, if the data for each row is aligned on word or other boundaries, it may have been necessary to allocate more memory for each row than there is data to fill it. rowBytes lets the object know whether that’s the case. If rowBytes is 0, the NSBitmapImageRep assumes that there’s no empty space at the end of a row.

•	pixelBits informs the NSBitmapImageRep how many bits are actually allocated per pixel in each plane of data. If the data is in planar configuration, this normally equals bps (bits per sample). If the data is in meshed configuration, it normally equals bps times spp (samples per pixel). However, it’s possible for a pixel specification to be followed by some meaningless bits (empty space), as may happen, for example, if pixel data is aligned on byte boundaries. NSBitmapImageRep supports only a limited number of pixelBits values (other than the default): for RGB images with 12 bps, pixelBits may be 16; for RGB images with 24 bps, pixelBits may be 32. The legal values for pixelBits are system dependent.

If pixelBits is 0, the object will interpret the number of bits per pixel to be the expected value, without any meaningless bits.

p	initWithBitmapHandle:

− (id)initWithBitmapHandle:(void *)bitmap

On Microsoft Windows platforms, initWithBitmapHandle: initializes the receiver, a newly allocated NSBitmapImageRep instance, with the contents of the Windows bitmap indicated by bitmap. If initWithBitmapHandle: is able to create one or more image representations, it returns self. Otherwise, the receiver is freed and nil is returned.

initWithData:

− (id)initWithData:(NSData *)bitmapData

Initializes a newly allocated NSBitmapImageRep from the data found in bitmapData. The contents of bitmapData can be any supported bitmap format. For TIFF data, the NSBitmapImageRep is initialized from the first header and image data found in bitmapData.

initWithData: returns an initialized NSBitmapImageRep if the initialization was successful, or nil if it was unable to interpret the contents of bitmapData.

initWithFocusedViewRect:

− (id)initWithFocusedViewRect:(NSRect)rect

Initializes the receiver, a newly allocated NSBitmapImageRep object, with bitmap data read from a rendered image. The image that’s read is located in the current window and is bounded by the rect rectangle as specified in the current coordinate system.

This method uses PostScript imaging operators to read the image data into a buffer; the object is then created from that data. The object is initialized with information about the image obtained from the Window Server.

If for any reason the new object can’t be initialized, this method frees it and returns nil. Otherwise, it returns the initialized object (self).

p	initWithIconHandle:

− (id)initWithIconHandle:(void *)icon

On Microsoft Windows platforms, initWithIconHandle: initializes the receiver, a newly allocated NSBitmapImageRep instance, with the contents of the Windows icon indicated by icon. If initWithIconHandle: is able to create one or more image representations, it returns self. Otherwise, the receiver is freed and nil is returned.

isPlanar

− (BOOL)isPlanar

Returns YES if image data is segregated into a separate plane for each color and coverage component (planar configuration), and NO if the data is integrated into a single plane (meshed configuration).

See also:	− samplesPerPixel

numberOfPlanes

− (int)numberOfPlanes

Returns the number of separate planes that image data is organized into. This is the number of samples per pixel if the data has a separate plane for each component (isPlanar returns YES) and 1 if the data is meshed (isPlanar returns NO).

See also:	− samplesPerPixel, − hasAlpha (NSImageRep), − bitsPerSample (NSImageRep)

samplesPerPixel

− (int)samplesPerPixel

Returns the number of components in the data. It includes both color components and the coverage component, if present.

See also:	− hasAlpha (NSImageRep), − bitsPerSample (NSImageRep)

setCompression:factor:

− (void)setCompression:(NSTIFFCompression)compression factor:(float)factor

Sets the receiver’s compression type and compression factor. compression is one of the supported compression types listed in the getTiffCompressionTypes:count: class method description. factor is a value that is specific to the compression type; many types of compression don’t support varying degrees of compression, and thus ignore factor. JPEG compression allows a compression factor ranging from 0.0 to 255.0, with 0.0 representing minimal compression.

When an NSBitmapImageRep is created, the instance stores the compression type and factor for the source data. TIFFRepresentation and TIFFRepresentationOfImageRepsInArray: (class method) try to use the stored compression type and factor. Use this method to change the compression type and factor.

See also:	− canBeCompressedUsing:

TIFFRepresentation

− (NSData *)TIFFRepresentation

Returns a TIFF representation of the image, using the compression that’s returned by getCompression:factor: (if applicable). This method invokes TIFFRepresentationUsingCompression:factor: using the stored compression type and factor retrieved from the initial image data or changed using setCompression:factor:. If the stored compression type isn’t supported for writing TIFF data (for example, NSTIFFCompressionNEXT), the stored compression is changed to NSTIFFCompressionNone and the compression factor to 0.0 before invoking TIFFRepresentationUsingCompression:factor:.

If a problem is encountered during generation of the TIFF, TIFFRepresentation raises an NSTIFFException or an NSBadBitmapParametersException.

See also:	+ TIFFRepresentationOfImageRepsInArray:

TIFFRepresentationUsingCompression:factor:

− (NSData *)TIFFRepresentationUsingCompression:(NSTIFFCompression)comp factor:(float)factor

Returns a TIFF representation of the image, using the specified compression and factor. If the stored compression type isn’t supported for writing TIFF data (for example, NSTIFFCompressionNEXT), the stored compression is changed to NSTIFFCompressionNone and the compression factor to 0.0 before the TIFF representation is generated.

If a problem is encountered during generation of the TIFF, TIFFRepresentation raises an NSTIFFException or an NSBadBitmapParametersException.

See also:	− canBeCompressedUsing:, + TIFFRepresentationOfImageRepsInArray:


NSBox

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSView : NSResponder : NSObject

Conforms To:	NSCoding (from NSResponder)

NSObject (from NSObject)

Declared In:	AppKit/NSBox.h

Class Description

An NSBox object is a simple NSView that can do two things: It can draw a border around itself and it can title itself. You can use an NSBox to group, visually, some number of other NSViews. These other NSViews are added to the NSBox through the typical subview-adding methods, such as addSubview: and replaceSubview:with:.

An NSBox contains a content area, a rectangle set within the NSBox’s frame in which the NSBox’s subviews are displayed. The size and location of the content area depends on the NSBox’s border type, title location, the size of the font used to draw the title, and an additional measure that you can set through the setContentViewMargins: method. When you create an NSBox, an instance of NSView is created and added (as a subview of the NSBox object) to fill the NSBox’s content area. If you replace this content view with an NSView of your own, your NSView will be resized to fit the content area. Similarly, as you resize an NSBox its content view is automatically resized to fill the content area.

The NSViews that you add as subviews to an NSBox are actually added to the NSBox’s content view—NSView’s subview-adding methods are redefined by NSBox to ensure that a subview is correctly placed in the view hierarchy. However, you should note that the subviews method isn’t redefined: It returns an NSArray containing a single object, the NSBox’s content view.

Method Types

Getting and modifying the border and title

− borderRect

− borderType

− setBorderType:

− setTitle:

− setTitleFont:

− setTitlePosition:

− setTitleWithMnemonic:

− title

− titleCell

− titleFont

− titlePosition

− titleRect

Setting and placing the content view

− contentView

− contentViewMargins

− setContentView:

− setContentViewMargins:

Resizing the box	− setFrameFromContentFrame:

− sizeToFit

Instance Methods

borderRect

− (NSRect)borderRect

Returns the rectangle in which the border is drawn.

borderType

− (NSBorderType)borderType

Returns the NSBox’s border type. Border types are defined in NSView.h; currently, the following border types are defined:

NSNoBorder

NSLineBorder

NSBezelBorder

NSGrooveBorder

By default, an NSBox’s border type is NSGrooveBorder.

contentView

− (id)contentView

Returns the NSBox’s content view. The content view is created automatically when the box is created, and resized as the box is resized (you should never send frame-altering messages directly to a box’s content view). You can replace it with an NSView of your own through the setContentView: method.

contentViewMargins

− (NSSize)contentViewMargins

Returns the distances between the border and the content view. By default, on Mach systems both the width (the horizontal distance between the innermost edge of the border and the content view) and the height (the vertical distance between the innermost edge of the border and the content view) of the returned NSSize are 5.0 in the box’s coordinate system.

setBorderType:

− (void)setBorderType:(NSBorderType)aType

Sets the border type to aType, which must be a valid border type. Border types are defined in NSView.h; currently, the following border types are defined:

NSNoBorder

NSLineBorder

NSBezelBorder

NSGrooveBorder

If the size of the new border is different from that of the old border, the content view is resized to absorb the difference and the box is marked for redisplay.

See also:	− setNeedsDisplay: (NSView)

setContentView:

− (void)setContentView:(NSView *)aView

Sets the NSBox’s content view to aView, resizing the NSView to fit within the box’s current content area. The box is marked for redisplay.

See also:	− setFrameFromContentFrame:, − sizeToFit:, − setNeedsDisplay: (NSView)

setContentViewMargins:

− (void)setContentViewMargins:(NSSize)offsetSize

Sets the horizontal and vertical distance between the border of the NSBox and its content view. The horizontal value is applied (reckoned in the box’s coordinate system) fully and equally to the left and right sides of the box. The vertical value is similarly applied to the top and bottom.

Unlike changing a box’s other attributes, such as its title position or border type, changing the offsets doesn’t automatically resize the content view. In general, you should send a sizeToFit message to the box after changing the size of its offsets. This causes the content view to remain unchanged while the box is sized to fit around it.

setFrameFromContentFrame:

− (void)setFrameFromContentFrame:(NSRect)contentFrame

Places the NSBox so its content view lies on contentFrame, reckoned in the coordinate system of the box’s superview. The box is marked for redisplay.

See also:	− setContentViewMargins:, − setFrame: (NSView), − setNeedsDisplay (NSView)

setTitle:

− (void)setTitle:(NSString *)aString

Sets the title to aString, and marks the region of the receiver within the title rectangle as needing display. By default, an NSBox’s title is “Title”. If the size of the new title is different from that of the old title, the content view is resized to absorb the difference.

See also:	− setNeedsDisplayInRect: (NSView), − titleRect

setTitleFont:

− (void)setTitleFont:(NSFont *)aFont

Sets aFont as the NSFont object used to draw the NSBox’s title, and marks the region of the receiver within the title rectangle as needing display. On Mach systems the title is drawn using the 12.0 point system font by default. If the size of the new font is different from that of the old font, the content view is resized to absorb the difference.

See also:	− setNeedsDisplayInRect: (NSView)

setTitlePosition:

− (void)setTitlePosition:(NSTitlePosition)aPosition

Sets the title position to aPosition, which can be one of the values listed in the following table. The default position is NSAtTop.

Value	Meaning

NSNoTitle	The box has no title

NSAboveTop	Title positioned above the box’s top border

NSAtTop	Title positioned within the box’s top border

NSBelowTop	Title positioned below the box’s top border

NSAboveBottom	Title positioned above the box’s bottom border

NSAtBottom	Title positioned within the box’s bottom border

NSBelowBottom	Title positioned below the box’s bottom border

If the new title position changes the size of the box’s border area, the content view is resized to absorb the difference, and the box is marked as needing redisplay.

See also:	− setNeedsDisplay: (NSView)

p	setTitleWithMnemonic:

− (void)setTitleWithMnemonic:(NSString *)aString

Sets the title to aString, taking into account the fact that an embedded “&” character is not a literal but instead marks the title’s “mnemonic.” The character immediately following the “&” character will be underlined.

By default, an NSBox’s title is “Title”. The content view is not automatically resized, and the box is not marked for redisplay.

See also:	− setTitleWithMnemonic: (NSCell)

sizeToFit

− (void)sizeToFit

Resizes and moves the NSBox’s content view so that it just encloses its subviews. The box itself is then moved and resized to wrap around the content view. The box’s width is constrained so its title will be fully displayed.

You should invoke this method after:

•	Adding a subview (to the content view).

•	Altering the size or location of such a subview.

•	Setting the margins around the content view.

The mechanism by which the content view is moved and resized depends on whether the object responds to its own sizeToFit message: If it does respond, then that message is sent and the content view is expected to be so modified. If the content view doesn’t respond, the box moves and resizes the content view itself.

title

− (NSString *)title

Returns the NSBox’s title. By default, a box’s title is “Title”.

titleCell

− (id)titleCell

Returns the NSCell that’s used to display the NSBox’s title.

titleFont

− (NSFont *)titleFont

Returns the NSFont that’s used to draw the NSBox’s title. On Mach systems the title is drawn using the 12.0 point system font by default.

titlePosition

− (NSTitlePosition)titlePosition

Returns a constant representing the title position. See the description of setTitlePosition: for a list of the title position constants.

titleRect

− (NSRect)titleRect

Returns the rectangle in which the NSBox’s title is drawn.

See also:	 − setTitlePosition, − setTitle, − setTitleFont, − setFrameFromContentFrame:,

 − sizeToFit


NSBrowser

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSControl : NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSBrowser.h

Class Description

NSBrowser provides a user interface for displaying and selecting items from a list of data, or from hierarchically organized lists of data such as directory paths. When working with a hierarchy of data, the levels are displayed in columns, which are numbered from left to right, beginning with 0. Each column consists of an NSScrollView containing an NSMatrix filled with NSBrowserCells. NSBrowser relies on a delegate to provide the data in its NSBrowserCells. See the NSBrowserCell class description for more on its implementation.

Browser Selection

An entry in an NSBrowser’s column can be either a branch node (such as a directory) or a leaf node (such as a file). When the user selects a single branch node entry in a column, the NSBrowser sends itself the addColumn message, which messages its delegate to load the next column. The user’s selection can be represented as a character string; if the selection is hierarchical (for example, a filename within a directory), each component of the path to the selected node is separated by “/”. To use some other character as the delimiter, invoke setPathSeparator:.

An NSBrowser can be set to allow selection of multiple entries in a column, or to limit selection to a single entry. When set for multiple selection, it can also be set to limit multiple selection to leaf nodes only, or to allow selection of both types of nodes together.

As a subclass of NSControl, NSBrowser has a target object and action message. Each time the user selects one or more entries in a column, the action message is sent to the target. NSBrowser also adds an action to be sent when the user double-clicks on an entry, which allows the user to select items without any action being taken, and then double-click to invoke some useful action such as opening a file.

User Interface Features

The user interface features of an NSBrowser can be changed in a number of ways. The NSBrowser may or may not have a horizontal scroller. (The NSBrowser’s columns, by contrast, always have vertical scrollers—although a scroller’s buttons and knob might be invisible if the column doesn’t contain many entries.) You generally shouldn’t create an NSBrowser without a horizontal scroller; if you do, you must make sure the bounds rectangle of the NSBrowser is wide enough that all the columns can be displayed. An NSBrowser’s columns may be bordered and titled, bordered and untitled, or unbordered and untitled. A column’s title may be taken from the selected entry in the column to its left, or may be provided explicitly by the NSBrowser or its delegate.

NSBrowser’s Delegate

NSBrowser requires a delegate to provide it with data to display. The delegate is responsible for providing the data and for setting each item as a branch or leaf node, enabled or disabled. It can also receive notification of events like scrolling and requests for validation of columns that may have changed.

You can implement one of two delegate types: active or passive. An active delegate creates a column’s rows (that is, the NSBrowserCells) itself, while a passive one leaves that job to the NSBrowser. Normally, passive delegates are preferable, because they’re easier to implement. An active delegate must implement browser:createRowsForColumn:inMatrix: to create the rows of the specified column. A passive delegate, on the other hand, must implement browser:numberOfRowsInColumn: to let the NSBrowser know how many rows to create. These two methods are mutually exclusive; you can implement one or the other, but not both. (The NSBrowser ascertains what type of delegate it has by which method the delegate responds to.)

Both types of delegate implement browser:willDisplayCell:atRow:column: to set up state (such as the cell’s string value and whether the cell is a leaf or a branch) before an individual cell is displayed. (This delegate method doesn’t need to invoke NSBrowserCell’s setLoaded: method, because the NSBrowser can determine that state by itself.) An active delegate can instead set all the cells’ state at the time the cells are created, in which case it doesn’t need to implement browser:willDisplayCell:atRow:column:. However, a passive delegate must always implement this method.

Method Types

Setting component classes	+ cellClass

− setCellClass:

− cellPrototype

− setCellPrototype:

− matrixClass

− setMatrixClass:

Getting matrices,  cells, and rows	− selectedCell

− selectedCellInColumn:

− selectedCells

− selectAll:

− selectedRowInColumn:

− selectRow:inColumn:

− loadedCellAtRow:column:

− matrixInColumn:

Getting and setting paths	− path

− setPath:

− pathToColumn:

− pathSeparator

− setPathSeparator:

Manipulating columns	− addColumn

− displayAllColumns

− displayColumn:

− columnOfMatrix:

− selectedColumn

− lastColumn

− setLastColumn:

− firstVisibleColumn

− numberOfVisibleColumns

− lastVisibleColumn

− validateVisibleColumns

Loading columns	− isLoaded

− loadColumnZero

− reloadColumn:

Setting selection characteristics	− allowsBranchSelection

− setAllowsBranchSelection:

− allowsEmptySelection

− setAllowsEmptySelection:

− allowsMultipleSelection

− setAllowsMultipleSelection:

Setting column characteristics	− reusesColumns

− setReusesColumns:

− maxVisibleColumns

− setMaxVisibleColumns:

− minColumnWidth

− setMinColumnWidth:

− separatesColumns

− setSeparatesColumns:

− takesTitleFromPreviousColumn

− setTakesTitleFromPreviousColumn:

Manipulating column titles	− titleOfColumn:

− setTitle:ofColumn:

− isTitled

− setTitled:

− drawTitle:inRect:ofColumn:

− titleHeight

− titleFrameOfColumn:

Scrolling an NSBrowser	− scrollColumnToVisible:

− scrollColumnsLeftBy:

− scrollColumnsRightBy:

− updateScroller

− scrollViaScroller:

Showing a horizontal scroller	− hasHorizontalScroller

− setHasHorizontalScroller:

Setting the behavior of arrow keys	− acceptsArrowKeys

− setAcceptsArrowKeys:

− sendsActionOnArrowKeys

− setSendsActionOnArrowKeys:

Getting column frames	− frameOfColumn:

− frameOfInsideOfColumn:

Arranging browser components	− tile

Setting the delegate	− delegate

− setDelegate:

Target and action	− doubleAction

− setDoubleAction:

− sendAction

Event handling	− doClick:

− doDoubleClick:

Class Methods

cellClass

+ (Class)cellClass

Returns the NSBrowserCell class (regardless of whether a setCellClass: message has been sent to a particular instance)

See also:	− cellPrototype,− setCellPrototype:

Instance Methods

acceptsArrowKeys

− (BOOL)acceptsArrowKeys

Returns YES if the arrow keys are enabled.

See also:	− setAcceptsArrowKeys:

addColumn

− (void)addColumn

Adds a column to the right of the last column.

See also:	− columnOfMatrix:, − displayColumn:, − selectedColumn

allowsBranchSelection

− (BOOL)allowsBranchSelection

Returns whether the user can select branch items when multiple selection is enabled.

See also:	− setAllowsBranchSelection:

allowsEmptySelection

− (BOOL)allowsEmptySelection

Returns whether there can be nothing selected.

See also:	− setAllowsEmptySelection:

allowsMultipleSelection

− (BOOL)allowsMultipleSelection

Returns whether the user can select multiple items.

See also:	− setAllowsMultipleSelection:

cellPrototype

− (id)cellPrototype

Returns the NSBrowser’s prototype NSCell.

See also:	− setCellPrototype:, − setCellClass:

columnOfMatrix:

− (int)columnOfMatrix:(NSMatrix *)matrix

Returns the column number in which matrix is located.

See also:	− matrixInColumn:

delegate

− (id)delegate

Returns the NSBrowser’s delegate.

See also:	− setDelegate:

displayAllColumns

− (void)displayAllColumns

Updates the NSBrowser to display all loaded columns.

See also:	− addColumn, − validateVisibleColumns

displayColumn:

− (void)displayColumn:(int)column

Updates the NSBrowser to display the column with the given index.

See also:	− addColumn, − validateVisibleColumns

doClick:

− (void)doClick:(id)sender

Responds to (single) mouse clicks in a column of the NSBrowser.

See also:	− sendAction

doDoubleClick:

− (void)doDoubleClick:(id)sender

Responds to double-clicks in a column of the NSBrowser.

See also:	− setDoubleAction:

doubleAction

− (SEL)doubleAction

Returns the NSBrowser’s double-click action method.

See also:	− setDoubleAction:

drawTitle:inRect:ofColumn:

− (void)drawTitle:(NSString *)title inRect:(NSRect)aRect ofColumn:(int)column

Draws the title for the column at index column.

See also:	− titleFrameOfColumn:, − titleHeight

firstVisibleColumn

− (int)firstVisibleColumn

Returns the index of the first visible column.

See also:	− lastVisibleColumn, − numberOfVisibleColumns

frameOfColumn:

− (NSRect)frameOfColumn:(int)column

Returns the rectangle containing the column at index column.

frameOfInsideOfColumn:

− (NSRect)frameOfInsideOfColumn:(int)column

Returns the rectangle containing the column at index column, not including borders.

hasHorizontalScroller

− (BOOL)hasHorizontalScroller

Returns whether an NSScroller is used to scroll horizontally.

See also:	− setHasHorizontalScroller:

isLoaded

− (BOOL)isLoaded

Returns whether column zero is loaded.

See also:	− loadColumnZero, − reloadColumn:

isTitled

− (BOOL)isTitled

Returns whether columns display titles.

See also:	− setTitled:

lastColumn

− (int)lastColumn

Returns the index of the last column loaded.

See also:	− selectedColumn, − setLastColumn:

lastVisibleColumn

− (int)lastVisibleColumn

Returns the index of the last visible column.

See also:	− firstVisibleColumn, − numberOfVisibleColumns

loadColumnZero

− (void)loadColumnZero

Loads column zero; unloads previously loaded columns.

See also:	− isLoaded, − reloadColumn:

loadedCellAtRow:column:

− (id)loadedCellAtRow:(int)row column:(int)column

Loads if necessary and returns the NSCell at row in column.

See also:	− selectedCellInColumn:

matrixClass

− (Class)matrixClass

Returns the class of NSMatrix used in the NSBrowser’s columns.

See also:	− setMatrixClass:

matrixInColumn:

− (NSMatrix *)matrixInColumn:(int)column

Returns the matrix located in the column identified by index column.

maxVisibleColumns

− (int)maxVisibleColumns

Returns the maximum number of visible columns.

See also:	− setMaxVisibleColumns:

minColumnWidth

− (float)minColumnWidth

Returns the minimum column width in pixels.

See also:	− setMinColumnWidth:

numberOfVisibleColumns

− (int)numberOfVisibleColumns

Returns the number of columns visible.

See also:	− validateVisibleColumns

path

− (NSString *)path

Returns the browser’s current path.

See also:	− setPath:

pathSeparator

− (NSString *)pathSeparator

Returns the path separator. The default is “/”.

See also:	− setPathSeparator:

pathToColumn:

− (NSString *)pathToColumn:(int)column

Returns a string representing the path from the first column to the column at index column.

See also:	− path, − setPath:

reloadColumn:

− (void)reloadColumn:(int)column

Reloads column if it is loaded; sets it as the last column.

See also:	− isLoaded, − loadColumnZero

reusesColumns

− (BOOL)reusesColumns

Returns YES if NSMatrix objects aren’t freed when their columns are unloaded.

See also:	− setReusesColumns

scrollColumnToVisible:

− (void)scrollColumnToVisible:(int)column

Scrolls to make the column at index column visible.

See also:	− scrollViaScroller:, − updateScroller

scrollColumnsLeftBy:

− (void)scrollColumnsLeftBy:(int)shiftAmount

Scrolls columns left by shiftAmount columns.

See also:	− scrollViaScroller:, − updateScroller

scrollColumnsRightBy:

− (void)scrollColumnsRightBy:(int)shiftAmount

Scrolls columns right by shiftAmount columns.

See also:	− scrollViaScroller:, − updateScroller

scrollViaScroller:

− (void)scrollViaScroller:(NSScroller *)sender

Scrolls columns left or right based on an NSScroller.

See also:	− updateScroller

selectAll:

− (void)selectAll:(id)sender

Selects all NSCells in the last column of the NSBrowser.

See also:	− selectedCell, − selectedCells, − selectedColumn

selectRow:inColumn:

− (void)selectRow:(int)row inColumn:(int)column

Selects the cell at index row in the column identified by index column.

See also:	− loadedCellAtRow:column:, − selectedRowInColumn:

selectedCell

− (id)selectedCell

Returns the last (rightmost and lowest) selected NSCell.

See also:	− loadedCellAtRow:column:, − selectedCells, − selectRow:inColumn:

selectedCellInColumn:

− (id)selectedCellInColumn:(int)column

Returns the last (lowest) NSCell that’s selected in column.

See also:	− loadedCellAtRow:column:, − selectedCell, − selectedRowInColumn:

selectedCells

− (NSArray *)selectedCells

Returns all cells selected in the rightmost column.

See also:	− selectAll:, − selectedCell

selectedColumn

− (int)selectedColumn

Returns the index of the last column with a selected item.

See also:	− columnOfMatrix, − selectAll:

selectedRowInColumn:

− (int)selectedRowInColumn:(int)column

Returns the row index of the selected cell in the column specified by index column.

See also:	− loadedCellAtRow:column:, − selectedCell, − selectedCellInColumn:

sendAction

− (BOOL)sendAction

Sends the action message to the target. Returns YES upon success, NO if no target for the message could be found.

sendsActionOnArrowKeys

− (BOOL)sendsActionOnArrowKeys

Returns NO if pressing an arrow key only scrolls the browser, YES if it also sends the action message specified by setAction:.

See also:	 − acceptsArrowKeys, − setSendsActionOnArrayKeys:

separatesColumns

− (BOOL)separatesColumns

Returns whether columns are separated by bezeled borders.

See also:	− setSeparatesColumns:

setAcceptsArrowKeys:

− (void)setAcceptsArrowKeys:(BOOL)flag

Enables or disables the arrow keys as used for navigating within and between browsers.

See also:	− acceptsArrowKeys, − sendsActionOnArrowKeys

setAllowsBranchSelection:

− (void)setAllowsBranchSelection:(BOOL)flag

Sets whether the user can select branch items when multiple selection is enabled.

See also:	− allowsBranchSelection

setAllowsEmptySelection:

− (void)setAllowsEmptySelection:(BOOL)flag

Sets whether there can be nothing selected.

See also:	− allowsEmptySelection

setAllowsMultipleSelection:

− (void)setAllowsMultipleSelection:(BOOL)flag

Sets whether the user can select multiple items.

See also:	− allowsMultipleSelection

setCellClass:

− (void)setCellClass:(Class)factoryId

Sets the class of NSCell used in the columns of the NSBrowser.

See also:	+ cellClass:, − cellPrototype

setCellPrototype:

− (void)setCellPrototype:(NSCell *)aCell

Sets the NSCell instance copied to display items in the columns of NSBrowser.

See also:	+ cellClass:, − cellPrototype

setDelegate:

− (void)setDelegate:(id)anObject

Sets the NSBrowser’s delegate to anObject. Raises NSBrowserIllegalDelegateException if the delegate specified by anObject doesn’t respond to browser:willDisplayCell:atRow:column: and either of the methods browser:numberOfRowsInColumn: or browser:createRowsForColumn:inMatrix:.

See also:	− delegate

setDoubleAction:

− (void)setDoubleAction:(SEL)aSelector

Sets the NSBrowser’s double-click action to aSelector.

See also:	− doubleAction, − sendAction

setHasHorizontalScroller:

− (void)setHasHorizontalScroller:(BOOL)flag

Sets whether an NSScroller is used to scroll horizontally.

See also:	− hasHorizontalScroller

setLastColumn:

− (void)setLastColumn:(int)column

Sets the last column to column.

See also:	− lastColumn, − lastVisibleColumn

setMatrixClass:

− (void)setMatrixClass:(Class)factoryId

Sets the matrix class (NSMatrix or an NSMatrix subclass) used in the NSBrowser’s columns.

See also:	− matrixClass

setMaxVisibleColumns:

− (void)setMaxVisibleColumns:(int)columnCount

Sets the maximum number of columns displayed.

See also:	− maxVisibleColumns

setMinColumnWidth:

− (void)setMinColumnWidth:(float)columnWidth

Sets the minimum column width in pixels.

See also:	− minColumnWidth

setPath:

− (BOOL)setPath:(NSString *)path

Parses path and selects corresponding items in the NSBrowser columns.

See also:	− path, − pathToColumn:

setPathSeparator:

− (void)setPathSeparator:(NSString *)newString

Sets the path separator to newString.

See also:	− pathSeparator

setReusesColumns:

− (void)setReusesColumns:(BOOL)flag

If flag is YES, prevents NSMatrix objects from being freed when their columns are unloaded, so they can be reused.

See also:	− resusesColumns

setSendsActionOnArrowKeys:

− (void)setSendsActionOnArrowKeys:(BOOL)flag

Sets whether pressing an arrow key will cause the action message to be sent (in addition to causing scrolling).

See also:	− sendsActionOnArrowKeys

setSeparatesColumns:

− (void)setSeparatesColumns:(BOOL)flag

Sets whether to separate columns with bezeled borders.

See also:	− separatesColumns

setTakesTitleFromPreviousColumn:

− (void)setTakesTitleFromPreviousColumn:(BOOL)flag

Sets whether the title of a column is set to the string value of the selected NSCell in the previous column.

See also:	− takesTitleFromPreviousColumn:

setTitle:ofColumn:

− (void)setTitle:(NSString *)aString ofColumn:(int)column

Sets the title of the column at index column to aString.

See also:	− titleOfColumn:

setTitled:

− (void)setTitled:(BOOL)flag

Sets whether columns display titles.

See also:	− isTitled

takesTitleFromPreviousColumn

− (BOOL)takesTitleFromPreviousColumn

Returns YES if the title of a column is set to the string value of the selected NSCell in the previous column.

See also:	− setTakesTitleFromPreviousColumn:

tile

− (void)tile

Adjusts the various subviews of NSBrowser—scrollers, columns, titles, and so on—without redrawing.  Your code shouldn’t send this message.  It’s invoked any time the appearance of the NSBrowser changes.

titleFrameOfColumn:

− (NSRect)titleFrameOfColumn:(int)column

Returns the bounds of the title frame for the column at index column.

See also:	− drawTitle:inRect:ofColumn:

titleHeight

− (float)titleHeight

Returns the height of column titles.

See also:	− drawTitle:inRect:ofColumn:

titleOfColumn:

− (NSString *)titleOfColumn:(int)column

Returns the title displayed for the column at index column.

See also:	− setTitle:ofColumn:

updateScroller

− (void)updateScroller

Updates the horizontal scroller to reflect column positions.

See also:	− scrollViaScroller:

validateVisibleColumns

− (void)validateVisibleColumns

Invokes delegate method browser:isColumnValid: for visible columns.

See also:	− numberOfVisibleColumn

Methods Implemented By the Delegate

browser:createRowsForColumn:inMatrix:

− (void)browser:(NSBrowser *)sender

createRowsForColumn:(int)column

inMatrix:(NSMatrix *)matrix

Creates a row in matrix for each row of data to be displayed in column of the browser. Either this method or browser:numberOfRowsInColumn: must be implemented, but not both (or an NSBrowserIllegalDelegateException will be raised).

See also:	− browser:willDisplayCell:atRow:column:

browser:isColumnValid:

− (BOOL)browser:(NSBrowser *)sender isColumnValid:(int)column

Returns whether the contents of the specified column are valid. If NO is returned, sender reloads the column. This method is invoked in response to validateVisibleColumns being sent to sender.

browser:numberOfRowsInColumn:

− (int)browser:(NSBrowser *)sender numberOfRowsInColumn:(int)column

Returns the number of rows of data in the column at index column. Either this method or browser:createRowsForColumn:inMatrix: must be implemented, but not both.

See also:	− browser:willDisplayCell:atRow:column:

browser:selectCellWithString:inColumn:

− (BOOL)browser:(NSBrowser *)sender

selectCellWithString:(NSString *)title

inColumn:(int)column

Asks the delegate to select the NSCell with title title in the column at index column. If the delegate returns NO, the NSCell is not selected.

See also:	− selectedCellInColumn:

browser:selectRow:inColumn:

− (BOOL)browser:(NSBrowser *)sender

selectRow:(int)row

inColumn:(int)column

Asks the delegate to select the NSCell at row row in the column at index column. If the delegate returns NO, the NSCell is not selected.

See also:	− selectedRowInColumn:, − selectRow:inColumn:

browser:titleOfColumn:

− (NSString *)browser:(NSBrowser *)sender titleOfColumn:(int)column

Asks the delegate for the title to display above the column at index column.

See also:	− setTitle:ofColumn:, − titleOfColumn:

browser:willDisplayCell:atRow:column:

− (void)browser:(NSBrowser *)sender

willDisplayCell:(id)cell

atRow:(int)row

column:(int)column

Notifies the delegate before the NSBrowser displays the specified cell at row in column. The delegate should set any state necessary for the correct display of the cell.

See also:	− browser:createRowsForColumn:inMatrix:, − browser:numberOfRowsInColumn:

browserDidScroll:

− (void)browserDidScroll:(NSBrowser *)sender

Notifies the delegate when the NSBrowser has scrolled.

browserWillScroll:

− (void)browserWillScroll:(NSBrowser *)sender

Notifies the delegate when the NSBrowser will scroll.


NSBrowserCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSCell : NSObject

Conforms To:	NSCoding, NSCopying (NSCell)

NSObject (NSObject)

Declared In:	AppKit/NSBrowserCell.h

Class Description

NSBrowserCell is the subclass of NSCell used by default to display data in the columns of an NSBrowser. (Each column contains an NSMatrix filled with NSBrowserCells.) An NSBrowserCell can be a leaf or branch cell. A branch cell displays an image indicating that, when the cell is clicked, the NSBrowser will display a new column of NSBrowserCells; branch cells are thus important to the display of hierarchical information typical of NSBrowsers. An NSBrowserCell can also be loaded or unloaded; loaded NSBrowserCells have their state set and are ready for display.

Many of NSBrowserCell’s methods are designed to interact with NSBrowser and NSBrowser’s delegate. The delegate implements methods for loading the NSCells in NSBrowser by setting their values and status. If your code needs access to a specific NSBrowserCell, you can use the NSBrowser method loadedCellAtRow:column:.

Because NSBrowserCells do not inherit from NSActionCell, they don’t hold target and action values and thus don’t participate in the target/action paradigm of the Application Kit. However, NSBrowser does allow you to specify a target and an action, and you can obtain the last selected NSBrowserCell by sending selectedCell to an NSBrowser.

You may find it useful to create a subclass of NSBrowserCell to alter its behavior and to enable it to work with and display the type of data you wish to represent. Use NSBrowser’s setCellClass: or setCellPrototype: methods to have it use your subclass.

See the NSBrowser class specification for more details. In particular, the class description and the “Methods Implemented by the Delegate” section describe how the NSBrowser’s delegate interacts with both NSBrowser and NSBrowserCells.

Method Types

Accessing graphic images	+ branchImage

+ highlightedBranchImage

− alternateImage

− setAlternateImage:

Setting state 	− reset

− set

Determining cell attributes	− isLeaf

− setLeaf:

− isLoaded

− setLoaded

Class Methods

branchImage

+ (NSImage *)branchImage

Returns the default NSImage for branch NSBrowserCells (a right-pointing triangle).

See also:	− alternateImage, + highlightedBranchImage, − setAlternateImage:

highlightedBranchImage

+ (NSImage *)highlightedBranchImage

Returns the default NSImage for branch NSBrowserCells that are highlighted (a lighter version of the image returned by branchImage).

See also:	+ branchImage, − alternateImage, − setAlternateImage:

Instance Methods

alternateImage

− (NSImage *)alternateImage

Returns this NSBrowserCell’s image for the highlighted state or nil if no image is set.

See also:	− setAlternateImage:

isLeaf

− (BOOL)isLeaf

Returns whether the NSBrowserCell is a leaf or a branch cell. A branch NSBrowserCell has an image near its right edge indicating that more, hierarchically related information is available; when the user selects the cell, the NSBrowser displays a new column of NSBrowserCells. A leaf NSBrowserCell has no image, indicating that the user has reached a terminal piece of information; it doesn’t point to additional information.

See also:	− setLeaf:

isLoaded

− (BOOL)isLoaded

Returns YES if all the NSBrowserCell’s state has been set and the cell is ready to display.

See also:	− setLoaded:

reset

− (void)reset

Unhighlights the NSBrowserCell and sets its state to 0 (NO).

See also:	− set

set

− (void)set

Highlights the NSBrowserCell and sets its state to 1 (YES).

See also:	− reset

setAlternateImage:

− (void)setAlternateImage:(NSImage *)newAltImage

Sets this NSBrowserCell’s image for the highlighted state, retaining the image. If newAltImage is nil, it removes the alternate image for the NSBrowserCell.

See also:	− alternateImage

setLeaf:

− (void)setLeaf:(BOOL)flag

Sets whether the NSBrowserCell is a leaf or a branch cell. A branch NSBrowserCell has an image near its right edge indicating that more, hierarchically related information is available; when the user selects the cell, the NSBrowser displays a new column of NSBrowserCells. A leaf NSBrowserCell has no image, indicating that the user has reached a terminal piece of information; it doesn’t point to additional information.

See also:	− isLeaf

setLoaded:

− (void)setLoaded:(BOOL)flag

Sets whether the NSBrowserCell’s state has been set to 1 (YES) and the cell is ready to display.

See also:	− isLoaded


NSBundle Additions

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Declared In:	AppKit/NSImage.h

AppKit/NSNibLoading.h

Class Description

This “class” is really two categories that add three methods to the Foundation Framework’s NSBundle class. One method, pathForImageResource:, is used to locate image resources. The remaining two methods are used to load nib files.

Note:	These methods become part of the NSBundle class only for those applications that use the Application Kit.

For information on bundles, see the NSBundle class specification in the Foundation Framework Reference.

Method Types

Loading nib files	+ loadNibFile:externalNameTable:withZone:

+ loadNibNamed:owner:

Locating NSImage resources	− pathForImageResource:

Class Methods

loadNibFile:externalNameTable:withZone:

+ (BOOL)loadNibFile:(NSString *)fileName externalNameTable:(NSDictionary *)context withZone:(NSZone *)zone

Unarchives the contents of the nib file whose absolute path is fileName. Objects from the nib file are allocated in the memory zone specified by zone. The context argument is a name table—a dictionary whose keys are names like “NSOwner” and whose values are existing objects that can be referenced by the newly unarchived objects. Returns YES upon success, or NO if the specified nib file couldn’t be loaded.

This method is declared in NSNibLoading.h.

loadNibNamed:owner:

+ (BOOL)loadNibNamed:(NSString *)aNibName owner:(id)owner

Similar to loadNibFile:externalNameTable:withZone:, but the name table’s only element is the object specified by owner (stored with the key “NSOwner”). Objects from the nib file are allocated in owner’s zone. If there’s a bundle for owner’s class, this method looks in that bundle for the nib file named aNibName (this argument need not include the “.nib” extension); otherwise, it looks in the main bundle.

This method is declared in NSNibLoading.h.

See also:	+ bundleForClass: (NSBundle)

Instance Methods

pathForImageResource:

− (NSString *)pathForImageResource:(NSString *)name

Returns the absolute pathname of the file containing the specified image resource, or nil if the specified resource can’t be located. Image resources are those files in the bundle which are recognized by NSImage without filtering (essentially, a file whose type is one of those returned by the imageUnfilteredFileTypes method). The resource name is simply the filename without the path of its bundle directory; the filename extension is optional.

This method is declared in NSImage.h.

See also:	− pathForResource:ofType: (NSBundle)

*nil*


NSButton

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSControl : NSView : NSResponder : NSObject

Conforms To:	NSCoding (from NSResponder)

NSObject (from NSObject)

Declared In:	AppKit/NSButton.h

Class Description

NSButton is a subclass of NSControl that intercepts mouse-down events and sends an action message to a target object when it’s clicked or pressed. By virtue of its NSButtonCell, NSButton is a two-state NSControl—it’s either “off” or “on”—and it displays its state depending on the configuration of the NSButtonCell. NSButton acquires other attributes of NSButtonCell. The state is used as the value, so NSControl methods like setIntValue: actually set the state (the methods setState: and state are provided as a more conceptually accurate way of setting and getting the state). The NSButton can send its action continuously and display highlighting in several different ways. What’s more, an NSButton can have a key equivalent that’s eligible for triggering whenever the NSButton’s NSPanel or NSWindow is the key window.

NSButton and NSMatrix both provide a control view, which is needed to display an NSButtonCell object. However, while NSMatrix requires you to access the NSButtonCells directly, most of NSButton’s methods are “covers” for identically declared methods in NSButtonCell. (In other words, the implementation of the NSButton method invokes the corresponding NSButtonCell method for you, allowing you to be unconcerned with the NSButtonCell’s existence.) The only NSButtonCell methods that don’t have covers relate to the font used to display the key equivalent, and to specific methods for highlighting or showing the NSButton’s state (these last are usually set together with NSButton’s setButtonType: method).

Creating a Subclass of NSButton

Override the designated initializer (NSView’s initWithFrame: method) if you create a subclass of NSButton that performs its own initialization. If you want to use a custom NSButtonCell subclass with your subclass of NSButton, you have to override the setCellClass: method, as described in “Creating New NSControls” in the NSControl class specification.

See the NSButtonCell class specification for more on NSButton’s behavior.

Method Types

Initializing the NSButton factory	+ cellClass

+ setCellClass:

Setting the button type	− setButtonType:

Setting the state	− setState:

− state

Setting the repeat interval	− getPeriodicDelay:interval:

− setPeriodicDelay:interval:

Setting the titles	− alternateTitle

− attributedAlternateTitle

− attributedTitle

− setAlternateTitle:

− setAttributedAlternateTitle

− setAttributedTitle

− setTitle:

− title

Setting the images	− alternateImage

− image

− imagePosition

− setAlternateImage:

− setImage:

− setImagePosition:

Modifying graphic attributes	− isBordered

− isTransparent

− setBordered:

− setTransparent:

Displaying	− highlight:

Setting the key equivalent	− keyEquivalent

− keyEquivalentModifierMask

− setKeyEquivalent:

− setKeyEquivalentModifierMask:

Handling events and action messages

− performClick:

− performKeyEquivalent:

Class Methods

cellClass

+ (Class)cellClass

Returns the class of cells used by the receiving class (which must be NSButtonCell or one of its subclasses). Returns nil if no cell class has been specified for the receiving class or any of its superclasses (up to NSButtonCell).

setCellClass:

+ (void)setCellClass:(Class)classId

Configures the NSButton class to use instances of classId for its NSCells. classId should be the id of a subclass of NSButtonCell, obtained by sending the class message to either the NSCell subclass object or to an instance of that subclass. The default NSCell class is NSButtonCell.

If this method isn’t overridden by a subclass of NSButton, then when it’s sent to that subclass, NSButton and any other subclasses of NSButton will use the new NSCell subclass as well. To safely set an NSCell class for your subclass of NSButton, override this method to store the NSCell class in a static id. Also, override the designated initializer to replace the NSButton subclass instance’s NSCell with an instance of the NSCell subclass stored in that static id. See “Creating New NSControls” in the NSControl class specification’s class description for more information.

Instance Methods

alternateImage

− (NSImage *)alternateImage

Returns the image that appears on the button when it’s in its alternate state, or nil if there is no alternate image. Note that some button types don’t display an alternate image. Buttons don’t display images by default.

See also:	− image, − imagePosition, − keyEquivalent, − setButtonType:

alternateTitle

− (NSString *)alternateTitle

Returns the string that appears on the button when it’s in its alternate state, or the empty string if the button doesn’t display an alternate title. Note that some button types don’t display an alternate title. By default, a button’s alternate title is “Button”.

See also:	− attributedAlternateTitle, − setButtonType:, − title

p	attributedAlternateTitle

− (NSAttributedString *)attributedAlternateTitle

Returns the string that appears on the button when it’s in its alternate state as an NSAttributedString, or an empty attributed string if the button doesn’t display an alternate title. Note that some button types don’t display an alternate title. By default, a button’s alternate title is “Button”.

See also:	 − setButtonType:, − attributedTitle

p	attributedTitle

− (NSAttributedString *)attributedTitle

Returns the string that appears on the button when it’s in its normal state as an NSAttributedString, or an empty attributed string if the button doesn’t display a title. A button’s title is always displayed if the button doesn’t use its alternate contents for highlighting or displaying the alternate state. By default, a button’s title is “Button”.

See also:	− attributedAlternateTitle, − setButtonType:

getPeriodicDelay:interval:

− (void)getPeriodicDelay:(float *)delay interval:(float *)interval

Returns by reference the delay and interval periods for a continuous button. delay is the amount of time (in seconds) that the button will pause before starting to periodically send action messages to the target object. interval is the amount of time (also in seconds) between those messages.

Default delay and interval values are taken from a user’s defaults (60 seconds maximum for each); if the user hasn’t specified default values, delay defaults to 0.4 seconds and interval defaults to 0.075 seconds.

See also:	− isContinuous (NSControl)

highlight:

− (void)highlight:(BOOL)flag

Highlights (or unhighlights) the button according to flag. Highlighting may involve the button appearing “pushed in” to the screen, displaying its alternate title or image, or causing the button to appear to be “lit.” If the current state of the button matches flag, no action is taken.

See also:	− setButtonType:

image

− (NSImage *)image

Returns the image that appears on the button when it’s in its normal state, or nil if there is no such image. This image is always displayed on a button that doesn’t change its contents when highlighting or showing its alternate state. Buttons don’t display images by default.

See also:	− alternateImage, − setButtonType:

imagePosition

− (NSCellImagePosition)imagePosition

Returns the position of the button’s image relative to its title. The return value is one of the following (these are defined in NSCell.h):

Return Value	Meaning

NSNoImage	The button doesn’t display an image (this is the default)

NSImageOnly	The button displays an image, but not a title

NSImageLeft	The image is to the left of the title

NSImageRight	The image is to the right of the title

NSImageBelow	The image is below the title

NSImageAbove	The image is above the title

NSImageOverlaps	The image overlaps the title

If the title is above, below, or overlapping the image, or if there is no image, the text is horizontally centered within the button.

See also:	− setButtonType:, − setImage:, − setTitle:

isBordered

− (BOOL)isBordered

Returns YES if the button has a border, NO otherwise. A button’s border isn’t the single line of most other controls’ borders; instead, it’s a raised bezel. By default, buttons are bordered.

isTransparent

− (BOOL)isTransparent

Returns YES if the button is transparent, NO otherwise. A transparent button never draws itself, but it receives mouse-down events and tracks the mouse properly.

keyEquivalent

− (NSString *)keyEquivalent

Returns the key-equivalent character of the button, or the empty string if one hasn’t been defined. Buttons don’t have a default key equivalent.

See also:	− keyEquivalentFont (NSButtonCell), − performKeyEquivalent:

keyEquivalentModifierMask

− (unsigned int)keyEquivalentModifierMask

Returns the mask indicating the modifier keys that are applied to the button’s key equivalent. Mask bits are defined in NSEvent.h; only NSControlKeyMask, NSAlternateKeyMask, and NSCommandKeyMask bits are relevant in button key-equivalent modifier masks.

See also:	− keyEquivalent:

performClick:

− (void)performClick:(id)sender

Simulates the user’s clicking the button with the mouse. This method essentially highlights the button, sends the button’s action message to the target object, and then unhighlights the button. If an exception is raised while the target object is processing the action message, the button is unhighlighted before the exception is propagated out of performClick:.

See also:	− performKeyEquivalent:

performKeyEquivalent:

− (BOOL)performKeyEquivalent:(NSEvent *)anEvent

If the character in anEvent matches the button’s key equivalent, and the modifier flags in anEvent match the key-equivalent modifier mask, performKeyEquivalent: simulates the user clicking the button by sending performClick: to self, and returns YES. Otherwise, performKeyEquivalent: does nothing and returns NO. performKeyEquivalent: also returns NO in the event that the button is blocked by a modal panel or the button is disabled.

See also:	− keyEquivalentModifierMask

setAlternateImage:

− (void)setAlternateImage:(NSImage *)image

Sets the image that appears on the button when it’s in its alternate state to image and, if necessary, redraws the contents of the button. Note that some button types don’t display an alternate image.

See also:	− setImage:, − setButtonType:

setAlternateTitle:

− (void)setAlternateTitle:(NSString *)aString

Sets the string that appears on the button when it’s in its alternate state to aString. Note that some button types don’t display an alternate title.

See also:	− setTitle:, − setButtonType:, − setFont: (NSButtonCell)

p	setAttributedAlternateTitle:

− (void)setAttributedAlternateTitle:(NSAttributedString *)aString

Sets the string that appears on the button when it’s in its alternate state to the attributed string aString. Note that some button types don’t display an alternate title.

See also:	− setAttributedTitle:, − setButtonType:, − setFont: (NSButtonCell)

p	setAttributedTitle:

− (void)setAttributedTitle:(NSAttributedString *)aString

Sets the string that appears on the button when it’s in its normal state to the attributed string aString and redraws the button. The title is always shown on buttons that don’t use their alternate contents when highlighting or displaying their alternate state.

See also:	− setAttributedAlternateTitle:, − setButtonType:, − setFont: (NSButtonCell)

setBordered:

− (void)setBordered:(BOOL)flag

Sets whether the button has a bezeled border. If flag is YES, the button displays a border; if NO, the button doesn’t display a border. A button’s border is not the single line or most other controls’ borders; instead, it’s a raised bezel. This method redraws the button if setBordered: causes the bordered state to change.

setButtonType:

− (void)setButtonType:(NSButtonType)aType

Sets how the button highlights while pressed and how it shows its state. setButtonType: redisplays the button before returning.

The types available are for the most common button types, which are also accessible in Interface Builder. You can configure different behavior with NSButtonCell’s setHighlightsBy: and setShowsStateBy: methods.

aType can be one of eight constants:

Button Type	Description

NSMomentaryLight	While the button is held down it’s shown as “lit.” This type of button is best for simply triggering actions, as it doesn’t show its state; it always displays its normal image or title. This option is called “Momentary Light” in Interface Builder’s Button Inspector. This is the default button type.

NSMomentaryPushButton	While the button is held down it’s shown as “lit,” and also “pushed in” to the screen if the button is bordered. This type of button is best for simply triggering actions, as it doesn’t show its state; it always displays its normal image or title. This option is called “Momentary Push” in Interface Builder’s Button Inspector.

NSMomentaryChangeButton

While the button is held down, the alternate image and alternate title are displayed. The normal image or title are displayed when the button isn’t pressed. This option is called “Momentary Change” in Interface Builder’s Button Inspector.

NSPushOnPushOffButton	The first click both highlights and causes the button to be “pushed in” if the button is bordered. A second click returns it to its normal state. This option is called “Push On/Push Off” in Interface Builder’s Button Inspector.

NSOnOffButton	The first click highlights the button. A second click returns it to the normal (unhighlighted) state. This option is called “On/Off” in Interface Builder’s Button Inspector.

NSToggleButton	The first click highlights the button, while a second click returns it to its normal state. Highlighting is performed by changing to the alternate title or image and showing the button as “pushed in” if the button is bordered. This option is called “Toggle” in Interface Builder’s Button Inspector.

NSSwitchButton	This is a variant of NSToggleButton that has no border, with the default image set to “NSSwitch,” and the alternate image set to “NSHighlightedSwitch” (these are system bitmaps). This type of button is available as a separate palette item in Interface Builder.

NSRadioButton	Like NSSwitchButton, but the default image is set to “NSRadioButton” and the alternate image is set to “NSHighlightedRadioButton” (these are system bitmaps). This type of button is available as a separate palette item in Interface Builder.

See also:	− setAlternateImage:, − setButtonType: (NSButtonCell), − setImage:

setImage:

− (void)setImage:(NSImage *)image

Sets the button’s image to anImage, and redraws the button. A button’s image is displayed when the button is in its normal state, or all the time for a button that doesn’t change its contents when highlighting or displaying its alternate state.

See also:	− setImagePosition:, − setAlternateImage:, − setButtonType:

setImagePosition:

− (void)setImagePosition:(NSCellImagePosition)aPosition

Sets the position of the button’s image relative to its title. See the imagePosition method description for a listing of possible values for aPosition.

setKeyEquivalent:

− (void)setKeyEquivalent:(NSString *)charCode

Sets the key equivalent character of the button, and redraws the button’s interior if it displays a key equivalent instead of an image. The key equivalent isn’t displayed if the image position is set to NSNoImage, NSImageOnly or NSImageOverlaps; that is, the button must display both its title and its “image” (the key equivalent in this case), and they must not overlap.

To display a key equivalent on a button, set the image and alternate image to nil, then set the key equivalent, then set the image position.

See also:	− performKeyEquivalent:, − setAlternateImage:, − setImage:, − setImagePosition:, − setKeyEquivalentFont: (NSButtonCell)

setKeyEquivalentModifierMask:

− (void)setKeyEquivalentModifierMask:(unsigned int)mask

Sets the mask indicating the modifier keys to be applied to the button’s key equivalent. Mask bits are defined in NSEvent.h; only NSControlKeyMask, NSAlternateKeyMask, and NSCommandKeyMask bits are relevant in button key-equivalent modifier masks.

See also:	− setKeyEquivalent:

setPeriodicDelay:interval:

− (void)setPeriodicDelay:(float)delay interval:(float)interval

Sets the message delay and interval for the button. These two values are used if the button is configured (by a setContinuous: message) to continuously send the action message to the target object while tracking the mouse. delay is the amount of time (in seconds) that a continuous button will pause before starting to periodically send action messages to the target object. interval is the amount of time (also in seconds) between those messages.

The maximum value allowed for both delay and interval is 60.0 seconds; if a larger value is supplied, it’s ignored and 60.0 seconds is used.

See also:	− setContinuous (NSControl)

setState:

− (void)setState:(int)value

Sets the button’s state to value and, if necessary, redraws the button. 0 is the normal or “off” state, and any nonzero number is the alternate or “on” state.

setTitle:

− (void)setTitle:(NSString *)aString

Sets the title displayed by the button when in its normal state to aString and, if necessary, redraws the button’s contents. This title is always shown on buttons that don’t use their alternate contents when highlighting or displaying their alternate state.

See also:	− setAlternateTitle:, − setButtonType:, − setFont: (NSButtonCell)

setTransparent:

− (void)setTransparent:(BOOL)flag

Sets whether the button is transparent, and redraws the button if flag is NO and the button wasn’t already transparent. A transparent button tracks the mouse and sends its action, but doesn’t draw. A transparent button is useful for sensitizing an area on the screen so that an action gets sent to a target when the area receives a mouse click.

state

− (int)state

Returns the button’s state: 0 for normal or “off,” or 1 for alternate or “on.”

title

− (NSString *)title

Returns the title displayed on the button when it’s in its normal state (this title is always displayed if the button doesn’t use its alternate contents for highlighting or displaying the alternate state). Returns the empty string if the button doesn’t display a title. By default, a button’s title is “Button”.

See also:	− alternateTitle, − setButtonType:


NSButtonCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSActionCell : NSCell : NSObject

Conforms To:	NSCoding (from NSCell)

NSCopying (from NSCell)

NSObject (from NSObject)

Declared In:	AppKit/NSButtonCell.h

Class Description

NSButtonCell is a subclass of NSActionCell used to implement the user interfaces of push buttons, switches, and radio buttons. It can also be used for any other region of a view that’s designed to send a message to a target when clicked. The NSButton subclass of NSControl uses a single NSButtonCell. To create groups of switches or radio buttons, use an NSMatrix holding a set of NSButtonCells.

An NSButtonCell is a two-state cell; it’s either “off” or “on,” and can be configured to display the two states differently, with a separate title and/or image for either state. The two states are more often referred to as “normal” and “alternate.” An NSButtonCell’s state is also used as its value, so NSCell methods that set the value (setIntValue: and so on) actually set the NSButtonCell’s state to “on” if the value provided is non-zero (or non-null for strings), and to “off” if the value is zero or null. Similarly, methods that retrieve the value return 1 for the “on” or alternate state (stringValue returns an NSString containing a single character “1”), or 0 for the “off” or normal state (stringValue returns an NSString containing a single character “0”). You can also use NSCell’s setState: and state methods to set or retrieve the state directly. After changing the state, send a display message to show the NSButtonCell’s new appearance. (NSButton does this automatically.)

An NSButtonCell sends its action message to its target once if its view is clicked and it gets the mouse-down event, but can also send the action message continuously as long as the mouse is held down with the cursor inside the NSButtonCell. The NSButtonCell can show that it’s being pressed by highlighting in several ways—for example, a bordered NSButtonCell can appear pushed into the screen, or the image or title can change to an alternate form while the NSButtonCell is pressed.

An NSButtonCell can also have a key equivalent (like a menu item). If the NSButtonCell is displayed in the key window, the NSButtonCell gets the first chance to receive events related to key equivalents. This feature is used quite often in modal panels that have an “OK” button. An NSButtonCell can either display a graphical image representing the key equivalent, or you can mark the keyboard “mnemonic” character in the NSButtonCell’s title using setTitleWithMnemonic:, setAlternateTitleWithMnemonic:, or setAlternateMnemonicLocation:.

For more information on NSButtonCell’s behavior, see the NSButton and NSMatrix class specifications.

Exceptions

In its implementation of the compare: method (declared in NSCell), NSButtonCell raises an NSBadComparisonException if the otherCell argument is not of the NSButtonCell class.

Method Types

Setting the titles	− alternateMnemonic

− alternateMnemonicLocation

− alternateTitle

− attributedAlternateTitle

− attributedTitle

− setAlternateMnemonicLocation:

− setAlternateTitle:

− setAlternateTitleWithMnemonic:

− setAttributedAlternateTitle:

− setAttributedTitle:

− setFont:

− setTitle:

− setTitleWithMnemonic:

− title

Setting the images	− alternateImage

− imagePosition

− setAlternateImage:

− setImagePosition:

Setting the repeat interval	− getPeriodicDelay:interval:

− setPeriodicDelay:interval:

Setting the key equivalent	− keyEquivalent

− keyEquivalentFont

− keyEquivalentModifierMask

− setKeyEquivalent:

− setKeyEquivalentModifierMask:

− setKeyEquivalentFont:

− setKeyEquivalentFont:size:

Modifying graphic attributes	− imageDimsWhenDisabled

− isOpaque

− isTransparent

− setImageDimsWhenDisabled:

− setTransparent:

Displaying	− highlightsBy

− setHighlightsBy:

− setShowsStateBy:

− setButtonType:

− showsStateBy:

Simulating a click	− performClick:

Instance Methods

alternateImage

− (NSImage *)alternateImage

Returns the image that appears on the button when it’s in its alternate state, or nil if there is no alternate image. Note that some button types don’t display an alternate image. Buttons don’t display images by default.

See also:	− image (NSCell), − imagePosition, − keyEquivalent, − setButtonType:

p	alternateMnemonic

− (NSString *)alternateMnemonic

Returns the character in the alternate title (the title displayed on the button cell when it’s in its alternate state) that’s marked as the “keyboard mnemonic.” If the alternate title doesn’t have a keyboard mnemonic, the empty string is returned.

See also:	− alternateMnemonicLocation, − mnemonic (NSCell),

− setAlternateTitleWithMnemonic:

p	alternateMnemonicLocation

− (unsigned)alternateMnemonicLocation

Returns an unsigned integer indicating the character in the alternate title (the title displayed on the button cell when it’s in its alternate state) that’s marked as the “keyboard mnemonic.” If the alternate title doesn’t have a keyboard mnemonic, NSNotFound is returned.

See also:	− alternateMnemonic, − mnemonicLocation (NSCell),

− setAlternateTitleWithMnemonic:

p	alternateObjectValue

− (id)alternateObjectValue

alternateTitle

− (NSString *)alternateTitle

Returns the string that appears on the button when it’s in its alternate state, or the empty string if the button doesn’t display an alternate title. Note that some button types don’t display an alternate title. By default, a button’s alternate title is “Button”.

See also:	− alternateMnemonic, − attributedAlternateTitle, − setButtonType:, − title

p	attributedAlternateTitle

− (NSAttributedString *)attributedAlternateTitle

Returns the string that appears on the button when it’s in its alternate state as an NSAttributedString, or an empty attributed string if the button doesn’t display an alternate title. Note that some button types don’t display an alternate title. By default, a button’s alternate title is “Button”.

See also:	− alternateMnemonic, − attributedTitle, − setButtonType:

p	attributedTitle

− (NSAttributedString *)attributedTitle

Returns the string that appears on the button when it’s in its normal state as an NSAttributedString, or an empty attributed string if the button doesn’t display a title. A button’s title is always displayed if the button doesn’t use its alternate contents for highlighting or displaying the alternate state. By default, a button’s title is “Button”.

See also:	− attributedAlternateTitle, − mnemonic (NSCell), − setButtonType:

getPeriodicDelay:interval:

− (void)getPeriodicDelay:(float *)delay interval:(float *)interval

Returns by reference the delay and interval periods for a continuous button. delay is the amount of time (in seconds) that the button will pause before starting to periodically send action messages to the target object. interval is the amount of time (also in seconds) between those messages.

Default delay and interval values are taken from a user’s defaults (60 seconds maximum for each); if the user hasn’t specified default values, delay defaults to 0.4 seconds and interval defaults to 0.075 seconds.

See also:	− isContinuous (NSCell)

hasValidAlternateObjectValue

− (BOOL)hasValidAlternateObjectValue

highlightsBy

− (int)highlightsBy

Returns the logical OR of flags that indicate the way the button cell highlights when it receives a mouse-down event. See setHighlightsBy: for the list of flags.

See also:	− showStateBy

p	imageDimsWhenDisabled

− (BOOL)imageDimsWhenDisabled

Returns whether the button cell’s image and text appear “dim” when the button cell is disabled. By default, all button types except NSSwitchButton and NSRadioButton do dim when disabled. When NSSwitchButtons and NSRadioButtons are disabled, only the associated text dims.

See also:	− setButtonType:

imagePosition

− (NSCellImagePosition)imagePosition

Returns the position of the button’s image relative to its title. The return value is one of the following (these are defined in NSCell.h):

Return Value	Meaning

NSNoImage	The button doesn’t display an image (this is the default)

NSImageOnly	The button displays an image, but not a title

NSImageLeft	The image is to the left of the title

NSImageRight	The image is to the right of the title

NSImageBelow	The image is below the title

NSImageAbove	The image is above the title

NSImageOverlaps	The image overlaps the title

If the title is above, below, or overlapping the image, or if there is no image, the text is horizontally centered within the button.

See also:	− setButtonType:, − setImage: (NSCell), − setTitle:

isOpaque

− (BOOL)isOpaque

Returns YES if the button cell draws over every pixel in its frame, NO if not. The button cell is opaque only if it isn’t transparent and if it has a border.

See also:	− isTransparent

isTransparent

− (BOOL)isTransparent

Returns YES if the button is transparent, NO otherwise. A transparent button never draws itself, but it receives mouse-down events and tracks the mouse properly.

See also:	− isOpaque

keyEquivalent

− (NSString *)keyEquivalent

Returns the key-equivalent character of the button, or the empty string if one hasn’t been defined. Buttons don’t have a default key equivalent.

See also:	− keyEquivalentFont, − performKeyEquivalent:

keyEquivalentFont

− (NSFont *)keyEquivalentFont

Returns the font used to draw the key equivalent, or nil if the button cell doesn’t have a key equivalent. The default font is the same as that used to draw the title.

See also:	− setFont:

keyEquivalentModifierMask

− (unsigned int)keyEquivalentModifierMask

Returns the mask indicating the modifier keys that are applied to the button’s key equivalent. Mask bits are defined in NSEvent.h; only NSControlKeyMask, NSAlternateKeyMask, and NSCommandKeyMask bits are relevant in button key-equivalent modifier masks.

See also:	− keyEquivalent:

performClick:

− (void)performClick:(id)sender

Simulates the user’s clicking the button with the mouse. This method essentially highlights the button, sends the button’s action message to the target object, and then unhighlights the button. If an exception is raised while the target object is processing the action message, the button is unhighlighted before the exception is propagated out of performClick:.

setAlternateImage:

− (void)setAlternateImage:(NSImage *)image

Sets the image that appears on the button when it’s in its alternate state to image and, if necessary, redraws the contents of the button. Note that some button types don’t display an alternate image.

See also:	− setImage: (NSCell), − setButtonType:

p	setAlternateMnemonicLocation:

− (void)setAlternateMnemonicLocation:(unsigned)location

Sets the character in the alternate title (the title displayed on the button cell when it’s in its alternate state) that’s to be marked as the “keyboard mnemonic.” The character specified by location will be underlined; location can be any integer from 0 to 254. If you don’t want the alternate title to have a keyboard mnemonic, specify a location of NSNotFound.

setAlternateMnemonicLocation: doesn’t cause the button cell to be redisplayed.

See also:	− setAlternateTitleWithMnemonic:

setAlternateObjectValue:

− (void)setAlternateObjectValue:(id)obj

setAlternateTitle:

− (void)setAlternateTitle:(NSString *)aString

Sets the title that’s displayed on the button when it’s in its alternate state to aString. Note that some button types don’t display an alternate title.

See also:	− setAlternateMnemonicLocation:, − setAlternateTitleWithMnemonic:, − setTitle:, − setButtonType:, − setFont:

p	setAlternateTitleWithMnemonic:

− (void)setAlternateTitleWithMnemonic:(NSString *)aString

Sets the title that is displayed on the button cell when it’s in its alternate state to aString, taking into account the fact that an embedded “&” character is not a literal but instead marks the alternate state’s “keyboard mnemonic.” The character in the title that immediately follows the “&” character will be underlined.

If necessary, setAlternateTitleWithMnemonic: redraws the button cell. Note that some button types don’t display an alternate title.

See also:	− setAlternateMnemonicLocation:, − setTitleWithMnemonic:

p	setAttributedAlternateTitle:

− (void)setAttributedAlternateTitle:(NSAttributedString *)aString

Sets the string that appears on the button when it’s in its alternate state to the attributed string aString. Note that some button types don’t display an alternate title.

See also:	− setAlternateMnemonicLocation:, − setAlternateTitleWithMnemonic:,

− setAttributedTitle:, − setButtonType:, − setFont:

p	setAttributedTitle:

− (void)setAttributedTitle:(NSAttributedString *)aString

Sets the string that appears on the button when it’s in its normal state to the attributed string aString and redraws the button. The title is always shown on buttons that don’t use their alternate contents when highlighting or displaying their alternate state.

See also:	− setAttributedAlternateTitle:, − setButtonType:, − setFont:,

− setMnemonicLocation: (NSCell)

setButtonType:

− (void)setButtonType:(NSButtonType)aType

Sets how the button highlights while pressed and how it shows its state. setButtonType: redisplays the button before returning.

The types available are for the most common button types, which are also accessible in Interface Builder; you can configure different behavior with the setHighlightsBy: and setShowsStateBy: methods.

aType can be one of eight constants:

Button Type	Description

NSMomentaryLight	While the button is held down it’s shown as “lit.” This type of button is best for simply triggering actions, as it doesn’t show its state; it always displays its normal image or title. This option is called “Momentary Light” in Interface Builder’s Button Inspector. This is the default button type.

NSMomentaryPushButton	While the button is held down it’s shown as “lit,” and also “pushed in” to the screen if the button is bordered. This type of button is best for simply triggering actions, as it doesn’t show its state; it always displays its normal image or title. This option is called “Momentary Push” in Interface Builder’s Button Inspector.

NSMomentaryChangeButton

While the button is held down, the alternate image and alternate title are displayed. The normal image and title are displayed when the button isn’t pressed. This option is called “Momentary Change” in Interface Builder’s Button Inspector.

NSPushOnPushOffButton	The first click both highlights and causes the button to be “pushed in” if the button is bordered. A second click returns it to its normal state. This option is called “Push On/Push Off” in Interface Builder’s Button Inspector.

NSOnOffButton	The first click highlights the button. A second click returns it to the normal (unhighlighted) state. This option is called “On/Off” in Interface Builder’s Button Inspector.

NSToggleButton	The first click highlights the button, while a second click returns it to its normal state. Highlighting is performed by changing to the alternate title or image and showing the button as “pushed in” if the button is bordered. This option is called “Toggle” in Interface Builder’s Button Inspector.

NSSwitchButton	This is a variant of NSToggleButton that has no border, with the default image set to “NSSwitch,” and the alternate image set to “NSHighlightedSwitch” (these are system bitmaps). This type of button is available as a separate palette item in Interface Builder.

NSRadioButton	Like NSSwitchButton, but the default image is set to “NSRadioButton” and the alternate image is set to “NSHighlightedRadioButton” (these are system bitmaps). This type of button is available as a separate palette item in Interface Builder.

See also:	− setAlternateImage:, − setButtonType:, − setImage: (NSCell)

setFont:

− (void)setFont:(NSFont *)fontObj

Sets the font used to display the title and alternate title. Does nothing if the button cell has no title or alternate title.

If the button cell has a key equivalent, its font is not changed, but the key equivalent’s font size is changed to match the new title font.

See also:	− Font (NSCell), − setKeyEquivalentFont:, − setKeyEquivalentFont:size:

setHighlightsBy:

− (void)setHighlightsBy:(int)aType

Sets the way the button cell highlights itself while pressed. aType can be the logical OR of one or more of the following constants:

NSNoCellMask	The button cell doesn’t change. This flag is ignored if any others are set in aType.

NSPushInCellMask	The button cell “pushes in” when pressed if it has a border. This is the default behavior.

NSContentsCellMask	The button cell displays its alternate icon and/or title.

NSChangeGrayCellMask	The button cell swaps the “control color” (NSColor’s controlColor) and white pixels on the its background and icon.

NSChangeBackgroundCellMask

Same as NSChangeGrayCellMask, but only background pixels are changed.

If both NSChangeGrayCellMask and NSChangeBackgroundCellMask are specified, both are recorded, but which behavior is used depends on the button cell’s image. If the button has no image, or if the image has no alpha (transparency) data, NSChangeGrayCellMask is used. If the image does have alpha data, NSChangeBackgroundCellMask is used; this allows the color swap of the background to show through the image’s transparent pixels.

See also:	− setShowsStateBy:

p	setImageDimsWhenDisabled:

− (void)setImageDimsWhenDisabled:(BOOL)flag

Sets whether the button cell’s image and text appear “dim” when the button cell is disabled. By default, all button types except NSSwitchButton and NSRadioButton do dim when disabled. When NSSwitchButtons and NSRadioButtons are disabled, only the associated text associated dims. The default setting for this condition is reasserted whenever you invoke setButtonType:, so be sure to specify the button cell’s type before you invoke setImageDimsWhenDisabled:.

setImagePosition:

− (void)setImagePosition:(NSCellImagePosition)aPosition

Sets the position of the button’s image relative to its title. See the imagePosition method description for a listing of possible values for aPosition.

setKeyEquivalent:

− (void)setKeyEquivalent:(NSString *)aKeyEquivalent

Sets the key equivalent character of the button, and redraws the button’s inside if it displays a key equivalent instead of an image. The key equivalent isn’t displayed if the image position is set to NSNoImage, NSImageOnly or NSImageOverlaps; that is, the button must display both its title and its “image” (the key equivalent in this case), and they must not overlap.

To display a key equivalent on a button, set the image and alternate image to nil, then set the key equivalent, then set the image position.

See also:	− performKeyEquivalent:, − setAlternateImage:, − setImage: (NSCell),

− setImagePosition:, − setKeyEquivalentFont:

setKeyEquivalentFont:

− (void)setKeyEquivalentFont:(NSFont *)fontObj

Sets the font used to draw the key equivalent, and redisplays the button cell if necessary. Does nothing if the button cell doesn’t have a key equivalent associated with it. The default font is the same as that used to draw the title.

See also:	− setFont:

setKeyEquivalentFont:size:

− (void)setKeyEquivalentFont:(NSString *)fontName size:(float)fontSize

Sets by name and size the font used to draw the key equivalent, and redisplays the button cell if necessary. Does nothing if the button cell doesn’t have a key equivalent associated with it. The default font is the same as that used to draw the title.

See also:	− setFont:

setKeyEquivalentModifierMask:

− (void)setKeyEquivalentModifierMask:(unsigned int)mask

Sets the mask indicating the modifier keys to be applied to the button’s key equivalent. Mask bits are defined in NSEvent.h; only NSControlKeyMask, NSAlternateKeyMask, and NSCommandKeyMask bits are relevant in button key-equivalent modifier masks.

See also:	− setKeyEquivalent:

setPeriodicDelay:interval:

− (void)setPeriodicDelay:(float)delay interval:(float)interval

Sets the message delay and interval for the button. These two values are used if the button is configured (by a setContinuous: message) to continuously send the action message to the target object while tracking the mouse. delay is the amount of time (in seconds) that a continuous button will pause before starting to periodically send action messages to the target object. interval is the amount of time (also in seconds) between those messages.

The maximum value allowed for both delay and interval is 60.0 seconds; if a larger value is supplied, it’s ignored and 60.0 seconds is used.

See also:	− setContinuous (NSCell)

setShowsStateBy:

− (void)setShowsStateBy:(int)aType

Sets the way the button cell indicates its alternate state. aType should be the logical OR of one or more of the following constants:

NSNoCellMask	The button cell doesn’t change. This mask is ignored if any others are set in aType. This is the default.

NSContentsCellMask	The button cell displays its alternate icon and/or title.

NSChangeGrayCellMask	The button cell swaps the “control color” (NSColor’s controlColor) and white pixels on its background and icon.

NSChangeBackgroundCellMask

Same as NSChangeGrayCellMask, but only the background pixels are changed.

If both NSChangeGrayCellMask and NSChangeBackgroundCellMask are specified, both are recorded, but the actual behavior depends on the button cell’s image. If the button has no image, or if the image has no alpha (transparency) data, NSChangeGrayCellMask is used. If the image exists and has alpha data, NSChangeBackgroundCellMask is used; this allows the color swap of the background to show through the image’s transparent pixels.

See also:	− setHighlightsBy:

setTitle:

− (void)setTitle:(NSString *)aString

Sets the title displayed by the button cell when in its normal state to aString and, if necessary, redraws the button’s contents. This title is always shown on buttons that don’t use their alternate contents when highlighting or displaying their alternate state.

See also:	− setAlternateTitle:, − setButtonType:, − setFont:, − setTitleWithMnemonic:

p	setTitleWithMnemonic:

−  (void)setTitleWithMnemonic:(NSString *)aString

Sets the title displayed on the button cell when it’s in its normal state to aString, taking into account the fact that an embedded “&” character is not a literal but instead marks the normal state’s “keyboard mnemonic.” If necessary, setTitleWithMnemonic: redraws the button cell. This title is always shown on buttons that don’t use their alternate contents when highlighting or displaying their alternate state.

See also:	− setAlternateTitleWithMnemonic:, − setMnemonicLocation: (NSCell),

− setTitleWithMnemonic: (NSCell)

setTransparent:

− (void)setTransparent:(BOOL)flag

Sets whether the button is transparent, and redraws the button if flag is NO and the button wasn’t already transparent. A transparent button tracks the mouse and sends its action, but doesn’t draw. A transparent button is useful for sensitizing an area on the screen so that an action gets sent to a target when the area receives a mouse click.

showsStateBy

− (int)showsStateBy

Returns the logical OR of flags that indicate the way the button cell shows its alternate state. See setShowsStateBy: for the list of flags.

See also:	− highlightsBy

title

− (NSString *)title

Returns the title displayed on the button when it’s in its normal state (this title is always displayed if the button doesn’t use its alternate contents for highlighting or displaying the alternate state). Returns the empty string if the button doesn’t display a title. By default, a button’s title is “Button”.

See also:	− alternateTitle, − mnemonic, − mnemonicLocation, − setButtonType:


NSCachedImageRep

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSImageRep : NSObject

Conforms To:	NSCoding (from NSImageRep)

NSCopying (from NSImageRep)

NSObject (from NSObject)

Declared In:	AppKit/NSImageRep.h

Class Description

NSCachedImageRep, a subclass of NSImageRep, defines an object that stores its source data as a rendered image in a window, typically a window that stays off-screen. The only data that’s available for reproducing the image is the image itself. Thus an NSCachedImageRep differs from the other kinds of NSImageReps defined in the Application Kit, all of which can reproduce an image from the information originally used to draw it. Instances of this class are generally used indirectly, through an NSImage object.

See “Caching Representations” in the NSImage class description for more information.

Method Types

Initializing an NSCachedImageRep	− initWithSize:depth:separate:alpha:

− initWithWindow:rect:

Getting the representation	− rect

− window

Instance Methods

initWithSize:depth:separate:alpha:

− (id)initWithSize:(NSSize)size depth:(NSWindowDepth)depth separate:(BOOL)flag alpha:(BOOL)alpha

Initializes a new NSCachedImageRep for an image of the specified size and depth. flag indicates whether the image will get its own unique cache, instead of possibly sharing one with other images. For best performance (although it’s not essential), alpha should be set according to whether the image will have a channel for transparency information.

See also:	− setAlpha: (NSImageRep), − setBitsPerSample: (NSImageRep),

− setCacheDepthMatchesImageDepth: (NSImage), − setCachedSeparately (NSImage)

initWithWindow:rect:

− (id)initWithWindow:(NSWindow *)aWindow rect:(NSRect)aRect

Initializes the receiver, a new NSCachedImageRep instance, for an image that will be rendered within the aRect rectangle in the window aWindow, and returns the initialized object. The rectangle is specified in aWindow’s base coordinate system. The size of the image is set from the size of the rectangle. The window is retained.

You must draw the image in the rectangle yourself; there are no NSCachedImageRep methods for this purpose.

See also:	− size (NSImageRep)

rect

− (NSRect)rect

Returns the rectangle where the image is cached.

See also:	− size (NSImageRep)

window

− (NSWindow *)window

Returns the window where the image is cached.


NSCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding (NSObject),

NSCopying (NSObject),

NSObject (NSObject)

Declared In:	AppKit/NSCell.h

Class Description

The NSCell class provides a mechanism for displaying text or images in an NSView without the overhead of a full NSView subclass. In particular, it provides much of the functionality of the NSText class by providing access to a shared NSText object used by all instances of NSCell in an application. NSCells are also extremely useful for placing text or images at various locations in a custom subclass of NSView.

NSCell is used heavily by most of the NSControl classes to implement their internal workings. For example, NSSlider uses an NSSliderCell, NSTextField uses an NSTextFieldCell, and NSBrowser uses an NSBrowserCell. Sending a message to the NSControl is often simpler than dealing directly with the corresponding NSCell. For instance, NSControls typically invoke updateCell: (causing the cell to be displayed) after changing a cell attribute; whereas if you directly call the corresponding method of the NSCell, the NSCell might not automatically display itself again.

Some subclasses of NSControl (notably NSMatrix) group NSCells in an arrangement where they act together in some cooperative manner. Thus, with an NSMatrix, you can implement a uniformly sized group of radio buttons without needing an NSView for each button (and without needing an NSText object as the field editor for the text on each button).

The NSCell class provides primitives for displaying text or an image, editing text, setting and getting object values, maintaining state, highlighting, and tracking the mouse. NSCell’s method trackMouse:inRect:ofView:untilMouseUp: implements the mechanism that sends action messages to target objects. However, NSCell implements target/action features abstractly, deferring the details of implementation to NSActionCell and its subclasses.

Object Values and Formatters

Every NSCell that displays text has a value associated with it. The NSCell stores that value as an object of potentially any type, displays it as an NSString, and returns it as a primary value or string object, according to what’s requested (intValue, floatValue, stringValue, and so on). Formatters are objects associated with NSCells (through setFormatter:) that translate a cell’s object value to its it textual representation and that convert what users type into the underlying object. NSCells have built-in formatters to handle common string and numeric (int, float, double) translations. In addition, you can specify date and numeric types more precisely with  setEntryType: and specify floating-point format characteristics with setFloatingPointFormat:left:right:. You can also implement your own formatters to provide specialized object translation; see the NSFormatter specification for more information.

The text that an NSCell displays and stores can be an attributed string. Several methods help to set and get attributed-string values, including setAttributedStringValue: and setImportsGraphics:.

Represented Objects

Represented objects are objects that an NSCell "stands for." (They’re not to be confused with an NSCell’s object value, which is the value of the cell.) By setting a represented object for an NSCell (using setRepresentedObject:) you make an association between the NSCell and that object. For instance, you could have a pop-up list, each cell of which lists a color as its title; when the user selects a cell, the represented NSColor object is displayed in a color well.

Subclassing NSCell

The initImageCell: method is the designated initializer for NSCells that display images. The initTextCell: method is the designated initializer for NSCells that display text. Override one or both of these methods if you implement a subclass of NSCell that performs its own initialization. If you need to use target and action behavior, you may prefer to subclass NSActionCell or one of its subclasses, which provide the default implementation of this behavior.

If you want to implement your own mouse-tracking or mouse-up behavior, consider overriding startTrackingAt:inView:, continueTracking:at:inView:, and stopTracking:at:inView:mouseIsUp:. If you want to implement your own drawing, override drawWithFrame:inView: or drawInteriorWithFrame:inView:.

For more information on how NSCell is used, see the NSControl class specification.

Method Types

Initializing an NSCell	− initImageCell:

− initTextCell:

Setting and getting cell values	− setObjectValue:

− objectValue

− hasValidObjectValue

− setIntValue:

− intValue

− setStringValue:

− stringValue

− setDoubleValue:

− doubleValue

− setFloatValue:

− floatValue

Setting and getting cell attributes	− setCellAttribute:to:

− cellAttribute:

− setType:

− type

− setState:

− state

− setEnabled:

− isEnabled

− setBezeled:

− isBezeled

− setBordered:

− isBordered

− isOpaque

Modifying textual attributes of cells	− setEditable:

− isEditable

− setSelectable:

− isSelectable

− setScrollable:

− isScrollable

− setAlignment:

− alignment

− setFont:

− font

− setWraps:

− wraps

− setAttributedStringValue:

− attributedStringValue

− setAllowsEditingTextAttributes:

− allowsEditingTextAttributes

− setImportsGraphics:

− importsGraphics

− setUpFieldEditorAttributes:

Setting the target and action	− setAction:

− action

− setTarget:

− target

− setContinuous:

− isContinuous

− sendActionOn:

Setting and getting an image	− setImage:

− image

Assigning a tag	− setTag:

− tag

Formatting and validating data	− setFormatter:

− formatter

− setEntryType:

− entryType

− isEntryAcceptable:

− setFloatingPointFormat:left:right:

Managing menus for cells	+ defaultMenu

− setMenu:

− menu

− menuForEvent:inRect:ofView:

Comparing cells	− compare:

Making cells respond to keyboard events

− acceptsFirstResponder

− setShowsFirstResponder:

− showsFirstResponder

− setTitleWithMnemonic:

− mnemonic

− setMnemonicLocation:

− mnemonicLocation

− performClick:

Deriving values from other cells	− takeObjectValueFrom:

− takeIntValueFrom:

− takeStringValueFrom:

− takeDoubleValueFrom:

− takeFloatValueFrom:

Representing an object with a cell	− setRepresentedObject:

− representedObject

Tracking the mouse	− trackMouse:inRect:ofView:untilMouseUp:

− startTrackingAt:inView:

− continueTracking:at:inView:

− stopTracking:at:inView:mouseIsUp:

− mouseDownFlags

+ perfersTrackingUntilMouseUp

− getPeriodicDelay:interval:

Managing the cursor	− resetCursorRect:inView:

Handling keyboard alternatives	− keyEquivalent

Determining cell sizes	− calcDrawInfo:

− cellSize

− cellSizeForBounds:

− drawingRectForBounds:

− imageRectForBounds:

− titleRectForBounds:

Drawing and highlighting cells	− drawWithFrame:inView:

− drawInteriorWithFrame:inView:

− controlView

− highlight:withFrame:inView:

− isHighlighted

Editing and selecting cell text	− editWithFrame:inView:editor:delegate:event:

− selectWithFrame:inView:editor:delegate:start:length:

− endEditing:

Class Methods

p	defaultMenu

+ (NSMenu *)defaultMenu

Returns the default menu for instances of the receiver. The default implementation returns nil.

See also:	− menu, − setMenu:

prefersTrackingUntilMouseUp

+ (BOOL)prefersTrackingUntilMouseUp

The default implementation returns NO, so tracking stops when the mouse leaves the NSCell; subclasses may override.

See also:	− trackMouse:inRect:ofView:untilMouseUp:

Instance Methods

p	acceptsFirstResponder

− (BOOL)acceptsFirstResponder

The default implementation returns YES if the cell is enabled; subclasses can override.

See also:	− performClick:, − setShowsFirstResponder:, − setTitleWithMnemonic:

action

− (SEL)action

Implemented by NSActionCell and its subclasses to return the selector of the cell’s action method. The default implementation returns a null selector.

See also:	− setAction:, − setTarget:, − target

alignment

− (NSTextAlignment)alignment

Returns the alignment of text in the cell: NSLeftTextAlignment, NSRightTextAlignment, NSCenterTextAlignment,  NSJustifiedTextAlignment, or NSNaturalTextAlignment.

See also:	− setAlignment:

p	allowsEditingTextAttributes

− (BOOL)allowsEditingTextAttributes

Returns whether the receiver allows the editing of textual attributes.

See also:	− setAllowsEditingTextAttributes:

p	attributedStringValue

− (NSAttributedString *)attributedStringValue

Returns the value of the receiver as an attributed string, using the cell’s formatter object (if one exists) to create the attributed string. The textual attributes are determined by the default paragraph style, the receiver’s font and alignment, and whether the receiver is enabled and scrollable.

See also:	− setAttributedStringValue:

calcDrawInfo:

− (void)calcDrawInfo:(NSRect)aRect

Implemented by subclasses to recalculate drawing sizes with reference to aRect. Objects (such as NSConrols) that manage NSCells generally maintain a flag that informs them if any of their cells has been modified in such a way that the location or size of the cell should be recomputed. If so, NSControl’s calcSize method is automatically invoked prior to the display of the NSCell, and that method invokes the NSCell’s calcDrawInfo: method. The default implementation does nothing.

See also:	− cellSize, − drawingRectForBounds:

cellAttribute:

− (int)cellAttribute:(NSCellAttribute)aParameter

Depending on aParameter, returns a setting for a cell attribute, such as the receiver’s state, and whether it’s disabled, editable, or highlighted.

See also:	− setCellAttribute:

cellSize

− (NSSize)cellSize

Returns the minimum size needed to display the NSCell, taking account of the size of the image or text within a certain offset determined by border type. If the receiving cell is neither of image or text type, an extremely large size is returned; if the receiving cell is of image type, and no image has been set, an extremely small size is returned.

See also:	− drawingRectForBounds:

cellSizeForBounds:

− (NSSize)cellSizeForBounds:(NSRect)aRect

Returns the minimum size needed to display the NSCell, taking account of the size of the image or text within an offset determined by border type. If the receiving cell is of text type, the text is resized to fit within aRect (as much as aRect is within the bounds of the cell).  If the receiving cell is neither of image or text type, an extremely large size is returned; if the receiving cell is of image type, and no image has been set, an extremely small size is returned.

See also:	− drawingRectForBounds:

compare:

− (NSComparisonResult)compare:(id)otherCell

Compares the string values of this cell and otherCell (which must be a kind of NSCell), disregarding case. Raises NSBadComparisonException if otherCell is not of the NSCell class or if one of the cells being compared is not a text-type cell.

continueTracking:at:inView:

− (BOOL)continueTracking:(NSPoint)lastPoint

at:(NSPoint)currentPoint

inView:(NSView *)controlView

Returns whether mouse-tracking should continue in the receiving cell based on lastPoint and currentPoint within controlView (currentPoint is the current location of the mouse while lastPoint is either the initial location of the mouse or the previous currentPoint).  This method is invoked in trackMouse:inRect:ofView:untilMouseIsUp:. The default implementation returns YES if the cell is set to continuously send action messages to its target when the mouse is down or is being dragged. Subclasses can override this method to provide more sophisticated tracking behavior.

See also:	− startTrackingAt:inView:, − stopTracking:at:inView:mouseIsUp:

controlView

− (NSView *)controlView

Implemented by subclasses to return the NSView last drawn in (normally an NSControl). The default implementation returns nil.

See also:	− drawWithFrame:inView:

doubleValue

− (double)doubleValue

Returns the NSCell’s value as a double. If the receiver is not a text-type cell or the cell value is not scannable, the method returns zero.

drawInteriorWithFrame:inView:

− (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView

Draws the "inside" of the receiving cell; this includes the image or text within the NSCell’s frame in controlView (usually the cell’s NSControl) but excludes the border. cellFrame is the frame of the NSCell or (in some cases) a portion of it. Text-type NSCells display their contents in a rectangle slightly inset from cellFrame using a global NSText object; image-type NSCells display their contents centered within cellFrame. If the proper attributes are set, it also displays the dotted-line rectangle to indicate first responder and highlights the cell. This method is invoked from NSControl’s drawCellInside: to visually update the what the NSCell displays when its contents change. This drawing is minimal, and becomes more complex in objects such as NSButtonCell and NSSliderCell.

Subclasses often override this method to provide more sophisticated drawing of cell contents. Because drawWithFrame:inView: invokes drawInteriorWithFrame:inView: after it draws the NSCell’s border, don’t invoke drawWithFrame:inView: in your override implementation.

See also:	− isHighlighted, − setShowsFirstResponder:

drawWithFrame:inView:

− (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView

Draws the receiver’s regular or bezeled border (if those attributes are set) and then draws the interior of the cell by invoking drawInteriorWithFrame:inView:.

drawingRectForBounds:

− (NSRect)drawingRectForBounds:(NSRect)theRect

Returns the rectangle within which the cell draws itself; this rectangle is slightly inset from aRect on all sides to take the border into account.

See also:	− calcSize

editWithFrame:inView:editor:delegate:event:

− (void)editWithFrame:(NSRect)aRect

inView:(NSView *)controlView

editor:(NSText *)textObj

delegate:(id)anObject

event:(NSEvent *)theEvent

Begins editing of the receiver’s text by using the field editor textObj; usually invoked in response to a mouse-down event. aRect must be the rectangle used for displaying the NSCell. theEvent is the NSMouseDown event. anObject is made the delegate of textObj, and so will receive various NSText delegation and notification messages.

If the receiver isn’t a text-type NSCell, no editing is performed. Otherwise, textObj is sized to aRect and its superview is set to aView, so that it exactly covers the NSCell. Then it’s activated and editing begins. It’s the responsibility of the delegate to end the editing when responding to textShouldEndEditing:; in doing this, it should remove any data from textObj and invoke endEditing:.

See also:	− endEditing:, − selectWithFrame:inView:editor:delegate:start:length:

endEditing:

− (void)endEditing:(NSText *)textObj

Ends any editing of text occurring in the receiver begun with editWithFrame:inView:editor:delegate:event: and selectWithFrame:inView:editor:delegate:start:length:. Usually this method is invoked by the delegate of the field editor specified in one of these methods when that delegate’s textShouldEndEditing: method is invoked.

entryType

− (int)entryType

Returns the type of data the user can type into the receiver. If the receiver is not a text-type cell, or if no type has been set, NSAnyType is returned. See setEntryType: for a list of type constants.

See also:	− isEntryAcceptable:

floatValue

− (float)floatValue

Returns the NSCell’s value as a double. If the receiver is not a text-type cell or the cell value is not scannable, the method returns zero.

font

− (NSFont *)font

Returns the font used to display text in the receiving cell or nil if the receiver is not a text-type cell.

See also:	− setFont:

p	formatter

− (id)formatter

Returns the formatter object (a kind of NSFormatter) associated with the cell. This object handles translation of the cell’s contents between it’s on-screen representation and its object value.

See also:	− setFormatter:

getPeriodicDelay:interval:

− (void)getPeriodicDelay:(float *)delay interval:(float *)interval

Returns initial delay and repeat values for continuous sending of action messages to target objects. Subclasses can override to supply their own delay and interval values.

See also:	− isContinuous, − setContinuous:

p	hasValidObjectValue

− (BOOL)hasValidObjectValue

Returns whether the object associated with the receiver has a valid object value. A valid object value is one that the receiver’s formatter can "understand." Objects that are "invalid" have been rejected by the formatter, but accepted by the delegate of the receiver’s NSControl (in control:didFailToFormatString:errorDescription:).

See also:	− objectValue, − setObjectValue:

highlight:withFrame:inView:

− (void)highlight:(BOOL)flag

withFrame:(NSRect)cellFrame

inView:(NSView *)controlView

If the receiver’s highlight status is different from flag, sets that status to flag and, if flag is YES, highlights the rectangle cellFrame in the NSControl (controlView).

Note that NSCell’s highlighting does not appear when highlighted cells are printed (although instances of NSTextFieldCell, NSButtonCell, and others can print themselves highlighted). Generally, you cannot depend on highlighting being printed because implementations of this method may choose (or not choose) to use transparency.

See also:	− drawWithFrame:inView:, − isHighlighted

image

− (NSImage *)image

Returns the image displayed by the receiver or nil if the receiver is not an image-type cell.

See also:	− setImage:

imageRectForBounds:

− (NSRect)imageRectForBounds:(NSRect)theRect

Returns the rectangle that the cell’s image is drawn in, which is slightly offset from theRect.

See also:	− cellSizeForBounds:, − drawingRectForBounds:

p	importsGraphics

− (BOOL)importsGraphics

Sets whether the text of the receiver (if a text-type cell) is of Rich Text Format (RTF) and thus can import graphics.

See also:	− setImportsGraphics:

initImageCell:

− (id)initImageCell:(NSImage *)anImage

Returns an NSCell object initialized with anImage and set to have the cell’s default menu. If anImage is nil, no image is set.

initTextCell:

− (id)initTextCell:(NSString *)aString

Returns an NSCell object initialized with aString and set to have the cell’s default menu. If no field editor (a shared NSText object) has been created for all NSCells, one is created.

intValue

− (int)intValue

Returns the receiver’s value as an int. If the receiver is not a text-type cell or the cell value is not scannable, the method returns zero.

isBezeled

− (BOOL)isBezeled

Returns whether the receiving cell has a bezeled border.

See also:	− setBezeled:

isBordered

− (BOOL)isBordered

Returns whether the receiving cell has a plain border.

See also:	− setBordered:

isContinuous

− (BOOL)isContinuous

Returns whether the receiving cell sends its action message continuously on mouse down.

See also:	− setContinuous:

isEditable

− (BOOL)isEditable

Returns whether the receiving cell is editable.

See also:	− setEditable:

isEnabled

− (BOOL)isEnabled

Returns whether the receiving cell responds to mouse events.

See also:	− setEnabled:

isEntryAcceptable:

− (BOOL)isEntryAcceptable:(NSString *)aString

Returns whether a string representing a numeric or date value (aString) is formatted in a way suitable to  the entry type.

See also:	− entryType, − setEntryType:

isHighlighted

− (BOOL)isHighlighted

Returns whether the receiving cell is highlighted.

See also:	− setHighlighted:

isOpaque

− (BOOL)isOpaque

Returns whether the receiving cell is opaque (non-transparent).

isScrollable

− (BOOL)isScrollable

Returns whether the receiving cell scrolls typed text that exceeds the cell’s bounds.

See also:	− setScrollable:

isSelectable

− (BOOL)isSelectable

Returns whether the text of the receiving cell can be selected.

See also:	− setSelectable:

keyEquivalent

− (NSString *)keyEquivalent

Implemented by subclasses to return a key equivalent to clicking the cell. The default implementation returns an empty string object.

p	menu

− (NSMenu *)menu

Returns the menu with commands contextually related to the cell or nil if no menu is associated.

See also:	− setMenu:

p	menuForEvent:inRect:ofView:

− (NSMenu *)menuForEvent:(NSEvent *)anEvent

inRect:(NSRect)cellFrame

ofView:(NSView *)aView

Returns the NSMenu associated with the receiver through the setMenu: method and related to anEvent when the mouse is detected within cellFrame. It is usually invoked by the NSControl

(aView) managing the receiver. The default implementation simply invokes NSCell’s menu method and will return nil if no menu has been set. Subclasses can override to customize the returned menu according to the event received and the area in which the mouse event occurs.

p	mnemonic

− (NSString *)mnemonic

Returns the character in the cell title that appears underlined for use as a mnemonic. If there is no mnemonic character, returns an empty string.

See also:	− setTitleWithMnemonic:

p	mnemonicLocation

− (unsigned int)mnemonicLocation

Returns the position of the underlined character in the cell title used as a mnemonic. If there is no mnemonic character, returns NSNotFound.

See also:	− setMnemonicLocation:

mouseDownFlags

− (int)mouseDownFlags

Returns the modifier flags for the last (left) mouse-down event or zero if tracking hasn’t occured yet for the cell or if no modifier keys accompanied the mouse-down event.

See also:	− modifierFlags (NSEvent)

p	objectValue

− (id )objectValue

Returns the NSCell’s value as an Objective-C object if a valid object has been associated with the receiver; otherwise, returns nil. To be valid, the cell must have a formatter capable of converting the object to and from its textual representation.

p	performClick:

− (void)performClick:(id)sender

Programmatically simulates a mouse click on the receiver, including the invocation of the action method in the target object. Raises an exception if the action message cannot be successfully sent.

representedObject

− (id)representedObject

Returns the object the receiving cell represents. For example, you could have a pop-up list of color names, and the represented objects could be the appropriate NSColor objects.

See also:	− setRepresentedObject:

resetCursorRect:inView:

− (void)resetCursorRect:(NSRect)cellFrame inView:(NSView *)controlView

Sets the receiver to show the I-beam cursor within cellFrame while it tracks the mouse . The receiver must be an enabled and selectable (or editable) text-type cell. controlView is the NSControl that manages the cell.

selectWithFrame:inView:editor:delegate:start:length:

− (void)selectWithFrame:(NSRect)aRect

inView:(NSView *)controlView

editor:(NSText *)textObj

delegate:(id)anObject

start:(int)selStart

length:(int)selLength

Uses the field editor textObj to select text in a range marked by selStart and selLength, which will be highlighted and selected as though the user had dragged the cursor over it. This method is similar to editWithFrame:inView:editor:delegate:event:, except that it can be invoked in any situation, not only on a mouse-down event. aRect is the rectangle in which the selection should occur, controlView is the NSControl managing the receiver, and anObject is the delegate of the field editor. Returns without doing anything if controlView, textObj, or the receiver are nil, or if the receiver as no font set for it.

sendActionOn:

− (int)sendActionOn:(int)mask

Sets the conditions on which the receiver sends action messages to its target and returns a bit mask with which to detect the previous settings. mask is set with one or more of these bit masks:

NSLeftMouseUpMask	Don’t send action message on (left) mouse up.

NSLeftMouseDownMask	Send action message on (left) mouse down.

NSLeftMouseDraggedMask	Send action message when (left) mouse is dragged.

NSPeriodicMask	Send action message continuously.

You can send setContinuous: method to turn on the flag corresponding to NSPeriodicMask or NSLeftMouseDraggedMask, whichever is appropriate to the given subclass of NSCell.

See also:	− action

setAction:

− (void)setAction:(SEL)aSelector

In NSCell, raises NSInternalInconsistencyException. However, NSActionCell overrides this method to set the action method as part of the implementation of the target/action mechanism.

See also:	− action, − setTarget:, − target

setAlignment:

− (void)setAlignment:(NSTextAlignment)mode

Sets the alignment of text in the receiver. mode is one of five constants: NSLeftTextAlignment, NSRightTextAlignment, NSCenterTextAlignment, NSJustifiedTextAlignment, NSNaturalTextAlignment (the default alignment for the text).

See also:	− alignment, − setWrap:

p	setAllowsEditingTextAttributes:

− (void)setAllowsEditingTextAttributes:(BOOL)flag

Sets whether the textual attributes of the receiver can be modified. If flag is NO, the receiver cannot import graphics (that is, it does not support RTFD text).

See also:	− allowsEditingTextAttributes, − setImportsGraphics:

p	setAttributedStringValue:

− (void)setAttributedStringValue:(NSAttributedString *)attribStr

Sets the value of the receiver to the attributed string attribStr. If a formatter is set for the receiver, but the formatter does not understand the attributed string, it marks attribStr as an invalid object. If the receiver is not a text-type cell, it’s converted to one. The following example sets the text in a cell to 14 points, red, in the system font.

    NSColor *txtColor = [NSColor redColor];

    NSFont *txtFont = [NSFont boldSystemFontOfSize:14];

    NSDictionary *txtDict = [NSDictionary

dictionaryWithObjectsAndKeys:txtFont,

NSFontAttributeName, txtColor,

NSForegroundColorAttributeName, nil];

    NSAttributedString *attrStr = [[[NSAttributedString alloc]

        initWithString:@"Hello!" attributes:txtDict] autorelease];

    [[attrStrTextField cell] setAttributedStringValue:attrStr];

    [attrStrTextField updateCell:[attrStrTextField cell]];

See also:	− attributedStingValue, − hasInvalidObject

setBezeled:

− (void)setBezeled:(BOOL)flag

Sets whether the receiver draws itself with a bezeled border. The setBezeled: and setBordered: methods are mutually exclusive (that is, a border can be only plain or bezeled).

See also:	− isBezeled

setBordered:

− (void)setBordered:(BOOL)flag

Sets whether the receiver draws itself outlined with a plain border. The setBezeled: and setBordered: methods are mutually exclusive (that is, a border can be only plain or bezeled).

See also:	− isBordered

setCellAttribute:to:

− (void)setCellAttribute:(NSCellAttribute)aParameter to:(int)value

Sets a cell attribute identified by aParameter—such as the receiver’s state, and whether it’s disabled, editable, or highlighted—to value.

See also:	− cellAttribute

setContinuous:

− (void)setContinuous:(BOOL)flag

Sets whether the receiver continuously sends its action message to its target while it tracks the mouse. In practice, the continuous setting has meaning only for instances of NSActionCell and its subclasses, which implement the target/action mechanism. Some NSControl subclasses, notably NSMatrix, send a default action to a default target when a cell doesn’t provide a target or action.

See also:	− isContinuous; − sendActionOn:

setDoubleValue:

− (void)setDoubleValue:(double)aDouble

Sets the value of the receiving cell to an object representing a double. Does nothing if the receiver is not a text-type cell.

See also:	− doubleValue

setEditable:

− (void)setEditable:(BOOL)flag

Sets whether the receiver’s text is both editable and selectable. If flag is NO, and the cell’s text was not selectable before editing was last enabled (that is, before this message was last sent with an argument of YES), then the receiver’s text is set to be unselectable.

See also:	− isEditable, − setSelectable:

setEnabled:

− (void)setEnabled:(BOOL)flag

Sets whether the receiver is enabled or disabled. The text of disabled cells is changed to gray.  If a cell is disabled, it cannot be highlighted, does not support mouse tracking (and thus cannot participate in target/action functionality), and cannot be edited. However, you can still alter many attributes of a disabled cell programmatically (setState:, for instance, will still work).

See also:	− isEnabled

setEntryType:

− (void)setEntryType:(int)aType

Sets how numeric data are formatted in the receiver and places restrictions on acceptable input. aType can be one of the following constants:

Constant	Restrictions and Other Information

NSIntType	Must be between INT_MIN and INT_MAX

NSPositiveIntType	Must be between 1 and INT_MAX

NSFloatType	Must be between  -FLT_MAX and FLT_MAX

NSPositiveFloatType	Must be between FLT_MIN and FLT_MAX

NSDoubleType	Must be between  -DBL_MAX and DBL_MAX

NSPositiveDoubleType	Must be between  DBL_MAX and DBL_MAX

NSAnyType	Any value is allowed.

If the receiver isn’t a text-type cell, this method converts it to one; in the process, it makes its title "Cell" and sets its font to the user’s system font at 12 points.

You can check whether formatted strings conform to the entry types of cells with the isEntryAcceptable: method. NSControl subclasses also use isEntryAcceptable: to validate what users have typed in editable cells. You can control the format of values accepted and displayed in cells by creating a custom subclass of NSFormatter and associating an instance of that class with cells (through setFormatter:). In custom NSCell subclasses, you can also override isEntryAcceptable: to check for the validity of data entered into cells.

See also:	− entryType

setFloatingPointFormat:left:right:

− (void)setFloatingPointFormat:(BOOL)autoRange

left:(unsigned)leftDigits

right:(unsigned)rightDigits

Sets whether floating-point numbers are autoranged in the receiver, and sets the sizes of the fields to the left and right of the decimal point. If autoRange is NO, leftDigits specifies the maximum number of digits to the left of the decimal point, and rightDigits specifies the number of digits to the right (the fractional digit places will be padded with zeros to fill this width).  However, if a number is too large to fit its integer part in leftDigits digits, as many places as are needed on the left are effectively removed from rightDigits when the number is displayed.

If autoRange is YES, leftDigits and rightDigits are simply added to form a maximum total field width for the receiver (plus 1 for the decimal point).  The fractional part will be padded with zeros on the right to fill this width, or truncated as much as possible (up to removing the decimal point and displaying the number as an integer).  The integer portion of a number is never truncated—that is, it is displayed in full no matter what the field width limit is.

The following example sets a cell used to display dollar amounts up to 99,999.99:

    [[currencyDollarsField cell] setEntryType:NSFloatType];

    [[currencyDollarsField cell] setFloatingPointFormat:NO left:5 right:2];

See also:	− setEntryType:

setFloatValue:

− (void)setFloatValue:(float)aFloat

Sets the value of the receiving cell to an object representing a float. Does nothing if the receiver is not a text-type cell.

See also:	− floatValue

setFont:

− (void)setFont:(NSFont *)fontObj

Sets the font to be used when the receiver displays text. If the receiver is not a text-type cell, the method converts it to that type. If fontObj is nil and the receiver is a text-type cell, the font currently held by the receiver is autoreleased.

See also:	− font

p	setFormatter:

− (void)setFormatter:(NSFormatter *)newFormatter

Sets the formatter object used to format the textual representation of the receiver’s object value and to validate cell input and convert it to that object value. If the new formatter cannot interpret the receiver’s current object value, that value is converted to a string object. This method retains new formatters and releases replaced ones. If newFormatter is nil, the receiver is disassociated from the current formatter.

See also:	− formatter

setImage:

− (void)setImage:(NSImage *)image

Sets the image to be displayed by the receiver. If the receiver is not an image-type cell, the method converts it to that type. If image is nil and the receiver is an image-type cell, the image currently held by the receiver is autoreleased.

See also:	− image

p	setImportsGraphics:

− (void)setImportsGraphics:(BOOL)flag

Sets whether the receiver can import images into its text (that is, whether it supports RTFD text). If flag is YES, the receiver is also set to allow editing of text attributes (setAllowsEditingTextAttributes:).

See also:	− importsGraphics

setIntValue:

− (void)setIntValue:(int)anInt

Sets the value of the receiving cell to an object representing an int. Does nothing if the receiver is not a text-type cell.

See also:	− intValue

p	setMenu:

− (void)setMenu:(NSMenu *)aMenu

Associates a menu with the cell that has commands contextually related to the cell (a pop-up menu on Windows). The associated menu is retained. If aMenu is nil, any association with a previous menu is removed.

See also:	− menu

p	setMnemonicLocation:

− (void)setMnemonicLocation:(unsigned int)location

Sets the character of the cell title identified by location that is to be underlined. This character identifies the access key on Windows by which users can access the cell. location must be between 0 and 254.

See also:	− mnemonicLocation

p	setObjectValue:

− (void)setObjectValue:(id)object

Sets the receiver’s object value to object.

See also:	− objectValue, − setRepresentedObject:

setRepresentedObject:

− (void)setRepresentedObject:(id)anObject

Sets the object represented by the receiver, for example, an NSColor object for a cell with a title of "Blue."

See also:	 − setObjectValue:, − representedObject

setScrollable:

− (void)setScrollable:(BOOL)flag

Sets whether excess text in the receiver is scrolled past the cell’s bounds. If flag is YES, wrapping is turned off. When the scrollable attribute is turned on, the alignment of text in the cell is changed to left alignment.

See also:	− isScrollable

setSelectable:

− (void)setSelectable:(BOOL)flag

Sets whether text in the receiver can be selected; always makes the receiver’s text uneditable.

See also:	− isSelectable, − setEditable:

p	setShowsFirstResponder:

− (void)setShowsFirstResponder:(BOOL)flag

Sets whether the receiver displays a dotted-line outline when it assumes first responder status.

See also:	− showsFirstResponder

setState:

− (void)setState:(int)value

Sets the state of the receiver to 1 (YES) if value is positive and 0 (NO) if value is non-positive.

See also:	− state

setStringValue:

− (void)setStringValue:(NSString *)aString

Sets the value of the receiving cell to an NSString object. If no formatter is assigned to the receiver or if the formatter cannot "translate" aString to an underlying object, the receiver is flagged as having an invalid object. If the receiver is not a text-type cell, this method converts it to one before setting the object value.

See also:	− stringValue

setTag:

− (void)setTag:(int)anInt

Implemented by NSActionCell to set the receiver’s tag integer. NSCell’s implementation raises NSInternalInconsistencyException.

See also:	− tag

p	setTitleWithMnemonic:

− (void)setTitleWithMnemonic:(NSString *)aString

Sets the title of a cell with a character underlined to denote an access key (Windows only). Use an ampersand character to mark the character (the one following the ampersand) to be underlined. For example, the following message causes the "c" in "Receive" to be underlined:

[aCell setTitleWithMnemonic:NSLocalizedString(@"Re&ceive")];

See also:	− mnemonic, − setMnemonicLocation:

setTarget:

− (void)setTarget:(id)anObject

Implemented by NSActionCell to set the receiver’s target object receiving the action message. NSCell’s implementation raises NSInternalInconsistencyException.

See also:	− target

setType:

− (void)setType:(int)aType

If the type of the receiving cell is different from aType, sets it to aType, which must one of NSTextTypeCell, NSImageTypeCell, or NSNullCellType. If aType is NSTextTypeCell, converts the receiver to a cell of that type, giving it a default title and setting the font to the system font at the default size. If aType is NSImageTypeCell, sets a nil image.

See also:	− type

setUpFieldEditorAttributes:

− (NSText *)setUpFieldEditorAttributes:(NSText *)textObj

Sets textual and background attributes of the receiver, depending on certain attributes. If the receiver is disabled, sets the text color to dark gray; otherwise sets it to the default color. If the receiver has a bezeled border, sets the background to the default color for text backgrounds; otherwise, sets it to the color of the receiver’s NSControl.

setWraps:

− (void)setWraps:(BOOL)flag

Sets whether text in the receiver wraps when its length exceeds the frame of the cell. If flag is YES, then it also sets the receiver to be non-scrollable.

See also:	− wraps

showsFirstResponder

− (BOOL)showsFirstResponder

Returns whether the receiver displays a dotted-line outline when it assumes first responder status.

See also:	− setShowsFirstResponder:

startTrackingAt:inView:

− (BOOL)startTrackingAt:(NSPoint)startPoint inView:(NSView *)controlView

NSCell’s implementation of trackMouse:inRect:ofView:untilMouseIsUp: invokes this method when tracking begins. startPoint is the point the mouse is currently at and controlView is the NSControl managing the receiver. NSCell’s default implementation returns YES if the receiver is set to respond continuously or when the mouse is dragged. Subclasses override this method to implement special mouse-tracking behavior at the beginning of mouse tracking, for example, displaying a special cursor.

See also:	− continueTracking:at:inView:, − stopTracking:at:inView:mouseIsUp:

state

− (int)state

Returns the state of the receiver, either 1 (YES) or 0 (NO).

See also:	− setState:

stopTracking:at:inView:mouseIsUp:

− (void)stopTracking:(NSPoint)lastPoint

at:(NSPoint)stopPoint

inView:(NSView *)controlView

mouseIsUp:(BOOL)flag

NSCell’s implementation of trackMouse:inRect:ofView:untilMouseIsUp: invokes this method when the mouse has left the bounds of the receiver or the mouse goes up (in which case flag is YES). lastPoint is the point the mouse was at and stopPoint is its current point.  controlView is the NSControl managing the receiver. NSCell’s default implementation does nothing. Subclasses often override this method to provide customized tracking behavior. The following example increments the state of a tri-state cell when the mouse is clicked.

- (void)stopTracking:(NSPoint)lastPoint at:(NSPoint)stopPoint

inView:(NSView *)controlView mouseIsUp:(BOOL)flag

{

    if (flag == YES) {

        [self setTriState:([self triState]+1)];

    }

}

See also:	− startTracking:at:inView:, − stopTracking:at:inView:mouseIsUp:

stringValue

− (NSString *)stringValue

Returns the receiver’s value as an NSString as converted by the receiver’s formatter, if one exists. If no formatter exists and the value is an NSString, returns the value as an plain, attributed or localized formatted string. If the value is not an NSString or can’t be converted to one, returns an empty string.

See also:	− setStringValue:

tag

− (int)tag

Implemented by NSActionCell to return the receiver’s tag integer. NSCell’s implementation returns -1.

See also:	− setTag:

takeDoubleValueFrom:

− (void)takeDoubleValueFrom:(id)sender

Sets the receiver’s own value as a double using the double value of sender.

See also:	− setDoubleValue:

takeFloatValueFrom:

− (void)takeFloatValueFrom:(id)sender

Sets the receiver’s own value as a float using the float value of sender.

See also:	− setFloatValue:

takeIntValueFrom:

− (void)takeIntValueFrom:(id)sender

Sets the receiver’s own value as an int using the int value of sender. The following example shows this method being used to write the value taken from a slider (sender) to a text field cell:

- (void)sliderMoved:(id)sender

{

    [[valueField cell] takeIntValueFrom:[sender cell]];

    [valueField display];

}

See also:	− setIntValue:

takeObjectValueFrom:

− (void)takeObjectValueFrom:(id)sender

Sets the receiver’s own value as an object using the object value of sender.

See also:	− setObjectValue:

takeStringValueFrom:

− (void)takeStringValueFrom:(id)sender

Sets the receiver’s own value as a string object using the NSString value of sender.

See also:	− setStringValue:

target

− (id)target

Implemented by NSActionCell to return the target object to which the receiver’s action message is sent. NSCell’s implementation returns nil.

See also:	− setTarget:

titleRectForBounds:

− (NSRect)titleRectForBounds:(NSRect)theRect

If the receiver is a text-type cell, resizes the drawing rectangle for the title (theRect) inward by a small offset to accommodate the cell border. If the receiver is not a text-type cell, the method does nothing.

See also:	− imageRectForBounds:

trackMouse:inRect:ofView:untilMouseUp:

− (BOOL)trackMouse:(NSEvent *)theEvent

inRect:(NSRect)cellFrame

ofView:(NSView *)controlView

untilMouseUp:(BOOL)flag

Invoked by an NSControl to initiate the tracking behavior of one of its NSCells. It’s generally not overriden since the default implementation invokes other NSCell methods that can be overriden to handle specific events in a dragging session. Returns YES if the mouse goes up within cellFrame, NO otherwise. The argument theEvent is typically the mouse event received by the initiating NSControl, usually identified by controlView. The flag argument indicates whether tracking should continue until the mouse button goes up; if flag is NO, tracking ends when the mouse is dragged after the initial mouse down.

This method first invokes startTrackingAt:inView:.  If that method returns YES, then as mouse-dragged events are intercepted, continueTracking:at:inView: is invoked, and, finally, when the mouse leaves the bounds or if the mouse button goes up, stopTracking:at:inView:mouseIsUp: is invoked (if cellFrame is NULL, then the bounds are considered infinitely large).  You usually override one or more of these methods to respond to specific mouse events.

type

− (int)type

Returns the type of the receiver, one of NSTextTypeCell, NSImageTypeCell, or NSNullCellType.

See also:	− setType:

wraps

− (BOOL)wraps

Returns whether text of the receiver wraps when it exceeds the borders of the cell.

See also:	− setWraps:


NSChangeSpelling

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Adopted By:	NSText

Declared In:	AppKit/NSSpellProtocol.h

Protocol Description

This protocol is implemented by objects in the responder chain that can correct a misspelled word. See the description of the NSSpellChecker class for more information.

Instance Methods

changeSpelling:

− (void)changeSpelling:(id)sender

Implement this method to replace the selected word in the receiver with a corrected version from the Spelling panel.  This message is sent by the NSSpellChecker to the object whose text is being checked.  To get the corrected spelling, ask the sender for the string value of its selected cell (visible to the user as the text field in the Spelling panel).  This method should replace the selected portion of the text with the string that it gets from the NSSpellChecker.


NSClipView

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSClipView.h

Purpose

An NSClipView contains and scrolls the document view displayed by an NSScrollView. You normally don’t need to program with NSClipViews, as NSScrollView handles most of the details of their operation.

Principal Attributes

•	Efficient scrolling by copying drawn portions of the document view

•	Monitoring of document view for automatic update

Creation

Interface Builder

− initWithFrame:	Initializes the NSClipView.

Commonly Used Methods

− setDocumentView:	Sets the view scrolled within the NSClipView.

− setCopiesOnScroll:	Sets whether the NSClipView copies drawn portions of the document view during scrolling.

Class Description

An NSClipView holds the document view of an NSScrollView, clipping the document view to its frame, handling the details of scrolling in an efficient manner, and updating the NSScrollView when the document view’s size or position changes. You don’t normally use the NSClipView class directly; it’s provided primarily as the scrolling machinery for the NSScrollView class. However, you might use the NSClipView class to implement a class similar to NSScrollView.

When an NSClipView is instructed to scroll its document view, it copies as much of the already-drawn document view as possible. This allows for efficient scrolling by obviating the need to redraw large portions of the document view. The NSClipView then sends its document view a setNeedsDisplayInRect: message to mark as invalid the newly exposed region(s) of the document view. If copying drawn areas is inappropriate for your needs, you can turn it off by sending the NSClipView a setCopiesOnScroll: message with an argument of NO.

In addition to performing the details of scrolling, an NSClipView monitors its document view and sends its superview (usually an NSScrollView) a reflectScrolledClipView: message whenever the relationship between the NSClipView and the document view has changed. This allows the superview to update itself to reflect the change—for example, an NSScrollView uses this method to change the position of its scrollers when the user causes the document view to autoscroll or when the document view’s size changes.

Method Types

Setting the document view	− setDocumentView:

− documentView

Scrolling	− scrollToPoint:

− autoscroll:

− constrainScrollPoint:

Determining scrolling efficiency	− setCopiesOnScroll:

− copiesOnScroll

Getting the visible portion	− documentRect

− documentVisibleRect

Setting the document cursor	− setDocumentCursor:

− documentCursor

Setting the background color	− setBackgroundColor:

− backgroundColor

Overridden NSView methods	− acceptsFirstResponder

− becomeFirstResponder

− isFlipped

− rotateByAngle:

− scaleUnitSquareToSize:

− setBoundsOrigin:

− setBoundsRotation:

− setBoundsSize:

− setFrameSize:

− setFrameOrigin:

− setFrameRotation:

− setNextKeyView:

− translateOriginToPoint:

− viewBoundsChanged:

− viewFrameChanged:

Instance Methods

acceptsFirstResponder

− (BOOL)acceptsFirstResponder

Returns YES if the receiver has a document view, NO otherwise.

See also:	− documentView, − acceptsFirstResponder (NSResponder)

autoscroll:

− (BOOL)autoscroll:(NSEvent *)theEvent

Scrolls the receiver proportionally to theEvent’s distance outside of it. theEvent’s location should be expressed in the window’s base coordinate system (which it normally is), not the receiving NSClipView’s. Returns YES if any scrolling is performed; otherwise returns NO.

Never invoke this method directly; instead, the NSClipView’s document view should repeatedly send itself autoscroll: messages when the mouse is dragged outside the NSClipView’s frame during a modal event loop initiated by a mouse-down event. The NSView class implements autoscroll: to forward the message to the receiver’s superview; thus the message is ultimately forwarded to the NSClipView.

backgroundColor

− (NSColor *)backgroundColor

Returns the color of the receiver’s background.

See also:	− setBackgroundColor:

becomeFirstResponder

− (BOOL)becomeFirstResponder

If the key view selection direction of the receiver’s NSWindow isn’t NSSelectingPrevious, attempts to make the document view the first responder. If the direction is NSSelectingPrevious, attempts to make the receiver’s previous key view (typically the containing NSScrollView) the first responder. Returns YES if successful and NO otherwise

See also:	− becomeFirstResponder: (NSResponder), − makeFirstResponder: (NSWindow),

− keyViewSelectionDirection (NSWindow)

constrainScrollPoint:

− (NSPoint)constrainScrollPoint:(NSPoint)proposedNewOrigin

Returns a scroll point adjusted from proposedNewOrigin, if necessary, to guarantee that the receiver will still lie within its document view. For example, if proposedNewOrigin’s y coordinate lies to the left of the document view’s origin, then the y coordinate returned is set to that of the document view’s origin.

See also:	− scrollToPoint:

copiesOnScroll

− (BOOL)copiesOnScroll

Returns YES if the receiver copies its existing rendered image while scrolling (only drawing exposed portions of its document view), NO if it forces its contents to be redrawn each time.

See also:	− setCopiesOnScroll:

documentCursor

− (NSCursor *)documentCursor

Returns the cursor object used when the mouse lies over the receiver.

See also:	− setDocumentCursor:

documentRect

− (NSRect)documentRect

Returns the rectangle defining the document view’s frame, adjusted to the size of the receiver if the document view is smaller. In other words, this rectangle is always at least as large as the receiver itself.

The document rectangle is used in conjunction with an NSClipView’s bounds rectangle to determine values for the indicators of relative position and size between the NSClipView and its document view. For example, NSScrollView uses these rectangles to set the size and position of the knobs in its scrollers. When the document view is much larger than the NSClipView, the knob is small; when the document view is near the same size, the knob is large; and when the document view is the same size or smaller, there is no knob.

See also:	− reflectScrolledClipView: (NSScrollView), − documentVisibleRect

documentView

− (id)documentView

Returns the receiver’s document view.

See also:	− setDocumentView:

documentVisibleRect

− (NSRect)documentVisibleRect

Returns the exposed rectangle of the receiver’s document view, in the document view’s own coordinate system. Note that this rectangle doesn’t reflect the effects of any clipping that may occur above the NSClipView itself. To get the portion of the document view that’s guaranteed to be visible, send it a visibleRect message.

See also:	− documentRect

isFlipped

− (BOOL)isFlipped

Returns YES if the document view is flipped, NO if it isn’t.

See also:	− isFlipped (NSView)

rotateByAngle:

− (void)rotateByAngle:(float)angle

Overrides NSView’s implementation to disable rotation.

scaleUnitSquareToSize:

− (void)scaleUnitSquareToSize:(NSSize)newUnitSize

Performs as NSView’s implementation and updates a containing NSScrollView based on the new bounds.

scrollToPoint:

− (void)scrollToPoint:(NSPoint)newOrigin

Changes the origin of the receiver’s bounds rectangle to newOrigin.

See also:	− constrainScrollPoint:

setBackgroundColor:

− (void)setBackgroundColor:(NSColor *)aColor

Sets the receiver’s background color to aColor.

See also:	− backgroundColor

setBoundsOrigin:

− (void)setBoundsOrigin:(NSPoint)aPoint

Performs as NSView’s implementation and updates a containing NSScrollView based on the new bounds.

setBoundsRotation:

− (void)setBoundsRotation:(float)angle

Overrides NSView’s implementation to disable rotation.

setBoundsSize:

− (void)setBoundsSize:(NSSize)aSize

Performs as NSView’s implementation and updates a containing NSScrollView based on the new bounds.

setCopiesOnScroll:

− (void)setCopiesOnScroll:(BOOL)flag

Controls whether the receiver copies rendered images while scrolling. If flag is YES, the receiver copies the existing rendered image to its new location while scrolling, and only draws exposed portions of its document view. If flag is NO, the receiver always forces its document view to draw itself on scrolling.

See also:	− copiesOnScroll

setDocumentCursor:

− (void)setDocumentCursor:(NSCursor *)aCursor

Sets the cursor object used over the receiver to aCursor.

See also:	− documentCursor

setDocumentView:

− (void)setDocumentView:(NSView *)aView

Sets the receiver’s document view to aView, removing any previous document view, and sets the origin of the receiver’s bounds rectangle to the origin of aView’s frame rectangle. If the receiver is contained in an NSScrollView, you should send the NSScrollView a setDocumentView: message instead, so that it can perform whatever updating it needs.

In the process of setting the document view, this method registers the receiver for the notifications NSViewFrameDidChangeNotification and NSViewBoundsDidChangeNotification, adjusts the key view loop to include the new document view, and updates a parent NSScrollView’s display if needed using reflectScrolledClipView:.

See also:	− documentView

setFrameOrigin:

− (void)setFrameOrigin:(NSPoint)aPoint

Performs as NSView’s implementation and updates a containing NSScrollView based on the new bounds.

setFrameRotation:

− (void)setFrameRotation:(float)angle

Overrides NSView’s implementation to disable rotation.

setFrameSize:

− (void)setFrameSize:(NSSize)aSize

Performs as NSView’s implementation and updates a containing NSScrollView based on the new bounds.

setNextKeyView:

− (void)setNextKeyView:(NSView *)aView

Performs as NSView’s implementation, except inserts the receiver’s document view between itself and aView in the key view loop.

See also:	− setNextKeyView: (NSView)

translateOriginToPoint:

− (void)translateOriginToPoint:(NSPoint)aPoint

Performs as NSView’s implementation and updates a containing NSScrollView based on the new bounds.

viewBoundsChanged:

− (void)viewBoundsChanged:(NSNotification *)aNotification

Handles an NSViewBoundsDidChangeNotification by updating a containing NSScrollView based on the new bounds.

viewFrameChanged:

− (void)viewFrameChanged:(NSNotification *)aNotification

Handles an NSViewFrameDidChangeNotification by updating a containing NSScrollView based on the new frame.

Methods Implemented by an NSClipView’s Superview

reflectScrolledClipView:

− (void)reflectScrolledClipView:(NSClipView *)aClipView

Notifies aClipView’s superview that either aClipView’s bounds rectangle or the document view’s frame rectangle has changed, and that any indicators of the scroll position need to be adjusted. NSScrollView implements this method to update its NSScrollers.

scrollClipView:toPoint:

− (void)scrollClipView:(NSClipView *)aClipView toPoint:(NSPoint)newOrigin

Notifies aClipView’s superview that aClipView needs to set its bounds rectangle origin to newOrigin. aClipView’s superview should then send a scrollToPoint: message to aClipView with newOrigin as the argument. This mechanism is provided so that the NSClipView’s superview can coordinate scrolling of multiple tiled NSClipViews.

See also:	− scrollToPoint: (NSClipView)


NSCoder Additions
p NSCoder Additions

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Declared In:	AppKit/NSColor.h

Class Description

This category adds a single method to the Foundation framework’s NSCoder class. This method, decodeNXColor, is used to convert archived NXColors into NSColors.

NXColor, a type that dates from pre-OpenStep versions of NEXTSTEP, was a struct. Its replacement, NSColor, is a class. The difficulties of converting from a struct to a class require a special method like decodeNXColor.

Note:	decodeNXColor becomes part of the NSCoder class only for applications that use the Application Kit.

For more information, see the NSCoder class specification in the Foundation Framework Reference.

Instance Methods

p	decodeNXColor

− (NSColor *)decodeNXColor

Returns an NSColor that is equivalent to the archived NXColor.


NSColor

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSResponder : NSObject

Conforms To:	NSCoding

NSCopying

NSObject (NSObject)

Declared In:	AppKit/NSColor.h

Purpose

An NSColor object represents a color, which is defined in a color space, each point of which has a set of components (such as red, green, and blue) that uniquely define a color.

Principal Attributes

•	Color space	•	Color components

Creation

colorWith... methods

Individual color methods

Commonly Used Methods

colorSpaceName	Gets the NSColor’s color space.

set	Sets the drawing color.

Class Description

An NSColor object represents a color. The color can be a grayscale value and can include alpha (opacity) information. By sending a set message to an NSColor instance, you set the color for the current PostScript drawing context. This causes subsequently drawn graphics to have the color represented by the NSColor instance.

Color Spaces

A color is defined in some particular color space. A color space consists of a set of dimensions—such as red, green, and blue in the case of RGB space. Each point in the space represents a unique color, and the point’s location along each dimension is called a component. An individual color is usually specified by the numeric values of its components, which range from 0.0 to 1.0. For instance, a pure red is specified in RGB space by the component values 1.0, 0.0, and 0.0.

Some color spaces include an alpha component, which defines the color’s opacity. An alpha value of 1.0 means completely opaque, and 0.0 means completely transparent. The alpha component is ignored when the color is used on a device that doesn’t support alpha, such as a printer.

There are three kinds of color spaces in NEXTSTEP:

•	Device-dependent. This means that a given color might not look the same on different displays and printers.

•	Device-independent, also known as calibrated. With this sort of color space, a given color should look the same on all devices.

•	Named. The “named color space” has components that aren’t numeric values, but simply names in various catalogs of colors. Named colors come with lookup tables that provide the ability to generate the correct color on a given device.

NEXTSTEP includes six different color spaces, referred to by these enumeration constants:

NSDeviceCMYKColorSpace

Cyan, magenta, yellow, black, and alpha components

NSDeviceWhiteColorSpace	White and alpha components

NSDeviceRGBColorSpace	Red, green, blue, and alpha components

Hue, saturation, brightness, and alpha components

NSCalibratedWhiteColorSpace

White and alpha components

NSCalibratedRGBColorSpace

Red, green, blue, and alpha components

Hue, saturation, brightness, and alpha components

NSNamedColorSpace	Catalog name and color name components

(Color spaces whose names start with “NSDevice” are device-dependent; those with “NSCalibrated” are device-independent.)

Color Components

There’s usually no need to retrieve the individual components of a color, but when needed, you can either retrieve a set of components (using such methods as getRed:green:blue:alpha:) or an individual component (using such methods as redComponent). However, it’s illegal to ask an NSColor for components that aren’t defined for its color space. You can identify the color space by sending a colorSpaceName message to the NSColor object. If you need to ask an NSColor for components that aren’t in its color space (for instance, when you’ve gotten the color from the color panel), first convert the color to the appropriate color space using the colorUsingColorSpaceName: method. If the color is already in the specified color space, you get the same color back; otherwise you get a conversion that’s usually lossy or that’s correct only for the current device. You get back nil if the specified conversion can’t be done.

Creating Subclasses

Subclasses of NSColor need to implement the colorSpaceName and set methods, as well as the methods that return the components for that color space and the methods in the NSCoding protocol. Some other methods—such as colorWithAlphaComponent:, isEqual:, and colorUsingColorSpaceName:device:—may also be implemented if they make sense for the color space. Mutable subclasses (if any) should additionally implement copyWithZone: to provide a true copy.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

NSCopying	− copyWithZone:

Method Types

Creating an NSColor object from Component Values

+ colorWithCalibratedHue:saturation:brightness:alpha:

+ colorWithCalibratedRed:green:blue:alpha:

+ colorWithCalibratedWhite:alpha:alpha

+ colorWithCatalogName:colorName:

+ colorWithDeviceCyan:magenta:yellow:black:alpha:

+ colorWithDeviceHue:saturation:brightness:alpha:

+ colorWithDeviceRed:green:blue:alpha:

+ colorWithDeviceWhite:alpha:

Creating an NSColor With Preset Components

+ blackColor

+ blueColor

+ brownColor

+ clearColor

+ cyanColor

+ darkGrayColor

+ grayColor

+ greenColor

+ lightGrayColor

+ magentaColor

+ orangeColor

+ purpleColor

+ redColor

+ whiteColor

+ yellowColor

Ignoring Alpha Components	+ ignoresAlpha

+ setIgnoresAlpha:

Copying and Pasting	+ colorFromPasteboard:

− writeToPasteboard:

Retrieving a Set of Components	− getCyan:magenta:yellow:black:alpha:

− getHue:saturation:brightness:alpha:

− getRed:green:blue:alpha:

− getWhite:alpha:

Retrieving Individual Components	− alphaComponent

− blackComponent

− blueComponent

− brightnessComponent

− catalogNameComponent

− colorNameComponent

− cyanComponent

− greenComponent

− hueComponent

− localizedCatalogNameComponent

− localizedColorNameComponent

− magentaComponent

− redComponent

− saturationComponent

− whiteComponent

− yellowComponent

Converting to Another Color Space	− colorSpaceName

− colorUsingColorSpaceName:

− colorUsingColorSpaceName:device:

Changing the Color	− blendedColorWithFraction:ofColor:

− colorWithAlphaComponent:

Drawing	− drawSwatchInRect:

− set

Class Methods

blackColor

+ (NSColor *)blackColor

Returns an NSColor in NSCalibratedWhiteColorSpace whose grayscale value is 0.0 and whose alpha value is 1.0.

See also:	− blackComponent

blueColor

+ (NSColor *)blueColor

Returns an NSColor in NSCalibratedRGBColorSpace whose RGB value is 0.0, 0.0, 1.0 and whose alpha value is 1.0.

See also:	− blueComponent

brownColor

+ (NSColor *)brownColor

Returns an NSColor in NSCalibratedRGBColorSpace whose RGB value is 0.6, 0.4, 0.2 and whose alpha value is 1.0.

clearColor

+ (NSColor *)clearColor

Returns an NSColor in NSCalibratedWhiteColorSpace whose grayscale and alpha values are both 0.0.

colorFromPasteboard:

+ (NSColor *)colorFromPasteboard:(NSPasteboard *)pasteBoard

Returns the NSColor currently on the pasteboard, or nil if the pasteboard doesn’t contain color data. The returned color’s alpha component is set to 1.0 if ignoresAlpha returns YES.

This method invokes colorWithAlphaComponent:.

See also:	− writeToPasteboard:

colorWithCalibratedHue:saturation:brightness:alpha:

+ (NSColor *)colorWithCalibratedHue:(float)hue

saturation:(float)saturation

brightness:(float)brightness

alpha:(float)alpha

Creates and returns a new NSColor whose color space is NSCalibratedRGBColorSpace, whose opacity value is alpha, and whose components in HSB space would be hue, saturation, and brightness. All values are not legal: Values less than 0.0 are set to 0.0, and values greater than 1.0 are set to 1.0.

See also:	+ colorWithCalibratedRed:green:blue:alpha:, + colorWithDeviceHue:saturation:brightness:alpha:, − getHue:saturation:brightness:alpha:

colorWithCalibratedRed:green:blue:alpha:

+ (NSColor *)colorWithCalibratedRed:(float)red

green:(float)green

blue:(float)blue

alpha:(float)alpha

Creates and returns a new NSColor whose color space is NSCalibratedRGBColorSpace, whose opacity value is alpha, and whose RGB components are red, green, and blue. All values are not legal: Values less than 0.0 are set to 0.0, and values greater than 1.0 are set to 1.0.

See also:	+ colorWithCalibratedHue:saturation:brightness:alpha:, + colorWithDeviceRed:green:blue:alpha:, − getRed:green:blue:alpha:

colorWithCalibratedWhite:alpha:

+ (NSColor *)colorWithCalibratedWhite:(float)white

alpha:(float)alpha

Creates and returns a new NSColor whose color space is NSCalibratedWhiteColorSpace, whose opacity value is alpha, and whose grayscale value is white. All values are not legal: Values less than 0.0 are set to 0.0, and values greater than 1.0 are set to 1.0.

See also:	+ colorWithDeviceWhite:alpha:, − getWhite:alpha:

colorWithCatalogName:colorName:

+ (NSColor *)colorWithCatalogName:(NSString *)listName

 colorName:(NSString *)colorName

Creates and returns a new NSColor whose color space is NSNamedColorSpace, by finding the color named colorName in the catalog named listName, which may be a standard catalog.

See also:	− catalogNameComponent, − colorNameComponent, − localizedCatalogNameComponent

colorWithDeviceCyan:magenta:yellow:black:alpha:

+ (NSColor *)colorWithDeviceCyan:(float)cyan

magenta:(float)magenta

yellow:(float)yellow

black:(float)black

alpha:(float)alpha

Creates and returns a new NSColor whose color space is NSDeviceCMYKColorSpace, whose opacity value is alpha, and whose CMYK components are cyan, magenta, yellow, and black. All values are not legal: Values less than 0.0 are set to 0.0, and values greater than 1.0 are set to 1.0. In PostScript, this colorspace corresponds directly to the device-dependent operator setcmykcolor.

See also:	− getCyan:magenta:yellow:black:alpha:

colorWithDeviceHue:saturation:brightness:alpha:

+ (NSColor *)colorWithDeviceHue:(float)hue

saturation:(float)saturation

brightness:(float)brightness

alpha:(float)alpha

Creates and returns a new NSColor whose color space is NSDeviceRGBColorSpace, whose opacity value is alpha, and whose components in HSB space would be hue, saturation, and brightness. All values are not legal: Values less than 0.0 are set to 0.0, and values greater than 1.0 are set to 1.0. In PostScript, this colorspace corresponds directly to the device-dependent operator setrgbcolor.

See also:	+ colorWithCalibratedHue:saturation:brightness:alpha:, − colorWithDeviceRed:green:blue:alpha:, − getHue:saturation:brightness:alpha:

colorWithDeviceRed:green:blue:alpha:

+ (NSColor *)colorWithDeviceRed:(float)red

green:(float)green

blue:(float)blue

alpha:(float)alpha

Creates and returns a new NSColor whose color space is NSDeviceRGBColorSpace, whose opacity value is alpha, and whose RGB components are red, green, and blue. All values are not legal: Values less than 0.0 are set to 0.0, and values greater than 1.0 are set to 1.0. In PostScript, this colorspace corresponds directly to the device-dependent operator setrgbcolor.

See also:	+ colorWithCalibratedRed:green:blue:alpha:, − colorWithDeviceHue:saturation:brightness:alpha:, − getRed:green:blue:alpha:

colorWithDeviceWhite:alpha:

+ (NSColor *)colorWithDeviceWhite:(float)white

alpha:(float)alpha

Creates and returns a new NSColor whose color space is NSDeviceWhiteColorSpace, whose opacity value is alpha, and whose grayscale value is white. All values are not legal: Values less than 0.0 are set to 0.0, and values greater than 1.0 are set to 1.0. In PostScript, this colorspace corresponds directly to the device-dependent operator setgray.

See also:	+ colorWithCalibratedWhite:alpha:, − getWhite:alpha:

cyanColor

+ (NSColor *)cyanColor

Returns an NSColor in NSCalibratedRGBColorSpace whose RGB value is 0.0, 1.0, 1.0 and whose alpha value is 1.0.

See also:	− cyanComponent

darkGrayColor

+ (NSColor *)darkGrayColor

Returns an NSColor in NSCalibratedWhiteColorSpace whose grayscale value is 1/3 and whose alpha value is 1.0.

grayColor

+ (NSColor *)grayColor

Returns an NSColor in NSCalibratedWhiteColorSpace whose grayscale value is 0.5 and whose alpha value is 1.0.

greenColor

+ (NSColor *)greenColor

Returns an NSColor in NSCalibratedRGBColorSpace whose RGB value is 0.0, 1.0, 0.0 and whose alpha value is 1.0.

See also:	− greenComponent

ignoresAlpha

+ (BOOL)ignoresAlpha

Returns YES if the application doesn’t support alpha. This value returned is consulted when an application imports alpha (through color dragging, for instance). The value determines whether the color panel has an opacity slider. This value is YES by default, indicating that the opacity components of imported colors will be set to 1.0. If an application wants alpha, it can invoke the setIgnoresAlpha method with a parameter of NO.

See also:	+ setIgnoresAlpha, − alphaComponent

lightGrayColor

+ (NSColor *)lightGrayColor

Returns an NSColor in NSCalibratedWhiteColorSpace whose grayscale value is 2/3 and whose alpha value is 1.0.

magentaColor

+ (NSColor *)magentaColor

Returns an NSColor in NSCalibratedRGBColorSpace whose RGB value is 1.0, 0.0, 1.0 and whose alpha value is 1.0.

See also:	− magentaComponent

orangeColor

+ (NSColor *)orangeColor

Returns an NSColor in NSCalibratedRGBColorSpace whose RGB value is 1.0, 0.5, 0.0 and whose alpha value is 1.0.

purpleColor

+ (NSColor *)purpleColor

Returns an NSColor in NSCalibratedRGBColorSpace whose RGB value is 0.5, 0.0, 0.5 and whose alpha value is 1.0.

redColor

+ (NSColor *)redColor

Returns an NSColor in NSCalibratedRGBColorSpace whose RGB value is 1.0, 0.0, 0.0 and whose alpha value is 1.0.

See also:	− redComponent

setIgnoresAlpha:

+ (void)setIgnoresAlpha:(BOOL)flag

If flag is YES, The application won’t support alpha. In this case, no opacity slider is displayed in the color panel, and colors dragged in or pasted have their alpha values set to 1.0. Applications which need to import alpha should invoke this method with flag set to NO and explicitly make colors opaque in cases where it matters to them.

See also:	+ ignoresAlpha, − alphaComponent

whiteColor

+ (NSColor *)whiteColor

Returns an NSColor in NSCalibratedWhiteColorSpace whose grayscale and alpha values are both 1.0.

See also:	− whiteComponent

yellowColor

+ (NSColor *)yellowColor

Returns an NSColor in NSCalibratedRGBColorSpace whose RGB value is 1.0, 1.0, 0.0 and whose alpha value is 1.0.

See also:	− yellowComponent

Instance Methods

alphaComponent

− (float)alphaComponent

Returns the alpha (opacity) component. Returns 1.0 (opaque) for colors that do not have alpha components.

See also:	− getCyan:magenta:yellow:black:alpha:, − getHue:saturation:brightness:alpha:, − getRed:green:blue:alpha:, − getWhite:alpha:

blackComponent

− (float)blackComponent

Returns the black component. It’s an error if the receiver isn’t a CMYK color.

See also:	+ blackColor, − getCyan:magenta:yellow:black:alpha:

blendedColorWithFraction:ofColor:

− (NSColor *)blendedColorWithFraction:(float)fraction

ofColor:(NSColor *)color

Returns a newly created NSColor in NSCalibratedRGBColorSpace whose component values are a weighted sum of the receiver’s and color’s. The method converts color and a copy of the receiver to RGB, and then sets each component of the returned color to fraction of color’s value plus 1 − fraction of the receiver’s. If the colors can’t be converted to NSCalibratedRGBColorSpace, nil is returned.

This method invokes colorUsingColorSpaceName:.

blueComponent

− (float)blueComponent

Returns the blue component. It’s an error if the receiver isn’t an RGB color.

See also:	+ blueColor, − getRed:green:blue:alpha:

brightnessComponent

− (float)brightnessComponent

Returns the brightness component of the HSB color equivalent to the receiver. It’s an error if the receiver isn’t an RGB color.

See also:	− getHue:saturation:brightness:alpha:

catalogNameComponent

− (NSString *)catalogNameComponent

Returns the name of the catalog containing this color, or nil if the receiver’s color space isn’t NSNamedColorSpace.

See also:	+ colorWithCatalogName:colorName:, − colorNameComponent, − localizedCatalogNameComponent

colorNameComponent

− (NSString *)colorNameComponent

Returns the name of this color, or nil if the receiver’s color space isn’t NSNamedColorSpace.

See also:	+ colorWithCatalogName:colorName:, − catalogNameComponent, − localizedCatalogNameComponent

colorSpaceName

− (NSString *)colorSpaceName

Returns the name of the NSColor’s color space. This method should be implemented in subclasses of NSColor.

See also:	− colorUsingColorSpaceName:, − colorUsingColorSpaceName:device:

colorUsingColorSpaceName:

− (NSColor *)colorUsingColorSpaceName:(NSString *)colorSpace

Returns a newly created NSColor whose color is the same as the receiver’s, except that the new NSColor is in the color space named colorSpace. If colorSpace is nil, the most appropriate color space is used.

This method invokes colorUsingColorSpaceName:device: with a nil device, indicating that the color is appropriate for the current device (the current window if drawing, or the current printer if printing).

Returns nil if the specified conversion cannot be done.

See also:	− colorSpaceName:

colorUsingColorSpaceName:device:

− (NSColor *)colorUsingColorSpaceName:(NSString *)colorSpace

device:(NSDictionary *)deviceDescription

Returns a newly created NSColor whose color is the same as the receiver’s, except that the new NSColor is in the color space named colorSpace and is specific to the device described by deviceDescription. Device descriptions can be obtained from windows, screens, and printers with the deviceDescription method. If colorSpace is nil, the most appropriate color space is used.

If deviceDescription is nil, the current device (as obtained from the currently lockFocus’ed view’s window or, if printing, the current printer) is used.

This method invokes colorSpaceName.

Returns nil if the specified conversion cannot be done.

See also:	− colorSpaceName:, − colorUsingColorSpaceName:

colorWithAlphaComponent:

− (NSColor *)colorWithAlphaComponent:(float)alpha

Returns a newly created NSColor that has the same color space and component values as the receiver, except that its alpha component is alpha. If the receiver’s color space doesn’t include an alpha component, the receiver is returned. A subclass which has explicit opacity components should override this method to return a color with the specified alpha.

See also:	− alphaComponent, − blendedColorWithFraction:ofColor:

cyanComponent

− (float)cyanComponent

Returns the cyan component. It’s an error if the receiver isn’t a CMYK color.

See also:	+ cyanColor, − getCyan:magenta:yellow:black:alpha:

drawSwatchInRect:

− (void)drawSwatchInRect:(NSRect)rect

Draws the current color in the rectangle rect. Subclasses adorn the rectangle in some manner to indicate the type of color. This method is invoked by color wells, swatches, and other user-interface objects that need to display colors.

getCyan:magenta:yellow:black:alpha:

− (void)getCyan:(float *)cyan

magenta:(float *)magenta

yellow:(float *)yellow

black:(float *)black

alpha:(float *)alpha

Returns the CMYK and alpha values in the respective arguments. If NULL is passed in as an argument, the method doesn’t set that value. It’s an error if the receiver isn’t a CMYK color.

See also:	 − alphaComponent, − blackComponent, − cyanComponent, − magentaComponent, − yellowComponent

getHue:saturation:brightness:alpha:

− (void)getHue:(float *)hue

saturation:(float *)saturation

brightness:(float *)brightness

alpha:(float *)alpha

Returns the HSB and alpha values in the respective arguments. If NULL is passed in as an argument, the method doesn’t set that value. It’s an error if the receiver isn’t an RGB color.

See also:	− alphaComponent, − brightnessComponent, − hueComponent, − saturationComponent

getRed:green:blue:alpha:

− (void)getRed:(float *)red

green:(float *)green

blue:(float *)blue

alpha:(float *)alpha

Returns the RGB and alpha values in the respective arguments. If NULL is passed in as an argument, the method doesn’t set that value. It’s an error if the receiver isn’t an RGB color.

See also:	− alphaComponent, − blueComponent, − greenComponent, − redComponent

getWhite:alpha:

− (void)getWhite:(float *)white

alpha:(float *)alpha

Returns the grayscale and alpha values in the respective arguments. If NULL is passed in as an argument, the method doesn’t set that value. It’s an error if the receiver isn’t a grayscale color.

See also:	 − alphaComponent, − whiteComponent

greenComponent

− (float)greenComponent

Returns the green component. It’s an error if the receiver isn’t an RGB color.

See also:	+ greenColor, − getRed:green:blue:alpha:

hueComponent

− (float)hueComponent

Returns the hue component of the HSB color equivalent to the receiver. It’s an error if the receiver isn’t an RGB color.

See also:	− getHue:saturation:brightness:alpha:

localizedCatalogNameComponent

− (NSString *)localizedCatalogNameComponent

Like catalogNameComponent, but returns a localized string.

See also:	+ colorWithCatalogName:colorName:, − colorNameComponent

localizedColorNameComponent

− (NSString *)localizedColorNameComponent

Like colorNameComponent, but returns a localized string.

See also:	+ colorWithCatalogName:colorName:, − catalogNameComponent, − colorNameComponent, − localizedCatalogNameComponent

magentaComponent

− (float)magentaComponent

Returns the magenta component. It’s an error if the receiver isn’t a CMYK color.

See also:	+ magentaColor, − getCyan:magenta:yellow:black:alpha:

redComponent

− (float)redComponent

Returns the red component. It’s an error if the receiver isn’t an RGB color.

See also:	+ redColor, − getRed:green:blue:alpha:

saturationComponent

− (float)saturationComponent

Returns the saturation component of the HSB color equivalent to the receiver. It’s an error if the receiver isn’t an RGB color.

See also:	− getHue:saturation:brightness:alpha:

set

− (void)set

Sets the color of subsequent PostScript drawing to the color that the receiver represents. If the application is drawing to the screen rather than printing, this method also sets the current drawing context’s alpha value to the value returned by alphaComponent; if the color doesn’t know about alpha, it’s set to 1.0. This method should be implemented in subclasses.

whiteComponent

− (float)whiteComponent

Returns the white component. It’s an error if the receiver isn’t a grayscale color.

See also:	+ whiteColor, − getWhite:alpha:

writeToPasteboard:

− (void)writeToPasteboard:(NSPasteboard *)pasteBoard

Writes the receiver’s data to the pasteboard, unless the pasteboard doesn’t support color data (in which case the method does nothing).

See also:	+ colorFromPasteboard:

yellowComponent

− (float)yellowComponent

Returns the yellow component. It’s an error if the receiver isn’t a CMYK color.

See also:	+ yellowColor, − getCyan:magenta:yellow:black:alpha:


NSColorList

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSObject (NSObject)

Declared In:	AppKit/NSColorList.h

Class Description

An NSColorList is an ordered list of NSColors, identified by keys. Instances of NSColorList, or more simply, color lists, are used to manage named lists of NSColors. NSColorPanel’s list-mode color picker uses instances of NSColorList to represent any lists of colors that come with the system, as well as any lists created by the user. An application can use NSColorList to manage document-specific color lists, which may be added to an application’s NSColorPanel using its attachColorList: method.

An NSColorList is similar to a dictionary object: An NSColor is added to, looked up in, and removed from the list by specifying its key, which is an NSString. These keys are used to identify the colors in the list and are used to display the color to the user in the color panel. In addition, colors can be inserted at specified positions in the list.

The color list has a name, specified when you create the object using either the initWithName: or initWithName:fromFile: method.

Instances of NSColorList are created for all user-created color lists (those in the color panel) and various color catalogs available on the system.

An NSColorList saves and retrieves its colors from files with the extension “.clr” in directories defined by a standard search path. To access all the color lists in the standard search path, use the availableColorLists method; this returns an array of NSColorLists, from which you can retrieve the individual color lists by name.

The standard search path for color lists is:

•	/NextLibrary/Colors

•	/LocalLibrary/Colors

•	~/Library/Colors

NSColorList reads color list files in several different formats; it saves color lists using the archiver API.

NSColorList posts an NSColorListChanged notification when a color list is changed.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

Method Types

Initializing an NSColorList 	− initWithName:

− initWithName:fromFile:

Getting All Color Lists	+ availableColorLists

Getting a Color List by Name	+ colorListNamed:

− name

Managing Colors by Key	− allKeys

− colorWithKey:

− insertColor:key:atIndex:

− removeColorWithKey:

− setColor:forKey:

Editing	− isEditable

Writing and Removing Files	− removeFile

− writeToFile:

Class Methods

availableColorLists

+ (NSArray *)availableColorLists

Returns an array of all NSColorLists found in the standard color list directories. Color lists created at run time aren’t included in this list unless they’re saved into one of the standard color list directories.

See also:	+ colorListNamed:

colorListNamed:

+ (NSColorList *)colorListNamed:(NSString *)name

Searches the array that’s returned by availableColorLists and returns the NSColorList named name, or nil if no such color list exists. name must not include the “.clr” suffix.

See also:	− name

Instance Methods

allKeys

− (NSArray *)allKeys

Returns an array of NSString objects that contains all the keys by which the NSColors are stored in the NSColorList. The length of this array equals the number of colors, and its contents are arranged according to the ordering specified when the colors were inserted.

colorWithKey:

− (NSColor *)colorWithKey:(NSString *)key

Returns the NSColor associated with key, or nil if there is none.

initWithName:

− (id)initWithName:(NSString *)name

Initializes and returns the receiver, registering it under the specified name if name isn’t in use already. This method invokes initWithName:fromFile: with a fromFile: argument of nil, indicating that the color list doesn’t need to be initialized from a file.

initWithName:fromFile:

− (id)initWithName:(NSString *)name

fromFile:(NSString *)path

Initializes and returns the receiver, registering it under the specified name if name isn’t in use already. path should be the full path to the file for the color list; name should be the name of the file for the color list (minus the “.clr” extension). A nil path indicates that the color list should be initialized with no colors.

insertColor:key:atIndex:

− (void)insertColor:(NSColor *)color

key:(NSString *)key

atIndex:(unsigned)location

Inserts color at the specified location in the color list (which is numbered starting with 0). If the list already contains a color with the same key at a different location, it’s removed from the old location. This method posts the NSColorListChangedNotification notification to the default notification center. It raises the NSColorListNotEditableException exception if the color list isn’t editable.

See also:	− colorWithKey:, − removeColorWithKey:, − setColor:forKey:

isEditable

− (BOOL)isEditable

Returns YES if the color list can be modified. This depends on the source of the list: If it came from a write-protected file, this method returns NO.

name

− (NSString *)name

Returns the name of the NSColorList.

removeColorWithKey:

− (void)removeColorWithKey:(NSString *)key

Removes the color associated with key from the list. This method does nothing if the list doesn’t contain the key. This method posts the NSColorListChangedNotification notification to the default notification center. It raises the NSColorListNotEditableException exception if the color list is not editable.

See also:	− insertColor:key:atIndex:, − setColor:forKey:

removeFile

− (void)removeFile

Removes the file from which the list was created, if the file is in a standard search path and is owned by the user. The receiver is removed from the list of available color lists returned by availableColorLists, but isn’t released.

setColor:forKey:

− (void)setColor:(NSColor *)color

forKey:(NSString *)key

Associates the specified NSColor with key. If the list already contains key, this method sets the corresponding color to color; otherwise, it inserts color at the end of the list by invoking insertColor:key:atIndex:.

See also:	− colorWithKey:, − insertColor:key:atIndex:, − removeColorWithKey:

writeToFile:

− (BOOL)writeToFile:(NSString *)path

If path is a directory, saves the NSColorList in a file named listname.clr in that directory (where listname is the name with which the NSColorList was initialized). If path includes a file name, this method saves the file under that name. If path is nil, this method saves the file as listname.clr in the standard location. Returns YES upon success and NO if it fails to write the file.

See also:	− removeFile

Notifications

NSColorListChangedNotification

Notification Object	The NSColorList

Posted whenever a color list changes, as when insertColor:key:atIndex: or removeColorWithKey: is invoked.


NSColorPanel

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSPanel : NSWindow : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSColorPanel.h

Class Description

NSColorPanel provides a standard user interface for selecting color in an application. It provides a number of standard color selection modes, and, with the NSColorPickingDefault and NSColorPickingCustom protocols, allows an application to add its own color selection modes. It allows the user to save swatches containing frequently used colors. Once set, these swatches are displayed by NSColorPanel in any application where it is used, giving the user color consistency between applications. NSColorPanel enables users to capture a color anywhere on the screen for use in the active application, and allows dragging colors from itself into views in an application. NSColorPanel’s action message is sent to the target object when the user changes the current color.

An application has only one instance of NSColorPanel, the shared instance. Invoking the sharedColorPanel: method returns the shared instance of NSColorPanel, instantiating it if necessary.

You can put NSColorPanel in any application created with Interface Builder by adding the “Colors...” item from the Menu palette to the application’s menu.

Color Mask and Color Modes

The color mask determines which of the color modes are enabled for NSColorPanel. This mask is set before you initialize a new instance of NSColorPanel. NSColorPanelAllModesMask represents the logical OR of the other color mask constants: It causes the NSColorPanel to display all standard color pickers. When initializing a new instance of NSColorPanel, you can logically OR any combination of color mask constants to restrict the available color modes.

Mode	Color Mask Constant

Grayscale-Alpha	NSColorPanelGrayModeMask

Red-Green-Blue	NSColorPanelRGBModeMask

Cyan-Yellow-Magenta-Black	NSColorPanelCMYKModeMask

Hue-Saturation-Brightness	NSColorPanelHSBModeMask

Custom palette	NSColorPanelCustomPaletteModeMask

Custom color list	NSColorPanelColorListModeMask

Color wheel	NSColorPanelWheelModeMask

All of the above	NSColorPanelAllModesMask

The NSColorPanel’s color mode mask is set using the class method setPickerMask:. The mask must be set before creating an application’s instance of NSColorPanel.

When an application’s instance of NSColorPanel is masked for more than one color mode, your program can set its active mode by invoking the setMode: method with a color mode constant as its argument; the user can set the mode by clicking buttons on the panel. Here are the standard color modes and mode constants:

Mode	Color Mode Constant

Grayscale-Alpha	NSGrayModeColorPanel

Red-Green-Blue	NSRGBModeColorPanel

Cyan-Yellow-Magenta-Black	NSCMYKModeColorPanel

Hue-Saturation-Brightness	NSHSBModeColorPanel

Custom palette	NSCustomPaletteModeColorPanel

Custom color list	NSColorListModeColorPanel

Color wheel	NSWheelModeColorPanel

In grayscale-alpha, red-green-blue, cyan-magenta-yellow-black, and hue-saturation-brightness modes, the user adjusts colors by manipulating sliders. In the custom palette mode, the user can load an NSImage file (TIFF or EPS) into the NSColorPanel, then select colors from the image. In custom color list mode, the user can create and load lists of named colors. The two custom modes provide NSPopUpButtons for loading and saving files. Finally, color wheel mode provides a simplified control for selecting colors.

If a color panel has been used, it uses whatever mode it was in last as the default mode when NSColorPanelAllModesMask is used to initialize the NSColorPanel. Otherwise, it uses color wheel mode.

Associated Classes and Protocols

The NSColorList class provides an API for managing custom color lists. The NSColorPanel methods attachColorList: and detachColorList: let your application add and remove custom lists from the NSColorPanel’s user interface.

The protocols NSColorPickingDefault and NSColorPickingCustom provide an API for adding custom color selection to the user interface. The NSColorPicker class implements the NSColorPickingDefault protocol; you can subclass NSColorPicker and implement the NSColorPickingCustom protocol in your subclass to create your own user interface for color selection.

See also:	NSColorList, NSColorPickingDefault, NSColorPicker, NSColorPickingDefault protocol, NSColorPickingCustom protocol, NSColorWell

Method Types

Creating the NSColorPanel 	+ sharedColorPanel

+ sharedColorPanelExists

Setting color picker modes	+ setPickerMask:

+ setPickerMode:

Setting the NSColorPanel 	− accessoryView

− isContinuous

− mode

− setAccessoryView:

− setAction:

− setContinuous:

− setMode:

− setShowsAlpha:

− setTarget:

− showsAlpha

Attaching a color list	− attachColorList:

− detachColorList:

Setting color	+ dragColor:withEvent:fromView:

− setColor:

Getting color information	− alpha

− color

Class Methods

dragColor:withEvent:fromView:

+ (BOOL)dragColor:(NSColor **)color

withEvent:(NSEvent *)anEvent

fromView:(NSView *)sourceView

Drags color into a destination view from sourceView. This method is usually invoked by the mouseDown: method of sourceView. The dragging mechanism handles all subsequent events.

Because it is a class method, dragColor:withEvent:fromView: can be invoked whether or not the instance of NSColorPanel exists. Returns YES.

setPickerMask:

+ (void)setPickerMask:(int)mask

Accepts as a parameter one or more logically OR’d color mode masks (defined in the header file AppKit/NSColorPanel.h):

•	NSColorPanelGrayModeMask

•	NSColorPanelRGBModeMask

•	NSColorPanelCMYKModeMask

•	NSColorPanelHSBModeMask

•	NSColorPanelCustomPaletteModeMask

•	NSColorPanelColorListModeMask

•	NSColorPanelWheelModeMask

•	NSColorPanelAllModesMask

This determines which color selection modes will be available in an application’s NSColorPanel. This method only has an effect before NSColorPanel is instantiated.

If you create a class that implements the color picking protocols (NSColorPickingDefault and NSColorPickingCustom), you may want to give it a unique mask—one different from those defined for the standard color pickers. To display your color picker, your application will need to logically OR that unique mask with the standard color mask constants when invoking this method.

See also:	+ setPickerMode:, NSColorPicker class, NSColorPickingDefault protocol, NSColorPickingCustom protocol

setPickerMode:

+ (void)setPickerMode:(int)mode

Sets the color panel’s initial picker to mode, which may be one of the symbolic constants described in the class description (declared in the header file AppKit/NSColorPanel.h). The mode determines which picker will initially be visible. This method may be called at any time, whether or not an application’s NSColorPanel has been instantiated.

See also:	+ setPickerMask:, − setMode:

sharedColorPanel

+ (NSColorPanel *)sharedColorPanel

Creates if necessary and returns the shared NSColorPanel.

sharedColorPanelExists

+ (BOOL)sharedColorPanelExists

Returns YES if the NSColorPanel has been created already.

See also:	+ sharedColorPanel

Instance Methods

accessoryView

− (NSView *)accessoryView

Returns the accessory view, or nil if there is none.

See also:	− setAccessoryView:

alpha

− (float)alpha

Returns the NSColorPanel’s current alpha value based on its opacity slider. Returns 1.0 (opaque) if the panel has no opacity slider.

See also:	− setShowsAlpha, − showsAlpha

attachColorList:

− (void)attachColorList:(NSColorList *)colorList

Adds the specified list of NSColors to all the color pickers in the color panel that display color lists by invoking attachColorList: on all color pickers in the application.

An application should use this method to add an NSColorList saved with a document in its file package or in a directory other than NSColorList’s standard search directories.

See also:	− detachColorList

color

− (NSColor *)color

Returns the currently selected color in the NSColorPanel.

See also:	− setColor

detachColorList:

− (void)detachColorList:(NSColorList *)colorList

Removes the specified list of NSColors from all the color pickers in the color panel that display color lists by invoking detachColorList: on all color pickers in the application.

Your application should use this method to remove an NSColorList saved with a document in its file package or in a directory other than NSColorList’s standard search directories.

See also:	− attachColorList

isContinuous

− (BOOL)isContinuous

Returns whether or not the NSColorPanel continuously sends the action message to the target as the user manipulates the color picker.

See also:	− setContinuous

mode

− (int)mode

Returns the color picker mode of the NSColorPanel. The mode constants for the standard color pickers are listed in the class description.

See also:	+ setPickerMode, − setMode

setAccessoryView:

− (void)setAccessoryView:(NSView *)aView

Sets the accessory view displayed in the NSColorPanel to aView. The accessory view can be any custom view that you want to display with NSColorPanel, such as a view offering color blends in a drawing program. The accessory view is displayed below the color picker and above the color swatches in the NSColorPanel. The NSColorPanel automatically resizes to accommodate the accessory view. Returns the previous accessory view, if there was one; otherwise, returns nil.

See also:	− accessoryView:

setAction:

− (void)setAction:(SEL)aSelector

Sets the action message sent to aSelector. The NSColorPanel’s action is the message sent to the target whenever the color is set in the color panel.

See also:	− setTarget

setColor:

− (void)setColor:(NSColor *)color

Sets the color of the NSColorPanel to color. This method posts the NSColorPanelChangedNotification notification with the receiving object to the default notification center.

See also:	− color

setContinuous:

− (void)setContinuous:(BOOL)flag

Sets the NSColorPanel to send the action message to its target continuously as the color of the NSColorPanel is set by the user. Send this message with flag YES if, for example, you want to continuously update the color of the target.

See also:	− isContinuous

setMode:

− (void)setMode:(int)mode

Sets the mode of the NSColorPanel if mode is one of the modes allowed by the color mask. The color mask is set when you first create the shared instance of NSColorPanel for an application. mode may be one of these symbolic constants described in the class description (and declared in the header file AppKit/NSColorPanel.h):

•	NSGrayModeColorPanel

•	NSRGBModeColorPanel

•	NSCMYKModeColorPanel

•	NSHSBModeColorPanel

•	NSCustomPaletteModeColorPanel

•	NSColorListModeColorPanel

•	NSWheelModeColorPanel

See also:	+ setPickerMode, − mode

setShowsAlpha:

− (void)setShowsAlpha:(BOOL)flag

Tells the NSColorPanel whether or not to show alpha values and an opacity slider.

See also:	− alpha, − showsAlpha:

setTarget:

− (void)setTarget:(id)anObject

Sets the target of the NSColorPanel to anObject. The NSColorPanel’s target is the object to which the action message is sent when the user selects a color.

See also:	− setAction:, − setContinuous:

showsAlpha

− (BOOL)showsAlpha

Returns whether or not the NSColorPanel shows alpha values and an opacity slider.

See also:	− alpha, − setShowsAlpha:

Notifications

NSColorPanelColorChangedNotification

Notification Object	The NSColorPanel

Posted when the NSColorPanel’s color is set, as when setColor: is invoked.


NSColorPicker

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSColorPickingDefault

NSObject (NSObject)

Declared In:	AppKit/NSColorPicker.h

NSColorPicker is an abstract superclass that implements the NSColorPickingDefault protocol. The NSColorPickingDefault and NSColorPickingCustom protocols define a way to add color pickers (custom user interfaces for color selection) to the NSColorPanel. The simplest way to implement a color picker is to create a subclass of NSColorPicker, instead of implementing the NSColorPickingDefault protocol in another kind of object. (To add functionality, implement the NSColorPickingCustom methods in your subclass.)

The NSColorPickingDefault protocol specification describes the details of implementing a color picker and adding it to your application’s NSColorPanel; you should look there first for an overview of how NSColorPicker works. This specification is provided to document the specific behavior of NSColorPicker’s methods.

Adopted Protocols

NSColorPickingDefault	− alphaControlAddedOrRemoved:

− attachColorList:

− detachColorList:

− initWithPickerMask:colorPanel:

− insertNewButtonImage:in:

− provideNewButtonImage

− setMode:

− viewSizeChanged:

Method Types

Initializing an NSColorPicker	− initWithPickerMask:colorPanel:

Getting the color panel	− colorPanel

Adding button images 	− insertNewButtonImage:in:

− provideNewButtonImage

Setting the mode	− setMode:

Using color lists 	− attachColorList:

− detachColorList:

Responding to a resized view	− viewSizeChanged:

Instance Methods

attachColorList:

− (void)attachColorList:(NSColorList *)colorList

Does nothing. Override to attach a color list to a color picker.

See also:	− detachColorList

colorPanel

− (NSColorPanel *)colorPanel

Returns the NSColorPanel that owns this NSColorPicker.

detachColorList:

− (void)detachColorList:(NSColorList *)colorList

Does nothing. Override to detach a color list from a color picker.

See also:	− attachColorList

initWithPickerMask:colorPanel:

− (id)initWithPickerMask:(int)mask

colorPanel:(NSColorPanel *)owningColorPanel

Sets the color picker’s color panel to owningColorPanel, caching the owningColorPanel value so it can later be returned by the colorPanel method. Returns self. Override this method to respond to the values in mask or do other custom initialization. If you override this method in a subclass, you should forward the message to super as part of the implementation.

See also:	− colorPanel

insertNewButtonImage:in:

− (void)insertNewButtonImage:(NSImage *)newButtonImage

in:(NSButtonCell *)buttonCell

Sets newButtonImage as buttonCell’s image by invoking NSButtonCell’s setImage: method. Called by the color panel to insert a new image into the specified cell. Override this method to customize newButtonImage before insertion in buttonCell.

See also:	− provideNewButtonImage

provideNewButtonImage

− (NSImage *)provideNewButtonImage

Returns the button image for the color picker. The color panel will place this image in the mode button that the user uses to select this picker. (This is the same image that the color panel uses as an argument when sending the insertNewButtonImage:in: message.) The default implementation looks in the color picker’s bundle for a TIFF file named after the color picker’s class, with the extension “.tiff”.

See also:	− insertNewButtonImage:in:

setMode:

− (void)setMode:(int)mode

Does nothing. Override to set the color picker’s mode. Here are the standard color picking modes and mode constants (defined in AppKit/NSColorPanel.h):

Mode	Color Mode Constant

Grayscale-Alpha	NSGrayModeColorPanel

Red-Green-Blue	NSRGBModeColorPanel

Cyan-Yellow-Magenta-Black	NSCMYKModeColorPanel

Hue-Saturation-Brightness	NSHSBModeColorPanel

Custom palette	NSCustomPaletteModeColorPanel

Custom color list	NSColorListModeColorPanel

Color wheel	NSWheelModeColorPanel

In grayscale-alpha, red-green-blue, cyan-magenta-yellow-black, and hue-saturation-brightness modes, the user adjusts colors by manipulating sliders. In the custom palette mode, the user can load an NSImage file (TIFF or EPS) into the NSColorPanel, then select colors from the image. In custom color list mode, the user can create and load lists of named colors. The two custom modes provide NSPopUpLists for loading and saving files. Finally, color wheel mode provides a simplified control for selecting colors.

viewSizeChanged:

− (void)viewSizeChanged:(id)sender

Does nothing. Override to respond to a size change.


NSColorPickingCustom

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Adopted By:	NSColorPicker

Declared In:	AppKit/NSColorPicking.h

Protocol Description

Together with the NSColorPickingDefault protocol, NSColorPickingCustom provides a way to add color pickers—custom user interfaces for color selection—to an application’s NSColorPanel. The NSColorPickingDefault protocol provides basic behavior for a color picker. The NSColorPicker class adopts the NSColorPickingDefault protocol. The easiest way to implement a color picker is to create a subclass of NSColorPicker and implement the NSColorPickingCustom protocol for this new class.

Note:	All of NSColorPickingCustom’s methods must be implemented by the custom color picker.

Here are the standard color picking modes and mode constants (defined in AppKit/NSColorPanel.h):

Mode	Color Mode Constant

Grayscale-Alpha	NSGrayModeColorPanel

Red-Green-Blue	NSRGBModeColorPanel

Cyan-Yellow-Magenta-Black	NSCMYKModeColorPanel

Hue-Saturation-Brightness	NSHSBModeColorPanel

Custom palette	NSCustomPaletteModeColorPanel

Custom color list	NSColorListModeColorPanel

Color wheel	NSWheelModeColorPanel

In grayscale-alpha, red-green-blue, cyan-magenta-yellow-black, and hue-saturation-brightness modes, the user adjusts colors by manipulating sliders. In the custom palette mode, the user can load an NSImage file (TIFF or EPS) into the NSColorPanel, then select colors from the image. In custom color list mode, the user can create and load lists of named colors. The two custom modes provide NSPopUpLists for loading and saving files. Finally, color wheel mode provides a simplified control for selecting colors.

If your color picker includes submodes, you should define a unique value for each submode. As an example, the slider picker has four values defined in the above list (NSGrayModeColorPanel, NSRGBModeColorPanel, NSCMYKModeColorPanel, and NSHSBModeColorPanel)—one for each of its submodes.

See also:	NSColorPickingDefault, NSColorPicker (class)

Method Types

Setting the Current Color 	− setColor:

Getting the Mode 	− currentMode

− supportsMode:

Getting the View 	− provideNewView:

Instance Methods

currentMode

− (int)currentMode

Returns the color picker’s current mode (or submode, if applicable). The returned value should be unique to your color picker. See this protocol description’s list of the unique values for the standard color pickers used by the Application Kit.

See also:	− supportsMode:

provideNewView:

− (NSView *)provideNewView:(BOOL)initialRequest

Returns the view containing the color picker’s user interface. This message is sent to the color picker whenever the color panel attempts to display it. This may be when the panel is first presented, when the user switches pickers, or when the picker is switched through API. The argument initialRequest is YES only when this method is first invoked for your color picker. If initialRequest is YES, the method should perform any initialization required (such as lazily loading a nib file, initializing the view, or performing any other custom initialization required for your picker). The NSView returned by this method should be set to automatically resize both its width and height.

setColor:

− (void)setColor:(NSColor *)color

Adjusts the color picker to make color the currently selected color. This method is invoked on the current color picker each time NSColorPanel’s setColor: method is invoked. If color is actually different from the color picker’s color (as it would be if, for example, the user dragged a color into NSColorPanel’s color well), this method could be used to update the color picker’s color to reflect the change.

supportsMode:

− (BOOL)supportsMode:(int)mode

Returns whether or not the receiver supports the specified picking mode. This method is invoked when the NSColorPanel’s is first initialized: It is used to attempt to restore the user’s previously selected mode. It is also invoked by NSColorPanel’s setMode: method to find the color picker that supports a particular mode. See this protocol description’s list of the unique mode values for the standard color pickers used by the Application Kit.

See also:	− currentMode:


NSColorPickingDefault

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Adopted By:	NSColorPicker

Declared In:	AppKit/NSColorPicking.h

Protocol Description

The NSColorPickingDefault protocol, together with the NSColorPickingCustom protocol, provides an interface for adding color pickers—custom user interfaces for color selection—to an application’s NSColorPanel. The NSColorPickingDefault protocol provides basic behavior for a color picker. The NSColorPickingCustom protocol provides implementation-specific behavior.

The NSColorPicker class implements the NSColorPickingDefault protocol. The simplest way to implement your own color picker is to create a subclass of NSColorPicker, implementing the NSColorPickingCustom protocol for that subclass. However, it’s possible to create a subclass of another class, such as NSView, and use it as a base upon which to add the methods of both NSColorPickingDefault and NSColorPickingCustom.

Color Picker Bundles

A class that implements the NSColorPickingDefault and NSColorPickingCustom protocols needs to be compiled and linked in an application’s object file. However, your application need not explicitly create an instance of this class. Instead, your application’s file package should include a directory named ColorPickers; within this directory you should place a directory MyPickerClass.bundle for each custom color picker your application implements. This bundle should contain all resources required for your color picker: nib files, TIFF files, and so on.

NSColorPanel will allocate and initialize an instance of each class for which a bundle is found in the ColorPickers directory. The class name is assumed to be the bundle directory name minus the .bundle extension.

Color Picker Buttons

NSColorPanel lets the user select a color picker from an NSMatrix of NSButtonCells. This protocol includes methods for providing and manipulating the image that gets displayed on the button.

Color Mask and Color Modes

The color mask determines which color mode is enabled for NSColorPanel. This mask is set before you initialize a new instance of NSColorPanel. NSColorPanelAllModesMask represents the logical OR of the other color mask constants: It causes the NSColorPanel to display all standard color pickers. When initializing a new instance of NSColorPanel, you can logically OR any combination of color mask constants to restrict the available color modes. The predefined color mask constants are:

Mode	Color Mask Constant

Grayscale-Alpha	NSColorPanelGrayModeMask

Red-Green-Blue	NSColorPanelRGBModeMask

Cyan-Yellow-Magenta-Black	NSColorPanelCMYKModeMask

Hue-Saturation-Brightness	NSColorPanelHSBModeMask

Custom palette	NSColorPanelCustomPaletteModeMask

Custom color list	NSColorPanelColorListModeMask

Color wheel	NSColorPanelWheelModeMask

All of the above	NSColorPanelAllModesMask

When an application’s instance of NSColorPanel is masked for more than one color mode, your program can set its active mode by invoking the setMode: method with a color mode constant as its argument; the user can set the mode by clicking buttons on the panel. Here are the standard color modes and mode constants:

Mode	Color Mode Constant

Grayscale-Alpha	NSGrayModeColorPanel

Red-Green-Blue	NSRGBModeColorPanel

Cyan-Yellow-Magenta-Black	NSCMYKModeColorPanel

Hue-Saturation-Brightness	NSHSBModeColorPanel

Custom palette	NSCustomPaletteModeColorPanel

Custom color list	NSColorListModeColorPanel

Color wheel	NSWheelModeColorPanel

In grayscale-alpha, red-green-blue, cyan-magenta-yellow-black, and hue-saturation-brightness modes, the user adjusts colors by manipulating sliders. In the custom palette mode, the user can load an NSImage file (TIFF or EPS) into the NSColorPanel, then select colors from the image. In custom color list mode, the user can create and load lists of named colors. The two custom modes provide NSPopUpLists for loading and saving files. Finally, color wheel mode provides a simplified control for selecting colors.

These constants are defined in AppKit/NSColorPanel.h.

See also:	NSColorPickingCustom, NSColorPicker (class), NSColorPanel (class)

Method Types

Initializing a Color Picker	− initWithPickerMask:colorPanel:

Setting the Mode	− setMode:

Using Color Lists	− attachColorList:

− detachColorList:

Adding Button Images	− insertNewButtonImage:in:

− provideNewButtonImage

Showing Opacity Controls	− alphaControlAddedOrRemoved:

Responding to a Resized View	− viewSizeChanged:

Instance Methods

alphaControlAddedOrRemoved:

− (void)alphaControlAddedOrRemoved:(id)sender

Sent by the color panel when the opacity controls have been hidden or displayed. Invoked automatically when the NSColorPanel’s opacity slider is added or removed; you never invoke this method directly.

If the color picker has its own opacity controls, it should hide or display them, depending on whether the sender’s showsAlpha method returns NO or YES.

attachColorList:

− (void)attachColorList:(NSColorList *)colorList

Tells the color picker to attach the given colorList, if it isn’t already displaying the list. You never invoke this method; it’s invoked automatically by the NSColorPanel when its attachColorList: method is invoked. Since NSColorPanel’s list mode manages NSColorLists, this method need only be implemented by a custom color picker that manages NSColorLists itself. This method ordinarily doesn’t do anything, since NSColorPanel’s list mode manages NSColorLists.

See also:	− detachColorList

detachColorList:

− (void)detachColorList:(NSColorList *)colorList

Tells the color picker to detach the given colorList, unless the receiver isn’t displaying the list. You never invoke this method; it’s invoked automatically by the NSColorPanel when its detachColorList: method is invoked. Since NSColorPanel’s list mode manages NSColorLists, this method need only be implemented by a custom color picker that manages NSColorLists itself. This method ordinarily doesn’t do anything, since NSColorPanel’s list mode manages NSColorLists.

See also:	− attachColorList

initWithPickerMask:colorPanel:

− (id)initWithPickerMask:(int)mask

colorPanel:(NSColorPanel *)owningColorPanel

Notifies the color picker of the color panel’s mask and initializes the color picker. This method is sent by the NSColorPanel to all implementors of the color picking protocols when the application’s color panel is first initialized. In order for your color picker to receive this message, it must have a bundle in your application’s “ColorPickers” directory (described in “Color Picker Bundles” in the Protocol Description).

mask is determined by the argument to the NSColorPanel method setPickerMask:. If no mask has been set, mask is NSColorPanelAllModesMask. If your color picker supports any additional modes, you should invoke the setPickerMask: method when your application initializes to notify the NSColorPanel class. The standard mask constants are:

Mode	Color Mask Constant

Grayscale-Alpha	NSColorPanelGrayModeMask

Red-Green-Blue	NSColorPanelRGBModeMask

Cyan-Yellow-Magenta-Black	NSColorPanelCMYKModeMask

Hue-Saturation-Brightness	NSColorPanelHSBModeMask

Custom palette	NSColorPanelCustomPaletteModeMask

Custom color list	NSColorPanelColorListModeMask

Color wheel	NSColorPanelWheelModeMask

All of the above	NSColorPanelAllModesMask

This method should examine the mask and determine whether it supports any of the modes included there. You may also check the value in mask to enable or disable any subpickers or optional controls implemented by your color picker. Your color picker may also retain owningColorPanel in an instance variable for future communication with the color panel.

This method is provided to initialize your color picker; however, much of a color picker’s initialization may be done lazily through the NSColorPickingCustom protocol’s provideNewView: method. If your color picker responds to any of the modes represented in mask, it should perform its initialization and return self. Color pickers that do so have their buttons inserted in the color panel and continue to receive messages from the panel as the user manipulates it. If the color picker doesn’t respond to any of the modes represented in mask, it should do nothing and return nil.

See also:	+ setPickerMask: (NSColorPanel class)

insertNewButtonImage:in:

− (void)insertNewButtonImage:(NSImage *)newButtonImage

in:(NSButtonCell *)buttonCell

Sets newButtonImage as buttonCell’s image. buttonCell is the NSButtonCell object that lets the user choose the picker from the color panel—the color picker’s representation in the NSColorPanel’s picker NSMatrix. This method should perform application-specific manipulation of the image before it’s inserted and displayed by the button cell.

See also:	− provideNewButtonImage

provideNewButtonImage

− (NSImage *)provideNewButtonImage

Returns the image for the mode button that the user uses to select this picker in the color panel, that is, the color picker’s representation in the NSColorPanel’s picker NSMatrix. (This is the same image that the color panel uses as an argument when sending the insertNewButtonImage:in: message.)

setMode:

− (void)setMode:(int)mode

Sets the color picker’s mode. This method is invoked by NSColorPanel’s setMode: method to ensure that the color picker reflects the current mode. For example, invoke this method during color picker initialization to ensure that all color pickers are restored to the mode the user left them in the last time an NSColorPanel was used.

Most color pickers have only one mode, and thus don’t need to do any work in this method. An example of a color picker that uses this method is the slider picker, which can choose from one of several submodes depending on the value of mode. The available modes are:

Mode	Color Mode Constant

Grayscale-Alpha	NSGrayModeColorPanel

Red-Green-Blue	NSRGBModeColorPanel

Cyan-Yellow-Magenta-Black	NSCMYKModeColorPanel

Hue-Saturation-Brightness	NSHSBModeColorPanel

Custom palette	NSCustomPaletteModeColorPanel

Custom color list	NSColorListModeColorPanel

Color wheel	NSWheelModeColorPanel

viewSizeChanged:

− (void)viewSizeChanged:(id)sender

Tells the color picker when the NSColorPanel’s view size changes in a way that might affect the color picker. sender is the NSColorPanel that contains the color picker. Use this method to perform special preparation when resizing the color picker’s view. Since this method is invoked only as appropriate, it’s better to implement this method than to override the method superviewSizeChanged: for the NSView in which the color picker’s user interface is contained.

See also:	− provideNewView: (NSColorPickingCustom protocol)


NSColorWell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSControl : NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSColorWell.h

Class Description

NSColorWell is an NSControl for selecting and displaying a single color value. An example of an NSColorWell object (or simply color well) is found in NSColorPanel, which uses a color well to display the current color selection. A color well is available from the Palettes panel of Interface Builder.

An application can have one or more active color wells. You can activate multiple color wells by invoking the activate: method with NO as its argument. When a mouse-down event occurs on a color well’s border, it becomes the only active color well. When a color well becomes active, it brings up the color panel also.

The mouseDown: method enables a color well to send its color to another color well or any other subclass of NSView that implements the NSDraggingDestination protocol.

See also:	NSColorPanel (class)

Method Types

Drawing	− drawWellInside:

Activating	− activate:

− deactivate

− isActive

Managing Color	− color

− setColor:

− takeColorFrom:

Managing Borders	− isBordered

− setBordered:

Instance Methods

activate:

− (void)activate:(BOOL)exclusive

Activates the NSColorWell, displays the Color panel, and makes the NSColorPanel’s current color the same as its own. If exclusive is YES, deactivates any other color wells; if NO, keeps them active. Redraws the receiver. An active color well will have its color updated when the NSColorPanel's current color changes. Any color well that shows its border highlights the border when it’s active.

See also:	− deactivate, − isActive

color

− (NSColor *)color

Returns the color of the NSColorWell.

See also:	− setColor:, − takeColorFrom:

deactivate

− (void)deactivate

Deactivates the NSColorWell and redraws it.

See also:	− activate, − isActive

drawWellInside:

− (void)drawWellInside:(NSRect)insideRect

Draws the colored area inside the NSColorWell at the location specified by insideRect without drawing borders.

isActive

− (BOOL)isActive

Indicates whether the NSColorWell is active.

isBordered

− (BOOL)isBordered

Indicates whether the NSColorWell is bordered.

See also:	− setBordered:

setBordered:

− (void)setBordered:(BOOL)bordered

Places or removes a border on the NSColorWell, depending on bordered, and redraws the receiver.

See also:	− isBordered

setColor:

− (void)setColor:(NSColor *)color

Sets the color of the NSColorWell to color and redraws the receiver.

See also:	− color, − takeColorFrom:

takeColorFrom:

− (void)takeColorFrom:(id)sender

Changes the color of the NSColorWell to that of sender.

See also:	− color, − setColor:


NSControl

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	<AppKit/NSControl.h>

Class Description

NSControl is an abstract superclass that provides three fundamental features for implementing user-interface devices. First, as a subclass of NSView, NSControl draws, or coordinates the drawing of, the on-screen representation of the device. Second, it receives and responds to user-generated events within its bounds by overriding NSResponder’s mouseDown: method and providing a position in the responder chain. Third, it implements the sendAction:to: method to send an action message to the NSControl’s target object. Subclasses of NSControl defined in the Application Kit are NSBrowser, NSButton (and its subclass NSPopUpButton), NSColorWell, NSImageView, NSMatrix (and its subclass NSForm), NSScroller, NSSlider, NSTableView, and NSTextField. Instances of concrete NSControl subclasses are often referred to as, simply, controls.

Controls and Cells

Controls are usually associated with one or more cells—instances of a subclass of the abstract class NSCell. A control’s cell (or cells) usually fit just inside the bounds of the control. Cells are objects that can draw themselves and respond to events, but they can do so only indirectly, upon instruction from their control, which acts as a kind of coordinating backdrop.

Controls manage the behavior of their cells. By inheritance from NSView, controls derive the ability for responding to user actions and rendering their on-screen representation. When users click on a control, it responds in part by sending trackMouse:inRect:ofView:untilMouseUp: to the cell that was clicked; upon receiving this message, the cell tracks the mouse and may have the control send the cell’s action message to its target (either upon mouse-up or continuously, depending on the cell’s attributes). When controls receive a display request, they, in turn, send their cell (or cells) a drawWithFrame:inView: message to have the cells draw themselves.

This relationship of control and cell makes two things possible: A control can manage cells of different types and with different targets and actions (see below); and a single control can manage muliple cells. Most Application Kit controls, like NSButtons and NSTextFields, manage only a single cell. But some controls, notably NSMatrix and NSForm, manage multiple cells (usually of the same size and attributes, and arranged in a regular pattern). Because cells are lighter-weight than controls, in terms of inherited data and behavior, it is more efficient to use a multi-cell control rather than multiple controls.

Many methods of NSControl—particularly methods that set or obtain values and attributes—have corresponding methods in NSCell. Sending a message to the control causes it to be forwarded to the control’s cell or (if a multi-cell control) its selected cell. However, many NSControl methods are effective only in controls with single cells (these are noted in the method descriptions).

An NSControl subclass doesn’t have to use an NSCell subclass to implement itself; NSScroller and NSColorWell are examples of NSControls that don’t. However, such subclasses have to take care of details that NSCell would otherwise handle. Specifically, they have to override methods designed to work with a cell. What’s more, the lack of a cell means you can’t make use of NSMatrix capability for managing multi-cell arrays such as radio buttons.

Target and Action

Target objects and action methods (or messages) are part of the mechanism by which controls respond to user actions and enable users to communicate their intentions to an application. A target is an object that a control uses as the receiver of action messages. The target’s class defines an action method to enable its instances to respond to these messages, which are sent as users click or otherwise manipulate the control. NSControl’s sendAction:to: asks the NSApplication object, NSApp, to send an action message to the control’s target object.

NSControl provides methods for setting and obtaining the target object and the action method. However, these methods require that an NSControl’s cell (or cells) be cells that inherit from NSActionCell or custom cells that hold action and target as instance variables and can respond to the NSControl methods.

See the NSActionCell class specification for more on the implementation of target and action behavior, particularly how action messages with nil targets travel up the responder chain.

Field Validation and Entry Error-Handling

NSControl provides the delegation method control:isValidObject: for validating the contents of cells embedded in controls (instances of NSTextField and NSMatrix in particular). In validating you check for values that are permissible as objects, but that are undesirable in a given context, such as a date field in which dates should never be in the future, or zip codes that are valid for a certain state.

The method control:isValidObject: is invoked when the cursor leaves a cell (that is, the associated control relinquishes first-responder status) but before the string value of the cell's object is displayed. Return YES to allow display of the string and NO to reject display and return the cursor to the cell. The following example evaluates an object (an NSDate) and rejects it if the date is in the future:

- (BOOL)control:(NSControl *)control isValidObject:(id)obj

{

if (control == contactsForm) {

if (![obj isKindOfClass:[NSDate class]]) return NO;

if ([[obj laterDate:[NSDate date]] isEqual:obj]) {

NSRunAlertPanel(@"Date not valid",

@"Reason: date in future", NULL, NULL, NULL);

return NO;

}

}

return YES;

}

NSControl also provides delegation methods that are invoked when formatters for a control’s cells cannot format a string (control:didFailToFormatString:errorDescription:) or reject a partial string entry (control:didFailToValidatePartialString:errorDescription:). It also provides  control:textView:doCommandBySelector:, which allows delegates the opportunity to detect and respond to key bindings, such as complete: (name completion).

Changing the NSCell Class

Since NSControl uses objects derived from the NSCell class to implement most of its actual functionality, you can usually implement a unique user interface device by creating a subclass of NSCell rather than NSControl. As an example, let’s say you want all your application’s NSSliders to have a type of cell other than the generic NSSliderCell. First, you create a subclass of NSCell, NSActionCell, or NSSliderCell. (Let’s call it MyCellSubclass.) Then, you can simply invoke NSSlider’s setCellClass: class method:

[NSSlider setCellClass:[MyCellSubclass class]];

All NSSliders created thereafter will use MyCellSubclass, until you call setCellClass: again.

If you want to create generic NSSliders (ones that use NSSliderCell) in the same application as the customized NSSliders that use MyCellSubclass, there are two possible approaches. One is to invoke setCellClass: as above whenever you’re about to create a custom NSSlider, resetting the cell class to NSSliderCell afterwards. The other approach is to create a custom subclass of NSSlider that automatically uses MyCellSubclass, as explained below.

Creating New NSControls

If you create a custom NSControl subclass that uses a custom subclass of NSCell, you should override NSControl’s cellClass method:

+ (Class) cellClass

{

    return [MyCellSubclass class];

}

NSControl’s initWithFrame: method will use the return value of cellClass to allocate and initialize an NSCell of the correct type.

Override the designated initializer (initWithFrame:) if you create a subclass of NSControl that performs its own initialization.

Method Types

Initializing an NSControl	− initWithFrame:

Setting the control’s cell	+ cellClass

+ setCellClass:

− cell

− setCell:

Enabling and disabling the control	− isEnabled

− setEnabled:

Identifying the selected cell	− selectedCell

− selectedTag

Setting the control’s value	− doubleValue

− setDoubleValue:

− floatValue

− setFloatValue:

− intValue

− setIntValue:

− objectValue

− setObjectValue:

− stringValue

− setStringValue:

− setNeedsDisplay

Interacting with other controls	− takeDoubleValueFrom:

− takeFloatValueFrom:

− takeIntValueFrom:

− takeObjectValueFrom:

− takeStringValueFrom:

Formating text	− alignment

− setAlignment:

− font

− setFont:

− setFloatingPointFormat:left:right:

Managing the field editor	− abortEditing

− currentEditor

− validateEditing

Resizing the control	− calcSize

− sizeToFit

Displaying a cell	− selectCell:

− drawCell:

− drawCellInside:

− updateCell:

− updateCellInside:

Implementing the target/action mechanism

− action

− setAction:

− target

− setTarget:

− isContinuous

− setContinuous:

− sendAction:to:

− sendActionOn:

Getting and setting attributed-string values

− attributedStringValue

− setAttributedStringValue:

Getting and setting tags	− tag

− setTag:

Simulating mouse clicks	− performClick:sender:

Tracking the mouse	− mouseDown:

− ignoresMultiClick

− setIgnoresMultiClick:

Class Methods

cellClass

+ (Class)cellClass

Returns the class of cells used by the receiving class (which must be NSControl or one of its subclasses). Returns nil if no cell class has been specified for the receiving class or any of its superclasses (up to NSControl).

See also:	 − cell, − setCell:

setCellClass:

+ (void)setCellClass:(Class)class

Sets the class of cells used by instances of the receiver, which must be the NSControl class or one of its subclasses.

See also:	− cell, − setCell:

Instance Methods

abortEditing

− (BOOL)abortEditing

Terminates and discards any editing of text displayed by the receiving control and removes the field editor’s delegate. Returns YES if there was a field editor associated with the control, NO otherwise.

See also:	− currentEditor, − validateEditing

action

− (SEL)action

Returns the action-message selector of the receiver's cell (the default NSControl behavior), or the default action-message selector for a control with multiple cells (such as an NSMatrix or an NSForm).   For controls with multiple cells, it's better to get the action-message selector for a particular cell, for instance:

someAction = [[theControl selectedCell] action];

See also:	− setAction:, − setTarget:, − target

alignment

− (NSTextAlignment)alignment

Returns the alignment mode of the text in the receiver's cell.  The return value can be one of these constants:  NSLeftTextAlignment, NSRightTextAlignment, NSCenterTextAlignment, NSJustifiedTextAlignment, or NSNaturalTextAlignment (the default alignment).

See also:	− setAlignment:

p	attributedStringValue

− (NSAttributedString *)attributedStringValue

Returns the object value of the receiver’s cell (or selected cell) as an attributed string after validating any editing currently being done. If no cell is associated with the receiver, returns an empty attributed string.

See also:	 − setAttributedStringValue:

calcSize

− (void)calcSize

Recomputes any internal sizing information for the NSControl, if necessary, by invoking its NSCell’s calcDrawInfo: method. Most NSControls maintain a flag that informs them if any of their cells have been modified in such a way that the location or size of the cell should be recomputed. If this happens, calcSize is automatically invoked whenever the NSControl is displayed; you never need to invoke it yourself.

See also:	− calcSize (NSMatrix, NSForm), − sizeToFit

cell

− (id)cell

Returns the receiver’s cell. In NSControls with multiple cells (such as NSMatrix or NSForm), use selectedCell or a similar method for finding a particular cell.

See also:	+ cellClass, − setCell:,  + setCellClass:

currentEditor

− (NSText *)currentEditor

If the receiving NSControl is being edited—that is, it has an NSText object acting as its field editor, and is the first responder of its NSWindow—this method returns the NSText editor; otherwise, it returns nil.

See also:	− abortEditing, − validateEditing

doubleValue

− (double)doubleValue

Returns the value of the receiver's cell as a double-precision floating point number.  If the NSControl contains many cells (for example, NSMatrix), then the value of the currently selectedCell is returned.  If the NSControl is in the process of editing the affected Cell, then validateEditing is invoked before the value is extracted and returned.

See also:	− floatValue, − intValue, − objectValue, − setDoubleValue:, − stringValue

drawCell:

− (void)drawCell:(NSCell *)aCell

If aCell is the cell used to implement this NSControl, then the NSControl is displayed.  This method is provided primarily to support a consistent set of methods between NSControls with single and multiple cells, since a NSControl with multiple cells needs to be able to draw a single cell at a time.

See also:	− selectCell:, − updateCell:, − updateCellInside:

drawCellInside:

− (void)drawCellInside:(NSCell *)aCell

Draws the inside of the receiver’s cell (the area within a bezel or border). If the NSControl is transparent, the method causes the superview to draw itself.  This method invokes NSCell's drawInteriorWithFrame:inView: method.  This method has no effect on NSControls (such as NSMatrix and NSForm) that have multiple cells.

See also:	− selectCell:, − updateCell:, − updateCellInside:

floatValue

− (float)floatValue

Returns the value of the receiver's cell (or selected cell, if a multiple-cell NSControl) as a single-precision floating point number.  See doubleValue for more details.

See also:	− doubleValue, − intValue, − objectValue,  − setFloatValue:, − stringValue

font

− (NSFont *)font

Returns the NSFont used to draw text in the receiver’s cell.

See also:	 − setFont:

ignoresMultiClick

− (BOOL)ignoresMultiClick

Returns whether the receiving NSControl ignores multiple clicks made in rapid succession. See setIgnoresMultiClick: for details.

initWithFrame:

− (id)initWithFrame:(NSRect)frameRect

Initializes and returns a new NSControl object in frameRect, and creates a cell for it if the cell’s class has been specified for controls of this type with setCellClass:. Because NSControl is an abstract class, invocations of this method should appear only in the designated initializers of sublcasses; that is, there should always be a more specific designated initializer for the subclass, as this initWithFrame: is the designated initializer for NSControl.

intValue

− (int)intValue

Returns the value of the receiver's cell (or selected cell, if a multiple-cell NSControl) as an integer.  See doubleValue for more details.

See also:	− floatValue, − doubleValue,  − objectValue, − setIntValue:, − stringValue

isContinuous

− (BOOL)isContinuous

Returns whether the control’s NSCell continuously sends its action message to its target during mouse tracking.

See also:	− setContinous:

isEnabled

− (BOOL)isEnabled

Returns whether the receiver reacts to mouse events.

See also:	 − setEnabled:

mouseDown:

− (void)mouseDown:(NSEvent *)theEvent

Invoked when the mouse button is pressed while the cursor is within the bounds of the NSControl. This method highlights the NSControl’s NSCell and sends it a trackMouse:inRect:ofView:untilMouseUp: message. Whenever the NSCell finishes tracking the mouse (for example, because the cursor has left the cell’s bounds), the cell is unhighlighted. If the mouse button is still down and the cursor reenters the bounds, the cell is again highlighted and a new trackMouse:inRect:ofView:untilMouseUp: message is sent. This behavior repeats until the mouse button goes up. If it goes up with the cursor in the control, the state of the control is changed, and the action message is sent to the target. If the mouse button goes up when the cursor is outside the control, no action message is sent.

See also:	 − ignoresMultiClick, − trackMouse:inRect:ofView:untilMouseUp:(NSCell)

p	objectValue

− (id)objectValue

Returns the value of the receiver's cell (or selected cell, if a multiple-cell NSControl) as an Objective-C object.  See doubleValue for more details.

See also:	− floatValue, − doubleValue,  − intValue, − setObjectValue:, − stringValue

p	performClick:

− (void)performClick:sender

Programmatically simulates a mouse click on the receiver’s cell, including the invocation of the action method in the target object. Raises an exception if the action message cannot be successfully sent.

selectCell:

− (void)selectCell:(NSCell *)aCell

If aCell is a cell of the receiving NSControl and is unselected, this method selects aCell (by setting its state to YES) and redraws the NSControl.

See also:	− selectedCell

selectedCell

− (id)selectedCell

Returns the receiver’s selected cell. The default implementation for NSControl simply returns the associated cell (or nil if no cell has been set). Subclasses of NSControl that manage multiple cells (such as NSMatrix and NSForm) override this method to return the cell selected by users.

See also:	   − cell, − setCell:

selectedTag

− (int)selectedTag

Returns the tag integer of the receiver’s selected cell (see selectedCell) or -1 if there is no selected cell. When you set the tag of an control with a single cell in Interface Builder, it sets the tags of both the control and the cell with the same value as a convenience.

See also:	− setTag:, − tag

sendAction:to:

− (BOOL)sendAction:(SEL)theAction to:(id)theTarget

Sends sendAction:to:from: to NXApp, which in turn sends a message to theTarget to perform theAction, adding the receiver as the argument to the from: keyword. sendAction:to: is invoked primarily by NSCell's trackMouse:inRect:ofView:untilMouseUp:.

If theAction is nil, no message is sent. If theTarget is nil, NXApp looks for an object that can respond to the message by following the responder chain (see the class description for NSActionCell). This method returns nil if no object that responds to theAction could be found.

See also:	− action, − target

sendActionOn:

− (int)sendActionOn:(int)mask

Sets the conditions on which the receiver sends action messages to its target (continuously, mouse up, and others) and returns a bit mask with which to detect the previous settings. NSControl’s default implementation simply invokes the sendActionOn: method of its associated cell

See also:	− sendAction:to:, − sendActionOn:(NSCell)

setAction:

− (void)setAction:(SEL)aSelector

Sets the NSControl’s action method to aSelector. If aSelector is nil, then no action messages will be sent from the NSControl.

See also:	− action, − setTarget:, − target

setAlignment:

− (void)setAlignment:(NSTextAlignment)mode

Sets the alignment of text in the receiver’s cell and, if the cell is being edited, aborts editing and updates the cell. mode is one of five constants: NSLeftTextAlignment, NSRightTextAlignment, NSCenterTextAlignment, NSJustifiedTextAlignment, NSNaturalTextAlignment (the default alignment for the text).

See also:	− alignment

p	setAttributedStringValue:

− (void)setAttributedStringValue:(NSAttributedString *)object

Sets the value of the receiver’s cell (or selected cell) as an attributed string. If the cell is being edited, it aborts all editing before setting the value; if the cell doesn’t inherit from NSActionCell, it marks it for automatic redisplay (NSActionCell performs its own updating of cells).

See also:	− attributedStringValue

setCell:

− (void)setCell:(NSCell *)aCell

Sets the receiver’s cell to aCell. Use this method with great care as it can irrevocably damage the affected control; specifically, you should only use this method in initializers for subclasses of NSControl.

See also:	− cell, − selectedCell

setContinuous:

− (void)setContinuous:(BOOL)flag

Sets whether the receiver’s cell continuously sends its action message to its target as it tracks the mouse.

See also:	− isContinuous

setDoubleValue:

− (void)setDoubleValue:(double)aDouble

Sets the value of the receiver’s cell (or selected cell) as aDouble (a double-precision floating point number). If the cell is being edited, it aborts all editing before setting the value; if the cell doesn’t inherit from NSActionCell, it marks the cell’s interior for automatic redisplay (NSActionCell performs its own updating of cells).

See also:	− doubleValue,− setFloatValue:, − setIntValue:, − setObjectValue:,  − setStringValue:

setEnabled:

− (void)setEnabled:(BOOL)flag

Sets whether the receiving NSControl’s cell—or if there is no associated cell, the NSControl itself—is active (that is, whether it tracks the mouse and sends its action to its target). If flag is NO, any editing is aborted. Redraws the entire Control if autodisplay is enabled. Subclasses may want to override this method to redraw only a portion of the control when the enabled state changes, as do NSButton and NSSlider.

See also:	 − isEnabled

setFloatValue:

− (void)setFloatValue:(float)aFloat

Sets the value of the receiver’s cell (or selected cell) as aFloat (a single-precision floating point number). If the cell is being edited, it aborts all editing before setting the value; if the cell doesn’t inherit from NSActionCell, it marks the cell’s interior for automatic redisplay (NSActionCell performs its own updating of cells).

See also:	− floatValue, − setDoubleValue:, − setIntValue:, − setObjectValue:,  − setStringValue:

setFloatingPointFormat:left:right:

− (void)setFloatingPointFormat:(BOOL)autoRange

left:(unsigned)leftDigits

right:(unsigned)rightDigits

Sets the autoranging and floating point number format of the receiver's cell, so that at most leftDigits are displayed to the left of the decimal point, and rightDigits to the right. See the description of this method in the NSCell class specification for details.  If the cell is being edited, what’s typed is discarded and the cell’s interior is redrawn.

See also:	− setFloatingPointFormat:left:right:(NSCell)

setFont:

− (void)setFont:(NSFont *)fontObject

Sets the font used to draw text in the receiver’s cell to fontObject. If the cell is being edited, the text in the cell is redrawn in the new font and the cell’s editor (the NSText object used globally for editing) is updated with the new NSFont.

See also:	− setFont:

setIgnoresMultiClick:

− (void)setIgnoresMultiClick:(BOOL)flag

Sets whether the receiving NSControl ignores multiple clicks made in rapid succession. By default, controls treat double-clicks as two distinct clicks, triple-clicks as three distinct clicks, and so on. However, when an NSControl returning YES to this method receives multiple clicks (within a predetermined interval), each mouseDown event after the first is passed on to super.

See also:	− ignoresMultiClick

setIntValue:

− (void)setIntValue:(int)anInt

Sets the value of the receiver’s cell (or selected cell) as an integer (anInt). If the cell is being edited, it aborts all editing before setting the value; if the cell doesn’t inherit from NSActionCell, it marks the cell’s interior for automatic redisplay (NSActionCell performs its own updating of cells).

See also:	− intValue,− setDoubleValue:, − setFloatValue:, − setObjectValue:,  − setStringValue:

setNeedsDisplay

− (void)setNeedsDisplay

Marks the receiving NSControl as needing redisplay (assuming automatic display is enabled) after recalculation of its dimensions.

See also:	− setsNeedsDisplay:(NSView)

p	setObjectValue:

− (void)setObjectValue:(id)object

Sets the value of the receiver’s cell (or selected cell) as an Objective-C object. If the cell is being edited, it aborts all editing before setting the value; if the cell doesn’t inherit from NSActionCell, it marks the cell’s interior for automatic redisplay (NSActionCell performs its own updating of cells).

See also:	− objectValue, − setDoubleValue:, − setFloatValue:, − setIntValue:,  − setStringValue:

setStringValue:

− (void)setStringValue:(NSString *)aString

Sets the value of the receiver’s cell (or selected cell) as an NSString object (aString). If the cell is being edited, it aborts all editing before setting the value; if the cell doesn’t inherit from NSActionCell, it marks the cell’s interior for automatic redisplay (NSActionCell performs its own updating of cells).

See also:	− setDoubleValue:, − setFloatValue:, − setIntValue:,  − setObjectValue:, − stringValue

setTag:

− (void)setTag:(int)anInt

Sets the tag of the receiving NSControl to anInt. It doesn’t affect the tag of the receiver’s cell.

See also:	− tag

setTarget:

− (void)setTarget:(id)anObject

Sets the target object for the action message of the receiver’s cell; NSCell’s setTarget: is used instead of any subclass override of this method. If anObject is nil and the control sends an action message, the application looks for an object that can respond to the message by following the responder chain (see description of the NSActionCell class for details).

See also:	− action, − setAction:, − target, − setTarget:(NSCell)

sizeToFit

− (void)sizeToFit

Changes the width and the height of the receiver's frame so that they are the minimum needed to contain its cell.  If you want a multiple-cell custom subclass of NSControl to size itself to fit its cells, you must override this method.

See also:	 − calcSize

stringValue

− (NSString *)stringValue

Returns the value of the receiver's cell (or selected cell, if a multiple-cell NSControl) as an NSString object.  See doubleValue for details.

See also:	− floatValue, − doubleValue,  − intValue, − objectValue, − setStringValue:

tag

− (int)tag

Returns the tag identifying the receiving control (not the tag of the receiver’s cell).

See also:	− setTag:

takeDoubleValueFrom:

− (void)takeDoubleValueFrom:(id)sender

Sets the double-precision floating-point value of the receiving control's cell (or selected cell) to the value obtained by sending a doubleValue message to sender. You can use this method to link action messages between controls.  It permits one control or cell (sender) to affect the value of another control (the receiver) by invoking this method in an action message to the receiver.  For example, a text field can be made the target of a slider.  Whenever the slider is moved, it will send a takeDoubleValueFrom: message to the text field.  The text field will then get the slider's floating-point value, turn it into a text string, and display it, thus tracking the value of the slider.

takeFloatValueFrom:

− (void)takeFloatValueFrom:(id)sender

Sets the receiving NSControl's selected cell to the value obtained by sending a floatValue message to another control or cell (sender). See takeDoubleValueFrom: for more information.

takeIntValueFrom:

− (void)takeIntValueFrom:(id)sender

Sets the receiving NSControl's selected cell to the value obtained by sending a intValue message to another control or cell (sender). See takeDoubleValueFrom: for more information.

p	takeObjectValueFrom:

− (void)takeObjectValueFrom:(id)sender

Sets the receiving NSControl's selected cell to the value obtained by sending a objectValue message to another control or cell (sender). See takeDoubleValueFrom: for more information.

takeStringValueFrom:

− (void)takeStringValueFrom:(id)sender

Sets the receiving NSControl's selected cell to the value obtained by sending a stringValue message to another control or cell (sender). See takeDoubleValueFrom: for more information.

target

− (id)target

Returns the target object of the receiver’s cell.

See also:	− action, − setAction:, − setTarget:

updateCell:

− (void)updateCell:(NSCell *)aCell

Redisplays aCell or marks it for redisplay.

updateCellInside:

− (void)updateCellInside:(NSCell *)aCell

Redisplays the inside of aCell or marks it for redisplay.

validateEditing

− (void)validateEditing

Validates the user’s changes to text in a cell of the receiving control. Validation sets the object value of the cell to the current contents of the cell’s editor (the NSText object used for editing), storing its a simple NSString or an attributed string object based on the attributes of the editor.

See also:	 − abortEditing, − currentEditor

Methods Implemented By the Delegate

p	control:didFailToFormatString:errorDescription:

− (BOOL)control:(NSControl *)control

didFailToFormatString:(NSString *)string

errorDescription:(NSString *)error

Invoked when the formatter for control’s cell (or selected cell) cannot convert an NSString (string) to an underlying object. error is a localized user-presentable NSString that explains why the conversion failed. Evaluate the error or query the user and return YES if string should be accepted as-is, or NO if string should be rejected.

See also:	− getObjectValue:forString:errorDescription:(NSFormatter)

p	control:didFailToValidatePartialString:errorDescription:

− (void)control:(NSControl *)control

didFailToValidatePartialString:(NSString *)string

errorDescription:(NSString *)error

Invoked when the formatter for control’s cell (or selected cell) rejects a partial string a user is typing into the cell. This NSString (string) includes the character that caused the rejection. error is a localized user-presentable NSString that explains why the validation failed. Evaluate the error or query the user and return YES if string should be accepted as-is, or NO if string should be rejected.

See also:	− isPartialStringValid:newEditingString:errorDescription:(NSFormatter)

p	control:isValidObject:

− (BOOL)control:(NSControl *)control isValidObject:(id)object

Invoked when the cursor leaves a cell but before the string value of the cell's object is displayed. Return YES to allow display of the string and NO to reject display and return the cursor to the cell. This method gives the delegate the opportunity to validate the contents of control’s cell (or selected cell). In validating, the delegate checks object to determine if it falls within a permissible range, has required attributes, accords with a given context, and so on. An example of an object subject to such and evaluation is an NSDate object which should not represent a future date, or a monetary amount (represented by an NSNumber) that exceeds a predetermined limit.

control:textShouldBeginEditing:

− (BOOL)control:(NSControl *)control textShouldBeginEditing:(NSText *)fieldEditor

Sent directly by control to the delegate when the cursor tries to enter a cell of the control that allows editing of text (such as a text field or form field). Return YES if the NSControl’s fieldEditor should be allowed to start editing the text, NO otherwise.

control:textShouldEndEditing:

− (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor

Sent directly by control to the delegate when the cursor tries to leave a a cell of the control that allows editing of text (such as a text field or a form field). Return YES if the control’s fieldEditor should be allowed to end its edit session, NO otherwise.

p	control:textView:doCommandBySelector:

− (BOOL)control:(NSControl *)control

textView:(NSTextView *)textView

doCommandBySelector:(SEL)command

Invoked when users press keys with predefined bindings in control’s cell or selected cell, as communicated to the control by the cell’s field editor (textView). The delegate returns YES if it handles the key binding, and NO otherwise. These bindings are usually implemented as methods (command) defined in NSResponder; examples of such key bindings are arrow keys (for directional movement) and the Escape key (for name completion). By implementing this method, the delegate can override the default implementation of command and supply its own behavior.

For example, the default method for completing partially typed pathnames or symbols (usually when users press the Escape key) is complete:. The default implementation of complete: (in NSResponder) does nothing. The delegate could evaluate command and, if it’s complete:, get the current string from textView and then expand it, or display a list of potential completions, or do whatever else is appropriate.

controlTextDidBeginEditing:

− (void)controlTextDidBeginEditing:(NSNotification *)aNotification

Sent by the default notification center to the delegate and all observers of the notification when a control with editable cells (such as a text field, form field, or an NSMatrix) begins editing text.  The name of the notification (aNotification) is always NSControlTextDidBeginEditingNotification. Use the key @"NSFieldEditor" to obtain the field editor from aNotification’s userInfo dictionary. If the delegate implements this method, it’s automatically registered to receive this notification.

controlTextDidEndEditing:

− (void)controlTextDidEndEditing:(NSNotification *)aNotification

Sent by the default notification center to the delegate and all observers of the notification when a control with editable cells (such as a text field, form field, or an NSMatrix) ends editing text.  The name of the notification (aNotification) is always NSControlTextDidEndEditingNotification. Use the key @"NSFieldEditor" to obtain the field editor from aNotification’s userInfo dictionary. If the delegate implements this method, it’s automatically registered to receive this notification.

controlTextDidChange:

− (void)controlTextDidChange:(NSNotification *)aNotification

Sent by the default notification center to the delegate when the text in the receiving control (usually a text field, form, or NSMatrix with editable cells) changes. The name of the notification aNotification is always NSControlTextDidChangeNotification. Use the key @"NSFieldEditor" to obtain the field editor from aNotification’s userInfo dictionary. If the delegate implements this method, it’s automatically registered to receive this notification.

Notifications

NSControl posts the following notifications to interested observers and its delegate.

NSControlTextDidBeginEditingNotification

Notification Object	The NSControl posting the notification. The field editor of the edited cell originally sends a NSTextDidBeginEditingNotification to the control, which passes it on in this form to its delegate.

User Info

Key	Value

@"NSFieldEditor"	The edited cell’s field editor

See description of controlTextDidBeginEditing:, above, for details.

NSControlTextDidChangeNotification

Notification Object	The NSControl posting the notification. The field editor of the edited cell originally sends a NSTextDidChangeNotification to the control, which passes it on in this form to its delegate.

User Info

Key	Value

@"NSFieldEditor"	The edited cell’s field editor

See description of controlTextDidChange:, above, for details.

NSControlTextDidEndEditingNotification

Notification Object	The NSControl posting the notification. The field editor of the edited cell originally sends a NSTextDidEndEditingNotification to the control, which passes it on in this form to its delegate.

User Info

Key	Value

@"NSFieldEditor"	The edited cell’s field editor

See description of controlTextDidEndEditing:, above.


NSCursor

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSObject (NSObject)

Declared In:	AppKit/NSCursor.h

Class Description

Instances of the NSCursor class manage the appearance of the cursor. When you initialize an cursor—the designated initializer is initWithImage:—you assign it a 16-by-16 pixel NSImage. Later, if you want to change the image, you can use setImage:. The image is usually an small, opaque icon—for example, a pair of cross-hairs—surrounded by transparent pixels. The pixels in the cursor image are mapped on a flipped coordinate system:  the upper left pixel is (0,0); the lower right is (15,15).

An application may use several cursor instances—for example, one that looks like an arrow and one that looks like an I-beam. The instance that currently appears on the screen is called the “current cursor,” and is referenced by the currentCursor class method. You can make a cursor current in several ways:

•	Most simply, you can send a cursor a set message. This message makes the receiver current.

•	You can manage cursors in a stack, using the push and pop methods. The stack’s top cursor is current.

•	You can tell a cursor to become current when the mouse enters a part of the screen known as the “cursor rectangle.” To do this, you first assign the cursor to an NSRect, using NSView’s addCursorRect:cursor: method:

[aView addCursorRect:&aRect cursor:aCursor];

This assignment means that when the mouse enters aRect, aCursor will receive a mouseEntered: event message. Next, using NSCursor’s setOnMouseEntered: method, you tell aCursor to respond to the mouseEntered: event by setting itself—that is, by making itself current:

[aCursor setOnMouseEntered:YES];

•	Conversely, you can tell a cursor to set itself when the mouse exits the cursor’s rectangle, using the setOnMouseExited: method.

To determine when exactly the mouse is inside a particular cursor rectangle, the Application Kit tracks a single pixel in the cursor image. This pixel is known as the hot spot, and you can reference it using the hotSpot method. By definition, the location of the current cursor’s hot spot is the location of the mouse; when the hot spot is inside a cursor rectangle, so is the mouse.

The hot spot is useful not only for determining which cursor is current, but for determining where a mouse click should have its effect. You should usually set the hot spot, using setHotSpot:, to the point where users will focus their attention. In a cursor that looks like cross-hairs, for example, you should set the hot spot at the crossing point.

The Application Kit provides two ready-made cursors for commonly used cursor images. You can retrieve these cursors by using the arrowCursor and IBeamCursor class methods. There’s no NSCursor instance for the wait cursor, because the system automatically displays it at the appropriate times.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

Method Types

Initializing a new cursor	− initWithImage:

Setting cursor attributes	− image

− setImage:

− hotSpot

− setHotSpot:

+ hide

+ unhide

+ setHiddenUntilMouseMoves:

Controlling which cursor is current	+ pop

− pop

− push

− set

− mouseEntered:

− setOnMouseEntered:

− isSetOnMouseEntered

− mouseExited:

− setOnMouseExited:

− isSetOnMouseExited

Retrieving cursor instances	+ arrowCursor

+ currentCursor

+ IBeamCursor

Class Methods

arrowCursor

+ (NSCursor *)arrowCursor

Returns the default cursor, a slanted arrow with its hot spot at the tip. The arrow cursor is the one you’re used to seeing over buttons, cursors and many other objects in the window system.

See also:	 + IBeamCursor, + currentCursor, − hotSpot

currentCursor

+ (NSCursor *)currentCursor

Returns the cursor that’s currently displayed on the screen.

See also:	  − set, − push, + pop, − mouseEntered:, − mouseExited:

hide

+ (void)hide

Makes the current cursor invisible. If another cursor becomes current, that cursor will be invisible, too. It will remain invisible until you invoke the unhide method.

hide overrides setHiddenUntilMouseMoves:.

IBeamCursor

+ (NSCursor *)IBeamCursor

Returns a cursor that looks like a capital I with a tiny crossbeam at its middle. This is the cursor that you’re used to seeing over editable or selectable text. The I-beam cursor’s default hot spot is where the crossbeam intersects the I.

See also:	 + arrowCursor, + currentCursor

pop

+ (void)pop

Sends a pop instance message to the cursor on top of the stack.

setHiddenUntilMouseMoves:

+ (void)setHiddenUntilMouseMoves:(BOOL)flag

If flag is YES, hides the cursor. The cursor remains invisible until either:

•	the mouse moves, or

•	you invoke the method again, with flag set to NO.

Don’t try to counter this method with unhide. The results are undefined.

See also:	+ hide

unhide

+ (void)unhide

Negates an earlier call to hide.

See also:	+ setHiddenUntilMouseMoves:

Instance Methods

hotSpot

− (NSPoint)hotSpot

Returns the position of the hot spot, specified according to the cursor’s flipped 16-by-16 coordinate system. For a fuller explanation, see the class description.

image

− (NSImage *)image

Returns the image that determines the appearance of the receiving cursor; if no image has been set, returns nil.

See also:	− initWithImage:

initWithImage:

− (id)initWithImage:(NSImage *)anImage

This method is the designated initializer for the class. It initializes the receiver, assigns it anImage (which must be 16-by-16 pixels) and sets its hot spot to (0,0), the upper left corner of the image.

Later, you can change the image and hotSpot, using setImage: and setHotSpot:.

Returns self.

See also:	−  hotSpot, − image

isSetOnMouseEntered

− (BOOL)isSetOnMouseEntered

Returns YES if the receiving cursor will become current when it receives a mouseEntered: message; otherwise, returns NO.

To receive such a message, the receiver must first be assigned a cursor rectangle. This assignment can be made using NSView’s addCursorRect:cursor: method. For a fuller explanation, see the class description.

See also:	 −  setOnMouseEntered:, −  isSetOnMouseExited:

isSetOnMouseExited

− (BOOL)isSetOnMouseExited

Returns YES if the receiving cursor will become current when it receives a mouseExited: message; otherwise, returns NO. The preconditions parallel those for isSetOnMouseEntered:.

See also:	 −  setOnMouseExited:

mouseEntered:

− (void)mouseEntered:(NSEvent *)anEvent

This message is automatically sent to the receiver when the mouse enters the receiver’s cursor rectangle. If used after setOnMouseEntered:YES, mouseEntered: can make the receiver the the current cursor.

In your programs, you won’t invoke mouseEntered: explicity. It’s only included in the class interface so that you can override it.

For a fuller explanation, see the class description.

See also:	−  isSetOnMouseEntered, − mouseExited:

mouseExited:

− (void)mouseExited:(NSEvent *)theEvent

This message is automatically sent to the receiver when the mouse exits the receiver’s cursor rectangle. Like mouseEntered:, it is part of the class interface only so that you can override it.

See also:	−  setOnMouseExited:, −  isSetOnMouseExited

pop

− (void)pop

Removes the receiver from the top of the cursor stack. Automatically, the next cursor down in the stack becomes the current cursor.

When the last remaining cursor is popped from the stack, the current cursor defaults to the arrow cursor.

See also:	 − push

push

− (void)push

Puts the receiver on top of the cursor stack. Automatically, the receiver becomes the current cursor.

See also:	 − pop

set

− (void)set

Sets the receiver to be the current cursor.

See also:	 + currentCursor

setHotSpot:

− (void)setHotSpot:(NSPoint)hotSpot

Sets the location of the cursor’s hot spot. The hot spot should be specified in terms of the cursor’s flipped 16-by-16 coordinate system.

See also:	− hotSpot

setImage:

− (void)setImage:(NSImage *)anImage

Assigns anImage to the receiving cursor. anImage must be 16 pixels wide by 16 pixels high.

Don’t reset the image of the current cursor. The results may be unpredictable.

See also:	+ currentCursor, − image, − initWithImage:

setOnMouseEntered:

− (void)setOnMouseEntered:(BOOL)flag

Determines, based on flag, whether the NSCursor instance will set itself to be the current cursor when it receives a mouseEntered: event message.

setOnMouseExited:

− (void)setOnMouseExited:(BOOL)flag

Determines, based on flag, whether NSCursor will set itself to be the currentCursor when it receives a mouseExited: event message.


NSCustomImageRep

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSImageRep : NSObject

Conforms To:	NSCoding (from NSImageRep)

NSCopying (from NSImageRep)

NSObject (from NSObject)

Declared In:	AppKit/NSCustomImageRep.h

Class Description

An NSCustomImageRep is an object that uses a delegated method to render an image. When called upon to produce the image, it sends a message to its delegate to have the method performed.

Like most other kinds of NSImageReps, an NSCustomImageRep is generally used indirectly, through an NSImage object. An NSImage must be able to choose between various representations of a given image. It also needs to provide an off-screen cache of the appropriate depth for any image it uses. It determines this information by querying its NSImageReps.

Thus to work with an NSImage, an NSCustomImageRep must be able to provide some information about its image. Use the following methods, inherited from the NSImageRep class, to set these attributes of the NSCustomImageRep:

setSize:

setColorSpaceName:

setAlpha:

setPixelsHigh:

setPixelsWide:

setBitsPerSample:

Note that if these attributes aren’t set, and an NSCustomImageRep is used in an NSImage with other representations, NSImage won’t be able to select between them. In actual practice, this usually isn’t a problem.

Method Types

Initializing a new NSCustomImageRep

− initWithDrawSelector:delegate:

Identifying the object	− delegate

− drawSelector

Instance Methods

delegate

− (id)delegate

Returns the delegate object that renders the image for the NSCustomImageRep.

drawSelector

− (SEL)drawSelector

Returns the associated draw method selector.

initWithDrawSelector:delegate:

− (id)initWithDrawSelector:(SEL)aMethod delegate:(id)anObject

Initializes the receiver, a newly allocated NSCustomImageRep instance, so that it delegates responsibility for rendering the image to anObject. When the NSCustomImageRep receives a draw message, it will in turn send a message to anObject to perform the aMethod method. The aMethod method should take only one argument, the id of the NSCustomImageRep. It should draw the image at location (0.0, 0.0) in the current coordinate system.

Returns self.

See also:	− draw (NSImageRep)


NSDPSContext

CCopyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSDPSContext.h

Class Description

The NSDPSContext class is the programmatic interface to objects that represent Display PostScript System contexts. A context can be thought of as a destination to which PostScript code is sent for execution. Each Display PostScript context contains its own complete PostScript environment including its own local VM (PostScript Virtual Memory). Every context has its own set of stacks, including an operand stack, graphics state stack, dictionary stack, and execution stack. Every context also contains a FontDirectory which is local to that context, plus a SharedFontDirectory that is shared across all contexts. There are three built-in dictionaries in the dictionary stack. From top to bottom, they are userdict, globaldict, and systemdict. userdict is private to the context, while globaldict and systemdict are shared by all contexts. globaldict is a modifiable dictionary containing information common to all contexts. systemdict is a read-only dictionary containing all the PostScript operators.

At any time there is the notion of the current context. The current context for the current thread may be set using setCurrentContext:.

NSDPSContext objects by default write their output to a specified data destination. This is used for printing, faxing, and for generation of saved EPS (Encapsulated PostScript) code. The means to create contexts that interact with displays are platform-specific.

The NSApplication object creates an NSDPSContext by default.

NSDPSContext Objects and Display PostScript System Context Records

When an NSDPSContext object is created, it creates and manages a DPSContext record. Programmers familiar with the client side C function interface to the Display PostScript System can access the DPSContext record by sending a context message to an NSDPSContext object. You can then operate on this context record using any of the functions or single operator functions defined in the Display PostScript System client library. Conversely, you can create an NSDPSContext object from a DPSContext record with the DPSContextObject() function, as defined in “Client Library Functions”. You can then work with the created NSDPSContext object using any of the methods described here.

General Exception Conditions

A variety of exceptions can be raised from NSDPSContext. In most cases, exceptions are raised because of errors returned from the Display PostScript Server. Exceptions are listed under “Types and Constants.” Also see the Display PostScript System, Client Library Reference Manual, by Adobe Systems Incorporated, for more details on Display PostScript System error names and their possible causes.

Method Types

Initializing a context	− initWithMutableData:forDebuggin:languageEncoding:

   nameEncoding:textProc:errorProc:

Testing the drawing destination	− isDrawingToScreen

Accessing context data	− mutableData

Setting and identifying the current context

+ currentContext

+ setCurrentContext:

− DPSContext

Controlling the context	− flush

− interruptExecution

− notifyObjectWhenFinishedExecuting:

− resetCommunications

− wait

Managing returned text and errors	+ stringForDPSError:

− errorProc

− setErrorProc:

− setTextProc:

− textProc

Sending raw data	− printFormat:

− printFormat:arguments:

− writeData:

− writePostScriptWithLanguageEncodingConversion:

Managing binary object sequences	− awaitReturnValues

− writeBOSArray:count:ofType:

− writeBOSNumString:length:ofType:scale:

− writeBOSString:length:

− writeBinaryObjectSequence:length:

− updateNameMap

Managing chained contexts	− chainChildContext:

− childContext

− parentContext

− unchainContext

Controlling  the wait cursor	− startWaitCursorTimer

− setWaitCursorEnabled:

− isWaitCursorEnabled

Debugging aids	+ areAllContextsOutputTraced

+ areAllContextsSynchronized

+ setAllContextsOutputTraced:

+ setAllContextsSynchronized:

− isOutputTraced

− isSynchronized

− setOutputTraced:

− setSynchronized:

Class Methods

areAllContextsOutputTraced

+ (BOOL)areAllContextsOutputTraced

Returns YES if the data flowing between the application’s contexts and their destinations is copied to diagnostic output.

areAllContextsSynchronized

+ (BOOL)areAllContextsSynchronized

Returns YES if all NSPDSContext objects invoke the wait method after sending each batch of output.

currentContext

+ (NSDPSContext *)currentContext

Returns the current context of the current thread.

setAllContextsOutputTraced:

+ (void)setAllContextsOutputTraced:(BOOL)flag

Causes the data (PostScript code, return values, and so forth) flowing between the all the application’s contexts and their destinations to be copied to diagnostic output.

setAllContextsSynchronized:

+ (void)setAllContextsSynchronized:(BOOL)flag

Causes the wait method to be invoked each time an NSDPSContext object sends a batch of output to its destination.

setCurrentContext:

+ (void)setCurrentContext:(NSDPSContext *)context

Installs context as the current context of the current thread.

stringForDPSError:

+ (NSString *)stringForDPSError:(const DPSBinObjSeqRec *)error

Returns a string representation of error.

Instance Methods

DPSContext

− (DPSContext)DPSContext

Returns the corresponding DPScontext.

awaitReturnValues

− (void)awaitReturnValues

Waits for all return values from the result table.

chainChildContext:

− (void)chainChildContext:(NSDPSContext *)child

Links child (and all of it’s children) to the receiver as its chained context, a context that receives a copy of all PostScript code sent to the receiver.

childContext

− (NSDPSContext *)childContext

Returns the receiver’s child context, or nil if none exists.

errorProc

− (DPSErrorProc)errorProc

Returns the context’s error callback function.

flush

− (void)flush

Forces any buffered data to be sent to its destination.

initWithMutableData:forDebugging:languageEncoding:nameEncoding:textProc:errorProc:

− initWithMutableData:(NSMutableData *)data forDebugging:(BOOL)debug languageEncoding:(DPSProgramEncoding)langEnc nameEncoding:(DPSNameEncoding)nameEnc textProc:(DPSTextProc)tProc errorProc:(DPSErrorProc)errorProc

Initializes a newly allocated NSDPSContext that writes itsoutput to data using the language and name encodingsspecified by langEnc and nameEnc. The callback functions tProc and errorProc handle text and errorsgenerated by the context. If debug is YES, the output is given in human-readable form in which large structures (such as images) may be represented by comments.

interruptExecution

− (void)interruptExecution

Interrupts execution in the receiver’s context.

isDrawingToScreen

− (BOOL)isDrawingToScreen

Returns YES if the drawing destination is the screen.

isOutputTraced

− (BOOL)isOutputTraced

Returns YES if the data flowing between the application’s single context and its destination is copied to diagnostic output.

isSynchronized

− (BOOL)isSynchronized

Returns whether the wait method is invoked each time the receiver sends a batch of output to the server.

p	  isWaitCursorEnabled

− (BOOL)isWaitCursorEnabled

Returns whether the wait cursor is enabled.

See also:  PScurrentwaitcursorenabled()

mutableData

− (NSMutableData *)mutableData

Returns the receiver’s data object.

notifyObjectWhenFinishedExecuting:

− (void)notifyObjectWhenFinishedExecuting:(id )object

Registers object to receive a contextFinishedExecuting: message when the NSDPSContext’s destination is ready to receive more input.

parentContext

− (NSDPSContext *)parentContext

Returns the receiver’s parent context, or nil if none exists.

printFormat:

− (void)printFormat:(NSString *)format,...

Constructs a string from format and following string objects (in the manner of printf()) and sends it to the context’s destination.

printFormat:arguments:

− (void)printFormat:(NSString *)format arguments:(va_list)argList

Constructs a string from format and argList (in themanner of vprintf()) and sends it to the context’s destination.

resetCommunication

− (void)resetCommunication

Discards any data that hasn’t already been sent to its destination.

setErrorProc:

− (void)setErrorProc:(DPSErrorProc)proc

Sets the context’s error callback function to proc.

setOutputTraced:

− (void)setOutputTraced:(BOOL)flag

Causes the data (PostScript code, return values, and so on) flowing between the application’s single context and the Display PostScript server to be copied to diagnostic output.

setSynchronized:

− (void)setSynchronized:(BOOL)flag

Sets whether the wait method is invoked each time the receiver sends a batch of output to its destination.

setTextProc:

− (void)setTextProc:(DPSTextProc)proc

Sets the context’s text callback function to proc.

p	  setWaitCursorEnabled:

− (void)setWaitCursorEnabled:(BOOL)flag

Sets whether the wait cursor is enabled or disabled according to flag.

See also:  PSsetwaitcursorenabled()

p	  startWaitCursorTimer

− (void)startWaitCursorTimer

Generates a pseudo-event to start wait cursor timer.

See also:  setWaitCursorEnabled:

textProc

− (DPSTextProc)textProc

Returns the context’s text callback function.

unchainContext

− (void)unchainContext

Unlinks the child context (and all of it’s children) from the receiver’s list of chained contexts.

updateNameMap

− (void)updateNameMap

Updates the context’s name map from the client library’s name map.

wait

− (void)wait

Waits until the NSDPSContext’s destination is ready to receive more input.

writeBOSArray:count:ofType:

− (void)writeBOSArray:(const void *)data count:(unsigned int)items ofType:(DPSDefinedType)type

Write an array to the context’s destination as part of a  binary object sequence. The array is taken from data and consists of items items of type type.

writeBOSNumString:length:ofType:scale:

− (void)writeBOSNumString:(const void *)data length:(unsigned int)count ofType:(DPSDefinedType)type scale:(int)scale

Write a number string to the context’s destination as part of a binary object sequence. The string is taken from dataas described by count, type, and scale.

writeBOSString:length:

− (void)writeBOSString:(const void *)data length:(unsigned int)bytes

Write a string to the context’s destination as part of a binary object sequence. The string is taken from bytes (a count) of data.

writeBinaryObjectSequence:length:

− (void)writeBinaryObjectSequence:(const void *)data length:(unsigned int)bytes

Write a binary object sequence to the context’s destination. The sequence consists of bytes (a count) of data.

writeData:

− (void)writeData:(NSData *)buf

Sends the PostScript data in buf to the context’s destination.

writePostScriptWithLanguageEncodingConversion:

− (void)writePostScriptWithLanguageEncodingConversion:(NSData *)buf

Writes the PostScript data in buf to the context’s destination. The data, formatted as plain text, encoded tokens, or a binary object sequence, is converted as necessary depending on the language encoding of the receiving context.


NSDataLink

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding, NSCopying

NSObject (NSObject)

Declared In:	AppKit/NSDataLink.h

Class Description

An NSDataLink object (or data link) defines a single link between a selection in a source document and a dependent, dynamically updated selection in a destination document.

A data link is typically created when linkable data is copied to the pasteboard. First, an NSSelection object describing the data is created. Then a link to that selection is created using initLinkedToSourceSelection:managedBy:supportingTypes:. The link can then be written to the pasteboard using writeToPasteboard:. Usually, after the link has been written to the pasteboard (or saved to a file using writeToFile:) the link is released because it’s generally of no further use to the source application.

Once the data and link have been written to the pasteboard, they can be added to a destination document by an object that can respond to a message to Paste and Link. The object responding to this message will paste the data as usual. The destination application will then read the link from the pasteboard using initWithPasteboard:, create an NSSelection describing the linked data within the destination document, and will add the link by sending addLink:at: to the document’s NSDataLinkManager object (also known as a data link manager or simply link manager).

When the link is added to the destination document’s link manager, it becomes a destination link. At that time, the data link’s object establishes a connection with the source document’s link manager, which automatically creates a source link in the source application; the source link refers to the source selection.

A link that isn’t managed by a link manager is a broken link. (Both source and destination links have link managers.) All links are broken links when they are created. Links can be explicitly broken (ensuring that they cause no updates) using the break method. Broken links (that aren’t former source links) can be hooked up as destination links with the addLink:at: method. The disposition of a link (destination, source, or broken) can be retrieved with the disposition method. Most of the messages defined by the NSDataLink class can be sent to a link of any disposition, but some only make sense when sent to a link with a specific disposition; these are so noted in their method descriptions.

Links of all dispositions (except links to files) maintain an NSSelection object referring to the link’s selection in the source document; this selection is returned by the sourceSelection method. Links directly to files represent entire files rather than selections in a document; these links are created with initLinkedToFile: and have no source selection.

Source and destination links also maintain an NSSelection describing the location of the data in the destination document; this selection is returned by the destinationSelection method.

See the NSSelection class description for more information on NSSelection objects.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

NSCopying	− copyWithZone:

Method Types

Creating an NSDataLink	− initLinkedToFile:

− initLinkedToSourceSelection:managedBy:supportingTypes:

− initWithContentsOfFile:

− initWithPasteboard:

− copyWithZone:

Exporting the link	− saveLinkIn:

− writeToFile:

− writeToPasteboard:

Getting information about the link	− disposition

− linkNumber

− manager

Getting information about the link’s source

− lastUpdateTime

− openSource

− sourceApplicationName

− sourceFilename

− sourceSelection

− types

Getting information about the link’s destination

− destinationApplicationName

− destinationFilename

− destinationSelection

Changing the link	− break

− noteSourceEdited

− setUpdateMode:

− updateMode

− updateDestination

Instance Methods

break

− (BOOL)break

Breaks the link so the data referred to by its selection will not get updated.

copyWithZone:

@protocol NSCopying

− (id)copyWithZone:(NSZone *)zone

Returns a copy of the receiving data link allocated from zone. The copy is essentially linked to the source data, but not hooked up to the destination document. The copy has a copy of the receiver’s source selection, has no destination selection, and its disposition is NSLinkBroken.

See also:	− addLink:at: (NSDataLinkManager)

destinationApplicationName

− (NSString *)destinationApplicationName

Returns the name of the application that owns the destination document.

See also:	− destinationFilename, − sourceApplicationName

destinationFilename

− (NSString *)destinationFilename

Returns the file name of the destination document.

See also:	 − destinationApplicationName, − sourceFilename

destinationSelection

− (NSSelection *)destinationSelection

Returns the destination selection.

See also:	− sourceSelection

disposition

− (NSDataLinkDisposition)disposition

Identifies the link as a destination link, a source link, or a broken link by returning one of the following values:

NSLinkInDestination

NSLinkInSource

NSLinkBroken

initLinkedToFile:

− (id)initLinkedToFile:(NSString *)filename

Initializes a new instance corresponding to the entire file filename.

See also:	− addLink:at: (NSDataLinkManager), − writeToPasteboard, − sourceSelection

initLinkedToSourceSelection:managedBy:supportingTypes:

− (id)initLinkedToSourceSelection:(NSSelection *)selection

managedBy:(NSDataLinkManager *)linkManager

supportingTypes:(NSArray *)newTypes

Initializes a newly allocated instance corresponding to a selection in the source document selection. linkManager is the source document's link manager. newTypes is an array of the types that linkManager's delegate is willing to provide (using copyToPasteboard:at:cheapCopyAllowed:) when a destination of the link requests the data described by selection.

See also:	− dataLinkManager:startTrackingLink: (NSDataLinkManager delegate)

initWithContentsOfFile:

− (id)initWithContentsOfFile:(NSString *)filename

Initializes a new instance from filename, a link that was previously saved using the saveLinkIn: or writeToFile: method.

See also:	− saveLinkIn:, − writeToFile:

initWithPasteboard:

− (id)initWithPasteboard:(NSPasteboard *)pasteboard

Initializes a new instance from pasteboard. The new link is generally used by adding it to a destination document’s link manager with addLink:at:.

For this method to succeed, a link must have been placed on the pasteboard using writeToPasteboard:, or the file name of a saved link (data of type NSFilenamesPboardType with an extension of NSDataLinkFilenameExtension) must be on the pasteboard.

See also:	− saveLinkIn:

lastUpdateTime

− (NSDate *)lastUpdateTime

Returns the last time the link was updated.

linkNumber

− (NSDataLinkNumber)linkNumber

Returns the link’s number. This number is constant through the life of the document, and unique among the document’s links.

manager

− (NSDataLinkManager *)manager

Returns the link’s manager, or nil if it doesn’t have one (for instance, if the link is broken).

noteSourceEdited

− (void)noteSourceEdited

Informs a source link that the data referred to by its source selection has changed. If the link’s destination link has been set to update continuously, the destination will be updated.

This message only has meaning if sent to a source link.

openSource

− (BOOL)openSource

Opens the source document of the link and makes the source selection visible. This message only has meaning when sent to a destination link.

saveLinkIn:

− (BOOL)saveLinkIn:(NSString *)directoryName

Saves the link in a file specified by the user through an NSSavePanel. The NSSavePanel’s initial directory is set to directoryName.

See also:	− initWithContentsOfFile:

setUpdateMode:

− (void)setUpdateMode:(NSDataLinkUpdateMode)mode

Sets the link’s update mode to mode, which must be one of the following:

NSUpdateContinuously

NSUpdateWhenSourceSaved

NSUpdateManually

NSUpdateNever

A mode of NSUpdateContinuously updates the link’s destination data every time the source is edited. NSUpdateWhenSourceSaved updates the link’s destination data every time the source is saved.  NSUpdateManually updates the link’s destination data every time an updateDestination message is sent to the destination link; this message can be sent programmatically or by the data link panel.  NSUpdateNever keeps the link from ever updating; once a destination link has been set to this mode, it can’t be set back to any other mode until it is broken. (This mode is used for link buttons, for example.)

This message only has meaning when sent to a destination link or to a broken link.

See also:	− updateMode

sourceApplicationName

− (NSString *)sourceApplicationName

Returns the name of the application that owns the source document.

See also:	− sourceFilename, − destinationApplicationName

sourceFilename

− (NSString *)sourceFilename

Returns the file name of the source document.

See also:	− sourceApplicationName, − destinationFilename

sourceSelection

− (NSSelection *)sourceSelection

Returns the source selection.

See also:	− destinationSelection

types

− (NSArray *)types

Returns the types that the source document can provide.

updateDestination

− (BOOL)updateDestination

Updates the data referred to by the link’s destination selection with the contents referred to by the source selection.

updateMode

− (NSDataLinkUpdateMode)updateMode

Returns the link’s update mode, which determines when the data referred to by the link’s destination selection will be updated.

The update modes are listed and described in the method description for setUpdateMode:.

writeToFile:

− (BOOL)writeToFile:(NSString *)filename

Writes the link into filename, returning NO if the file can’t be written.

See also:	− saveLinkIn:, − initWithContentsOfFile:

writeToPasteboard:

− (void)writeToPasteboard:(NSPasteboard *)pasteboard

Writes the link onto pasteboard. When a link is written to a pasteboard, the type NSDataLinkPboardType must be included in the pasteboard’s types.

See also:	− initWithPasteboard:


NSDataLinkManager

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSObject (NSObject)

Declared In:	AppKit/NSDataLinkManager.h

Class Description

An NSDataLinkManager object (also known as a data link manager or simply link manager) manages data linked from and into a document through NSDataLink objects. NSDataLink objects (or data links) provide a link between a selection (NSSelection object) in a source document and a dependent, dynamically updated selection in a destination document. When a user does a Paste and Link command in the destination document, the link manager creates the link in response to a addLink:at: message. When this link is added to the destination document, it makes a connection with the source document’s link manager, which creates a source link in the source application.

If an application supports data linking, a link manager should be instantiated for every document the application creates. A link manager must be assigned a delegate that assists it in keeping the document up to date; this delegate must implement some or all of the methods listed in the “Methods Implemented by the Delegate” section of this class specification. In addition, the delegate must keep the link manager informed of the state of the document, sending messages such as noteDocumentEdited and noteDocumentSaved whenever the document is edited, saved, or otherwise altered.

Only applications that support continuously updating links need to be aware of when source links are created; these applications can have the delegate of the destination document’s link manager return YES in response to a dataLinkManagerTracksLinksIndividually: message, and then respond to dataLinkManager:startTrackingLink: messages to receive notifications that source links are created.

For more information about NSDataLink objects and NSSelection objects, see their class descriptions.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

Method Types

Creating an NSDataLinkManager	− initWithDelegate:

− initWithDelegate:fromFile:

Handling links	− addLink:at:

− addLinkAsMarker:at:

− addLinkPreviouslyAt:fromPasteboard:at:

− destinationLinkEnumerator

− destinationLinkWithSelection:

− sourceLinkEnumerator

− breakAllLinks

− writeLinksToPasteboard:

− setLinkOutlinesVisible

− areLinkOutlinesVisible

Informing the link manager of document status

− noteDocumentClosed

− noteDocumentEdited

− noteDocumentReverted

− noteDocumentSaved

− noteDocumentSavedAs:

− noteDocumentSavedTo:

Getting and setting information about the link manager

− delegate

− setDelegateVerifiesLinks:

− delegateVerifiesLinks

− setInteractsWithUser:

− interactsWithUser

− filename

− isEdited

Methods implemented by the delegate

− copyToPasteboard:at:cheapCopyAllowed:

− dataLinkManager:didBreakLink:

− dataLinkManager:isUpdateNeededForLink:

− dataLinkManager:startTrackingLink:

− dataLinkManager:stopTrackingLink:

− dataLinkManagerCloseDocument:

− dataLinkManagerDidEditLinks:

− dataLinkManagerRedrawLinkOutlines:

− dataLinkManagerTracksLinksIndividually

− importFile:at:

− pasteFromPasteboard:at:

− showSelection:

− windowForSelection:

Instance Methods

addLink:at:

− (BOOL)addLink:(NSDataLink *)link

at:(NSSelection *)selection

Adds link to the document, indicating that the data in the document described by selection is dependent upon the link. This method is invoked as part of the Paste and Link command to actually link in the data that was just pasted. It can also be used at other times; for example, to link to files that are dragged into the document.

This method makes link a destination link and sets selection as link's destination selection. When the link's source is modified, the link manager's delegate will be sent a pasteFromPasteboard:at: or importFile:at: message with selection as an argument, indicating that the destination data must be updated.

Returns a boolean indicating whether the link was successfully added. There are several situations that will result in failure to add the link, such as an inability to resolve the link to its source, so it's important to check the return value of this method and undo the requested operation if the linking fails.

See also:	− addLinkAsMarker:at:

addLinkAsMarker:at:

− (BOOL)addLinkAsMarker:(NSDataLink *)link

at:(NSSelection *)selection

Incorporates link into the document as a marker. This method is used to implement link buttons that allow access to the link's source, but are never asked to receive data from the source document. The link button in the destination document is described by selection. This method adds the link and, upon success, sets its the link's update mode to NSUpdateNever. Returns a boolean indicating whether the link was successfully added.

See also:	− addLink:at:

addLinkPreviouslyAt:fromPasteboard:at:

− (NSDataLink *)addLinkPreviouslyAt:(NSSelection *)oldSelection

fromPasteboard:(NSPasteboard *)pasteboard

at:(NSSelection *)selection

Creates and adds a new destination link corresponding to the same source data as the link described by the destination selection oldSelection. The new link's destination selection is provided in selection. This method is useful if you paste data that is already linked. It's similar to copying the old link and adding it using addLink:at:, except you specify the old destination selection rather than the old link. Before invoking this method, the document's links must be written to pasteboard using writeLinksToPasteboard:.   Returns the new link if it's successfully added, or nil if the link can't be added.

See also:

areLinkOutlinesVisible

− (BOOL)areLinkOutlinesVisible

Used to inform the link manager's delegate of whether link outlines should be drawn around linked destination data. When the delegate receives a dataLinkManagerRedrawLinkOutlines: message, it should query the link manager with an areLinkOutlinesVisible message. If this message returns YES, the delegate should call the NSFrameLinkRect() function to draw a distinctive link outline around the dependent data.

See also:	− setLinkOutlinesVisible

breakAllLinks

− (void)breakAllLinks

Breaks all the destination links in the document by sending each link a break message. This method is typically invoked by the application's data link panel in response to user input.

See also:	− break (NSDataLink), − pickedBreakAllLinks: (NSDataLinkPanel)

delegate

− (id)delegate

Returns the data link manager’s delegate. The delegate is sent messages to provide source data, paste destination data, and help the data link manager keep links up-to-date.

See also:	− initWithDelegate:

delegateVerifiesLinks

− (BOOL)delegateVerifiesLinks

Return YES if the link manager's delegate will be asked to verify whether data based on the delegate's source links needs to be updated. If so, the delegate should implement the dataLinkManager:isUpdateNeededForLink: method.

See also:	− setDelegateVerifiesLinks:

destinationLinkEnumerator

− (NSEnumerator *)destinationLinkEnumerator

Returns an enumerator of the destination’s source links.

See also:	− destinationLinkWithSelection:, − sourceLinkEnumerator

destinationLinkWithSelection:

− (NSDataLink *)destinationLinkWithSelection:(NSSelection *)destSel

Returns the destination link for the selection destSel, or nil if the document has no link for that selection.

See also:	− destinationLinkWithSelection:,

filename

− (NSString *)filename

Returns the filename of the link manager's document. This is the name that was set with the initWithDelegate:fromFile: or documentSavedAs: method.

initWithDelegate:

− (id)initWithDelegate:(id)anObject

Initializes and returns a newly allocated link manager for a new document. The link manager's delegate, specified by anObject, will be expected to provide source data, paste destination data, and help the data link manager keep links up-to-date. Before data in the document can be linked to, the document will have to be saved and the link manager will have to be informed of the document's name by a noteDocumentSavedAs: message.

See “Methods Implemented by the Delegate” at the end of this class specification for information about the methods the delegate should implement to assist the link manager.

See also:	− initWithDelegate:fromFile:

initWithDelegate:fromFile:

− (id)initWithDelegate:(id)anObject fromFile:(NSString *)path

Initializes a newly allocated link manager for a new document. The link manager's delegate, specified by anObject, will be expected to provide source data, paste destination data, and help the data link manager keep links up-to-date. The document's file is specified by the full path path. The file must exist or initialization will fail.

Returns the new link manager upon success; frees the allocated storage and returns nil if initialization fails.

See “Methods Implemented by the Delegate” at the end of this class specification for information about the methods the delegate should implement to assist the link manager.

See also:	− initWithDelegate:

interactsWithUser

− (BOOL)interactsWithUser

Returns a boolean indicating whether the link manager will display alert panels to the user when problems occur with links. The default value is YES.

See also:	− setInteractsWithUser:

isEdited

− (BOOL)isEdited

Returns a boolean indicating whether the document has been edited since the last time it was saved. It’s the application’s responsibility to inform the link manager when the document’s edit state changes, using noteDocumentEdited, noteDocumentSaved, and related methods.

noteDocumentClosed

− (void)noteDocumentClosed

An application should send this message to the link manager to inform it that the manager’s document has been closed.

noteDocumentEdited

− (void)noteDocumentEdited

An application should send this message to the link manager to inform it that the manager's document has been edited. If the delegate doesn't track source links individually, this method marks all source links as dirty, indicating that the dependent destination data will eventually need to be updated.

See also:	− dataLinkManagerTracksLinksIndividually: (NSDataLinkManager)

noteDocumentReverted

− (void)noteDocumentReverted

An application should send this message to the link manager to inform it that the manager's document has been reverted to the last saved copy. This method restores the link manager and its links to their last saved state, from the last time the link manager received a noteDocumentSaved or noteDocumentSavedAs: message.

noteDocumentSaved

− (void)noteDocumentSaved

An application should send this message to the link manager to inform it that the manager's document has been saved. This method writes the document's destination link information to a file associated with the document’s path, then initiates updates of other documents dependent upon the document's source links.

See also:	− noteDocumentSavedAs:, − noteDocumentSavedTo:

noteDocumentSavedAs:

− (void)noteDocumentSavedAs:(NSString *)path

An application should send this message to the link manager to inform it that the manager's document has been saved as the file specified by the full pathname path. This method updates the document’s destination links to the new path and writes the destination link information to a file associated with path.

See also:	− noteDocumentSaved, − noteDocumentSavedTo:

noteDocumentSavedTo:

− (void)noteDocumentSavedTo:(NSString *)path

An application should send this message to the link manager to inform it that a copy of the manager's document has been saved to the file specified by the full pathname path. This method writes the appropriate link information to a file associated with path.

See also:	− noteDocumentSaved, − noteDocumentSavedAs:

setDelegateVerifiesLinks:

− (void)setDelegateVerifiesLinks:(BOOL)flag

Tells the link manager whether the link manager’s delegate will verify the update status of links. If YES, the delegate must implement the dataLinkManager:isUpdateNeededForLink: method to tell the link manager if data based on a source link needs to be updated.

By default, the update status of an individual link isn't verified by the delegate, so the link manager verifies a link based on its last update time. An example where this verification could be incorrect might be a link to a database query; if the query itself doesn't change, the link manager might return that data is up-to-date, even though the database referred to by the query might have changed.

See also:	− delegateVerifiesLinks

setInteractsWithUser:

− (void)setInteractsWithUser:(BOOL)flag

Tells the link manager whether it should display alert panels to the user when link problems occur. The default value is YES.

See also:	− interactsWithUser

setLinkOutlinesVisible:

− (void)setLinkOutlinesVisible:(BOOL)flag

Sets whether link outlines should be displayed, and sends dataLinkManagerRedrawLinkOutlines to the link manager’s delegate if the delegate implements it.

sourceLinkEnumerator

− (NSEnumerator *)sourceLinkEnumerator

Returns an enumerator of the link manager’s source links.

See also:	− destinationLinkEnumerator

writeLinksToPasteboard:

− (void)writeLinksToPasteboard:(NSPasteboard *)pasteboard

Writes all the link manager's links to pasteboard in preparation for an invocation of addLinkPreviouslyAt:fromPasteboard:at:, which expects to find one link matching its specified selection.

The links are written with NSPasteboard's addTypes:owner: method, which doesn't change the pasteboard's owner or change count, using a private pasteboard type.

Methods Implemented By the Delegate

copyToPasteboard:at:cheapCopyAllowed:

− (BOOL)copyToPasteboard:(NSPasteboard *)pasteboard

at:(NSSelection *)selection

cheapCopyAllowed:(BOOL)flag

Implemented by the link manager’s delegate to supply the source data described by selection on pasteboard. selection was previously provided by the application when it created an NSDataLink using initLinkedToSourceSelection:managedBy:supportingTypes:.

NSPasteboard works lazily, so the delegate doesn't have to provide all data representations at this time; it simply has to declare the pasteboard types it's willing to provide for selection. Normally, the delegate must put at least one representation on the pasteboard in order to generate any of the specified types when one is requested. However, if flag is YES, the system guarantees that no events will be processed by the application before the delegate is requested to provide the specified data; in this case, the application doesn't necessarily have to write any data representations to the pasteboard.

This method should return YES upon success, or NO if the selection can't be resolved.

dataLinkManager:didBreakLink:

− (void)dataLinkManager:(NSDataLinkManager *)sender

didBreakLink:(NSDataLink *)link

If the delegate implements this method, it is invoked to inform the delegate that the destination link link was broken and thus data based on the link’s destination selection will no longer be updated.

dataLinkManager:isUpdateNeededForLink:

− (BOOL)dataLinkManager:(NSDataLinkManager *)sender

isUpdateNeededForLink:(NSDataLink *)link

This method should return a boolean indicating whether the source data identified by link’s source selection has been modified since the link’s last update time. If the link manager has been sent a setLinksVerifiedByDelegate: message indicating that the delegate will verify the update status of individual links, the delegate should implement this method.

dataLinkManager:startTrackingLink:

− (void)dataLinkManager:(NSDataLinkManager *)sender

startTrackingLink:(NSDataLink *)link

Informs the delegate that another document has established a data link to the link manager's document. The delegate need only implement this method if it returns YES in response to a dataLinkManagerTracksLinksIndividually: message. link is a newly added source link; the data that it applies to is identified by link's source selection.

dataLinkManager:stopTrackingLink:

− (void)dataLinkManager:(NSDataLinkManager *)sender

stopTrackingLink:(NSDataLink *)link

Informs the delegate that link is no longer linked to the document. There are many reasons that a source link might be removed; the destination document could get closed, the link could be explicitly broken, or the destination application might have died.

See also:	− dataLinkManagerTracksLinksIndividually:

dataLinkManagerCloseDocument:

− (void)dataLinkManagerCloseDocument:(NSDataLinkManager *)sender

Used for closing documents that were not opened through the user interface. This method is never invoked by the Application Kit classes.

dataLinkManagerDidEditLinks

− (void)dataLinkManagerDidEditLinks:(NSDataLinkManager *)sender

Informs the delegate that link data has been modified. The link data is stored alongside the document's data and should be considered part of the document, so the delegate should use this notification to mark the document as edited.

dataLinkManagerRedrawLinkOutlines

− (void)dataLinkManagerRedrawOutlines:(NSDataLinkManager )sender

If the delegate implements this method, it is invoked any time the manager is instructed to show or hide link outlines through setLinkOutlinesVisible:. This method should query the link manager with areLinkOutlinesVisible to find out if link outlines should be displayed. If so, it should invoke NSFrameLinkRect() to draw a distinctive outline around the linked data; otherwise it should display the data without outlines.

dataLinkManagerTracksLinksIndividually

− (BOOL)dataLinkManagerTracksLinksIndividually:(NSDataLinkManager *)sender

If the delegate wishes to track links individually, it should implement this method and return YES. If the delegate doesn't implement this method, links are not individually tracked.

If the delegate implements this method and returns YES, it should also implement dataLinkManager:startTrackingLink: and dataLinkManager:stopTrackingLink: to follow the links in use.

To support continuous updating of links, your application needs to track links individually.  This is also useful if your application must store selection-state information in the document. It should only do so for selections (and their associated links) that actually get used; many links may be placed on the pasteboard when data is copied, but few of those links will actually ever get used. This method indicates whether the delegate wants to be informed when a link gets used.

importFile:at:

− (BOOL)importFile:(NSString *)filename

at:(NSSelection *)selection

If the application has added a link based on an entire file (that is, used addLink:at: to incorporate a link created by initLinkedToFile:), the delegate must implement this method to import the file filename at the destination described by selection.

This method should return YES upon success, or NO if the selection can't be resolved.

pasteFromPasteboard:at:

− (BOOL)pasteFromPasteboard:(NSPasteboard *)pasteboard

at:(NSSelection *)selection

If the application has added an ordinary destination link (that is, used addLink:at: to incorporate a link created by initWithPasteboard: or a related method), the delegate must implement this method to paste the updated data that has been made available on the pasteboard. The destination for the data is described by selection, which was supplied to the link manager as an argument to the addLink:at: method.

The data is read from the pasteboard just as it is for any ordinary paste operation; see the NSPasteboard class specification for more information on reading data from a pasteboard.

This method should return YES upon success, or NO if the selection can't be resolved.

showSelection

− (BOOL)showSelection:(NSSelection *)selection

In an application that serves as a link source, the delegate should implement this method to show the source data for selection. This method should scroll the document so the selected data is visible. It might additionally highlight the selected data using the function NSFrameLinkRect() with the argument isDestination set to NO.

This method should return YES upon success, or NO if the selection can't be resolved.

windowForSelection

− (NSWindow *)windowForSelection:(NSSelection *)selection

In an application that serves as a link source, the delegate should implement this method to return the NSWindow for the given selection, or nil if the selection can't be resolved.


NSDataLinkPanel

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSPanel : NSWindow : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSDataLinkPanel.h

Class Description

An NSDataLinkPanel is an NSPanel that allows the user to inspect data links. The NSDataLinkPanel functions primarily by sending messages to the current data link manager (representing the current document) and to the current link (representing the current selection if it’s based on a data link). Thus, the panel should be sent a setLink:manager:isMultiple: message any time the selection changes or a document is created or activated. Since the selection may need to be tracked even before the panel is created, this message can be sent to either the NSDataLinkPanel class or the shared instance.

The NSDataLinkPanel is generally displayed using NSApplication’s orderFrontDataLinkPanel: method. An application’s sole instance of NSDataLinkPanel can be accessed with the sharedDataLinkPanel method.

Method Types

Creating and initializing an NSDataLinkPanel

+ sharedDataLinkPanel

Keeping the panel up to date	+ getLink:manager:isMultiple:

+ setLink:manager:isMultiple:

− getLink:manager:isMultiple:

− setLink:manager:isMultiple:

Customizing the panel	− accessoryView

− setAccessoryView:

Responding to user input	− pickedBreakAllLinks:

− pickedBreakLink:

− pickedOpenSource:

− pickedUpdateDestination:

− pickedUpdateMode:

Class Methods

getLink:manager:isMultiple:

+ (void)getLink:(NSDataLink **)link

manager:(NSDataLinkManager **)linkManager

isMultiple:(BOOL *)flag

Gets information about the NSDataLinkPanel’s currently selected link; returns the link in link, the link manager in linkManager, and the multiple selection status in flag.

See also:	+ setLink:manager:isMultiple:

setLink:manager:isMultiple:

+ (void)setLink:(NSDataLink *)link

manager:(NSDataLinkManager *)linkManager

isMultiple:(BOOL)flag

Informs the receiver of the current document and selection using link as the currently selected link and linkManager as the current link manager. flag is YES if the panel will indicate that more than one link is selected.

This message must be sent whenever data based on a data link is selected or deselected, or when a document (and therefore a new link manager) is activated. This message can be sent to either the NSDataLinkPanel class or instance.

See also:	+ getLink:manager:isMultiple:

sharedDataLinkPanel

+ (NSDataLinkPanel *)sharedDataLinkPanel

Initializes and returns the shared NSDataLinkPanel object.

Instance Methods

accessoryView

− (NSView *)accessoryView

Returns the NSDataLinkPanel’s custom accessory view.

See also:	− setAccessoryView:

getLink:manager:isMultiple:

− (void)getLink:(NSDataLink **)link

manager:(NSDataLinkManager **)linkManager

isMultiple:(BOOL *)flag

Gets information about the NSDataLinkPanel’s currently selected link; returns the link in link, the link manager in linkManager, and the multiple selection status in flag. This method functions identically to the class method of the same name.

See also:	− setLink:manager:isMultiple:, + getLink:manager:isMultiple:

pickedBreakAllLinks:

− (void)pickedBreakAllLinks:(id)sender

Invoked when the user clicks the Break All Links button, this method puts up an attention panel to confirm the user’s action, then sends a breakAllLinks message to the current link manager.

See also:	− breakAllLinks (NSDataLinkManager)

pickedBreakLink:

− (void)pickedBreakLink:(id)sender

Invoked when the user clicks the Break Link button, this method puts up an attention panel to confirm the user’s action, then sends a break message to the current link.

See also:	− break (NSDataLink)

pickedOpenSource:

− (void)pickedOpenSource:(id)sender

Invoked when the user clicks the Open Source button, this method sends an openSource message to the current link.

See also:	− openSource (NSDataLink)

pickedUpdateDestination:

− (void)pickedUpdateDestination:(id)sender

Invoked when the user clicks the Update from Source button, this method sends a message to the current link to verify and update the data source and then update the destination data.

See also:	− updateDestination (NSDataLink)

pickedUpdateMode:

− (void)pickedUpdateMode:(id)sender

Invoked when the user selects the update mode, this method sends a setUpdateMode: message to the current link.

See also:	− setUpdateMode: (NSDataLink)

setAccessoryView:

− (void)setAccessoryView:(NSView *)aView

Adds aView to the NSDataLinkPanel’s view hierarchy. Applications can invoke this method to add an NSView that contains their own controls. The panel is automatically resized to accommodate aView. This method can be invoked repeatedly to change the accessory view depending on the situation. If aView is nil, then the panel’s current accessory view, if any, is removed.

See also:	− accessoryView

setLink:manager:isMultiple:

− (void)setLink:(NSDataLink *)link

manager:(NSDataLinkManager *)linkManager

isMultiple:(BOOL)flag

Informs the receiver of the current document and selection using link as the currently selected link and linkManager as the current link manager. flag is YES if the panel will indicate that more than one link is selected.

This message must be sent whenever data based on a data link is selected or deselected, or when a document (and therefore a new link manager) is activated. This message can be sent to either the NSDataLinkPanel class or instance.

See also:	− getLink:manager:isMultiple:, + setLink:manager:isMultiple:


NSDraggingDestination

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

 (informal protocol)

Category Of:	NSObject

Declared In:	AppKit/NSDragging.h

Description

The NSDraggingDestination informal protocol declares methods that the destination (or recipient) of a dragged image must implement. The destination automatically receives NSDraggingDestination messages as an image enters, moves around inside, and then exits or is released within the destination’s boundaries.

In the text here and in the other dragging protocol descriptions, the term dragging session is the entire process during which an image is selected, dragged, released, and absorbed or rejected by the destination. A dragging operation is the action that the destination takes in absorbing the image when it’s released. The dragging source is the object that “owns” the image that’s being dragged. It’s specified as an argument to the dragImage:at:offset:event:pasteboard:source:slideBack: message, sent to a window or view object, that instigated the dragging session.

The Dragged Image

The image that’s dragged in an image-dragging session is simply an image that represents data that resides on the pasteboard. Although a dragging destination can access the image (through the draggedImage method described in the NSDraggingInfo protocol), its primary concern is with the pasteboard data that the image represents—the dragging operation that a destination ultimately performs is on the pasteboard data, not on the image itself.

Valid Destinations

Dragging is a visual phenomenon. To be an image-dragging destination, an object must represent a portion of screen real estate; thus, only window and view objects can be destinations. Furthermore, you must register the pasteboard types that the object will accept by sending the object a registerForDraggedTypes: message, defined in both NSWindow and NSView. During a dragging session, a candidate destination only receives NSDraggingDestination messages if the destination is registered for a pasteboard type that matches the type of the pasteboard data being dragged. See the NSPasteboard class specification for more information about pasteboard types.

Although NSDraggingDestination is declared as an informal protocol, the NSWindow and NSView subclasses that you create to adopt the protocol need only implement those methods that are pertinent. (The NSWindow and NSView classes provide private implementations for all of the methods.) Either a window object or its delegate may implement these methods; however, the delegate’s implementation takes precedence if there are implementations in both places.

The Sender of Destination Messages

Each of the NSDraggingDestination methods sports a single argument: sender, the object that invoked the method. Within its implementations of the NSDraggingDestination methods, the destination can send NSDraggingInfo messages to sender to get more information on the current dragging session.

The Order of Destination Messages

The six NSDraggingDestination methods are invoked in a distinct order:

•	As the image is dragged into the destination’s boundaries, the destination is sent a draggingEntered: message

•	While the image remains within the destination, a series of draggingUpdated: messages are sent.

•	If the image is dragged out of the destination, draggingExited: is sent and the sequence of NSDraggingDestination messages stops. If it re-enters, the sequence begins again (with a new draggingEntered: message).

•	When the image is released, it either slides back to its source (and breaks the sequence) or a prepareForDragOperation: message is sent to the destination, depending on the value returned by the most recent invocation of draggingEntered: or draggingUpdated:.

•	If the prepareForDragOperation: message returned YES, a performDragOperation: message is sent.

•	Finally, if performDragOperation: returned YES, concludeDragOperation: is sent.

Method Types

Before the image is released	− draggingEntered:

− draggingUpdated:

− draggingExited:

After the image is released	− prepareForDragOperation:

− performDragOperation:

− concludeDragOperation:

Instance Methods

concludeDragOperation:

− (void)concludeDragOperation:(id <NSDraggingInfo>)sender

Invoked when the dragging operation is complete and the previous performDragOperation: returned YES. The destination implements this method to perform any tidying up that it needs to do, such as updating its visual representation now that it has incorporated the dragged data. This is the last message that’s sent from sender to the destination during a dragging session.

draggingEntered:

− (unsigned int)draggingEntered:(id <NSDraggingInfo>)sender

Invoked when a dragged image enters the destination. Specifically, this method is invoked when the mouse pointer enters the destination’s bounds rectangle (if it’s a view object) or its frame rectangle (if it’s a window object).

This method must return a value that indicates which dragging operation the destination will perform when the image is released. In deciding which dragging operation to return, the method should evaluate the overlap between both the dragging operations allowed by the source (accessible through the draggingSourceOperationMask method) and the dragging operations and pasteboard data types that the destination itself supports. The returned value should be exactly one of the following:

Option	Meaning

NSDragOperationCopy	The data represented by the image will be copied.

NSDragOperationLink	The data will be shared.

NSDragOperationGeneric	The operation will be defined by the destination.

NSDragOperationPrivate	The operation is negotiated privately between the source and the destination.

NSDragOperationAll	Combines all the above.

If none of the operations is appropriate, this method should return NSDragOperationNone (this is the default response if the method isn’t implemented by the destination).

The code below is a simple example of a method that responds distinctly when one of two different types of data is dragged into the destination view or window. If the dragged data is a color and the source object permits copying, the return value indicates that the destination will permit copying of the color data on the pasteboard. If the dragged data is an RTF file and the source object permits linking, the return value indicates that the destination will permit linking of the RTF file on the pasteboard. Otherwise the code returns NSDragOperationNone, indicating that the destination will not permit any dragging operations with the data on pastboard.

- (unsigned int)draggingEntered:(id <NSDraggingInfo>)sender

{

    NSPasteboard *pboard;

    NSDragOperation sourceDragMask;

    sourceDragMask = [sender draggingSourceOperationMask];

    pboard = [sender draggingPasteboard];

    if ([[pboard types] indexOfObject:NSColorPboardType] != NSNotFound) {

        if (sourceDragMask & NSDragOperationCopy) {

            return NSDragOperationCopy;

        }

    }

    if ([[pboard types] indexOfObject:NSRTFPboardType] != NSNotFound) {

        if (sourceDragMask & NSDragOperationLink) {

            return NSDragOperationLink;

        }

    }

    return NSDragOperationNone;

}

See also:	− draggingUpdated:, − draggingExited:, − prepareForDragOperation:

draggingExited:

− (void)draggingExited:(id <NSDraggingInfo>)sender

Invoked when the dragged image exits the destination’s bounds rectangle (in the case of a view object) or its frame rectangle (in the case of a window object).

draggingUpdated:

− (unsigned int)draggingUpdated:(id <NSDraggingInfo>)sender

Invoked periodically as the image is held within the destination. The messages continue until the image is either released or dragged out of the window or view. The return value should be one of the dragging operation options listed under the draggingEntered: method. The default return value (if this method isn’t implemented by the destination) is the value returned by the previous draggingEntered: message.

This method provides the destination with an opportunity to modify the dragging operation depending on the position of the mouse pointer inside of the destination view or window object. For example, you may have several graphics or areas of text contained within the same view and wish to tailor the dragging operation, or to ignore the drag event completely, depending upon which object is underneath the mouse pointer at the time when the user releases the dragged image and the performDragOperation: method is invoked.

You typically examine the contents of the pasteboard in the draggingEntered: method, where this examination is performed only once, rather than in the draggingUpdate: method which is invoked multiple times.

Only one destination at a time receives a sequence of draggingUpdated: messages. If the mouse pointer is within the bounds of two overlapping views that are both valid destinations, the uppermost view receives these messages until the image is either released or dragged out.

See also:	− draggingExited:, − prepareForDragOperation:

performDragOperation:

− (BOOL)performDragOperation:(id <NSDraggingInfo>)sender

Invoked after the released image has been removed from the screen and the previous prepareForDragOperation: message has returned YES. The destination should implement this method to do the real work of importing the pasteboard data represented by the image. If the destination accepts the data, it returns YES, otherwise it returns NO. The default is to return NO.

See also:	 − concludeDragOperation:

prepareForDragOperation:

− (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender

Invoked when the image is released, if the most recent draggingEntered: or draggingUpdated: message returned an acceptable drag-operation value. Returns YES if the receiver agrees to perform the drag operation and NO if not.

See also:	 − performDragOperation:


NSDraggingInfo

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Adopted By:	 no OPENSTEP classes

Declared In:	 AppKit/NSDragging.h

Protocol Description

The NSDraggingInfo protocol declares methods that supply information about a dragging session (see the NSDraggingDestination protocol for definitions of dragging terms). NSDraggingInfo methods are designed to be invoked from within a class’s implementations of NSDraggingDestination informal protocol methods. The Application Kit automatically passes an object that conforms to the NSDraggingInfo protocol as the argument to each of the methods defined by NSDraggingDestination. NSDraggingInfo messages should be sent to this object; you never need to create a class that implements the NSDraggingInfo protocol.

Method Types

Dragging-session information	− draggingSource

− draggingSourceOperationMask

− draggingDestinationWindow

− draggingPasteboard

− draggingSequenceNumber

− draggingLocation

Image information	− draggedImage

− draggedImageLocation

Sliding the image	− slideDraggedImageTo:

Instance Methods

draggedImage

− (NSImage *)draggedImage

Returns the image being dragged. This image object visually represents the data put on the pasteboard during the drag operation; however, it is the pasteboard data and not this image that are ultimately utilized in the dragging operation.

See also:	 − draggedImageLocation

draggedImageLocation

− (NSPoint)draggedImageLocation

Returns the current location of the dragged image’s origin in the base coordinate system of the destination object’s window. The image moves along with the mouse pointer (the position of which is given by draggingLocation) but may be positioned at some offset.

See also:	 − draggedImage

draggingDestinationWindow

− (NSWindow *)draggingDestinationWindow

Returns the destination window for the dragging operation. Either this window is the destination itself, or it contains the view object that is the destination.

draggingLocation

− (NSPoint)draggingLocation

Returns the current location of the mouse pointer in the base coordinate system of the destination object’s window.

See also:	 − draggedImageLocation

draggingPasteboard

− (NSPasteboard *)draggingPasteboard

Returns the pasteboard object that holds the data being dragged. The dragging operation that is ultimately performed utilizes this pasteboard data and not the image returned by the draggedImage method.

draggingSequenceNumber

− (int)draggingSequenceNumber

Returns a number that uniquely identifies the dragging session.

draggingSource

− (id)draggingSource

Returns the source, or owner, of the dragged data or nil if the source isn’t in the same application as the destination.

draggingSourceOperationMask

− (unsigned int)draggingSourceOperationMask

Returns the dragging operation mask declared by the dragging source (through its draggingSourceOperationMaskForLocal: method). If the source permits dragging operations, the elements in the mask will be one or more of the following, combined using the C bitwise OR operator:

Option	Meaning

NSDragOperationCopy	The data represented by the image can be copied.

NSDragOperationLink	The data can be shared.

NSDragOperationGeneric	The operation can be defined by the destination.

NSDragOperationPrivate	The operation is negotiated privately between the source and the destination.

NSDragOperationAll	Combines all the above.

If the source does not permit any dragging operations, then method should return NSDragOperationNone.

If the user is holding down a modifier key during the dragging session and the source doesn’t prohibit modifier keys from affecting the drag operation (through its ignoreModifierKeysWhileDragging method), then the operating system combines the dragging operation value that corresponds to the modifier key (see the descriptions below) with the source’s mask using the C bitwise AND operator.

On Mach the modifier keys are associated with the dragging operation options shown below,

Modifier Key	Dragging Option

Control	NSDragOperationLink

Alternate	NSDragOperationCopy

Command	NSDragOperationGeneric

while on Windows the modifier keys are associated with the following dragging operation options.

Modifier Key	Dragging Option

Control	NSDragOperationCopy

Shift-Control	NSDragOperationLink

Alternate	NSDragOperationCopy

slideDraggedImageTo:

− (void)slideDraggedImageTo:(NSPoint)aPoint

Slides the image to aPoint, a specified location in the screen coordinate system. This method can be used to snap the image down to a particular location. It should only be invoked from within the destination’s implementation of prepareForDragOperation:—in other words, after the user has released the image but before it’s removed from the screen.


NSDraggingSource

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

 (informal protocol)

Category Of:	NSObject

Declared In:	AppKit/NSDragging.h

Description

The NSDraggingSource informal protocol declares methods that are implemented by the source object in a dragging session (see the NSDraggingDestination protocol for definitions of dragging terms). The dragging source is specified as an argument to the dragImage:at:offset:event:pasteboard:source:slideBack: message, sent to a window or view object to initiate the dragging session.

See the documentation of the dragImage:... method in NSView for a warning regarding the mouse-down event that initiates a dragging session.

Of the methods declared below, only draggingSourceOperationMaskForLocal: must be implemented. The other methods are invoked only if the dragging source implements them. All four methods are invoked automatically during a dragging session—you never send an NSDraggingSource message directly to an object.

Method Types

Specifying dragging options	− draggingSourceOperationMaskForLocal:

− ignoreModifierKeysWhileDragging

Responding to dragging sessions	− draggedImage:beganAt:

− draggedImage:endedAt:deposited:

Instance Methods

draggedImage:beganAt:

− (void)draggedImage:(NSImage *)aInimage beganAt:(NSPoint)aPoint

Invoked when anImage is displayed but before it starts following the mouse. aPoint is the origin of the image in screen coordinates. This method provides the source object with an opportunity to respond to the initiation of a dragging session. For example, you might choose to have the source give a visual indication to the user that data is being dragged from the source.

See also:	− convertScreenToBase: (NSWindow), − convertBaseToScreen: (NSWindow), − convertPoint: fromView: (NSView), − convertPoint: toView: (NSView)

draggedImage:endedAt:deposited:

− (void)draggedImage:(NSImage *)anImage

endedAt:(NSPoint)aPoint

deposited:(BOOL)flag

Invoked after anImage has been released and the dragging destination has been given a chance to operate on the data it represents. aPoint is the location of the image’s origin in the screen coordinate system when it was released. A YES value for flag indicates that the destination accepted the dragged data, while a NO value indicates that it was rejected.

This method provides the source object with an opportunity to respond to either a successful or a failed dragging session. For example, if you are moving data from one location to another, you could use this method to make the source data disappear from its previous location, if the dragging session is successsful, or reset itself to its previous state, in the event of a failure.

See also:	− convertScreenToBase: (NSWindow), − convertBaseToScreen: (NSWindow), − convertPoint: fromView: (NSView), − convertPoint: toView: (NSView)

draggingSourceOperationMaskForLocal:

− (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)flag

This is the only NSDraggingSource method that must be implemented by the source object. It should return a mask, built by combining the applicable constants listed below using the C bitwise OR operator. You should use this mask to indicate which types of dragging operations the source object will allow to be performed on the dragged image’s data. A YES value for flag indicates that the candidate destination object (the window or view over which the dragged image is currently poised) is in the same application as the source, while a NO value indicates that the destination object is in a different application.

Option	Meaning

NSDragOperationCopy	The data represented by the image can be copied.

NSDragOperationLink	The data can be shared.

NSDragOperationGeneric	The operation can be defined by the destination.

NSDragOperationPrivate	The operation is negotiated privately between the source and the destination.

NSDragOperationAll	Combines all the above.

If the source does not permit any dragging operations, then it should return NSDragOperationNone.

ignoreModifierKeysWhileDragging

− (BOOL)ignoreModifierKeysWhileDragging

Sets whether the use of the modifier keys should have no effect on the type of operation performed. If this method is not implemented or returns NO, then the user can tailor the drag operation by holding down a modifier key during the drag. The dragging option that corresponds to the modifier key is combined with the source’s mask (as set with the draggingSourceOperationMaskForLocal: method) using the C bitwise AND operator. See the description for the draggingSourceOperationMask method in the NSDraggingInfo protocol specification for more information about dragging masks and modifier keys.


NSEPSImageRep

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSImageRep : NSObject

Conforms To:	NSCoding (from NSImageRep)

NSCopying (from NSImageRep)

NSObject (from NSObject)

Declared In:	AppKit/NSEPSImageRep.h

Class Description

An NSEPSImageRep is an object that can render an image from encapsulated PostScript code (EPS).

Like most other kinds of NSImageReps, an NSEPSImageRep is generally used indirectly, through an NSImage object. An NSImage must be able to choose between various representations of a given image. It also needs to provide an off-screen cache of the appropriate depth for any image it uses. It determines this information by querying its NSImageReps.

Thus to work with an NSImage, an NSEPSImageRep must be able to provide some information about its image. The size of the object is set from the bounding box specified in the EPS header comments. Use these methods, inherited from the NSImageRep class, to set the other attributes of the NSEPSImageRep:

setColorSpaceName:

setAlpha:

setPixelsHigh:

setPixelsWide:

setBitsPerSample:

Note that if these attributes aren’t set, and an NSEPSImageRep is used in an NSImage with other representations, NSImage won’t be able to select between them. In actual practice, this usually isn’t a problem.

Method Types

Creating an NSEPSImageRep	+ imageRepWithData:

− initWithData:

Getting image data	− boundingBox

− EPSRepresentation

Drawing the image	− prepareGState

Class Methods

imageRepWithData:

+ (id)imageRepWithData:(NSData *)epsData

Creates a new NSEPSImageRep instance and then invokes initWithData: to initialize it with the contents of epsData. If the new object can’t be initialized for any reason (for example, epsData doesn’t contain EPS code), this method frees the receiver and returns nil. Otherwise, it returns self.

The size of the object is set from the bounding box specified in the EPS header comments.

Instance Methods

EPSRepresentation

− (NSData *)EPSRepresentation

Returns the EPS representation of the image.

boundingBox

− (NSRect)boundingBox

Returns the rectangle that bounds the image. The rectangle is obtained from the “%%BoundingBox:” comment in the EPS header when the NSEPSImageRep is initialized.

See also:	+ imageRepWithData:, − initWithData:

initWithData:

− (id)initWithData:(NSData *)epsData

Initializes the receiver, a newly allocated NSEPSImageRep object, with the contents of epsData. If the new object can’t be initialized for any reason (for example, epsData doesn’t contain EPS code), this method frees the receiver and returns nil. Otherwise, it returns self.

The size of the object is set from the bounding box specified in the EPS header comments.

prepareGState

− (void)prepareGState

Implemented by subclasses to initialize the graphics state before the image is drawn. NSEPSImageRep’s draw method sends a prepareGState message just before rendering the EPS code. The default implementation of prepareGState does nothing.


NSEvent

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSCopying

NSObject (NSObject)

Declared In:	AppKit/NSEvent.h

Class Description

An NSEvent object, or simply an event, contains information about an input action such as a mouse click or a key down. The Application Kit associates each such user action with a window, reporting the event to the application that created the window. The NSEvent object contains pertinent information about each event, such as where the mouse was located or which character was typed. As the application receives events, it temporarily places them in a buffer called the event queue. When the application is ready to process an event, it takes one from the queue.

NSEvents are typically passed up the application’s responder chain, a series of objects that stand in line for event messages and untargeted action messages, as described in the NSResponder class specification. When the NSApplication object retrieves an event from the event queue, it dispatches the event to the appropriate NSWindow by invoking sendEvent:. The NSWindow then passes the event to its first responder in an event message such as mouseDown: or keyDown:, and the event gets passed on up the responder chain until some object handles it. In the case of a mouse-down event, a mouseDown: message is sent to the NSView where the user clicked the mouse; if it doesn’t handle the event itself, the NSView relays the message to its next responder.

Most events follow this same path: from the windowing system to the application’s event queue, and from there to the appropriate objects in the application. Though it rarely need do so, an application can also create an event from scratch and insert it into the event queue for distribution, or send it directly to its destination in an event message. The newly created events can be added to the event queue by invoking NSWindow’s (or NSApplication’s) postEvent:atStart: method.

While most events are distributed automatically through the responder chain, sometimes an object needs to retrieve events explicitly—for example, while handling mouse-dragged events. NSWindow and NSApplication define the method nextEventMatchingMask:untilDate:inMode:dequeue:, which allows an object to retrieve events of specific types. The nature of the retrieved event can then be ascertained by invoking NSEvent instance methods—type, window, and so on. All types of events are associated with an NSWindow; the window method returns this object. The location of a mouse event within the window’s coordinate system is given by locationInWindow, and the time of the event by timestamp. The modifierFlags method returns an indication of which modifier keys (Command, Control, Shift, and so on) the user held down while the event occurred.

The type method returns an NSEventType value that identifies the sort of event. The different types of events fall into five groups:

•	Keyboard events

•	Mouse events

•	Tracking-rectangle and cursor-update events

•	Periodic events

•	Other events

Some of these groups comprise several NSEventType constants, others only one. The following sections discuss the groups, along with the corresponding NSEventType constants.

Keyboard Events

Among the most common events sent to an application are direct reports of the user’s keyboard actions, identified by these NSEventType constants:

•	NSKeyDown. The user generated a character or characters by pressing a key.

•	NSKeyUp. The key was released.

•	NSFlagsChanged. The user pressed or released a modifier key, or turned Alpha Lock on or off.

Of these, key-down events are the most useful to an application. When a type message returns NSKeyDown, the next step is typically to get the characters generated by the key-down using the characters method.

Key-up events are used less frequently since they follow almost automatically when there’s been a key-down event. And because NSEvent’s modifierFlags method returns the state of the modifier keys regardless of the type of event, applications normally don’t need to receive flags-changed events; they’re useful only for applications that have to keep track of the state of these keys at all times.

For more information on keyboard events, see “Keyboard Events” under “Event Handling” in the NSView class specification.

Mouse Events

Mouse events are generated by changes in the state of the mouse buttons and by changes in the position of the mouse cursor on the screen. This category consists of:

•	NSLeftMouseDown, NSLeftMouseUp, NSRightMouseDown, NSRightMouseUp. “Mouse-down” means the user pressed the button; “mouse-up” means the user released it. If the mouse has just one button, only left mouse events are generated. By sending a clickCount message to the event, you can determine whether the mouse event was a single click, double click, and so on.

•	NSLeftMouseDragged, NSRightMouseDragged. The user moved the mouse with one or more buttons down. NSLeftMouseDragged events are generated when the mouse is moved with its left mouse button down or with both buttons down, and NSRightMouseDragged when it's moved with just the right button down. A mouse with a single button generates only left mouse-dragged events. A series of mouse-dragged events is always preceded by a mouse-down event and followed by a mouse-up event.

•	NSMouseMoved. The user moved the mouse without holding down either mouse button. Mouse-moved events are normally not tracked, as they quickly flood the event queue; use NSWindow’s setAcceptsMouseMovedEvents: to turn on tracking of mouse movements.

Mouse-dragged and mouse-moved events are generated repeatedly as long as the user keeps moving the mouse. If the mouse is stationary, neither type of event is generated until the mouse moves again.

Note:	Neither the OpenStep specification nor NeXT’s OPENSTEP implementation specifies facilities for the third button of a three-button mouse.

See “Mouse Events” under “Event Handling” in the NSView class specification for more information on mouse events.

Tracking-Rectangle and Cursor-Update Events

Because following the mouse’s movements precisely is an expensive operation, the Application Kit provides a less intensive mechanism for tracking the location of the mouse. It does this by allowing the application to define regions of the screen, called tracking rectangles, that generate events when the cursor enters or leaves them. The event types are NSMouseEntered and NSMouseExited, and they’re generated when the application has asked the Window Server to set a tracking rectangle in a window, typically by using NSView’s addTrackingRect:owner:userData:assumeInside: method. A window can have any number of tracking rectangles; NSEvent’s trackingNumber method identifies the rectangle that triggered the event.

A special kind of tracking event is the NSCursorUpdate event. This type is used to implement NSView’s cursor-rectangle mechanism. An NSCursorUpdate event is generated when the cursor has crossed the boundary of a predefined rectangular area. Applications rarely use NSCursorUpdate events directly, instead using NSView’s far more convenient methods.

See “Tracking Rectangles and Cursor Rectangles” under “Event Handling” in the NSView class specification for more information.

Periodic Events

An event of type NSPeriodic simply notifies an application that a certain time interval has elapsed. By using the NSEvent class method startPeriodicEventsAfterDelay:withPeriod:, an application can register to receive periodic events and have them placed in its event queue at a certain frequency. When the application no longer needs them, the flow of periodic events can be turned off by invoking stopPeriodicEvents. An application can have only one stream of periodic events active for each thread. Unlike keyboard and mouse events, periodic events aren’t dispatched to an NSWindow. The application must retrieve them explicitly using nextEventMatchingMask:untilDate:inMode:dequeue:, typically in a modal loop.

Periodic events are particularly useful in situations where input events aren’t generated. For example, when the user holds the mouse down over a scroll button but doesn’t move it, no events are generated after the mouse-down event. The scrolling mechanism then has to start and use a stream of periodic events to keep the document scrolling at a reasonable pace until the user releases the mouse. When a mouse-up event occurs, the scrolling mechanism terminates the periodic event stream.

Other Events

The remaining event types—NSAppKitDefined, NSSystemDefined, and NSApplicationDefined—are less structured, containing only generic subtype and data fields. These three types are extensions to the OpenStep specification, so you shouldn’t use them in portable code (periodic events are also implemented in this manner, but are in the specification). Of the three miscellaneous event types, only NSApplicationDefined is of real use to application programs. It allows the application to generate totally custom events and insert them into the event queue. Each such event can have a subtype and two additional codes to different it from others. otherEventWithType:... creates one of these events, and the subtype, data1, and data2 methods return the information specific to these events.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

NSCopying	− copyWithZone:

− copy

Method Types

Creating events	+ keyEventWithType:location:modifierFlags:timestamp:

windowNumber:context:characters:

charactersIgnoringModifier:isARepeat:keyCode:

+ mouseEventWithType:location:modifierFlags:

timestamp:windowNumber:context:eventNumber:

clickCount:pressure:

+ enterExitEventWithType:location:modifierFlags:

timestamp:windowNumber:context:eventNumber:

trackingNumber:userData:

+ otherEventWithType:location:modifierFlags:

timestamp:windowNumber:context:subtype:data1:

data2:

Requesting and stopping periodic events

+ startPeriodicEventsAfterDelay:withPeriod:

+ stopPeriodicEvents

Getting general event information	− context

− locationInWindow

− modifierFlags

− timestamp

− type

− window

− windowNumber

Getting key event information	− characters

− charactersIgnoringModifiers

− isARepeat

− keyCode

Getting mouse event information	− clickCount

− eventNumber

− pressure

Getting tracking-rectangle event information

− eventNumber

− trackingNumber

− userData

Getting custom event information	− data1

− data2

− subtype

Class Methods

enterExitEventWithType:location:modifierFlags:timestamp:

windowNumber:context:eventNumber:trackingNumber:userData:

+ (NSEvent *)enterExitEventWithType:(NSEventType)type

location:(NSPoint)location

modifierFlags:(unsigned int)flags

timestamp:(NSTimeInterval)time

windowNumber:(int)windowNumber

context:(NSDPSContext *)context

eventNumber:(int)eventNumber

trackingNumber:(int)trackingNumber

userData:(void *)userData

Returns a new NSEvent object describing a tracking-rectangle or cursor-update event. type must be one of the following, else an NSInvalidArgumentException is raised:

NSMouseEntered

NSMouseExited

NSCursorUpdate

location, flags, time, windowNumber, and context are as described under keyEventWithType:.... Arguments specific to mouse tracking events are:

eventNumber is an identifier for the new event. It’s normally taken from a counter for mouse events, which continually increases as the application runs.

trackingNumber is the number that identifies the tracking rectangle. This identifier is the same returned by NSView’s addTrackingRect:owner:userData:assumeInside:.

userData is data arbitrarily associated with the tracking rectangle when it was set up using NSView’s addTrackingRect:owner:userData:assumeInside:.

See also:	− eventNumber, − trackingNumber, − userData

keyEventWithType:location:modifierFlags:timestamp:windowNumber:

context:characters:charactersIgnoringModifier:isARepeat:keyCode:

+ (NSEvent *)keyEventWithType:(NSEventType)type

location:(NSPoint)location

modifierFlags:(unsigned int)flags

timestamp:(NSTimeInterval)time

windowNumber:(int)windowNum

context:(NSDPSContext *)context

characters:(NSString *)characters

charactersIgnoringModifiers:(NSString *)unmodCharacters

isARepeat:(BOOL)repeatKey

keyCode:(unsigned short int)code

Returns a new NSEvent object describing a key event. type must be one of the following, else an NSInvalidArgumentException is raised:

NSKeyDown

NSKeyUp

NSFlagsChanged

location is the mouse location in the base coordinate system of the window specified by windowNumber.

flags is an integer bit field containing any of these modifier key masks, combined using the C bitwise OR operator:

NSAlphaShiftKeyMask

NSShiftKeyMask

NSControlKeyMask

NSAlternateKeyMask

NSCommandKeyMask

NSNumericPadKeyMask

NSHelpKeyMask

NSFunctionKeyMask

time is the time the event occurred in seconds since system startup. How to get this value varies with the platform.

windowNumber identifies the PostScript window device associated with the event, which is associated with the NSWindow that will receive the event.

context is the Display PostScript context of the event.

characters is a string of characters associated with the key event. Though most key events contain only one character, it is possible for a single keypress to generate a series of characters.

unmodCharacters is the string of characters generated by the key event as if no modifier key had been pressed (except for Shift). This is useful for getting the “basic” key value in a hardware-independent manner.

repeatKey is YES if the key event is a repeat caused by the user holding the key down, NO if the key event is new.

code identifies the keyboard key associated with the key event. Its value is hardware-dependent.

See also:	− characters, − charactersIgnoringModifiers, − isARepeat, − keyCode

mouseEventWithType:location:modifierFlags:timestamp:

windowNumber:context:eventNumber:clickCount:pressure:

+ (NSEvent *)mouseEventWithType:(NSEventType)type

location:(NSPoint)location

modifierFlags:(unsigned int)flags

timestamp:(NSTimeInterval)time

windowNumber:(int)windowNum

context:(NSDPSContext *)context

eventNumber:(int)eventNumber

clickCount:(int)clickNumber

pressure:(float)pressure

Returns a new NSEvent object describing a mouse-down, -up, -moved, or -dragged event. type must be one of the following, else an NSInvalidArgumentException is raised:

NSLeftMouseDown

NSLeftMouseUp

NSRightMouseDown

NSRightMouseUp

NSMouseMoved

NSLeftMouseDragged

NSRightMouseDragged

location, flags, time, windowNumber, and context are as described under keyEventWithType:....

eventNumber is an identifier for the new event. It’s normally taken from a counter for mouse events, which continually increases as the application runs.

clickNumber is the number of mouse clicks associated with the mouse event.

pressure is a value from 0.0 to 1.0 indicating the pressure applied to the input device on a mouse event, used for an appropriate device such as a graphics tablet. For devices that aren’t pressure-sensitive, the value should be either 0.0 or 1.0. How to determine whether the input device is pressure-sensitive depends on the platform.

See also:	− clickCount, − eventNumber, − pressure

otherEventWithType:location:modifierFlags:timestamp:

windowNumber:context:subtype:data1:data2:

+ (NSEvent *)otherEventWithType:(NSEventType)type

location:(NSPoint)location

modifierFlags:(unsigned int)flags

timestamp:(NSTimeInterval)time

windowNumber:(int)windowNum

context:(NSDPSContext *)context

subtype:(short int)subtype

data1:(int)data1

data2:(int)data2

Returns a new NSEvent object describing a custom event. type must be one of the values below, else an NSInvalidArgumentException is raised. Your code should only create events of type NSApplicationDefined.

NSAppKitDefined (NeXT extension to the OpenStep specification)

NSSystemDefined (NeXT extension to the OpenStep specification)

NSApplicationDefined (NeXT extension to the OpenStep specification)

NSPeriodic

location, flags, time, windowNumber, and context are as described under keyEventWithType:.... Arguments specific to mouse tracking events are:

subtype further differentiates custom events of type NSAppKitDefined, NSSystemDefined, and NSApplicationDefined. NSPeriodic events don’t use this attribute.

data1 and data2 contain additional data associated with the event. NSPeriodic events don’t use these attributes.

See also:	− subtype, − data1, − data2

startPeriodicEventsAfterDelay:withPeriod:

+ (void)startPeriodicEventsAfterDelay:(NSTimeInterval)delaySeconds

withPeriod:(NSTimeInterval)periodSeconds

Begins generating periodic events for the current thread every periodSeconds, after a delay of delaySeconds. Raises an NSInternalInconsistencyException if periodic events are already being generated for the current thread. This method is typically used in a modal loop while tracking mouse-dragged events.

See also:	+ stopPeriodicEvents

stopPeriodicEvents

+ (void)stopPeriodicEvents

Stops generating periodic events for the current thread and discards any periodic events remaining in the queue. This message is ignored if periodic events aren’t currently being generated.

See also:	+ startPeriodicEventsAfterDelay:withPeriod:

Instance Methods

characters

− (NSString *)characters

Returns the characters associated with the receiving key-up or key-down event. These characters are derived from a keyboard mapping that associates various key combinations with Unicode characters. Raises an NSInternalInconsistencyException if sent to any other kind of event.

See also:	− charactersIgnoringModifiers, + keyEventWithType:...

charactersIgnoringModifiers

− (NSString *)charactersIgnoringModifiers

Returns the characters generated by the receiving key event as if no modifier key (except for Shift) applies. Raises an NSInternalInconsistencyException if sent to a non-key event. The return value of this method is meaningless for an NSFlagsChanged event.

This method is useful for determining “basic” key values in a hardware-independent manner, enabling such features as keyboard equivalents and mnemonics defined in terms of modifier keys plus character keys. For example, to determine if the user typed Alt-s, you don’t have to know whether Alt-s generates a German double ess, an integral sign, or a section symbol. You simply examine the string returned by this method along with the event’s modifier flags, checking for “s” and NSAlternateKeyMask.

See also:	− characters, − modifierFlags, + keyEventWithType:...

clickCount

− (int)clickCount

Returns the number of mouse clicks associated with the receiver, a mouse-down or -up event. Raises an NSInternalInconsistencyException if sent to a non-mouse event.

The return value of this method is meaningless for events other than mouse-down or -up events.

See also:	+ mouseEventWithType:...

context

− (NSDPSContext *)context

Returns the Display PostScript context of the receiving event.

data1

− (int)data1

Returns additional data associated with the receiving event. Raises an NSInternalInconsistencyException if sent to an event not of type NSAppKitDefined, NSSystemDefined, NSApplicationDefined, or NSPeriodic.

NSPeriodic events don’t use this attribute.

See also:	− data2, − subtype, + otherEventWithType:...

data2

− (int)data2

Returns additional data associated with the receiving event. Raises an NSInternalInconsistencyException if sent to an event not of type NSAppKitDefined, NSSystemDefined, NSApplicationDefined, or NSPeriodic.

NSPeriodic events don’t use this attribute.

See also:	− data1, − subtype, + otherEventWithType:...

eventNumber

− (int)eventNumber

Returns the counter value of the latest mouse or tracking-rectangle event; every system-generated mouse and tracking-rectangle event increments this counter. Raises an NSInternalInconsistencyException if sent to any other type of event.

See also:	+ enterExitEventWithType:...,

+ mouseEventWithType:...

isARepeat

− (BOOL)isARepeat

Returns YES if the receiving key event is a repeat caused by the user holding the key down, NO if the key event is new. Raises an NSInternalInconsistencyException if sent to a non-key event.

The return value of this method is meaningless for NSFlagsChanged events.

See also:	+ keyEventWithType:...

keyCode

− (unsigned short int)keyCode

Returns the code for the keyboard key associated with the receiving key event. Its value is hardware-dependent. Raises an NSInternalInconsistencyException if sent to a non-key event.

See also:	+ keyEventWithType:...

locationInWindow

− (NSPoint)locationInWindow

Returns the receiving event’s location in the base coordinate system of the associated window.

See also:	− window

modifierFlags

− (unsigned int)modifierFlags

Returns an integer bit field indicating the modifier keys in effect for the receiving event. You can examine individual flag settings using the C bitwise AND operator with these predefined masks:

NSAlphaShiftKeyMask

NSShiftKeyMask

NSControlKeyMask

NSAlternateKeyMask

NSCommandKeyMask

NSNumericPadKeyMask

NSHelpKeyMask

NSFunctionKeyMask

pressure

− (float)pressure

Returns a value between 0.0 and 1.0 indicating the pressure applied to the input device (used for appropriate devices). For devices that aren’t pressure-sensitive, the value is either 0.0 or 1.0. How to determine whether the input device is pressure-sensitive depends on the platform. Raises an NSInternalInconsistencyException if sent to a non-mouse event.

See also:	+ mouseEventWithType:...

subtype

− (short int)subtype

Returns the subtype of the receiving custom event. Raises an NSInternalInconsistencyException if sent to an event not of type NSAppKitDefined, NSSystemDefined, NSApplicationDefined, or NSPeriodic.

NSPeriodic events don’t use this attribute.

See also:	− data1, − data2, + otherEventWithType:...

timestamp

− (NSTimeInterval)timestamp

Returns the time the event occurred in seconds since system startup.

trackingNumber

− (int)trackingNumber

Returns the identifier of the tracking rectangle for a tracking-rectangle event. Raises an NSInternalInconsistencyException if sent to any other type of event.

See also:	+ enterExitEventWithType:...

type

− (NSEventType)type

Returns the type of the receiving event, one of:

NSLeftMouseDown	NSKeyDown

NSLeftMouseUp	NSKeyUp

NSRightMouseDown	NSFlagsChanged

NSRightMouseUp	NSAppKitDefined (NeXT extension to the OpenStep specification)

NSMouseMoved	NSSystemDefined (NeXT extension to the OpenStep specification)

NSLeftMouseDragged	NSApplicationDefined (NeXT extension to the OpenStep specification)

NSRightMouseDragged	NSPeriodic

NSMouseEntered	NSCursorUpdate

NSMouseExited

userData

− (void *)userData

Returns data associated with a tracking-rectangle event, assigned to the tracking rectangle when it was set up using NSView’s addTrackingRect:owner:userData:assumeInside:. Raises an NSInternalInconsistencyException if sent to any other type of event.

See also:	+ enterExitEventWithType:...

window

− (NSWindow *)window

Returns the window object associated with the event. A periodic event, however, has no window; in this case the return value is undefined.

See also:	− windowNumber

windowNumber

− (int)windowNumber

Returns the identifier for the PostScript window device associated with the event. A periodic event, however, has no window; in this case the return value is undefined.

See also:	− window


NSFileWrapper
p NSFileWrapper

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSFileWrapper.h

Class Description

An NSFileWrapper holds a file’s contents in dynamic memory. In this role it enables a document object to embed a file, treating it as a unit of data that can be displayed as an image (and possibly edited in place), saved to disk, or transmitted to another application. It can also store an icon for representing the file in a document or in a dragging operation.

Instances of this class are referred to as file wrapper objects, and when no confusion will result, merely as file wrappers. A file wrapper can be one of three specific types: a regular file wrapper, which holds the contents of a single actual file; a directory wrapper, which holds a directory and all of the files or directories within it; or a link wrapper, which simply represents a symbolic link in the file system (sometimes called a shortcut or alias). Some NSFileWrapper methods apply only to a specific type, and raise an exception if sent to a file wrapper of the wrong type. To determine the type of a file wrapper, use the isRegularFile, isDirectory, and isSymbolicLink methods.

You can create a file wrapper from data in memory using initWithSerializedRepresentation: or from data on disk using initWithPath:. Both create the appropriate type of file wrapper based on the nature of the serialized representation or of the file on disk. Three convenience methods each create a file wrapper of a specific type: initRegularFileWithContents:, initDirectoryWithFileWrappers:, and initSymbolicLinkWithDestination:. Because each initialization method creates file wrappers of different types or states, they’re all designated initializers for this class—subclasses must meaningfully override them all as necessary.

Memory and Disk Representations

Because the purpose of a file wrapper is to represent files in memory, it’s very loosely coupled to any disk representation. A file wrapper doesn’t record the path to the disk representation of its contents. This allows you to save the same file wrapper with different paths, but it also requires you to record those paths if you want to update the file wrapper from disk later. NSFileWrapper allows you to set a preferred filename for save operations and records the last filename it was actually saved to; the preferredFilename and filename methods return these names. This feature is more important for directory wrappers, though, and so is discussed below under “Working with Directory Wrappers.”

A file wrapper stores file system information (such as modification time and access permissions), which it updates when reading from disk and uses when writing files to disk. The fileAttributes method returns this information in the format described in the NSFileManager class specification. You can also set the file attributes using the setFileAttributes: method.

When saving a file wrapper to disk, you typically determine the directory you want to save it in, then append the preferred filename to that directory path and use writeToFile:atomically:updateFilenames:, which saves the file wrapper’s contents and updates the file attributes. You can save a file wrapper under a different name if you wish, but this may result in the recorded filename differing from the preferred filename, depending on how you invoke the writeToFile:... method.

Besides saving its contents to disk, a file wrapper can re-read them from disk when necessary. The needsToBeUpdatedFromPath: method determines whether a disk representation may have changed, based on the file attributes stored the last time the file was read or written. If the file wrapper’s modification time or access permissions are different from those of the file on disk, this method returns YES. You can then use updateFromPath: to re-read the file from disk.

Finally, to transmit a file wrapper to another process or system (for example, over a distributed objects connection or through the pasteboard), you use the serializedRepresentation method to get an NSData object containing the file wrapper’s contents in the NSFileContentsPboardType format. You can safely transmit this representation over whatever channel you desire. The recipient of the representation can then reconstitute the file wrapper using the initWithSerializedRepresentation: method.

Working with Directory Wrappers

A directory wrapper contains other file wrappers (of any type), and allows you to access them by keys derived from their preferred filenames. You can add any type of file wrapper to a directory wrapper with addFileWrapper: or addFileWithPath:, and remove it with removeFileWrapper:. The convenience methods addRegularFileWithContents:preferredFilename: and addSymbolicLinkWithDestination:preferredFilename: allow you to add regular file and link wrappers while also setting their preferred names.

A directory wrapper stores its contents in an NSDictionary, which you can retrieve using the fileWrappers method. The keys of this dictionary are based on the preferred filenames of each file wrapper contained in the directory wrapper. There exist, then, three identifiers for a file wrapper within a directory wrapper:

•	Preferred filename. This doesn’t uniquely identify the file wrapper, but the following identifiers are always based on it.

•	Dictionary key. This is always equal to the preferred name when there are no other file wrappers of the same preferred name in the same directory wrapper. Otherwise, it’s a string made by adding a unique prefix to the preferred filename (note that the same file wrapper can have a different dictionary key for each directory wrapper that contains it). You use the dictionary key to retrieve the file wrapper object in memory, in order to get its contents or its filename (to update it from disk). You can get a file wrapper’s dictionary key by sending a keyForFileWrapper: message to the directory wrapper that contains it.

•	Filename. This is usually based on the preferred filename, but isn’t necessarily the same as it or the dictionary key. You use the filename to update a single file wrapper relative to the path of the directory wrapper that contains it. Note that the filename may change whenever you save a directory wrapper containing the file wrapper (particularly if the file wrapper has been added to several different directory wrappers); thus, you should always retrieve the filename from the file wrapper itself each time you need it rather than caching it.

When working with the contents of a directory wrapper, you can use a dictionary enumerator to retrieve each file wrapper and perform whatever operation you need. Note that with the exceptions of saving and updating, a directory file wrapper defines no recursive operations for its contents. To set the file attributes for all contained file wrappers, or to perform any other such operation, you must define a recursive method that examines the type of each file wrapper and invokes itself anew for any directory wrapper it encounters.

Method Types

Initializing a file wrapper	− initWithPath:

− initDirectoryWithFileWrappers:

− initRegularFileWithContents:

− initSymbolicLinkWithDestination:

− initWithSerializedRepresentation:

Writing to a file or serializing	− writeToFile:atomically:updateFilenames:

− serializedRepresentation

Checking a file wrapper’s type	− isRegularFile

− isDirectory

− isSymbolicLink

Setting attributes	− setFilename:

− filename

− setPreferredFilename:

− preferredFilename

− setIcon:

− icon

− setFileAttributes:

− fileAttributes

Updating	− needsToBeUpdatedFromPath:

− updateFromPath:

Modifying a directory wrapper	− addFileWrapper:

− removeFileWrapper:

− addFileWithPath:

− addRegularFileWithContents:preferredFilename:

− addSymbolicLinkWithDestination:preferredFilename:

− fileWrappers

− keyForFileWrapper:

Inspecting a regular file wrapper	− regularFileContents

Inspecting a link wrapper	− symbolicLinkDestination

Instance Methods

p	addFileWithPath:

− (NSString *)addFileWithPath:(NSString *)path

Adds a new file wrapper to the receiving directory wrapper. Initializes the new file wrapper with initWithPath: using path as the argument, then adds the new file wrapper by invoking addFileWrapper:. Returns the dictionary key used for the newly added file wrapper within the directory wrapper. Raises an NSInternalInconsistencyException if sent to a regular file or link wrapper.

See also:	− addRegularFileWithContents:preferredFilename:, − addSymbolicLinkWithDestination:preferredFilename:, − removeFileWrapper:, − fileWrappers

p	addFileWrapper:

− (NSString *)addFileWrapper:(NSFileWrapper *)wrapper

Adds wrapper to the receiving directory wrapper. Returns the dictionary key used for wrapper within the directory wrapper. Raises an NSInternalInconsistencyException if sent to a regular file or link wrapper, or an NSInvalidArgumentException if wrapper doesn’t have a preferred name (set using setPreferredName:).

See also:	− addFileWithPath:, − addRegularFileWithContents:preferredFilename:, − addSymbolicLinkWithDestination:preferredFilename:, − removeFileWrapper:, − fileWrappers

p	addRegularFileWithContents:preferredFilename:

− (NSString *)addRegularFileWithContents:(NSData *)contents preferredFilename:(NSString *)filename

Adds a new regular file wrapper to the receiving directory wrapper. Initializes the new file wrapper with initRegularFileWithContents: using contents as the argument, sets its preferred name with setPreferredName: using filename as the argument, then adds the new file wrapper by invoking addFileWrapper:. Returns the dictionary key used for the newly added file wrapper within the directory wrapper. Raises an NSInternalInconsistencyException if sent to a regular file or link wrapper, or an NSInvalidArgumentException if filename is nil or empty.

See also:	− addFileWithPath:, − addSymbolicLinkWithDestination:preferredFilename:, − removeFileWrapper:, − fileWrappers

p	addSymbolicLinkWithDestination:preferredFilename:

− (NSString *)addSymbolicLinkWithDestination:(NSString *)path preferredFilename:(NSString *)filename

Adds a new link wrapper to the receiving directory wrapper. Initializes the new link wrapper with initSymbolicLinkWithDestination: using path as the argument, sets its preferred name with setPreferredName: using filename as the argument, then adds the new link wrapper by invoking addFileWrapper:. Returns the dictionary key used for the newly added link wrapper within the directory wrapper. Raises an NSInternalInconsistencyException if sent to a regular file or link wrapper, or an NSInvalidArgumentException if filename is nil or empty.

See also:	− addFileWithPath:, − addFileWrapper:, − addRegularFileWithContents:preferredFilename:, − removeFileWrapper:, − fileWrappers

p	fileAttributes

− (NSDictionary *)fileAttributes

Returns the file attributes last read from disk or set using setFileAttributes:. These attributes are used whenever the file wrapper is saved using writeToFile:atomically:updateFilenames:. See the NSFileManager class specification for information on the contents of the attributes dictionary.

p	filename

− (NSString *)filename

Returns the filename for the last known disk representation of the receiver, or nil if the receiver has no filename. The filename is used for record-keeping purposes only, and is set automatically when the file wrapper is created from disk using initWithPath: and when it’s saved to a disk using writeToFile:atomically:updateFilenames: (although this method allows you to request that the filename not be updated).

See also:	− preferredFilename:, − setFilename:

p	fileWrappers

− (NSDictionary *)fileWrappers

Returns the file wrappers contained in a directory wrapper. Raises an NSInternalInconsistencyException if sent to a regular file or link wrapper. See “Working with Directory Wrappers” in the class description for information on the dictionary.

See also:	− filename, − addFileWrapper:

p	icon

− (NSImage *)icon

Returns an image that can be used to represent the file wrapper to the user, or nil if the file wrapper has none. You don’t have to use this image; for example, a file viewer typically looks up icons automatically based on file extensions, and so wouldn’t need this image. Similarly, if a file wrapper represents an image file, you can display the image directly rather than a file icon.

See also:	− setIcon:

p	initDirectoryWithFileWrappers:

− (id)initDirectoryWithFileWrappers:(NSDictionary *)wrappers

Initializes a newly allocated NSFileWrapper as a directory wrapper containing wrappers. The new directory wrapper has no filename or associated disk representation until you save it using writeToFile:atomically:updateFilenames:. It’s also initialized with open permissions; anyone can read, write, or change directory to the disk representations that it saves.

If any file wrapper in wrappers doesn’t have a preferred name, its preferred name is automatically set to its corresponding dictionary key in wrappers.

This method is a designated initializer for the NSFileWrapper class. Returns self.

See also:	− setPreferredFilename:, − filename, − setFileAttributes:

p	initRegularFileWithContents:

− (id)initRegularFileWithContents:(NSData *)contents

Initializes a newly allocated NSFileWrapper as a regular file wrapper with contents. The new file wrapper has no filename or associated disk representation until you save it using writeToFile:atomically:updateFilenames:. It’s also initialized with open permissions; anyone can read or write the disk representations that it saves.

This method is a designated initializer for the NSFileWrapper class. Returns self.

See also:	− setPreferredFilename:, − filename, − fileAttributes

p	initSymbolicLinkWithDestination:

− (id)initSymbolicLinkWithDestination:(NSString *)path

Initializes a newly allocated NSFileWrapper as a link wrapper pointing to path. The new file wrapper has no filename or associated disk representation until you save it using writeToFile:atomically:updateFilenames:. It’s also initialized with open permissions; anyone can read or write the disk representations that it saves.

This method is a designated initializer for the NSFileWrapper class. Returns self.

See also:	− setPreferredFilename:, − filename, − fileAttributes

p	initWithPath:

− (id)initWithPath:(NSString *)path

Initializes a newly allocated NSFileWrapper with the file or directory at path, setting its type to regular file, directory, or link wrapper based on the type of that file and caching the file’s attributes. Also sets the receiver’s preferred filename and recorded filename to the last component of path. If path identifies a directory, this method recursively creates file wrappers for each file or directory within that directory.

This method is a designated initializer for the NSFileWrapper class. Returns self.

See also:	− setPreferredFilename:, − filename, − fileAttributes

p	initWithSerializedRepresentation:

− (id)initWithSerializedRepresentation:(NSData *)data

Initializes a newly allocated NSFileWrapper with data, setting its type to regular file, directory, or link wrapper based on the nature of that data and reading the file attributes from the data as well. data is a serialized representation of a file’s or directory’s contents in the format used for the pasteboard type NSFileContentsPboardType. Data of this format is returned by such methods as serializedRepresentation or NSAttributedString’s RTFDFromRange:.

The new file wrapper has no filename or associated disk representation until you save it using writeToFile:atomically:updateFilenames:. This method is a designated initializer for the NSFileWrapper class. Returns self.

See also:	− setPreferredFilename:, − filename, − fileAttributes

p	isDirectory

− (BOOL)isDirectory

Returns YES if the receiver is a directory wrapper, NO otherwise.

See also:	− isRegularFile, − isSymbolicLink

p	isRegularFile

− (BOOL)isRegularFile

Returns YES if the receiver is a regular file wrapper, NO otherwise.

See also:	− isDirectory, − isSymbolicLink

p	isSymbolicLink

− (BOOL)isSymbolicLink

Returns YES if the receiver is a link wrapper, NO otherwise.

See also:	− isDirectory, − isRegularFile

p	keyForFileWrapper:

− (NSString *)keyForFileWrapper:(NSFileWrapper *)wrapper

Returns the key by which the receiving directory wrapper stores wrapper in its dictionary (as returned by the fileWrappers method). This is not necessarily the filename for wrapper. Raises an NSInternalInconsistencyException if sent to a regular file or link wrapper.

See also:	− filename

p	needsToBeUpdatedFromPath:

− (BOOL)needsToBeUpdatedFromPath:(NSString *)path

Returns YES if the receiver’s contents on disk may have changed, NO otherwise. For a regular file wrapper, this is determined by comparing the modification time and access permissions of the file or directory at path against those of the receiver. For a link wrapper, this is determined by checking whether the destination path has changed (not by checking the modification time or access attributes of the destination). For a directory, this is determined as needed recursively for each file wrapper contained in the directory; added or removed files also count as changes.

See also:	− updateFromPath:, − fileAttributes

p	preferredFilename

− (NSString *)preferredFilename

Returns the file wrapper’s preferred filename. This name is used as the default dictionary key and filename when a file wrapper is added to a directory wrapper. However, if another file wrapper with the same preferred name already exists in the directory wrapper when the receiver is added, the dictionary key and filename assigned may differ from the preferred filename.

See also:	− setPreferredFilename:, − filename

p	regularFileContents

− (NSData *)regularFileContents

Returns the contents of the receiving regular file wrapper. Raises an NSInternalInconsistencyException if sent to a directory or link wrapper.

p	removeFileWrapper:

− (void)removeFileWrapper:(NSFileWrapper *)wrapper

Removes wrapper from the receiving directory wrapper and releases it. Raises an NSInternalInconsistencyException if sent to a regular file or link wrapper.

See also:	− addFileWithPath:, − addFileWrapper:, − addRegularFileWithContents:preferredFilename:, − addSymbolicLinkWithDestination:preferredFilename:, − fileWrappers

p	serializedRepresentation

− (NSData *)serializedRepresentation

Returns the receiver’s contents as an opaque collection of data, in the format used for the pasteboard type NSFileContentsPboardType.

See also:	− initWithSerializedRepresentation:

p	setFileAttributes:

− (void)setFileAttributes:(NSDictionary *)attributes

Sets the file attributes that are applied whenever the file wrapper is saved using writeToFile:atomically:updateFilenames: to attributes. See the NSFileManager class specification for information on the contents of the attributes dictionary.

See also:	− fileAttributes

p	setFilename:

− (void)setFilename:(NSString *)filename

Sets the filename for the disk representation of the receiver to filename. The filename is used for record-keeping purposes only, and is set automatically when the file wrapper is saved to a disk using writeToFile:atomically:updateFilenames: (although this method allows you to request that the filename not be updated). You should rarely need to invoke this method.

Raises an NSInvalidArgumentException if filename is nil or empty.

See also:	− setPreferredFilename:, − filename

p	setIcon:

− (void)setIcon:(NSImage *)anImage

Sets the image that can be used to represent the file wrapper to the user to anImage. You don’t have to use this image; for example, a file viewer typically looks up icons automatically based on file extensions, and so wouldn’t need this image. Similarly, if a file wrapper represents an image file, you can display the image directly rather than a file icon.

See also:	− icon

p	setPreferredFilename:

− (void)setPreferredFilename:(NSString *)filename

Sets the receiver’s preferred filename to filename. This name is used as the default dictionary key and filename when a file wrapper is added to a directory wrapper. However, if another file wrapper with the same preferred name already exists in the directory wrapper when the receiver is added, the dictionary key and filename assigned may differ from the preferred filename. Raises an NSInvalidArgumentException if filename is nil or empty.

See also:	− preferredFilename, − addFileWrapper:, − setFilename:

p	symbolicLinkDestination

− (NSString *)symbolicLinkDestination

Returns the actual path represented by the receiving link wrapper. Raises NSInternalInconsistencyException if sent to a regular file or directory wrapper.

p	updateFromPath:

− (BOOL)updateFromPath:(NSString *)path

Re-reads the file wrapper’s information from the file or directory at path, including contents or link destination, icon, file attributes. For a directory wrapper, the contained file wrappers are also sent updateFromPath: messages. If files in the directory on disk have been added or removed, corresponding file wrappers are released or created as needed. Returns YES if updating actually occurred, NO if it wasn’t necessary.

See also:	− needsUpdateFromPath:, − updateAttachmentsFromPath: (NSAttributedString class cluster)

p	writeToFile:atomically:updateFilenames:

− (BOOL)writeToFile:(NSString *)path

atomically:(BOOL)atomicFlag

updateFilenames:(BOOL)updateNamesFlag

Writes the receiver’s contents to a file or directory at path. Returns YES on success and NO on failure. If atomicFlag is YES, attempts to write the file safely so that an existing file at path is not overwritten, nor does a new file at path actually get created, unless the write is successful. If updateNamesFlag is YES and the contents are successfully written, changes the receiver’s filename to the last component of path, and the filenames of any children of a directory wrapper to the filenames under which they’re written to disk.

If you’re executing a “save” or “save as” style operation, pass YES for updateNamesFlag; if you’re executing a “save to” style operation, pass NO for updateNamesFlag.

See also:	− filename


NSFont

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSCopying

NSObject (NSObject)

Declared In:	AppKit/NSFont.h

Class Description

NSFont objects represent PostScript fonts to an application, providing access to characteristics of the font and assistance in laying out glyphs relative to one another. Font objects are also used to establish the current font when drawing in an NSView, using the set method.

You don’t create Font objects using the alloc and init methods. Instead, you use one of the fontWithName:... methods to look up an available font and alter its size or matrix to your needs. These methods check for an existing font object with the specified characteristics, returning it if there is one. Otherwise, they look up the font data requested and create the appropriate object. NSFont also defines a number of methods for getting standard system fonts, such as systemFontOfSize:, userFontOfSize:, and messageFontOfSize:.

Drawing Text with NSFonts

In most cases you draw text using an NSTextView object. You can also draw an NSString directly in an NSView using the methods drawAtPoint:withAttributes: and drawInRect:withAttributes:, which the Application Kit adds to NSString. These methods take an NSDictionary of attributes, as used by the NSAttributedString class, and apply them when drawing the string.

If you need to draw text using PostScript operators such as show, it’s recommended that you set the current font using NSFont’s set method, rather than the PostScript operators setfont or selectfont. This allows the Application Kit printing mechanism to record the fonts used in the PostScript output. If you absolutely must set the font using a PostScript operator, you can record the font with the Application Kit using the class method useFont:. See the description of that method for more information.

Getting Font Metrics

NSFont defines a number of methods for accessing a font’s metrics information, when that information is available. Methods such as boundingRectForGlyph:, boundingRectForFont, xHeight, and so on, all correspond to standard font metrics information. See the various method descriptions for specific information. You can also get a complete dictionary of font metrics using the afmDictionary method, or retrieve the original contents of the metrics file using afmFileContents.

Calculating Glyph Layout

The OPENSTEP extended text system handles many complex aspects of laying glyphs out. If you need to calculate layout for your own purposes, you can use several methods defined by NSFont. There are three basic kinds of glyph layout: sequential, for running text; overstruck, for diacritics and other non-spacing marks; and stacked, for scripts such as Indic and Tibetan.

The first kind of layout is supported by the method positionOfGlyph:precededByGlyph:isNominal:. This method calculates the position of a glyph relative to glyph preceding it, using font metrics if they’re available. This is the most straightforward kind of glyph layout.

Layout of overstruck glyphs is potentially the most complex, as it requires detailed information about placement of many kinds of modifying marks. When you know both the base glyph and the non-spacing mark being struck over it, you first use the method positionOfGlyph:struckOverGlyph:metricsExist: to calculate the location of the non-spacing mark. This method also indicates whether metrics are available for the two glyphs. If they’re not, you must fall back to calculating the layout based on the bounding rectangle of the base glyph (which you can get using boundingRectForGlyph:). There are two methods for doing this. The first, positionOfGlyph:struckOverRect:metricsExist:, attempts to use metrics to place the non-spacing mark in a reasonable fashion relative to the base glyph’s bounding box. If this method indicates that metrics aren’t available (which NSFont’s implementation always does, because current fonts don’t provide for metrics relative to bare rectangles), you must resort to the last method, positionOfGlyph:forCharacter:struckOverRect:. This method attempts to place the non-spacing mark in a legible if not pleasing manner, treating it as a well-known character such as an acute accent, tilde, or other modifier.

An additional method for laying out a series of overstruck glyphs is positionsForCompositeSequence:numberOfGlyphs:pointArray:. This method accepts a C array containing the base glyph followed by all of its non-spacing marks, and calculates the positions for as many as it can. For those that it can’t determine, you must resort to the individual methods described immediately above.

The final kind of layout, of stacked glyphs, is supported by the method positionOfGlyph:withRelation:toBaseGlyph:totalAdvancement:metricsExist:. Stacked glyphs often have special compressed forms, which standard font metrics don’t account for. NSFont’s implementation of this method simply abuts the bounding boxes of the two glyphs for approximate layout of the individual glyphs. Subclasses of NSFont can override this method to access any extra metrics information in order to provide more sophisticated layout of stacked glyphs.

Special Glyphs

NSFont defines two special glyphs. NSNullGlyph indicates no glyph at all, and is useful in some layout methods for calculating information that isn’t relative to another glyph. For example, with positionOfGlyph:precededByGlyph:isNominal:, you can specify NSNullGlyph as the first glyph to get the nominal advancement of the preceding glyph.

The other special glyph is NSControlGlyph, which the text system maps onto control characters such as linefeed and tab. This glyph has no graphic representation and has no inherent advancement of its own. Instead, the text system examines the control character underlying the glyph to determine what kind of special layout it needs to perform.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

NSCopying	− copyWithZone:

Method Types

Creating arbitrary fonts	+ fontWithName:size:

+ fontWithName:matrix:

Creating user fonts	+ userFontOfSize:

+ userFixedPitchFontOfSize:

Creating system fonts	+ boldSystemFontOfSize:

+ menuFontOfSize:

+ messageFontOfSize:

+ paletteFontOfSize:

+ systemFontOfSize:

+ titleBarFontOfSize:

+ toolTipsFontOfSize:

Getting preferred fonts	+ setPreferredFontNames:

+ preferredFontNames

Using a font to draw	− set

Adding fonts to print operations	+ useFont:

Getting general font information	− encodingScheme

− isBaseFont

− isFixedPitch

− mostCompatibleStringEncoding

Getting information about glyphs	− glyphIsEncoded:

− glyphWithName:

Getting metrics information	− advancementForGlyph:

− afmDictionary

− afmFileContents

− ascender

− boundingRectForFont

− boundingRectForGlyph:

− capHeight

− descender

− italicAngle

− matrix

− maximumAdvancement

− pointSize

− underlinePosition

− underlineThickness

− widthOfString:

− widths

− xHeight

Getting font names	− displayName

− familyName

− fontName

Laying out sequential glyphs	− positionOfGlyph:precededByGlyph:isNominal:

− positionsForCompositeSequence:numberOfGlyphs:pointArray:

Laying out overstruck glyphs	− positionOfGlyph:forCharacter:struckOverRect:

− positionOfGlyph:struckOverGlyph:metricsExist:

− positionOfGlyph:struckOverRect:metricsExist:

Laying out stacked glyphs	− positionOfGlyph:withRelation:toBaseGlyph:totalAdvancement:

metricsExist:

Setting user fonts	+ setUserFont:

+ setUserFixedPitchFont:

Getting corresponding device fonts	− printerFont

− screenFont

Class Methods

boldSystemFontOfSize:

+ (NSFont *)boldSystemFontOfSize:(float)fontSize

Returns the font used for standard interface items that are rendered in boldface type, in fontSize. This is equivalent to titleBarFontOfSize:.

See also:	+ fontWithName:size:

fontWithName:matrix:

+ (NSFont *)fontWithName:(NSString *)typeface matrix:(const float *)fontMatrix

Returns a font object for typeface and fontMatrix. A typeface is a fully specified family-face name, such as Helvetica-BoldOblique or Times-Roman (not a name as shown in the Font Panel). fontMatrix is a standard 6-element transformation matrix as used in the PostScript language, specifically with the makefont operator. In most cases, you can simply use fontWithName:size: to create standard scaled fonts.

You can use the defined value NSFontIdentityMatrix for [1 0 0 1 0 0]. Fonts created with a matrix other than NSFontIdentityMatrix don’t automatically flip themselves in flipped views.

See also:	− isFlipped (NSView)

fontWithName:size:

+ (NSFont *)fontWithName:(NSString *)fontName size:(float)fontSize

Returns a font object for typeface and fontSize. A typeface is a fully specified family-face name, such as Helvetica-BoldOblique or Times-Roman. fontSize is used to scale the font, and is equivalent to using a font matrix of [fontSize 0 0 fontSize 0 0] with fontWithName:matrix:. Fonts created with this method automatically flip themselves in flipped views. This method is the preferred means for creating fonts.

p	menuFontOfSize:

+ (NSFont *)menuFontOfSize:(float)fontSize

Returns the font used for menu items in fontSize.

See also:	+ fontWithName:size:

p	messageFontOfSize:

+ (NSFont *)messageFontOfSize:(float)fontSize

Returns the font used for standard interface items, such as button labels, menu items, and so on, in fontSize. This is equivalent to systemFontOfSize:.

See also:	+ fontWithName:size:

p	paletteFontOfSize:

+ (NSFont *)paletteFontOfSize:(float)fontSize

Returns the font used for palette window title bars.

See also:	+ fontWithName:size:, + titleBarFontOfSize:

p	preferredFontNames

+ (NSArray *)preferredFontNames

Returns the names of fonts that the Application Kit tries first when a character has no font specified, or when the font specified doesn’t have a glyph for that character. If none of these fonts provides a glyph, the remaining fonts on the system are searched for a glyph.

See also:	+ setPreferredFontNames:, − glyphIsEncoded:

p	setPreferredFontNames:

+ (void)setPreferredFontNames:(NSArray *)fontNames

Sets the list of preferred font names to fontNames, and records them in the user defaults database for all applications. The Application Kit tries these fonts first when a character has no font specified, or when the font specified doesn’t have a glyph for that character. If none of these fonts provides a glyph, the remaining fonts on the system are searched for a glyph.

This method is useful for optimizing glyph rendering for uncommon scripts, by guaranteeing that appropriate fonts are searched first.

See also:	+ preferredFontNames

setUserFixedPitchFont:

+ (void)setUserFixedPitchFont:(NSFont *)aFont

Sets the font used by default for documents and other text under the user’s control, when that font should be fixed-pitch, to aFont, and records the font in the user defaults database for all applications.

See also:	+ setUserFont:, + userFixedPitchFontOfSize:

setUserFont:

+ (void)setUserFont:(NSFont *)aFont

Sets the font used by default for documents and other text under the user’s control to aFont, and records the font in the user defaults database for all applications.

See also:	+ setUserFixedPitchFont:, + userFontOfSize:

systemFontOfSize:

+ (NSFont *)systemFontOfSize:(float)fontSize

Returns the font used for standard interface items, such as button labels, menu items, and so on, in fontSize. This is equivalent to messageFontOfSize:.

See also:	+ boldSystemFontOfSize:, + userFontOfSize:, + userFixedPitchFontOfSize:, + fontWithName:size:

p	titleBarFontOfSize:

+ (NSFont *)titleBarFontOfSize:(float)fontSize

Returns the font used for window title bars, in fontSize. This is equivalent to boldSystemFontOfSize:.

See also:	+ paletteFontOfSize:

p	toolTipsFontOfSize:

+ (NSFont *)toolTipsFontOfSize:(float)fontSize

Returns the font used for tool-tips labels, in fontSize.

See also:	+ fontWithName:size:

useFont:

+ (void)useFont:(NSString *)fontName

Records fontName as one used in the current print operation.

The NSFont class object keeps track of the fonts used in an NSView by recording each one that receives a set message. When the view is called upon to generate conforming PostScript language output (such as during printing), the NSFont class provides the list of fonts required for the %%DocumentFonts comment, as required by Adobe’s Document Structuring Conventions.

useFont: augments this system by providing a way to register fonts that are included in the document but not set using NSFont’s set method. For example, you might set a font by executing the setfont operator within a function created by the pswrap utility. In such a case, be sure to pair the use of the font with a useFont: message to register the font for listing in the document comments.

userFixedPitchFontOfSize:

+ (NSFont *)userFixedPitchFontOfSize:(float)fontSize

Returns the font used by default for documents and other text under the user’s control (that is, text whose font the user can normally change), when that font should be fixed-pitch.

See also:	+ userFontOfSize:, + fontWithName:size:, + setUserFixedPitchFont:

userFontOfSize:

+ (NSFont *)userFontOfSize:(float)fontSize

Returns the font used by default for documents and other text under the user’s control (that is, text whose font the user can normally change).

See also:	+ userFixedPitchFontOfSize:, + fontWithName:size:, + setUserFont:

Instance Methods

advancementForGlyph:

− (NSSize)advancementForGlyph:(NSGlyph)aGlyph

Returns the nominal spacing for aGlyph—the distance that the current point moves after showing the glyph—accounting for the receiving font’s size. This spacing is given according to the glyph’s movement direction, which is either strictly horizontal or strictly vertical.

See also:	− boundingRectForGlyph, − maximumAdvancement

afmDictionary

− (NSDictionary *)afmDictionary

Returns the receiving font’s AFM information in dictionary form. It contains the following information under these keys, with all values as strings:

NSAFMFamilyName	NSAFMCapHeight

NSAFMFontName	NSAFMXHeight

NSAFMFormatVersion	NSAFMAscender

NSAFMFullName	NSAFMDescender

NSAFMNotice	NSAFMUnderlinePosition

NSAFMVersion	NSAFMUnderlineThickness

NSAFMWeight	NSAFMItalicAngle

NSAFMEncodingScheme	NSAFMMappingScheme

NSAFMCharacterSet

For any other items, use the AFM file contents, as returned by afmFileContents.

afmFileContents

− (NSString *)afmFileContents

Returns the receiving font’s AFM file as a string object.

ascender

− (float)ascender

Returns the top y coordinate of the receiving font’s longest ascender.

See also:	− descender, − capHeight, − xHeight

boundingRectForFont

− (NSRect)boundingRectForFont

Returns the receiving font’s bounding rectangle, scaled to the font’s size. The bounding rectangle is the union of the bounding rectangles of every glyph in the font.

See also:	− boundingRectForGlyph:

boundingRectForGlyph:

− (NSRect)boundingRectForGlyph:(NSGlyph)aGlyph

Returns the bounding rectangle for aGlyph, scaled to the receiving font’s size.

See also:	− boundingRectForFont

capHeight

− (float)capHeight

Returns the receiving font’s cap height.

See also:	− ascender, − descender, − xHeight

descender

− (float)descender

Returns the bottom y coordinate of the receiving font’s longest descender.

displayName

− (NSString *)displayName

Returns the name used to represent the receiving font in the user interface, typically localized for the user’s  language.

encodingScheme

− (NSString *)encodingScheme

Returns the name of the receiving font’s encoding scheme, such as “AdobeStandardEncoding”, “ISOLatin1Encoding”, “FontSpecific”, and so on.

familyName

− (NSString *)familyName

Returns the receiving font’s family name; for example, “Times” or “Helvetica”.

See also:	− fontName

fontName

− (NSString *)fontName

Returns the receiver’s full font name, as used in PostScript language code; for example, “Times-Roman” or “Helvetica-Oblique”.

See also:	− familyName

glyphIsEncoded:

− (BOOL)glyphIsEncoded:(NSGlyph)aGlyph

Returns YES if the receiving font encodes aGlyph, NO if it doesn’t contain it.

glyphWithName:

− (NSGlyph)glyphWithName:(NSString *)glyphName

Returns the encoded glyph named glyphName, or −1 if the receiving font contains no such glyph. Also returns −1 if the glyph named glyphName isn’t encoded.

isBaseFont

− (BOOL)isBaseFont

Returns YES if the receiver is a PostScript base font, NO if it’s a PostScript composite font composed of other base fonts.

isFixedPitch

− (BOOL)isFixedPitch

Returns YES if all glyphs in the receiving font have the same advancement, NO if any advancements differ.

See also:	− advancementForGlyph:

italicAngle

− (float)italicAngle

Returns the receiving font’s italic angle, as read from its AFM file.

matrix

− (const float *)matrix

Returns the receiver’s font matrix, a standard 6-element transformation matrix as used in the PostScript language, specifically with the makefont operator. In most cases, with a font of fontSize, this matrix is [fontSize 0 0 fontSize 0 0].

See also:	+ fontWithName:matrix:

p	maximumAdvancement

− (NSSize)maximumAdvancement

Returns the greatest advancement of any of the receiving font’s glyphs. This is always either strictly horizontal or strictly vertical.

See also:	− advancementForGlyph:

p	mostCompatibleStringEncoding

− (NSStringEncoding)mostCompatibleStringEncoding

Returns the string encoding that works best with the receiving font, where there are the fewest possible unmatched characters in the string encoding and glyphs in the font. You can use NSString’s dataUsingEncoding: or dataUsingEncoding:allowLossyConversion: method to convert the string to this encoding.

Note:	This method works heuristically using well-known font encodings, so for nonstandard encodings it may not in fact return the optimal string encoding.

See also:	− widthOfString:

pointSize

− (float)pointSize

Returns the receiving font’s point size, or the vertical point size for a font with a nonstandard matrix.

p	positionOfGlyph:forCharacter:struckOverRect:

− (NSPoint)positionOfGlyph:(NSGlyph)aGlyph

forCharacter:(unichar)aChar

struckOverRect:(NSRect)aRect

Calculates and returns a suitable location for aGlyph to be drawn as a diacritic or non-spacing mark relative to aRect, assuming that aGlyph represents aChar. Returns NSZeroPoint if the location can’t be calculated. The nature of aChar as one appearing above or below its base character determines the location returned. For example, in the first figure below, the gray tilde and box represent aGlyph and aRect, and the black dot is the point returned (defined relative to the origin of the aRect).

To place multiple glyphs over a rectangle, work from the innermost ones to the outermost. As you calculate the position of each glyph, enlarge the rectangle to include the bounding rectangle of the glyph in preparation for the next glyph. The second figure shows a tilde, acute accent, and cedilla all placed over a rectangle, with the acute accent placed relative to bounding box of the base rectangle and the tilde.

This method is the last fallback mechanism for performining minimally legible typography when metrics aren’t available, and should be used when positionOfGlyph:struckOverGlyph:metricsExist: indicates that metrics don’t exist for the base glyph specified. It can account for the layout and placement of most Latin, Greek, and Cyrillic non-spacing marks. You should draw the glyph at the returned location, even if it’s NSZeroRect.

positionOfGlyph:precededByGlyph:isNominal:

− (NSPoint)positionOfGlyph:(NSGlyph)aGlyph

precededByGlyph:(NSGlyph)prevGlyph

isNominal:(BOOL *)flag

Calculates and returns the location of aGlyph relative to prevGlyph, assuming that prevGlyph precedes it in the layout (not necessarily in the character stream). The point returned should be used relative to whatever location is used for prevGlyph. If flag is non-NULL, it’s filled with NO if font metrics are available and were used in the calculation, YES if the default spacing for the glyphs was used.

Returns NSZeroPoint is either aGlyph or prevGlyph is NSControlGlyph or is invalid. Returns the nominal advancement of prevGlyph if aGlyph is NSNullGlyph.

This method is useful for sequential glyph placement when glyphs aren’t drawn with a single PostScript operation.

p	positionOfGlyph:struckOverGlyph:metricsExist:

− (NSPoint)positionOfGlyph:(NSGlyph)aGlyph

struckOverGlyph:(NSGlyph)baseGlyph

metricsExist:(BOOL *)flag

Calculates and returns a suitable location for aGlyph to be drawn as a diacritic or non-spacing mark relative to baseGlyph. The point returned should be used relative to whatever location is used for baseGlyph. If flag is non-NULL it’s filled with YES if font metrics are available, NO if they’re not. If flag is returned as NO, the result isn’t valid and shouldn’t be used. In that case, use positionOfGlyph:struckOverRect:metricsExist: or positionOfGlyph:forCharacter:struckOverRect: to calculate a reasonable offset.

See also:	− positionsForCompositeSequence:numberOfGlyphs:pointArray:, − positionOfGlyph:structOverRect:metricsExist:

p	positionOfGlyph:struckOverRect:metricsExist:

− (NSPoint)positionOfGlyph:(NSGlyph)aGlyph

struckOverRect:(NSRect)aRect

metricsExist:(BOOL *)flag

Overridden by subclasses to calculate and return a suitable location for aGlyph to be drawn as a diacritic or non-spacing mark relative to aRect, provided metrics exist. Returns NSZeroRect if the location can’t be determined. If flag is non-NULL it’s filled with YES if font metrics are available, NO if they’re not. If flag is returned as NO, the result isn’t valid and shouldn’t be used. In that case, use positionOfGlyph:forCharacter:struckOverRect: to calculate a reasonable offset.

Because current font metrics don’t include support for generic placement relative to rectangles, NSFont’s implementation of this method always returns NSZeroPoint and returns flag as NO.

p	positionOfGlyph:withRelation:toBaseGlyph:totalAdvancement:metricsExist:

− (NSPoint)positionOfGlyph:(NSGlyph)aGlyph

withRelation:(NSGlyphRelation)relation

toBaseGlyph:(NSGlyph)baseGlyph

totalAdvancement:(NSSize *)offset

metricsExist:(BOOL *)flag

Calculates and returns a suitable location for aGlyph to be drawn relative to baseGlyph, where relation is NSGlyphBelow or NSGlyphAbove. The point returned should be used relative to whatever location is used for baseGlyph. This method is useful for calculating the layout of stacked glyphs, such as those in Indic and Tibetan scripts.

If offset is non-NULL, it’s filled with the larger of the two glyphs’ advancements, allowing for reasonable layout of following glyphs.

If flag is non-NULL it’s filled with YES if font metrics are available, NO if they’re not. If metrics aren’t available, the location is calculated as a simple stacking with no gap between baseGlyph and aGlyph.

Note:	This method only supports horizontally laid-out base glyphs.

p	positionsForCompositeSequence:numberOfGlyphs:pointArray:

− (int)positionsForCompositeSequence:(NSGlyph *)glyphs

numberOfGlyphs:(int)numGlyphs

pointArray:(NSPoint *)points

Calculates and fills points with the locations for glyphs, assuming that the first glyph is a base character and those following are non-spacing marks. These points should all be interpreted as relative to the location of the first glyph in glyphs. Returns the number of points that could be calculated.

If the number of points calculated is less than numGlyphs, the number of glyphs provided, you can use positionOfGlyph:structOverRect:metricsExist: to determine the positions for the remaining glyphs. When using that method, calculate the base rectangle for each glyph from the bounding rectangles and positions of all preceding glyphs.

printerFont

− (NSFont *)printerFont

When sent to a font object representing a scalable PostScript font, returns self. When sent to a font object representing a bitmapped screen font, returns its corresponding scalable PostScript font.

See also:	− screenFont

screenFont

− (NSFont *)screenFont

When sent to a font object representing a bitmapped screen font, returns self. When sent to a font object representing a scalable PostScript font, returns a bitmapped screen font matching the receiver in typeface and matrix (or size), or nil if such a font can’t be found.

Note:	Screen fonts are for direct use with the Window Server only. Never use them with Application Kit objects, such as in setFont: methods.

See also:	− printerFont

set

− (void)set

Establishes the receiving font as the current font for PostScript show and other text-drawing operators. During a print operation, also records the font as used in the PostScript code emitted.

See also:	+ useFont:

underlinePosition

− (float)underlinePosition

Returns the baseline offset that should be used when drawing underlines with the receiving font, as determined by the font’s AFM file. This value is usually negative, which must be considered when drawing in a flipped coordinate system.

See also:	− underlineThickness

underlineThickness

− (float)underlineThickness

Returns the thickness that should be used when drawing underlines with the receiving font, as determined by the font’s AFM file.

See also:	− underlinePosition

widthOfString:

− (float)widthOfString:(NSString *)aString

Returns the x axis offset of the current point when aString is drawn with a PostScript show operator in the receiving font. This method performs lossy conversion of aString to the most compatible encoding for the receiving font.

Use this method only when you’re sure all of aString can be rendered with the receiving font. In general, it’s better to use the Application Kit’s string-drawing methods, as described under NSString Additions.

See also:	− mostCompatibleStringEncoding

widths

− (float *)widths

Returns a C array of 256 floats, giving the unscaled width of each glyph in the font. This data is useful only for simple fonts without non-spacing marks, and doesn’t account for Unicode-related issues at all. You should avoid using this method wherever possible; use advancementForGlyph: instead.

xHeight

− (float)xHeight

Returns the x-height of the receiving font.

See also:	− ascender, − descender


NSFontManager

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSFontManager.h

Class Description

NSFontManager is the center of activity for the font conversion system. It records the currently selected font, updates the Font Panel and Font menu to reflect the selected font, initiates font changes, and converts fonts in response to requests from text-bearing objects. In a more prosaic role, NSFontManager can be queried for the fonts available to the application, and for the particular attributes of a font, such as whether it’s condensed or extended.

You normally set up a font manager and the Font Menu using Interface Builder. However, you can also do so programmatically by getting the shared font manager instance and having it create the standard Font menu at run time:

NSFontManager *fontManager = [NSFontManager sharedFontManager];

NSMenu *fontMenu = [fontManager fontMenu:YES];

You can then add the Font menu to your application’s main menu. Once the Font menu is installed, your application automatically gains the functionality of both the Font menu and the Font Panel.

Recording the Selected Font

Any object that records fonts that the user can change should tell the font manager what the font of its selection is whenever it becomes the first responder and whenever its selection changes while it’s the first responder. The object does so by sending the shared font manager a setSelectedFont:isMultiple: message. It should pass in the first font of the selection, along with a flag indicating whether there’s more than one font.

The font manager uses this information to update the Font Panel and Font menu to reflect the selected font. For example, suppose the selected font is set as Helvetica Oblique 12.0 point. In this case the Font Panel selects that font and displays its name; the Font menu changes its Italic command to Unitalic; if there’s no Bold variant of Helvetica available, the Bold menu item is disabled; and so on.

Initiating Font Changes

The user normally changes the font of the selection by manipulating the Font Panel and Font menu. These objects initiate the intended change by sending an action message to the font manager. There are four font-changing action methods:

− addFontTrait:

− removeFontTrait:

− modifyFont:

− modifyFontViaPanel:

The first three cause the font manager to query the sender of the message in order to determine which trait to add or remove, or how to modify the font. The last causes the font manager to use the settings in the Font Panel to modify the font. The font manager records this information and uses it in later requests to convert fonts, as described under “Responding to Font Changes.”

When the font manager receives an addFontTrait: or removeFontTrait: message, it queries the sender with a tag message, interpreting the return value as a trait mask for use with convertFont:toHaveTrait: or convertFont:toNotHaveTrait:, as described below under “Converting Fonts Manually.” The Italic and Bold Font menu commands, for example, have tags of NSItalicFontMask and NSBoldFontMask, respectively. See convertFont:toHaveTrait: for a list of trait mask values.

When the font manager receives a modifyFont: message, it queries the sender with a tag message and interprets the return value as a particular kind of conversion to perform, via the various conversion methods described under “Converting Fonts Manually.” For example, a button whose tag value is NSSizeUpFontAction causes the font manager’s convertFont: method to increase the size of the NSFont passed as the argument. See modifyFont: for a list of conversion tag values.

For modifyFontViaPanel:, the font manager sends the application’s Font Panel a panelConvertFont: message. The Font Panel in turn uses the font manager to convert the font provided according to the user’s choices. For example, if the user selects only the font family in the Font Panel (perhaps to Helvetica), then whatever fonts are provided to panelConvertFont:, only the family is changed: Courier Medium 10.0 point becomes Helvetica Medium 10.0 point, while Times Italic 12.0 point becomes Helvetica Oblique 12.0 point.

Responding to Font Changes

The font manager responds to a font-changing action method by sending a changeFont: action message up the responder chain. A text-bearing object that receives this message should have the font manager convert the fonts in its selection by invoking convertFont: for each font and using the NSFont object returned. convertFont: uses the information recorded by the font-changing action method, such as addFontTrait:, modifying the font provided appropriately. (There’s no way to explicitly set the font-changing action or trait; instead, you use the methods described under “Converting Fonts Manually.”)

This simple example assumes there’s only one font in the selection:

− (void)changeFont:(id)sender

{

    NSFont *oldFont = [self selectionFont];

    NSFont *newFont = [sender convertFont:oldFont];

    [self setSelectionFont:newFont];

    return;

}

Most text-bearing objects will have to scan the selection for ranges with different fonts, and invoke convertFont: for each one.

Font Trait Masks

NSFontManager categorizes fonts according to a small set of traits. You can convert fonts by adding and removing individual traits, and you can get a font with a specific combination of traits. The traits defined and available for your use are:

NSItalicFontMask	NSCondensedFontMask

NSBoldFontMask	NSExpandedFontMask

NSNarrowFontMask	NSCompressedFontMask

NSFixedPitchFontMask	NSSmallCapsFontMask

NSPosterFontMask

NSCondensedFontMask and NSExpandedFontMask are mutually exclusive. In addition to these, NSFontManager defines the masks NSUnitalicFontMask, NSUnboldFontMask, and NSNonStandardCharacterSetFontMask for its own internal use. Though they’re defined in the header file, you shouldn’t use these masks.

Converting Fonts Manually

NSFontManager defines a number of methods for explicitly converting particular traits and characteristics of a font. These methods are:

− convertFont:toFace:

− convertFont:toFamily:

− convertFont:toHaveTrait:

− convertFont:toNotHaveTrait:

− convertFont:toSize:

− convertWeight:ofFont:

Each returns a transformed version of the font provided, or the original font if it can’t be converted. convertFont:toFace: and convertFont:toFamily: both alter the basic design of the font provided. The first method requires a fully-specified typeface name, such as “Times-Roman” or “Helvetica-BoldOblique”, while the second expects only a family name, such as “Times” or “Helvetica”.

convertFont:toHaveTrait: and convertFont:toNotHaveTrait: use trait masks to add or remove a single trait such as Italic, Bold, Condensed, or Extended.

convertFont:toSize: returns a font of the requested size, with all other characteristics the same as those of the original font.

convertWeight:ofFont: either increases or decreases the weight of the font provided, according to a boolean flag. Font weights are typically indicated by a series of names, which can vary from font to font. Some go from Light to Medium to Bold, while others have Book, SemiBold, Bold, and Black. This method offers a uniform way of incrementing and decrementing any font’s weight.

The default implementation of font conversion is very conservative, making a change only if no other trait or aspect is affected. For example, if you try to convert Helvetica Oblique 12.0 point by adding the Bold trait, and only Helvetica Bold is available, the font isn’t converted. You can create a subclass of NSFontManager and override the conversion methods to perform less conservative conversion, perhaps using Helvetica Bold in this case and losing the Oblique trait.

In addition to the font-conversion methods, NSFontManager defines fontWithFamily:traits:weight:size: to construct a font with a given set of characteristics. If you don’t care to make a subclass of NSFontManager, you can use this method to perform approximate font conversions yourself.

Examining Fonts

In addition to converting fonts, NSFontManager provides information on which fonts are available to the application, and on the characteristics of any given font. availableFonts returns an array of the names of all fonts available. availableFontNamesWithTraits: filters the available fonts based on a font trait mask.

There are three methods for examining individual fonts. fontNamed:hasTraits: returns YES if the font matches the trait mask provided. traitsOfFont: returns a trait mask for a given font. weightOfFont: returns an approximate ranking of a font’s weight on a scale of 0−15, where 0 is the lightest possible weight, 5 is Normal or Book weight, 9 is the equivalent of Bold, and 15 is the heaviest possible (often called Black or Ultra Black).

Customizing the Font Conversion System

If you need to customize the font conversion system by creating subclasses of NSFontManager or NSFontPanel, you must inform the NSFontManager class of this change with a setFontManagerFactory: or setFontPanelFactory: message, before either the shared font manager or shared font panel is created. These methods record your class as the one to instantiate the first time the font manager or Font Panel is requested.

You may be able to avoid using subclasses if all you need is to add some custom controls to the Font Panel. In this case, you can invoke NSFontPanel’s setAccessoryView: method to add an NSView below its font browser. This allows you to add controls for such things as font color, kerning, and so on.

If you provide your own Font menu, you should register it with the font manager using the setFontMenu: method. The font manager is responsible for validating Font menu items and changing their titles and tags according to the selected font. For example, when the selected font is Italic the font manager changes the Italic Font menu item to Unitalic, and changes its tag to NSUnitalicFontMask. Your Font menu’s items should use the appropriate action methods and tags. Here are some examples:

Font Menu Item	Action	Tag

Italic	addFontTrait:	NSItalicFontMask

Bold	addFontTrait:	NSBoldFontMask

Heavier	modifyFont:	NSHeavierFontAction

Larger	modifyFont:	NSSizeUpFontAction

Normally, the application’s Font Panel displays all the standard fonts available on the system. If this isn’t appropriate for your application—for example, if only fixed-pitch fonts should be used—you can assign a delegate to the font manager object to filter the available fonts. Before the Font Panel displays a particular font family or face, it asks the font manager to confirm it. The font manager in turn queries its delegate with a fontManager:willIncludeFont: message. If the delegate returns YES (or doesn’t implement this method), the font is displayed in the Font Panel. If the delegate returns NO, the font isn’t listed.

Method Types

Getting the shared font manager	+ sharedFontManager

Changing the default font conversion classes

+ setFontManagerFactory:

+ setFontPanelFactory:

Getting available fonts	− availableFonts

− availableFontNamesWithTraits:

Setting and examining the selected font

− setSelectedFont:isMultiple:

− selectedFont

− isMultiple

− sendAction

Action methods	− addFontTrait:

− removeFontTrait:

− modifyFont:

− modifyFontViaPanel:

Converting fonts automatically	− convertFont:

Converting fonts manually	− convertFont:toFace:

− convertFont:toFamily:

− convertFont:toHaveTrait:

− convertFont:toNotHaveTrait:

− convertFont:toSize:

− convertWeight:ofFont:

Getting a particular font	− fontWithFamily:traits:weight:size:

Examining fonts	− traitsOfFont:

− fontNamed:hasTraits:

− weightOfFont:

Enabling the Font Panel and Font menu

− setEnabled:

− isEnabled

Setting the Font menu	− setFontMenu:

− fontMenu:

Getting the Font Panel	− fontPanel:

− orderFrontFontPanel:

Setting the delegate	− setDelegate:

− delegate

Setting the action method	− setAction:

− action

Class Methods

setFontManagerFactory:

+ (void)setFontManagerFactory:(Class)aClass

Sets the class object used to create the font manager to aClass, which should be a subclass of NSFontManager. When the NSFontManager class object receives a sharedFontManager message, it creates an instance of aClass, if no instance already exists. Your font manager class should implement init as its designated initializer. The default font manager factory is NSFontManager.

This method must be invoked before your application’s main nib file is loaded, such as in the application delegate’s applicationWillFinishLaunching: method.

See also:	+ setFontPanelFactory:

setFontPanelFactory:

+ (void)setFontPanelFactory:(Class)factoryId

Sets the class used to create the Font Panel to aClass, which should be a subclass of NSFontPanel. Invoke this method before accessing the Font Panel in any wa, such as in the application delegate’s applicationWillFinishLaunching: method.

See also:	+ setFontManagerFactory:

sharedFontManager

+ (NSFontManager *)sharedFontManager

Returns the singleton instance of the font manager factory for the application, creating it if necessary.

See also:	+ setFontManagerFactory:

Instance Methods

action

− (SEL)action

Returns the action that’s sent to the first responder when the user selects a new font from the Font panel or chooses a command from the Font menu. The default action is changeFont:.

See also:	− setAction:

addFontTrait:

− (void)addFontTrait:(id)sender

This action method causes the receiver to send its action message (changeFont: by default) up the responder chain. When a responder replies by providing a font to convert in a convertFont: message, the receiver converts the font by adding the trait specified by sender. This trait is determined by sending a tag message to sender and interpreting it as a font trait mask for a convertFont:toHaveTrait: message.

See also:	− removeFontTrait:, − modifyFont:, − modifyFontViaPanel:

availableFontNamesWithTraits:

− (NSArray *)availableFontNamesWithTraits:(NSFontTraitMask)fontTraitMask

Returns the names of the fonts available in the system whose traits are described exactly by fontTraitMask (not the NSFont objects themselves). These fonts are discovered by searching the user’s personal font directory, the local font directory, and the OPENSTEP system font directory. You specify the desired traits by combining these font trait mask values using the C bitwise OR operator:

NSItalicFontMask	NSCondensedFontMask

NSBoldFontMask	NSExpandedFontMask

NSNarrowFontMask	NSCompressedFontMask

NSFixedPitchFontMask	NSSmallCapsFontMask

NSPosterFontMask

NSCondensedFontMask and NSExpandedFontMask are mutually exclusive.

See also:	− availableFonts

availableFonts

− (NSArray *)availableFonts

Returns the names of the fonts available in the system (not the NSFont objects themselves). These fonts are discovered by searching the user’s personal font directory, the local font directory, and the OPENSTEP system font directory.

See also:	− availableFontNamesWithTraits:

convertFont:

− (NSFont *)convertFont:(NSFont *)aFont

Converts aFont according to the object that initiated a font change, typically the Font Panel or Font menu. Returns the converted font, or aFont itself if the conversion isn’t possible.

This method is invoked in response to a changeFont: message, which is itself initiated by an action message such as addFontTrait: or modifyFontViaPanel:. These initiating methods cause the font manager to query the sender for the action to take and the traits to change. See the class description for more information.

See also:	− convertFont:toFace:, − convertFont:toFamily:, − convertFont:toHaveTrait:, − convertFont:toNotHaveTrait:, − convertFont:toSize:, − convertWeight:ofFont:

convertFont:toFace:

− (NSFont *)convertFont:(NSFont *)aFont toFace:(NSString *)typeface

Returns an NSFont whose traits are as similar as possible to those of aFont except for the typeface, which is changed to typeface. Returns aFont if it can’t be converted. A typeface is a fully specified family-face name, such as Helvetica-BoldOblique or Times-Roman.

This method attempts to match the weight and angle of aFont as closely as possible. Italic is mapped to Oblique, for example. Weights are mapped based on an approximate numeric scale of 0−15.

See also:	− convertFont:toFamily:, − convertFont:toHaveTrait:, − convertFont:toNotHaveTrait:, − convertFont:toSize:, − convertWeight:ofFont:, − convertFont:

convertFont:toFamily:

− (NSFont *)convertFont:(NSFont *)aFont toFamily:(NSString *)family

Returns an NSFont whose traits are as similar as possible to those of aFont except for the font family, which is changed to family. Returns aFont if it can’t be converted. A family is a generic font name, such as Helvetica or Times.

This method attempts to match the weight and angle of aFont as closely as possible. Italic is mapped to Oblique, for example. Weights are mapped based on an approximate numeric scale of 0−15.

See also:	− convertFont:toFace:, − convertFont:toHaveTrait:, − convertFont:toNotHaveTrait:, − convertFont:toSize:, − convertWeight:ofFont:, − convertFont:

convertFont:toHaveTrait:

− (NSFont *)convertFont:(NSFont *)aFont toHaveTrait:(NSFontTraitMask)fontTrait

Returns an NSFont whose traits are the same as those of aFont except for the traits, which are changed to include the single trait fontTrait, which may be any one of:

NSItalicFontMask	NSCondensedFontMask

NSBoldFontMask	NSExpandedFontMask

NSNarrowFontMask	NSCompressedFontMask

NSFixedPitchFontMask	NSSmallCapsFontMask

NSPosterFontMask

NSCondensedFontMask and NSExpandedFontMask are mutually exclusive.

Returns aFont if it can’t be converted.

See also:	− convertFont:toNotHaveTrait:, − convertFont:toFace:, − convertFont:toFamily:, − convertFont:toSize:, − convertWeight:ofFont:, − convertFont:

convertFont:toNotHaveTrait:

− (NSFont *)convertFont:(NSFont *)aFont toNotHaveTrait:(NSFontTraitMask)fontTraitMask

Returns an NSFont whose traits are the same as those of aFont except for the traits, which are changed so as not to include the single trait fontTrait, which may be any one of:

NSItalicFontMask	NSCondensedFontMask

NSBoldFontMask	NSExpandedFontMask

NSNarrowFontMask	NSCompressedFontMask

NSFixedPitchFontMask	NSSmallCapsFontMask

NSPosterFontMask

NSCondensedFontMask and NSExpandedFontMask are mutually exclusive.

Returns aFont if it can’t be converted.

See also:	− convertFont:toHaveTrait:, − convertFont:toFace:, − convertFont:toFamily:, − convertFont:toSize:, − convertWeight:ofFont:, − convertFont:

convertFont:toSize:

− (NSFont *)convertFont:(NSFont *)aFont toSize:(float)size

Returns an NSFont whose traits are the same as those of aFont except for the size, which is changed to size. Returns aFont if it can’t be converted.

See also:	− convertFont:toFace:, − convertFont:toFamily:, − convertFont:toHaveTrait:, − convertFont:toNotHaveTrait:, − convertWeight:ofFont:, − convertFont:

convertWeight:ofFont:

− (NSFont *)convertWeight:(BOOL)increaseFlag ofFont:(NSFont *)aFont

Returns an NSFont whose weight is greater or lesser than that of aFont, if possible. If increaseFlag is YES, a heavier font is returned; if it’s NO, a lighter font is returned. Returns aFont unchanged if it can’t be converted. Weights are typically graded along this scale:

NSFontManager’s implementation of this method refuses to convert a font’s weight if it can’t maintain all other traits, such as Italic and Condensed. You might wish to override this method to allow a looser interpretation of weight conversion.

See also:	− convertFont:toFace:, − convertFont:toFamily:, − convertFont:toHaveTrait:, − convertFont:toNotHaveTrait:, − convertFont:toSize:, − convertFont:

delegate

− (id)delegate

Returns the receiver’s delegate.

See also:	− setDelegate:

fontMenu:

− (NSMenu *)fontMenu:(BOOL)createFlag

Returns the menu that’s hooked up to the font conversion system, creating it if necessary and if createFlag is YES.

See also:	− setFontMenu:

fontNamed:hasTraits:

− (BOOL)fontNamed:(NSString *)typeface hasTraits:(NSFontTraitMask)fontTraitMask

Returns YES if the font named typeface has all the traits specified in fontTraitMask, NO if it doesn’t. You specify the desired traits by combining these font trait mask values using the C bitwise OR operator:

NSItalicFontMask	NSCondensedFontMask

NSBoldFontMask	NSExpandedFontMask

NSNarrowFontMask	NSCompressedFontMask

NSFixedPitchFontMask	NSSmallCapsFontMask

NSPosterFontMask

NSCondensedFontMask and NSExpandedFontMask are mutually exclusive.

fontPanel:

− (NSFontPanel *)fontPanel:(BOOL)createFlag

Returns the application’s shared Font Panel object, creating if necessary and if createFlag is YES.

See also:	+ sharedFontPanel (NSFontPanel), + sharedFontPanelExists (NSFontPanel), + setFontPanelFactory:

fontWithFamily:traits:weight:size:

− (NSFont *)fontWithFamily:(NSString *)family

traits:(NSFontTraitMask)fontTraitMask

weight:(int)weight

size:(float)size

Attempts to load a font with the specified characteristics, returning the font if successful and nil if not. family is the generic name of the font desired, such as Times or Helvetica. weight is a hint for the weight desired, on a scale of 0−15: a value of 5 indicates a normal or book weight and 9 or more a bold or heavier weight. It’s ignored if fontTraitMask includes NSBoldFontMask.

You specify fontTraitMask by combining these font trait mask values using the C bitwise OR operator:

NSItalicFontMask	NSCondensedFontMask

NSBoldFontMask	NSExpandedFontMask

NSNarrowFontMask	NSCompressedFontMask

NSFixedPitchFontMask	NSSmallCapsFontMask

NSPosterFontMask

NSCondensedFontMask and NSExpandedFontMask are mutually exclusive.

isEnabled

− (BOOL)isEnabled

Returns YES if the font-conversion system’s user interface items (the Font Panel and Font menu items) are enabled, NO if they’re not.

See also:	− isEnabled (NSFontPanel), − isEnabled (NSMenuItem), − setEnabled:

isMultiple

− (BOOL)isMultiple

Returns YES if the last font selection recorded has multiple fonts, NO if it’s a single font.

See also:	− setSelectedFont:isMultiple:, − selectedFont

modifyFont:

− (void)modifyFont:(id)sender

This action method causes the receiver to send its action message (changeFont: by default) up the responder chain. When a responder replies by providing a font to convert in a convertFont: message, the receiver converts the font in the manner specified by sender. The conversion is determined by sending a tag message to sender and invoking a corresponding method:

Sender’s Tag	Method Used

NSNoFontChangeAction	None, the font is returned unchanged

NSViaPanelFontAction	The Font Panel’s panelConvertFont:

NSAddTraitFontAction	convertFont:toHaveTrait:

NSRemoveTraitFontAction	convertFont:toNotHaveTrait:

NSSizeUpFontAction	convertFont:toSize:

NSSizeDownFontAction	convertFont:toSize:

NSHeavierFontAction	convertWeight:ofFont:

NSLighterFontAction	convertWeight:ofFont:

See also:	− addFontTrait:, − removeFontTrait:, − modifyFontViaPanel:

modifyFontViaPanel:

− (void)modifyFontViaPanel:(id)sender

This action method causes the receiver to send its action message (changeFont: by default) up the responder chain. When a responder replies by providing a font to convert in a convertFont: message, the receiver converts the font by sending a panelConvertFont: message to the Font Panel. The panel in turn may send convertFont:toFamily:, convertFont:toHaveTrait:, and other specific conversion methods to make its change.

See also:	− addFontTrait:, − removeFontTrait:, − modifyFont:

orderFrontFontPanel:

− (void)orderFrontFontPanel:(id)sender

This action method opens the Font Panel by sending it an orderFront: message, creating the Font Panel if necessary.

See also:	− fontPanel:, + setFontPanelFactory:

removeFontTrait:

− (void)removeFontTrait:(id)sender

This action method causes the receiver to send its action message (changeFont: by default) up the responder chain. When a responder replies by providing a font to convert in a convertFont: message, the receiver converts the font by removing the trait specified by sender. This trait is determined by sending a tag message to sender and interpreting it as a font trait mask for a convertFont:toNotHaveTrait: message.

See also:	− addFontTrait:, − modifyFont:, − modifyFontViaPanel:

selectedFont

− (NSFont *)selectedFont

Returns the last font recorded with a setSelectedFont:isMultiple: message. While fonts are being converted in response to a changeFont: message, you can determine the font selected in the Font Panel like this:

NSFontManager *fontManager = [NSFontManager sharedFontManager];

panelFont = [fontManager convertFont:[fontManager selectedFont]];

See also:	− isMultiple

sendAction

− (BOOL)sendAction

Sends the receiver’s action message, changeFont: by default, up the responder chain, initiating a font change for whatever conversion and trait to change were last requested. Returns YES if some object handled the changeFont: message, NO if the message went unheard.

This method is used internally by the font conversion system. You should never need to invoke it directly. Instead, use the action methods such as addFontTrait: or modifyFontViaPanel:.

See also:	− setAction:

setAction:

− (void)setAction:(SEL)aSelector

Sets the action that’s sent to the first responder when the user selects a new font from the Font panel or chooses a command from the Font menu to aSelector. The default action is changeFont:. You should rarely need to change this.

See also:	− action

setDelegate:

− (void)setDelegate:(id)anObject

Sets the receiver’s delegate to anObject.

See also:	− delegate

setEnabled:

− (void)setEnabled:(BOOL)flag

Controls whether the font-conversion system’s user interface items (the Font Panel and Font menu items) are enabled. If flag is YES they’re enabled; if flag is NO they’re disabled.

See also:	− setEnabled: (NSFontPanel), − isEnabled

setFontMenu:

− (void)setFontMenu:(NSMenu *)aMenu

Records aMenu as the application’s Font menu.

See also:	− fontMenu:

setSelectedFont:isMultiple:

− (void)setSelectedFont:(NSFont *)aFont isMultiple:(BOOL)flag

Records aFont as the currently selected font, and updates the Font Panel to reflect this. If flag is YES, the Font Panel indicates that more than one font is contained in the selection.

An object that manipulates fonts should invoke this method whenever it becomes first responder and whenever its selection changes. It shouldn’t invoke this method in the process of handling a changeFont: message, as this causes the font manager to lose the information necessary to effect the change. After all fonts have been converted, the font manager itself records the new selected font.

See also:	− selectedFont, − isMultiple

traitsOfFont:

− (NSFontTraitMask)traitsOfFont:(NSFont *)aFont

Returns the traits of aFont, a mask created by combining these options with the C bitwise OR operator:

NSItalicFontMask	NSCondensedFontMask

NSBoldFontMask	NSExpandedFontMask

NSNarrowFontMask	NSCompressedFontMask

NSFixedPitchFontMask	NSSmallCapsFontMask

NSPosterFontMask

NSCondensedFontMask and NSExpandedFontMask are mutually exclusive.

weightOfFont:

− (int)weightOfFont:(NSFont *)aFont

Returns a rough numeric measure of aFont’s weight, where 0 indicates the lightest possible weight, 5 indicates a normal or book weight, and 9 or more indicates a bold or heavier weight.

Methods Implemented By the Delegate

fontManager:willIncludeFont:

− (BOOL)fontManager:(id)theFontManager willIncludeFont:(const char *)fontName

Requests permission from the delegate to display fontName in the Font Panel. fontName is the full PostScript name of the font, such as “Helvetica-BoldOblique” or “Helvetica-Narrow-Bold”. If the delegate returns YES, fontName is listed; if the delegate returns NO, it isn’t.

This method is invoked repeatedly as necessary whenever the Font Panel needs updating, such as when the Font Panel is first loaded, and when the user selects a family name to see which typefaces in that family are available. Your implementation should execute fairly quickly to guarantee the responsiveness of the Font Panel.


NSFontPanel

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSPanel : NSWindow : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSFontPanel.h

Class Description

The NSFontPanel class implements the Font Panel—a user-interface object that displays a list of available fonts, letting the user preview them and change the font used to display text. The actual changes are made through conversion messages sent to the shared NSFontManager instance. There’s only one Font Panel for each application.

In general, you add the facilities of the Font Panel to your application, along with the NSFontManager and the Font menu, through Interface Builder. You do this by dragging a Font menu into one of your application’s menus. At run time, when the user chooses the Font Panel command for the first time, the Font Panel object is created and hooked into the font conversion system. You can also create (or access) the Font Panel using the sharedFontPanel class method.

You can add a custom view object to an NSFontPanel using setAccessoryView:, or limit the fonts display by assigning a delegate to the application’s font manager object. If you want the NSFontManager to instantiate the Font Panel from some class other than NSFontPanel, use NSFontManager’s setFontPanelFactory: class method. See the NSFontManager class specification for more information on using the font conversion system.

Method Types

Getting the Font Panel	+ sharedFontPanel

+ sharedFontPanelExists

Enabling font changes	− setEnabled:

− isEnabled

Updating the Font Panel	− setPanelFont:isMultiple:

Converting fonts	− panelConvertFont:

Working in modal loops	− worksWhenModal:

Setting an accessory view	− setAccessoryView:

− accessoryView

Class Methods

sharedFontPanel

+ (NSFontPanel *)sharedFontPanel

Returns the single NSFontPanel instance for the application, creating it if necessary.

See also:	+ sharedFontPanelExists, + setFontPanelFactory: (NSFontManager)

p	sharedFontPanelExists

+ (BOOL)sharedFontPanelExists

Returns YES if the shared Font Panel has been created, NO if it hasn’t.

See also:	+ sharedFontPanel

Instance Methods

accessoryView

− (NSView *)accessoryView

Returns the receiver’s accessory view.

See also:	− setAccessoryView:

isEnabled

− (BOOL)isEnabled

Returns YES if the receiver’s Set button is enabled, NO if it isn’t. The receiver continues to reflect the font of the selection for cooperating text objects regardless of this setting.

See also:	− setEnabled:

panelConvertFont:

− (NSFont *)panelConvertFont:(NSFont *)aFont

Converts aFont using the settings in the receiver, with the aid of the shared NSFontManager if necessary, and returns the converted font. If aFont can’t be converted it’s returned unchanged.

For example, if aFont is Helvetica Oblique 12.0 point and the user has selected the Times font family (and nothing else) in the Font Panel, the font returned is Times Italic 12.0 point.

See also:	− convertFont: (NSFontManager)

setAccessoryView:

− (void)setAccessoryView:(NSView *)aView

Establishes aView as the receiver’s accessory view, allowing you to add custom controls to your application’s Font Panel without having to create a subclass.

See also:	− accessoryView

setEnabled:

− (void)setEnabled:(BOOL)flag

Controls whether the receiver’s Set button is enabled. If flag is YES the Set button is enabled; if flag is NO it’s disabled. The receiver continues to reflect the font of the selection for cooperating text objects regardless of this setting.

See also:	− isEnabled

setPanelFont:isMultiple:

− (void)setPanelFont:(NSFont *)aFont isMultiple:(BOOL)flag

Sets the selected font in the receiver to aFont if flag is NO, otherwise selects no font and displays a message in the preview area indicating that multiple fonts are selected. You normally don’t use this method directly; instead, you send setSelectedFont:isMultiple: to the shared NSFontManager, which in turn invokes this method.

worksWhenModal

− (BOOL)worksWhenModal

Returns YES, regardless of the setting established using the NSPanel method setWorksWhenModal:. This allows fonts to be changed in modal windows and panels.

See also:	− worksWhenModal (NSWindow, NSPanel)


NSForm

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSMatrix : NSControl : NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSForm.h

Class Description

An NSForm is a vertical NSMatrix of NSFormCells. Here’s an example:

In NSForm’s methods, each NSFormCell is called an “entry” (or, sometimes, a “cell” or “item”). The left part of each entry is called the “title,” and the right part is called the “text.” Methods that refer to individual entries use an one-dimensional “index”; the indexing system starts at the top of the top of form, with zero.

Any entry in the form can be “selected.” When an entry is selected, its text area responds to the user’s keystrokes. You can select an entry using the selectTextAtIndex: method, or you can let the user select an entry by clicking it with the mouse. Once an entry is selected, the user can select the next entry by pressing Tab, or select the previous entry by pressing Shift-Tab.

To initiate the action of a selected entry, the user presses Return or Enter. In response, the entry sends an action message to its target. If the entry has no target, the NSForm sends an action message to its target.

NSForm includes a methods to change the appearance of entries (the set... methods). These methods affect every entry in the form. To change the appearance of an individual entry, you need to single it out, using cellAtIndex:, and then send it messages appropriate to an NSFormCell.

For more information, see the class specifications for NSFormCell and NSMatrix.

Method Types

Adding and removing entries	− addEntry:

− insertEntry:atIndex:

− removeEntryAtIndex:

Changing the appearance of all the entries

− setBezeled:

− setBordered:

− setEntryWidth:

− setInterlineSpacing:

− setTitleAlignment:

− setTextAlignment:

− setTitleFont:

− setTextFont:

Asking and changing the cell class	+ cellClass

+ setCellClass:

Getting cells and indices	− indexOfCellWithTag:

− indexOfSelectedItem

− cellAtIndex:

Displaying a cell	− drawCellAtIndex:

Editing text	− selectTextAtIndex:

Instance Methods

addEntry:

− (NSFormCell *)addEntry:(NSString *)title

Adds a new entry to the end of the form, and gives it the title title. The new entry has no tag, target, or action, but is enabled and editable.

See also:	− insertEntryAtIndex:,

− setTag:, − setTarget:, − setAction:, − setEnabled: (all from NSActionCell)

− setEditable: (NSCell)

cellAtIndex:

− (id)cellAtIndex:(int)entryIndex

Returns the entry specified by entryIndex.

See also:	 − indexOfCellWithTag:, − indexOfSelectedItem

drawCellAtIndex:

− (void)drawCellAtIndex:(int)entryIndex

Displays the entry specified by entryIndex. Since this method is called automatically whenever a cell needs drawing, you will never need to invoke it explicitly. It is only included in the API so that you can override it if you subclass NSFormCell.

See also:	 − indexOfCellWithTag:, − indexOfSelectedItem

indexOfCellWithTag:

− (int)indexOfCellWithTag:(int)tag

Returns the index of the entry whose tag is tag.

See also:	 − tag (NSCell)

indexOfSelectedItem

− (int)indexOfSelectedItem

Returns the index of the selected entry. If no entry is selected, indexOfSelectedItem returns -1.

insertEntry:atIndex:

− (NSFormCell *)insertEntry:(NSString *)title atIndex:(int)entryIndex

Inserts an entry with the title title at the position in the form specified by entryIndex. The new entry has no tag, target, or action, and, as explained in the class description, it won’t appear on the screen automatically.

Returns the newly inserted NSFormCell.

See also:	− addEntry:, − removeEntryAtIndex:

removeEntryAtIndex:

− (void)removeEntryAtIndex:(int)entryIndex

If entryIndex is a valid position in the form, removes the entry there and frees it.

selectTextAtIndex:

− (void)selectTextAtIndex:(int)entryIndex

If entryIndex is a valid position in the Form, selects the entry at that position.

setBezeled:

− (void)setBezeled:(BOOL)flag

If flag is YES, sets all the entries in the form to show a bezel around their editable text; if flag is NO, sets all the entries to show no bezel.

See also:	− isBezeled (Cell), − setBordered:

setBordered:

− (void)setBordered:(BOOL)flag

flag determines whether the entries in the form are set to display a border—that is, a thin line—around their editable text fields.  An entry can have a border or a bezel, but not both.

See also:	 − isBordered (Cell), − setBezeled:

setEntryWidth:

− (void)setEntryWidth:(float)width

Sets the width (in pixels) of all the entries in the form. This width includes both the title and the text field.

setInterlineSpacing:

− (void)setInterlineSpacing:(float)spacing

Sets the number of pixels between entries in the form to spacing.

setTextAlignment:

− (void)setTextAlignment:(int)alignment

Sets the alignment for all of the form’s editable text.  alignment can be one of three constants:  NSRightTextAlignment, NSCenterTextAlignment, or NSLeftTextAlignment (the default).

See also:	 − setTitleAlignment:

setTextFont:

− (void)setTextFont:(NSFont *)font

Sets the font for all of the form’s editable text fields.

See also:	 − setTitleFont:

setTitleAlignment:

− (void)setTitleAlignment:(NSTextAlignment)alignment

Sets the alignment for all of the entry titles. alignment can be one of three constants:  NSRightTextAlignment, NSCenterTextAlignment, or the default, NSLeftTextAlignment.

See also:	 − setTextAlignment:

setTitleFont:

− (void)setTitleFont:(NSFont *)font

Sets the font for all of the entry titles.

See also:	 − setTextFont:


NSFormCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSActionCell : NSCell : NSObject

Conforms To:	NSCoding (from NSCell)

NSCopying (from NSCell)

NSObject (from NSObject)

Declared In:	AppKit/NSFormCell.h

Class Description

This class is used to implement text entry fields in an NSForm. The left part of an NSFormCell is a title. The right part is an editable text entry field.

For more on the use of NSFormCell, see the class specification for NSForm.

Method Types

Initializing an NSFormCell	− initTextCell:

Asking about a cell’s appearance	− isOpaque

Asking about a cell’s title	− attributedTitle

− title

− titleAlignment

− titleFont

− titleWidth

Changing the cell’s title	− setAttributedTitle:

− setTitle:

− setTitleAlignment:

− setTitleFont:

− setTitleWidth:

Setting a keyboard equivalent	− setTitleWithMnemonic:

Instance Methods

p	attributedTitle

− (NSAttributedString *)attributedTitle

Returns the title as an attributed string.

initTextCell:

− (id)initTextCell:(NSString *)aString

Initializes a newly allocated NSFormCell. Its title is set to aString; the contents of its text entry field are set to the empty string (“”). The font for both title and text is the user’s chosen system font in 12.0 point, and the text area is drawn with a bezel. This method is the designated initializer for NSFormCell.

Returns self.

See also:	 − setTitle:

isOpaque

− (BOOL)isOpaque

Returns YES if both the title and the entry field are opaque, NO if one or both of them are transparent. Since titles are transparent by default, this method usually returns NO.

p	setAttributedTitle:

− (void)setAttributedTitle:(NSAttributedString *)anAttributedString

Sets the cell’s title and title attributes according to anAttributedString.

setTitle:

− (void)setTitle:(NSString *)aString

Sets the cell’s title to aString.

setTitleAlignment:

− (void)setTitleAlignment:(NSTextAlignment)alignment

Sets the alignment of the title. alignment can be one of three constants:  NSLeftTextAlignment, NSRightTextAlignment, or NSCenterTextAlignment.

setTitleFont:

− (void)setTitleFont:(NSFont *)font

Sets the title’s font.

setTitleWidth:

− (void)setTitleWidth:(float)width

You usually won’t need to to invoke this method, since the Application Kit automatically sets the title width whenever the title changes. If, however, the automatic width doesn’t suit your needs, you can use setTitleWidth: to set the width in pixels.

Once you have set the width explicity this way, the Application Kit stops setting the width automatically; you will need to invoke setTitleWidth: every time the title changes. If you want the Application Kit to resume automatic width assignments, invoke setTitleWidth: with a negative width value.

p	setTitleWithMnemonic:

− (void)setTitleWithMnemonic:(NSString *)titleWithAmpersand

Sets the cell title and a single mnemonic character. The mnemonic character, which follows the ampersand in titleWithAmpersand, serves as an Alt-key equivalent to clicking in the text entry field.

For example, if titleWithAmpersand is “T&itle,” the cell’s title will be displayed as “Title” (the mnemonic character, i, is underlined). If a user types Alt-i, it will have the same effect as clicking in the text entry field.

<<Should there be other functions to complement this one—that is, should there be methods called setAttributedTitleWithMnemonic:,  titleWithMnemonic:, and attributedTitleWithMnemonic:?>>

See also:	 − setTitle:

title

− (NSString *)title

Returns the cell’s title. The default title is “Field:”.

titleAlignment

− (NSTextAlignment)titleAlignment

Returns the alignment of the title, which will be one of the following:  NSLeftTextAlignment, NSCenterTextAlignment, or NSRightTextAlignment (the default).

titleFont

− (NSFont *)titleFont

Returns the font used to draw the cell’s title.

titleWidth

− (float)titleWidth

Returns the width (in pixels) of the title field. If you specified the width using setTitleWidth:, titleWidth returns the value you chose. Otherwise, it returns the width calculated automatically by the Application Kit.


NSHelpManager
p NSHelpManager

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSHelpManager.h

Class Description

NSHelpManager provides a platform-independent approach to displaying on-line help. An application contains one instance of NSHelpManager. Your application’s code rarely needs to access NSHelpManager directly. Instead, you use Interface Builder and Project Builder to set up on-line help for your application.

OpenStep applications can run on multiple platforms, and each platform provides its own support for on-line help. It’s important to users that applications use the native on-line help system (on Microsoft Windows, for instance, users want the Microsoft Windows help system and don’t want to have to learn how to use a different help system), so NSHelpManager does not provide a comprehensive solution for presenting help. Instead, it provides cross-platform support for context-sensitive help and allows you to present more comprehensive help (conceptual and task-based help) in any way you choose.

Context Help

Context-sensitive help (also referred to as context help) gives the user a small amount of information when they help-click an interface item. For example, if the user help-clicks a menu item called “Copy,” they should get context help that says something like “Copies the currently selected text to the pasteboard.” This text appears in a small window near where the user help-clicked, and the window disappears when the user clicks anywhere else in the application.

Help-clicking is performed in any one of several ways, depending on the platform and the hardware used. On Mach platforms, help-clicking is performed when the user holds down the Help key, the F1 key, or the Alternate and Control keys while pressing the mouse button. On Microsoft Windows platforms, users press Shift-F1 and then press the mouse button to display context-sensitive help. Some Microsoft Windows applications also have a What’s This menu item on the Help menu. When the user selects this item, the next mouse click displays context-sensitive help.

To provide context-sensitive help for your application, follow these steps:

1.	For each interface item that needs context help, create an RTF or RTFD file containing the text and any images you want to appear when the user help-clicks that interface item. Try to keep the text as brief as possible and the images as small as possible.

The text that you write will appear in a small window just under the cursor when the user help-clicks an interface item. If the user help-clicks near the edge of the screen, text may appear off-screen. (This is especially prevalent when the user help-clicks a menu item on the Mach platform.) Use hard returns in your text so that the window will be as narrow as possible.

2.	If you don’t need to localize your context help files, in Project Builder simply add these files to your project under Context Help.

If you do need to localize your context help files, first copy the files into the appropriate .lproj directory of your project, then add them to the project.

In Interface Builder, connect each interface item to its context help file by doing the following:

1.	Bring up the Interface Builder inspector and choose the Help display. The Help display lists all the context help files associated with your application. (You may have to quit and restart Interface Builder to get this to occur.)

2.	Select an interface item.

3.	In the Inspector, choose the appropriate help file.

When you build your application, /usr/bin/compileHelp packages your help files into a property list named Help.plist. NSHelpManager knows how to extract context help from an Help.plist file.

Comprehensive Help

Most applications provide some form of on-line help that is more comprehensive and detailed than context-sensitive help, such as conceptual or task help. NSHelpManager allows you to provide this sort of comprehensive help in any way you choose. Some help authors prefer to provide comprehensive help in HTML using a World-Wide Web browser; others use tools such as Digital Librarian or Concurrence; on Microsoft Windows a full-featured native help system is available.

When the user chooses the Help menu item, NSHelpManager simply asks NSWorkspace to open the help file you have specified for your application. That file should be the starting point of your help, and should allow users to access whatever information they might need.

To specify a help file for your application, do one of the following:

•	In Project Builder, specify the name of the help file in the Project Attributes inspector. (If you are creating an application that will run on both the Mach and Windows platforms, you need to enter this file twice—once for Mach and once for Windows). The specified value can be a full or relative path, and if it is relative, it is assumed to be a resource in the application wrapper.

•	As an alternative, you can place the help file in your application wrapper and name it after your application. If you haven’t specified a help file, NSHelpManager looks in the application wrapper for an appropriately named file.

On Mach, it must be an RTF file called appName.rtf (where appName is the name of the application).

On Microsoft Windows, it must be a Windows help file called appName.hlp.

Note:	It’s common for Windows applications to have more than one command under the Help menu and to have each command open a different help file. To implement this, connect each of the Help menu commands to a different action method. The actions methods should send openFile: to the shared NSWorkspace object to open the appropriate help file. For example:

[[NSWorkspace sharedWorkspace] openFile:@"AppKit.hlp"];

Method Types

Creating an NSHelpManager instance

+ sharedHelpManager

Getting and setting context help mode

+ setContextHelpModeActive:

+ isContextHelpModeActive

Returning context-sensitive help	− contextHelpForObject:

− showContextHelpForObject:locationHint:

Setting up context-sensitive help	− setContextHelp:forObject:

− removeContextHelp:forObject:

Class Methods

p	isContextHelpModeActive

+ (BOOL)isContextHelpModeActive

Returns YES if the application is currently in context-sensitive help mode, NO otherwise. In context-sensitive help mode, when a user clicks a user interface item, help for that item is displayed in a small window just below the cursor.

See also:	+ setContextHelpModeActive:

p	setContextHelpModeActive:

+ (void)setContextHelpModeActive:(BOOL)flag

Controls context-sensitive help mode. If flag is YES, the application enters context-sensitive help mode. If flag is NO, the application returns to normal operation.

You never send this message directly; instead, the NSApplication method activateContextHelpMode activates context-sensitive help mode, and the first mouse click after displaying the context-sensitive help window deactivates it.

When the application enters context-sensitive help mode, NSHelpManager posts NSContextHelpModeDidActivateNotification to the default notification center. When the application returns to normal operation, NSHelpManager posts NSContextHelpModeDidDeactivateNotification.

See also:	+ isContextHelpModeActive

p	sharedHelpManager

+ (NSHelpManager *)sharedHelpManager

Returns the shared NSHelpManager instance, creating it if it does not already exist.

Instance Methods

p	contextHelpForObject:

− (NSAttributedString *)contextHelpForObject:(id)object

Returns context-sensitive help for object.

See also:	− setContextHelp:forObject:, − showContextHelpForObject:locationHint:

p	removeContextHelpForObject:

− (void)removeContextHelpForObject:(id)object

Removes the association between object and its context-sensitive help. If object does not have context-sensitive help associated with it, this method does nothing. Typically, you use Interface Builder to remove context-sensitive help from an item.

See also:	− setContextHelp:forObject:

p	setContextHelp:forObject:

− (void)setContextHelp:(NSAttributedString *)help forObject:(id)object

Associates help with object. When the application enters context-sensitive help mode, if object is clicked, help will appear in the context-sensitive help window. Typically, you use Interface Builder to associate context-sensitive help with an object.

See also:	− removeContextHelpForObject:

p	showContextHelpForObject:locationHint:

− (BOOL)showContextHelpForObject:(id)object locationHint:(NSPoint)point

Displays the context-sensitive help for object at or near the point on the screen specified by point. This point is usually just under the cursor. Returns YES if it successfully displays context-sensitive help for the object, NO if it cannot (for example, if there is no context-sensitive help associated with this object).

See also:	− contextHelpForObject:

Notifications

p	NSContextHelpModeDidActivateNotification

Posted when the application enters context-sensitive help mode. This typically happens when the user holds down the Help key. It can also occur on Microsoft Windows platforms if the user chooses the What’s This command from the Help menu.

The notification contains:

Notification Object	The NSHelpManager object

Userinfo	None

p	NSContextHelpModeDidDeactivateNotification

Posted when the application exits context-sensitive help mode. This happens when the user clicks the mouse anywhere on the screen after displaying a context-sensitive help topic.

The notification contains:

Notification Object	The NSHelpManager object

Userinfo	None


NSIgnoreMisspelledWords

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Adopted By:	NSText

Declared In:	AppKit/NSSpellProtocol.h

Protocol Description

Implement this protocol to have the Ignore button in the Spelling panel function properly. The Ignore button allows the user to accept a word that the spelling checker believes is misspelled. In order for this action to update the “ignored words” list for the document being checked, the NSIgnoreMisspelledWords protocol must be implemented.

This protocol is necessary because a list of ignored words is useful only if it pertains to the entire document being checked, but the spelling checker (NSSpellChecker object) does not check the entire document for spelling at once. The spelling checker returns as soon as it finds a misspelled word. Thus, it checks only a subset of the document at any one time. The user usually wants to check the entire document, and so usually several spelling checks are run in succession until no misspelled words are found. This protocol allows the list of ignored words to be maintained per-document, even though the spelling checks are not run per-document.

The NSIgnoreMisspelledWords protocol specifies a method, ignoreSpelling:, which should be implemented like this:

- (void)ignoreSpelling:(id)sender

{

    [[NSSpellChecker sharedSpellChecker] ignoreWord:[[sender selectedCell]

        stringValue] inSpellDocumentWithTag:myDocumentTag];

}

The second argument to the NSSpellChecker method ignoreWord:inSpellDocumentWithTag: is a tag that the NSSpellChecker can use to distinguish the documents being checked. (See the discussion of “Matching a List of Ignored Words With the Document It Belongs To” in the description of the NSSpellChecker class.) Once the NSSpellChecker has a way to distinguish the various documents, it can append new ignored words to the appropriate list.

To make the ignored words feature useful, the application must store a document's ignored words list with the document. See the NSSpellChecker class description for more information.

Instance Methods

ignoreSpelling:

− (void)ignoreSpelling:(id)sender

Implement to allow an application to ignore misspelled words on a document-by-document basis. This message is sent by the NSSpellChecker instance to the object whose text is being checked.

Implement this method by using the code shown in the protocol description.


NSImage

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSCopying

NSObject (from NSObject)

Declared In:	AppKit/NSImage.h

Class Description

An NSImage object contains an image that can be composited anywhere without first being drawn in any particular view. It manages the image by:

•	Reading image data from the application bundle, from an NSPasteboard, or from an NSData object.

•	Keeping multiple representations of the same image.

•	Choosing the representation that’s appropriate for a particular data type.

•	Choosing the representation that’s appropriate for any given display device.

•	Caching the representations it uses by rendering them in off-screen windows.

•	Optionally retaining the data used to draw the representations, so that they can be reproduced when needed.

•	Compositing the image from the off-screen cache to where it’s needed on-screen.

•	Reproducing the image for the printer so that it matches what’s displayed on-screen, yet is the best representation possible for the printed page.

•	Automatically using any filtering services installed by the user to convert image data from unsupported formats to supported formats.

Defining an Image

An image can be created from various types of data:

•	Encapsulated PostScript code (EPS)

•	Bitmap data in Tag Image File Format (TIFF)

•	Bitmap data in Windows Bitmap format (BMP)

•	Untagged (raw) bitmap data

•	Other image data supported by an NSImageRep subclass registered with the NSImage class

•	Data that can be filtered to a supported type by a user-installed filter service

If data is placed in a file (for example, in an application bundle), the NSImage object can access the data whenever it’s needed to create the image. If data is read from an NSData object, the NSImage object may need to store the data itself.

Images can also be defined by the program, in two ways:

•	By drawing the image in an off-screen window maintained by the NSImage object. In this case, the NSImage maintains only the cached image.

•	By defining a method that can be used to draw the image when needed. This allows the NSImage to delegate responsibility for producing the image to some other object.

Image Representations

An NSImage object can keep more than one representation of an image. Multiple representations permit the image to be customized for the display device. For example, different hand-tuned TIFF images can be provided for monochrome and color screens, and an EPS representation or a custom method might be used for printing. All representations are versions of the same image.

An NSImage returns an NSArray of its representations in response to a representations message. Each representation is a kind of NSImageRep object:

NSEPSImageRep	An image that can be recreated from EPS data that’s either stored by the object or at a known location in the file system.

NSBitmapImageRep	An image that can be recreated from bitmap or TIFF data.

NSCustomImageRep	An image that can be redrawn by a method defined in the application.

NSCachedImageRep	An image that has been rendered in an off-screen cache from data or instructions that are no longer available. The image in the cache provides the only data from which the image can be reproduced.

You can define other NSImageRep subclasses for objects that render images from other types of source data. To make these new subclasses available to an NSImage object, they need to be added to the NSImageRep class registry by invoking the registerImageRepClass: class method. NSImage determines the data types that each subclass can support by invoking its imageUnfilteredFileTypes and imageUnfilteredPasteboardTypes methods.

Choosing Representations

The NSImage object will choose the representation that best matches the rendering device. By default, the choice is made according to the following set of ordered rules. Each rule is applied in turn until the choice of representation is narrowed to one.

1.	Choose a color representation for a color device, and a gray-scale representation for a monochrome device.

2.	Choose a representation with a resolution that matches the resolution of the device, or if no representation matches, choose the one with the highest resolution.

By default, any image representation with a resolution that’s an integer multiple of the device resolution is considered to match. If more than one representation matches, the NSImage will choose the one that’s closest to the device resolution. However, you can force resolution matches to be exact by passing NO to the setMatchesOnMultipleResolution: method.

Rule 2 prefers TIFF and bitmap representations, which have a defined resolution, over EPS representations, which don’t. However, you can use the setUsesEPSOnResolutionMismatch: method to have the NSImage choose an EPS representation in case a resolution match isn’t possible.

3.	If all else fails, choose the representation with a specified bits per sample that matches the depth of the device. If no representation matches, choose the one with the highest bits per sample.

By passing NO to the setPrefersColorMatch: method, you can have the NSImage try for a resolution match before a color match. This essentially inverts the first and second rules above.

If these rules fail to narrow the choice to a single representation—for example, if the NSImage has two color TIFF representations with the same resolution and depth—the one that will be chosen is system dependent.

Caching Representations

When first asked to composite the image, the NSImage object chooses the representation that’s best for the destination display device, as outlined above. It renders the representation in an off-screen window on the same device, then composites it from this cache to the desired location. Subsequent requests to composite the image use the same cache. Representations aren’t cached until they’re needed for compositing.

When printing, the NSImage tries not to use the cached image. Instead, it attempts to render on the printer—using the appropriate image data, or a delegated method—the best version of the image that it can. Only as a last resort will it image the cached bitmap.

Image Size

Before an NSImage can be used, the size of the image must be set, in units of the base coordinate system. If a representation is smaller or larger than the specified size, it can be scaled to fit.

If the size of the image hasn’t already been set when the NSImage is provided with a representation, the size will be set from the data. The bounding box is used to determine the size of an NSEPSImageRep. The TIFF fields “ImageLength” and “ImageWidth” are used to determine the size of an NSBitmapImageRep.

Coordinate Systems

Images have the horizontal orientation of the base coordinate system; they can’t be rotated or horizontally flipped. When composited, an image maintains this orientation, no matter what coordinate system it’s composited to. (The destination coordinate system is used only to determine the location of a composited image, not its size or orientation.) Images can be flipped in the vertical direction by using setFlipped:.

It’s possible to refer to portions of an image when compositing by specifying a rectangle in the image’s coordinate system, which is identical to the base coordinate system, except that the origin is at the lower left corner of the image.

Named Images

An NSImage object can be identified either by its id or by a name. Assigning an NSImage a name adds it to a table kept by the class object; each name in the database identifies one and only one instance of the class. When you ask for an NSImage object by name (with the imageNamed: method), the class object returns the one from its database, which also includes all the system bitmaps provided by the Application Kit. If there’s no object in the database for the specified name, the class object tries to create one by checking for a system bitmap of the same name, checking the name of the application’s own image, and then checking for the image in the application’s main bundle.

If a file matches the name, an NSImage is created from the data stored there. You can therefore create NSImage objects simply by including EPS, BMP, or TIFF data for them within the executable file, or in files inside the application’s file package.

Image Filtering Services

NSImage is designed to automatically take advantage of user-installed filter services for converting unsupported image file types to supported image file types. The class method imageFileTypes returns an array of all file types from which NSImage can create an instance of itself. This list includes all file types supported by registered subclasses of NSImageRep, and those types that can be converted to supported file types through a user-installed filter service.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

NSCopying	− copyWithZone:

Method Types

 Initializing a new NSImage instance

− initByReferencingFile:

− initWithBitmapHandle:

− initWithContentsOfFile:

− initWithData:

− initWithIconHandle:

− initWithPasteboard:

− initWithSize:

Setting the size of the image	− setSize:

− size

Referring to images by name	+ imageNamed:

− setName:

− name

Specifying the image	− addRepresentation:

− addRepresentations:

− lockFocus

− lockFocusOnRepresentation:

− unlockFocus

Using the image	− compositeToPoint:operation:

− compositeToPoint:fromRect:operation:

− dissolveToPoint:fraction:

− dissolveToPoint:fromRect:fraction:

Choosing which image representation to use

− setPrefersColorMatch:

− prefersColorMatch

− setUsesEPSOnResolutionMismatch:

− usesEPSOnResolutionMismatch

− setMatchesOnMultipleResolution:

− matchesOnMultipleResolution

Getting the representations	− bestRepresentationForDevice:

− representations

− removeRepresentation:

Determining how the image is stored

− setCachedSeparately:

− isCachedSeparately

− setDataRetained:

− isDataRetained

− setCacheDepthMatchesImageDepth:

− cacheDepthMatchesImageDepth

Determining how the image is drawn

− isValid

− setScalesWhenResized:

− scalesWhenResized

− setBackgroundColor:

− backgroundColor

− setFlipped:

− isFlipped

− drawRepresentation:inRect:

− recache

Assigning a delegate	− setDelegate:

− delegate

Producing TIFF data for the image	− TIFFRepresentation

− TIFFRepresentationUsingCompression:factor:

Managing NSImageRep subclasses	+ imageUnfilteredFileTypes

+ imageUnfilteredPasteboardTypes

Testing image data sources	+ canInitWithPasteboard:

+ imageFileTypes

+ imagePasteboardTypes

Class Methods

canInitWithPasteboard:

+ (BOOL)canInitWithPasteboard:(NSPasteboard *)pasteboard

Tests whether the receiver can create an instance of itself from the data represented by pasteboard. Returns YES if the receiver’s list of registered NSImageReps includes a class that can handle the data represented by pasteboard.

NSImage uses the NSImageRep class method imageUnfilteredPasteboardTypes to find a class that can handle the data in pasteboard. When creating a subclass of NSImageRep that accepts image data from a non-default pasteboard type, override the imageUnfilteredPasteboardTypes method to notify NSImage of the pasteboard types your class supports.

See also:	 + imagePasteboardTypes

imageFileTypes

+ (NSArray *)imageFileTypes

Returns an array of strings representing those file types for which a registered NSImageRep exists. This list includes all file types supported by registered subclasses of NSImageRep, plus those types that can be converted to supported file types through a user-installed filter service. The array returned by this method may be passed directly to the NSOpenPanel’s runModalForTypes: method.

File types are identified by extension. By default, the list returned by this method contains “tiff”, “tif”, “bmp”, and “eps”.

When creating a subclass of NSImageRep that accepts image data from non-default file types, override NSImageRep’s imageUnfilteredFileTypes method to notify NSImage of the file types your class supports.

See also:	 + imageUnfilteredFileTypes

imageNamed:

+ (id)imageNamed:(NSString *)name

Returns the NSImage instance associated with name. The returned object can be:

•	One that’s been assigned a name with the setName: method

•	One of the named system bitmaps provided by the Application Kit

If there’s no known NSImage with name, this method tries to create one by searching for image data in the application’s executable file and in the main bundle (see NSBundle’s class description for a description of how the bundle’s contents are searched). If a file contains data for more than one image, a separate representation is created for each. If an image representation can’t be found for name, no object is created and nil is returned.

The preferred way to name an image is to ask for a name without the extension, but to include the extension for a file name.

One particularly useful image is referenced by the string “NSApplicationIcon”. If you supply this string to imageNamed:, the returned image will be the application’s own icon. Icons for other applications can be obtained through the use of methods declared in the NSWorkspace class.

The image returned by this method should not be freed, unless it’s certain that no other objects reference it.

See also:	− setName:, − name, − iconForFile: (NSWorkspace), + imageFileTypes

imagePasteboardTypes

+ (NSArray *)imagePasteboardTypes

Returns a null-terminated list of pasteboard types for which a registered NSImageRep exists. This list includes all pasteboard types supported by registered subclasses of NSImageRep, and those that can be converted to supported pasteboard types through a user-installed filter service.

By default, the list returned by this method contains “NSPostScriptPboardType” and “NSTIFFPboardType”.

When creating a subclass of NSImageRep that accepts image data from non-default pasteboard types, override NSImageRep’s imageUnfilteredPasteboardTypes method to notify NSImage of the pasteboard types your class supports.

See also:	+ imageUnfilteredPasteboardTypes

imageUnfilteredFileTypes

+ (NSArray *)imageUnfilteredFileTypes

Returns a null-terminated array of strings representing those file types for which a registered NSImageRep exists. This list consists of all file types supported by registered subclasses of NSImageRep, and doesn’t include those types that can be converted to supported file types through a user-installed filter service. The array returned by this method may be passed directly to the NSOpenPanel’s runModalForTypes: method.

See also:	+ imageFileTypes

imageUnfilteredPasteboardTypes

+ (NSArray *)imageUnfilteredPasteboardTypes

Returns a null-terminated list of pasteboard types for which a registered NSImageRep exists. This list consists of all pasteboard types supported by registered subclasses of NSImageRep, and doesn’t include those that can be converted to supported pasteboard types through a user-installed filter service.

See also:	+ imagePasteboardTypes

Instance Methods

addRepresentation:

− (void)addRepresentation:(NSImageRep *)imageRep

Adds imageRep to the receiver’s list of representations. After invoking this method, you may need to explicitly set features of the new representation, such as size, number of colors, and so on. This is true in particular if the NSImage has multiple image representations to choose from. See NSImageRep and its subclasses for the methods you use to complete initialization.

Any representation that’s added by this method is retained by the NSImage. Note that representations can’t be shared among NSImages.

See also:	− representations, − removeRepresentation:

addRepresentations:

− (void)addRepresentations:(NSArray *)imageReps

Adds each of the representations in imageReps to the receiver’s list of representations. After invoking this method, you may need to explicitly set features of the new representations, such as size, number of colors, and so on. This is true in particular if the NSImage has multiple image representations to choose from. See NSImageRep and its subclasses for the methods you use to complete initialization.

Representations added by this method are retained by the NSImage. Note that representations can’t be shared among NSImages.

See also:	− representations, − removeRepresentation:

backgroundColor

− (NSColor *)backgroundColor

Returns the background color of the rectangle where the image is cached. If no background color has been specified, NSColor’s clearColor is returned, indicating a transparent background.

The background color will be visible when the image is composited only if the image doesn’t completely cover all the pixels within the area specified for its size.

bestRepresentationForDevice:

− (NSImageRep *)bestRepresentationForDevice:(NSDictionary *)deviceDescription

Returns the best representation for the device described by deviceDescription. If deviceDescription is nil, the current device is assumed. “Choosing Representations” in the class introduction outlines the process NSImage goes through in order to determine the “best” representation for a given device. For a list of dictionary keys and values appropriate to display and print devices, see NSGraphics.h.

See also:	− representations, − prefersColorMatch

cacheDepthMatchesImageDepth

− (BOOL)cacheDepthMatchesImageDepth

Returns NO if the application’s default depth limit applies to the off-screen windows where the NSImage’s representations are cached. If window depths are instead determined by the specifications of the representations, cacheDepthMatchesImageDepth returns YES.

compositeToPoint:fromRect:operation:

− (void)compositeToPoint:(NSPoint)aPoint fromRect:(NSRect)aRect operation:(NSCompositingOperation)op

Composites the portion of the image enclosed by the aRect rectangle to the location specified by aPoint in the current coordinate system. aRect must be a valid (non-null) rectangle. The aPoint argument is the same as for compositeToPoint:operation:. op should be one of the compositing operations as defined in dpsOpenStep.h.

The source rectangle is specified relative to a coordinate system that has its origin at the lower left corner of the image, but is otherwise the same as the base coordinate system.

This method doesn’t check to be sure that the rectangle encloses only portions of the image. Therefore, it can conceivably composite areas that don’t properly belong to the image, if the aRect rectangle happens to include them. If this turns out to be a problem, you can prevent it from happening by having the NSImage cache its representations in their own individual windows (with the setCachedSeparately: method). In this case, the window’s clipping path will prevent anything but the image from being composited.

Compositing part of an image is as efficient as compositing the whole image, but printing just part of an image is not. When printing, it’s necessary to draw the whole image and rely on a clipping path to be sure that only the desired portion appears.

See also:	− dissolveToPoint:fromRect:fraction:

compositeToPoint:operation:

− (void)compositeToPoint:(NSPoint)aPoint operation:(NSCompositingOperation)op

Composites the image to the location specified by aPoint using the specified compositing operation, op.

aPoint is specified in the current coordinate system—the coordinate system of the currently focused NSView—and designates where the lower left corner of the image will appear. The image will have the orientation of the base coordinate system, regardless of the destination coordinates. op should be one of the compositing operations as defined in dpsOpenStep.h.

The image is composited from its off-screen window cache. Since the cache isn’t created until the image representation is first used, this method may need to render the image before compositing.

When printing, the compositing methods do not composite, but attempt to render the same image on the page that compositing would render on the screen, choosing the best available representation for the printer. The op argument is ignored.

See also:	− dissolveToPoint:fraction:

delegate

− (id)delegate

Returns the delegate of the NSImage object, or nil if no delegate has been set.

dissolveToPoint:fraction:

− (void)dissolveToPoint:(NSPoint)aPoint fraction:(float)aFloat

Composites the image to the location specified by aPoint, just as compositeToPoint:operation: does, but uses the dissolve operator rather than composite. aFloat is a fraction between 0.0 and 1.0 that specifies how much of the resulting composite will come from the NSImage. If the source image contains alpha, this operation may promote the destination NSWindow to contain alpha.

To slowly dissolve one image into another, this method (or dissolveToPoint:fromRect:fraction:) needs to be invoked repeatedly with an ever-increasing aFloat. Since aFloat refers to the fraction of the source image that’s combined with the original destination (not the destination image after some of the source has been dissolved into it), the destination image should be replaced with the original destination before each invocation. This is best done in a buffered window before the results of the composite are flushed to the screen.

When printing, this method is identical to compositeToPoint:operation:. The delta argument is ignored.

dissolveToPoint:fromRect:fraction:

− (void)dissolveToPoint:(NSPoint)aPoint fromRect:(NSRect)aRect fraction:(float)aFloat

Composites the aRect portion of the image to the location specified by aPoint, just as compositeToPoint:fromRect:operation: does, but uses the dissolve operator rather than composite. aFloat is a fraction between 0.0 and 1.0 that specifies how much of the resulting composite will come from the NSImage. If the source image contains alpha, this operation may promote the destination NSWindow.

When printing, this method is identical to compositeToPoint:fromRect:operation:. The aFloat argument is ignored.

drawRepresentation:inRect:

− (BOOL)drawRepresentation:(NSImageRep *)imageRep inRect:(NSRect)rect

Fills the specified rectangle with the background color, then sends the imageRep a drawInRect: message to draw itself inside the rectangle (if the NSImage is scalable), or a drawAtPoint: message to draw itself at the location of the rectangle (if the NSImage is not scalable). The rectangle is located in the current window and is specified in the current coordinate system. This method returns the value returned by the drawInRect: or drawAtPoint: method, which indicates whether or not the representation was successfully drawn.

This method shouldn’t be called directly; the NSImage uses it to cache and print its representations. By overriding it in a subclass, you can change how representations appear in the cache, and thus how they’ll appear when composited. For example, your version of the method could scale or rotate the coordinate system, then send a message to super to perform this version.

If the background color is fully transparent and the image isn’t being cached by the NSImage, the rectangle won’t be filled before the representation draws.

initByReferencingFile:

− (id)initByReferencingFile:(NSString *)filename

Initializes the receiver, a newly allocated NSImage instance, for the file filename. This method initializes lazily: the NSImage doesn’t actually open filename or create image representations from its data until an application attempts to composite or requests information about the NSImage.

filename may be a full or relative pathname, and should include an extension that identifies the data type in the file. The mechanism that actually creates the image representation for filename will look for an NSImageRep subclass that handles that data type from among those registered with NSImage. By default, the files handled are those with the extensions “tiff”, “tif”, “bmp”, and “eps”.

After finishing the initialization, this method returns self. However, if the new instance can’t be initialized, it’s freed and nil is returned. Since this method doesn’t actually create image representations for the data, your application should do error checking before attempting to use the image; one way to do so is by invoking the isValid method to check whether the image can be drawn.

This method invokes setDataRetained:YES, thus enabling it to hold onto its file name. Note that if an image created with this method is archived, only the file name will be saved.

p	initWithBitmapHandle:

− (id)initWithBitmapHandle:(void *)bitmap

On Microsoft Windows platforms, initWithBitmapHandle: initializes the receiver, a newly allocated NSImage instance, with the contents of the Windows bitmap indicated by bitmap. If initWithBitmapHandle: is able to create one or more image representations, it returns self. Otherwise, the receiver is freed and nil is returned.

initWithContentsOfFile:

− (id)initWithContentsOfFile:(NSString *)filename

Initializes the receiver, a newly allocated NSImage instance, with the contents of the file filename. Unlike initByReferencingFile:, this method opens filename and creates one or more image representations from its data.

filename may be a full or relative pathname, and should include an extension that identifies the data type in the file. initWithContentsOfFile: will look for an NSImageRep subclass that handles that data type from among those registered with NSImage. By default, the files handled are those with the extensions “tiff”, “tif”, “bmp”, and “eps”.

After finishing the initialization, this method returns self. However, if at least one image representation can’t be created from the contents of the specified file, the receiver is freed and nil is returned.

initWithData:

− (id)initWithData:(NSData *)data

Initializes the receiver, a newly allocated NSImage instance, with the contents of the data object data. If initWithData: is able to create one or more image representations, it returns self. Otherwise, the receiver is freed and nil is returned.

p	initWithIconHandle:

− (id)initWithIconHandle:(void *)icon

On Microsoft Windows platforms, initWithIconHandle: initializes the receiver, a newly allocated NSImage instance, with the contents of the Windows icon indicated by icon. If initWithIconHandle: is able to create one or more image representations, it returns self. Otherwise, the receiver is freed and nil is returned.

initWithPasteboard:

− (id)initWithPasteboard:(NSPasteboard *)pasteboard

Initializes and returns the receiver, a newly allocated NSImage instance, from pasteboard. pasteboard should contain a type returned by one of the registered NSImageRep’s imageUnfilteredPasteboardTypes methods; the default types supported are NSPostscriptPboardType (NSEPSImageRep) and NSTIFFPboardType (NSBitmapImageRep). If pasteboard contains an NSFilenamesPboardType, the file name should have an extension returned by one of the registered NSImageRep’s imageUnfilteredFileTypes methods; the default types supported are “tiff”, “tif”, “bmp”, (all in NSBitmapImageRep) and “eps” (NSEPSImageRep).

If initWithPasteboard: is able to create one or more image representations, it returns self. Otherwise, the receiver is freed and nil is returned.

initWithSize:

− (id)initWithSize:(NSSize)aSize

Initializes the receiver, a newly allocated NSImage instance, to aSize and returns self. The size should be specified in units of the base coordinate system. Although you can initialize the receiver without specifying a size by passing a size of (0.0, 0.0) to initWithSize:, the receiver’s size must be set before the NSImage can be used.

See also:	− setSize:

isCachedSeparately

− (BOOL)isCachedSeparately

Returns YES if each representation of the image is cached separately in an off-screen window of its own, and NO if they can be cached in off-screen windows together with other images. A return of NO doesn’t mean that the windows are, in fact, shared, just that they can be. The default is NO.

isDataRetained

− (BOOL)isDataRetained

Returns YES if the NSImage retains the data needed to render the image, and NO if it doesn’t. The default is NO, except for images created with initByReferencingFile:, which should hold onto their file names. If the data is available in a file that won’t be moved or deleted, or if responsibility for drawing the image is delegated to another object with a custom method, there’s no reason for the NSImage to retain the data. However, if the NSImage reads image data from a file created with initWithContentsOfFile:, you may want to have it keep the data itself; for example, to render the same image on another device at a different resolution.

isFlipped

− (BOOL)isFlipped

Returns YES if a vertically flipped coordinate system is used when locating the image, and NO if it isn’t. The default is NO.

isValid

− (BOOL)isValid

Returns YES if a representation for the receiver can drawn in the cache, and NO if it can’t; for example, because the file from which it was initialized is non-existent, or the data in that file is invalid.

If no representations exist for the receiver, isValid first creates a cache with the default depth.

See also:	− initByReferencingFile:

lockFocus

− (void)lockFocus

Prepares for drawing of the best representation of the NSImage for the current device by making the off-screen window where the representation will be cached the current window and a coordinate system specific to the area where the image will be drawn the current coordinate system. If the receiver has no representations, lockFocus first creates one with the default depth. See “Choosing Representations” in the class description for information on how the “best” representation is chosen.

A successful lockFocus message must be balanced by a subsequent unlockFocus message to the same NSImage. These messages bracket the code that draws the image.

If lockFocus is unable to focus on the representation, it raises an NSImageCacheException.

See also:	− bestRepresentationForDevice:, − isValid, − prefersColorMatch, − representations

lockFocusOnRepresentation:

− (void)lockFocusOnRepresentation:(NSImageRep *)imageRepresentation

Prepares for drawing of the imageRepresentation representation by making the off-screen window where it will be cached the current window and a coordinate system specific to the area where the image will be drawn the current coordinate system. If imageRepresentation is nil, lockFocusOnRepresentation: acts like lockFocus, setting focus to the best representation for the NSImage. Otherwise, imageRepresentation must be one of the representations in the NSImage.

A successful lockFocusOnRepresentation: message must be balanced by a subsequent unlockFocus message to the same NSImage. These messages bracket the code that draws the image.

If lockFocusOnRepresentation: is unable to focus on the representation, it raises an NSImageCacheException.

See also:	− isValid

matchesOnMultipleResolution

− (BOOL)matchesOnMultipleResolution

Returns YES if the resolution of the device and the resolution specified for the image are considered to match if one is an integer multiple of the other, and NO if device and image resolutions are considered to match only if they are exactly the same. The default is YES.

name

− (NSString *)name

Returns the name assigned to the receiver, or nil if no name has been assigned.

prefersColorMatch

− (BOOL)prefersColorMatch

Returns YES if, when selecting the representation it will use, the NSImage first looks for one that matches the color capability of the rendering device (choosing a gray-scale representation for a monochrome device and a color representation for a color device), then if necessary narrows the selection by looking for one that matches the resolution of the device. If the return is NO, the NSImage first looks for a representation that matches the resolution of the device, then tries to match the representation to the color capability of the device. The default is YES.

recache

− (void)recache

Invalidates the off-screen caches of all representations and frees them. The next time any representation is composited, it will first be asked to redraw itself in the cache. NSCachedImageReps aren’t destroyed by this method.

If an image is likely not to be used again, it’s a good idea to free its caches, since that will reduce that amount of memory consumed by your program and therefore improve performance.

removeRepresentation:

− (void)removeRepresentation:(NSImageRep *)imageRep

Removes and releases the imageRep representation from the NSImage’s list of representations.

See also:	− representations

representations

− (NSArray *)representations

Returns an array containing all of the representations of the receiver.

scalesWhenResized

− (BOOL)scalesWhenResized

Returns YES if image representations are scaled to fit the size specified for the NSImage. If representations are not scalable, this method returns NO. The default is NO.

Representations created from data that specifies a size (for example, the “ImageLength” and “ImageWidth” fields of a TIFF representation or the bounding box of an EPS representation) will have the size the data specifies, which may differ from the size of the NSImage.

See also:	− setSize:

setBackgroundColor:

− (void)setBackgroundColor:(NSColor *)aColor

Sets the background color of the image. The default is NSColor’s clearColor, indicating a transparent background. The background color will be visible only for representations that don’t completely cover all the pixels within the image when drawing. This method doesn’t cause the receiver to recache itself.

See also:	− recache

setCacheDepthMatchesImageDepth:

− (void)setCacheDepthMatchesImageDepth:(BOOL)flag

Sets whether the application’s default depth limit applies to the off-screen windows where the NSImage’s representations are cached. If flag is NO (the default), window depths are instead determined by the specifications of the representations. This method doesn’t cause the receiver to recache itself.

See also:	− lockFocus, − recache

setCachedSeparately:

− (void)setCachedSeparately:(BOOL)flag

Sets whether each image representation will be cached in its own off-screen window or in a window shared with other images. If flag is YES, each representation is guaranteed to be in a separate window. If flag is NO (the default), a representation can be cached together with other images, though in practice it might not be.

If an NSImage is to be resized frequently, it’s more efficient to cache its representations separately.

This method doesn’t invalidate any existing caches.

See also:	− recache

setDataRetained:

− (void)setDataRetained:(BOOL)flag

Sets whether the NSImage retains the data needed to render the image. The default is NO. If the data is available in a file that won’t be moved or deleted, or if responsibility for drawing the image is delegated to another object with a custom method, there’s no reason for the NSImage to retain the data. However, if the NSImage reads image data from a file that could change, you may want to have it keep the data itself. Generally, this is useful to redraw the image to a device of different resolution.

If an image representation is created using initByReferencingFile:, the only data retained is the name of the source file.

setDelegate:

− (void)setDelegate:(id)anObject

Makes anObject the delegate of the receiver.

setFlipped:

− (void)setFlipped:(BOOL)flag

Determines whether the polarity of the y-axis is inverted when drawing an image. If flag is YES, the image will have its coordinate origin in the upper left corner and the positive y-axis will extend downward. This method affects only the coordinate system used to draw the image; it doesn’t affect the coordinate system for specifying portions of the image for methods like compositeToPoint:fromRect:operation: or dissolveToPoint:fromRect:fraction:.This method doesn’t cause the receiver to recache itself.

See also:	− recache

setMatchesOnMultipleResolution:

− (void)setMatchesOnMultipleResolution:(BOOL)flag

Sets whether image representations with resolutions that are integral multiples of the resolution of the device are considered to match the device. The default is YES.

setName:

− (BOOL)setName:(NSString *)aString

Registers the receiver under the name specified by aString, provided that no other NSImage is registered using that name. If the receiver is already registered under another name, setName: first unregisters the prior name. setName: returns YES unless another NSImage is registered using the name specified by aString, in which case setName: simply returns NO.

See also:	+ imageNamed:

setPrefersColorMatch:

− (void)setPrefersColorMatch:(BOOL)flag

Sets whether color matches are preferred over resolution matches when determining which representation to use. If flag is YES, the NSImage first tries to match the representation to the color capability of the rendering device (choosing a color representation for a color device and a gray-scale representation for a monochrome device), and then if necessary narrows the selection by trying to match the resolution of the representation to the resolution of the device. If flag is NO, the NsImage first tries to match the representation to the resolution of the device, and then tries to match it to the color capability of the device. The default is YES.

setScalesWhenResized:

− (void)setScalesWhenResized:(BOOL)flag

Sets whether representations with sizes that differ from the size of the NSImage will be scaled to fit. If flag is YES, representations are scaled to fit. The default is NO.

Generally, representations that are created through NSImage methods (such as initByReferencingFile:) have the same size as the NSImage. However, a representation that’s added with either addRepresentation: or addRepresentations: may have a different size, and representations created from data that specifies a size (for example, the “ImageLength” and “ImageWidth” fields of a TIFF representation or the bounding box of an EPS representation) will have the size specified.

This method doesn’t cause the receiving NSImage to recache itself when it is next composited.

See also:	− setSize:

setSize:

− (void)setSize:(NSSize)aSize

Sets the width and height of the image. The size referred to by aSize should be in units of the base coordinate system.

The size of an NSImage must be set before it can be used. You can change the size of an NSImage after it has been used, but changing it invalidates all its caches and frees them. When the image is next composited, the selected representation will draw itself in an off-screen window to recreate the cache.

If the size of the image hasn’t already been set when the NSImage is provided with a representation, the size will be set from the data. The bounding box is used to determine the size of an NSEPSImageRep. The TIFF fields “ImageLength” and “ImageWidth” are used to determine the size of an NSBitmapImageRep.

See also:	− initWithSize:, − setScalesWhenResized:

setUsesEPSOnResolutionMismatch:

− (void)setUsesEPSOnResolutionMismatch:(BOOL)flag

Sets whether EPS representations are preferred when there are no representations that match the resolution of the device. The default is NO.

See also:	− setMatchesOnMultipleResolution:

size

− (NSSize)size

Returns the size of the image. If no size has been set, and no size can be determined from any of the NSImage’s representations, the returned NSSize will have a width and height of 0.0.

TIFFRepresentation

− (NSData *)TIFFRepresentation

Returns a data object containing TIFF for all representations, using their default compressions.

TIFFRepresentationUsingCompression:factor:

− (NSData *)TIFFRepresentationUsingCompression:(NSTIFFCompression)comp factor:(float)aFloat

Returns a data object containing TIFF for all representations, using the specified compression type and compression factor. Legal values for comp can be found in NSBitmapImageRep.h, and are described in “Tiff Compression” in NSBitmapImageRep’s class description. aFloat provides a hint for those compression types that implement variable compression ratios; currently only JPEG compression uses a compression factor.

If the specified compression isn’t applicable, no compression is used. If a problem is encountered during generation of the TIFF, TIFFRepresentationUsingCompression:factor: raises an exception.

See also:	− TIFFRepresentationUsingCompression:factor: (NSBitmapImageRep)

unlockFocus

− (void)unlockFocus

Balances a previous lockFocus or lockFocusOnRepresentation: message. All successful lockFocus and lockFocusOnRepresentation: messages (those that don’t raise an NSImageCacheException) must be followed by a subsequent unlockFocus message. Those that raise should never be followed by unlockFocus.

usesEPSOnResolutionMismatch

− (BOOL)usesEPSOnResolutionMismatch

Returns whether EPS representations are preferred when there are no representations that match the resolution of the device. The default is NO.

See also:	− matchesOnMultipleResolution:

*nil*

imageDidNotDraw:inRect:

− (NSImage *)imageDidNotDraw:(id)sender inRect:(NSRect)aRect

Implemented by the delegate to respond to a message sent by the sender (an NSImage) when the sender was unable, for whatever reason, to composite or lock focus on its image. The delegate can:

•	return another NSImage to draw in the sender’s place,

•	draw the image itself and return nil, or

•	simply return nil to indicate that sender should give up the attempt at drawing the image.


NSImageCell
p NSImageCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSCell : NSObject

Conforms To:	NSCopying, NSCoding (from NSCell)

NSObject (from NSObject)

Declared In:	 AppKit/NSImageCell.h

Class Description

An NSImageCell displays a single NSImage in a frame. This class provides methods for choosing the frame, and for aligning and scaling the image to fit the frame.

The object value of an NSImageCell must be an NSImage, so if you use NSCell’s setObjectValue: method, be sure to supply an NSImage as an argument. Since an NSImage doesn’t need to be converted for display, you won’t use the NSCell methods relating to formatters.

An NSImageCell is usually associated with some kind of NSControl—an NSImageView, an NSMatrix, or an NSTableView. For more information, see the specifications for those classes.

Method Types

Aligning and scaling the image	− imageAlignment

− setImageAlignment:

− imageScaling

− setImageScaling:

Choosing the frame	− imageFrameStyle

− setImageFrameStyle:

Instance Methods

p	imageAlignment

− (NSImageAlignment)imageAlignment

Returns the position of the cell’s image in the frame. For a list of possible alignments, see setImageAlignment:.

p	imageFrameStyle

− (NSImageFrameStyle)imageFrameStyle

Returns the style of frame that appears around the image. For a list of frame styles, see setImageFrameStyle:.

p	imageScaling

− (NSImageScaling)imageScaling

Returns the way that the cell’s image alters to fit the frame. For a list of possible values, see setImageScaling:.

p	setImageAlignment:

− (void)setImageAlignment:(NSImageAlignment)alignment

Lets you specify the position of the image in the frame. The possible alignments are:

•	NSImageAlignLeft

•	NSImageAlignRight

•	NSImageAlignCenter

•	NSImageAlignTop

•	NSImageAlignBottom

•	NSImageAlignTopLeft

•	NSImageAlignTopRight

•	NSImageAlignBottomLeft

•	NSImageAlignBottomRight

The default alignment is NSImageAlignCenter.

See also:	− imageAlignment

p	setImageFrameStyle:

− (void)setImageFrameStyle:(NSImageFrameStyle)frameStyle

Lets you specify the kind of frame that borders the image . The possible styles are:

•	NSImageFrameNone—an invisible frame

•	NSImageFramePhoto—a thin black outline and a dropped shadow

•	NSImageFrameGrayBezel—a gray, concave bezel that makes the image look sunken

•	NSImageGroove—a thin groove that looks etched around the image

•	NSImageFrameButton—a convex bezel that makes the image stand out in relief, like a button

The default frameStyle is NSImageFrameNone.

See also:	− imageFrameStyle

p	setImageScaling:

− (void)setImageScaling:(NSImageScaling)scaling

Lets you specify the way that the image alters to fit the frame. The possible values are:

•	NSScaleProportionally. If the image is too large, it shrinks to fit inside the frame. If the image is too small, it expands. The proportions of the image are preserved.

•	NSScaleToFit. The image shrinks or expands, and its proportions distort, until it exactly fits the frame.

•	NSScaleNone. The size and proportions of the image don’t change. If the frame is too small to display the whole image, the edges of the image are trimmed off.

The default scaling is NSScaleProportionally.

The default scaling is NSScaleProportionally.

See also:	− imageScaling


NSImageRep

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSCopying

NSObject (NSObject)

Declared In:	AppKit/NSImageRep.h

Class Description

NSImageRep is a semi-abstract superclass (“semi,” because it has some instance variables and implementation of its own); each of its subclasses knows how to draw an image from a particular kind of source data. While an NSImageRep subclass can be used directly, it’s typically used through an NSImage object. An NSImage manages a group of representations, choosing the best one for the current output device.

There are four subclasses defined in the Application Kit:

Subclass	Source Data

NSBitmapImageRep	Tag Image File Format (TIFF), Windows bitmap (BMP) and other bitmap data

NSCachedImageRep	A rendered image, usually in an off-screen window

NSCustomImageRep	A delegated method that can draw the image

NSEPSImageRep	Encapsulated PostScript code (EPS)

You can define other NSImageRep subclasses for objects that render images from other types of source information. New subclasses must be added to the NSImageRep class registry by invoking the registerImageRepClass: class method. The NSImageRep subclass informs the registry of the data types it can support through its imageUnfilteredFileTypes, imageUnfilteredPasteboardTypes, and canInitWithData: class methods. Once an NSImageRep subclass is registered, an instance of that subclass is created any time NSImage encounters the type of data handled by that subclass.

Subclasses which deal with file and pasteboard types should implement imageUnfilteredFileTypes, imageUnfilteredPasteboardTypes, initWithData:, canInitWithData:, and, if they have the ability to read multiple images from a file, imageRepsWithData:. These last three should not do any filtering; all filtering is automatic.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

NSCopying	− copyWithZone:

Method Types

Creating an NSImageRep	+ imageRepsWithContentsOfFile:

+ imageRepsWithPasteboard:

+ imageRepWithContentsOfFile:

+ imageRepWithPasteboard:

Checking data types	+ canInitWithData:

+ canInitWithPasteboard:

+ imageFileTypes:

+ imagePasteboardTypes:

+ imageUnfilteredFileTypes:

+ imageUnfilteredPasteboardTypes:

Setting the size of the image	− setSize:

− size

Specifying information about the representation

− bitsPerSample

− colorSpaceName

− hasAlpha

− isOpaque

− pixelsHigh

− pixelsWide

− setAlpha:

− setBitsPerSample:

− setColorSpaceName:

− setOpaque:

− setPixelsHigh:

− setPixelsWide:

Drawing the image	− draw

− drawAtPoint:

− drawInRect:

Managing NSImageRep subclasses	+ imageRepClassForData:

+ imageRepClassForFileType:

+ imageRepClassForPasteboardType:

+ registeredImageRepClasses

+ registerImageRepClass:

+ unregisterImageRepClass:

*nil* Notifications

When the NSImageRep class registry changes

NSImageRepRegistryDidChangeNotification

Class Methods

canInitWithData:

+ (BOOL)canInitWithData:(NSData *)data

Overridden in subclasses to return YES if the receiver can initialize itself from data, and NO if it cannot. Note that this method doesn’t need to do a comprehensive check; it should return NO only if it knows that the receiver can’t initialize itself from data.

canInitWithPasteboard:

+ (BOOL)canInitWithPasteboard:(NSPasteboard *)pasteboard

Returns YES if the NSImageRep can handle the data represented by pasteboard, otherwise returns NO.

This method invokes the imageUnfilteredPasteboardTypes class method and checks the list of types returned by that method against the data types in pasteboard. If it finds a match, it returns YES. When creating a subclass of NSImageRep that accepts image data from a non-default pasteboard type, override the imageUnfilteredPasteboardTypes method to assure that this method returns the correct response.

imageFileTypes

+ (NSArray *)imageFileTypes

Returns an array of NSStrings representing all file types supported by NSImageRep or one of its subclasses. The list includes both those types returned by the imageUnfilteredFileTypes class method and those that can be converted to a supported type by a user-installed filter service. Don’t override this method when subclassing NSImageRep—it always returns a valid list for any subclass of NSImageRep that correctly overrides the imageUnfilteredFileTypes method.

imagePasteboardTypes

+ (NSArray *)imagePasteboardTypes

Returns an array of NSStrings representing all pasteboard types supported by NSImageRep or one of its subclasses. The list includes both those types returned by the imageUnfilteredPasteboardTypes class method and those that can be converted by a user-installed filter service to a supported type. Don’t override this method when subclassing NSImageRep—it always returns a valid list for any subclass of NSImageRep that correctly overrides the imageUnfilteredPasteboardTypes method.

imageRepClassForData:

+ (Class)imageRepClassForData:(NSData *)data

Returns the NSImageRep subclass that handles data of type data, or Nil if the NSImage class registry contains no subclasses that handle data of the specified type.

imageRepClassForFileType:

+ (Class)imageRepClassForFileType:(NSString *)type

Returns the NSImageRep subclass that handles files of type type, or Nil if the NSImage class registry contains no subclasses that handle files of the specified type.

imageRepClassForPasteboardType:

+ (Class)imageRepClassForPasteboardType:(NSString *)type

Returns the NSImageRep subclass that handles pasteboard data of type type, or Nil if the NSImage class registry contains no subclasses that handle pasteboard data of the specified type.

imageRepWithContentsOfFile:

+ (id)imageRepWithContentsOfFile:(NSString *)filename

If sent to the NSImageRep class object, this method returns a newly-allocated instance of a subclass of NSImageRep (chosen through the use of imageRepClassForFileType:) that’s initialized with the contents of the file filename. If sent to a subclass of NSImageRep that recognizes the type of file specified by filename, it returns an instance of that subclass initialized with the contents of the file filename

imageRepWithContentsOfFile: returns nil in any of the following cases:

•	The message is sent to the NSImageRep class object, and there are no subclasses in the NSImageRep class registry that handle data of the type indicated by filename.

•	The message is sent to a subclass of NSImageRep, and that subclass doesn’t handle data of the type indicated by filename.

•	The NSImageRep subclass is unable to initialize itself with the contents of filename.

filename may be a full or relative pathname, and should include an extension that identifies the data type in the file. By default, the files handled are those with the extensions “tiff”, “tif”, “bmp”, and “eps”.

The NSImageRep subclass is initialized by creating an NSData object based on the contents of the file, then passing it to imageRepWithData:.

See also:	+ imageFileTypes

imageRepWithPasteboard:

+ (id)imageRepWithPasteboard:(NSPasteboard *)pasteboard

If sent to the NSImageRep class object, this method returns a newly-allocated instance of a subclass of NSImageRep that’s initialized with the data in pasteboard. If sent to a subclass of NSImageRep that recognizes the type of data contained in pasteboard, it returns an instance of that subclass initialized with the data in pasteboard

imageRepWithPasteboard: returns nil in any of the following cases:

•	The message is sent to the NSImageRep class object, and there are no subclasses in the NSImageRep class registry that handle data of the type contained in pasteboard.

•	The message is sent to a subclass of NSImageRep, and that subclass doesn’t handle data of the type contained in pasteboard.

•	The NSImageRep subclass is unable to initialize itself with the contents of pasteboard.

The NSImageRep subclass is initialized by creating an NSData object based on the data in pasteboard, then passing it to imageRepWithData:.

See also:	+ imagePasteboardTypes

imageRepsWithContentsOfFile:

+ (NSArray *)imageRepsWithContentsOfFile:(NSString *)filename

If sent to the NSImageRep class object, this method returns an array of objects (all newly-allocated instances of a subclass of NSImageRep, chosen through the use of imageRepClassForFileType:) that have been initialized with the contents of the file filename. If sent to a subclass of NSImageRep that recognizes the type of file specified by filename, it returns an array of objects (all instances of that subclass) that have been initialized with the contents of the file filename

imageRepsWithContentsOfFile: returns nil in any of the following cases:

•	The message is sent to the NSImageRep class object, and there are no subclasses in the NSImageRep class registry that handle data of the type indicated by filename.

•	The message is sent to a subclass of NSImageRep, and that subclass doesn’t handle data of the type indicated by filename.

•	The NSImageRep subclass is unable to initialize itself with the contents of filename.

filename may be a full or relative pathname, and should include an extension that identifies the data type in the file. By default, the files handled are those with the extensions “tiff”, “tif”, “bmp”, and “eps”.

The NSImageRep subclass is initialized by creating an NSData object based on the contents of the file, then passing it to imageRepsWithData:.

See also:	+ imageFileTypes

imageRepsWithPasteboard:

+ (NSArray *)imageRepsWithPasteboard:(NSPasteboard *)pasteboard

If sent to the NSImageRep class object, this method returns an array of objects (all newly-allocated instances of a subclass of NSImageRep) that have been initialized with the data in pasteboard. If sent to a subclass of NSImageRep that recognizes the type of data contained in pasteboard, it returns an array of objects (all instances of that subclass) initialized with the data in pasteboard

imageRepsWithPasteboard: returns nil in any of the following cases:

•	The message is sent to the NSImageRep class object, and there are no subclasses in the NSImageRep class registry that handle data of the type contained in pasteboard.

•	The message is sent to a subclass of NSImageRep, and that subclass doesn’t handle data of the type contained in pasteboard.

•	The NSImageRep subclass is unable to initialize itself with the contents of pasteboard.

The NSImageRep subclass is initialized by creating an NSData object based on the data in pasteboard, then passing it to imageRepsWithData:.

See also:	+ imagePasteboardTypes

imageUnfilteredFileTypes

+ (NSArray *)imageUnfilteredFileTypes

Returns an array of NSStrings representing all file types (extensions) supported by the NSImageRep. By default, the returned array is empty.

When creating a subclass of NSImageRep, override this method to return a list of strings representing the supported file types. For example, NSBitmapImageRep implements the following code for this method:

+ (NSArray *)imageUnfilteredFileTypes {

    static NSArray *types = nil;

    if (!types) types = [[NSArray alloc]

        initWithObjects:@"tiff", @"tif", @"bmp", nil];

    return types;

}

If your subclass supports the types supported by its superclass, you must explicitly get the array of types from the superclass and put them in the array returned by this method.

See also:	+ imageFileTypes, + imageUnfilteredFileTypes: (NSImage)

imageUnfilteredPasteboardTypes

+ (NSArray *)imageUnfilteredPasteboardTypes

Returns an array representing all pasteboard types supported by the NSImageRep. By default, the returned array is empty.

When creating a subclass of NSImageRep, override this method to return a list representing the supported pasteboard types. For example, NSBitmapImageRep implements the following code for this method:

+ (NSArray *)imageUnfilteredPasteboardTypes {

    static NSArray *types = nil;

    if (!types) types = [[NSArray alloc] initWithObjects:NSTIFFPboardType, nil];

    return types;

}

If your subclass supports the types supported by its superclass, you must explicitly get the list of types from the superclass and add them to the array returned by this method.

See also:	+ imagePasteboardTypes, + imageUnfilteredPasteboardTypes: (NSImage)

registerImageRepClass:

+ (void)registerImageRepClass:(Class)imageRepClass

Adds imageRepClass to the registry of available NSImageRep classes. This method posts the NSImageRepRegistryChangedNotification notification, along with the receiving object, to the default notification center.

A good place to add image representation classes to the registry is in the load class method.

See also:	+ load (NSObject)

registeredImageRepClasses

+ (NSArray *)registeredImageRepClasses

Returns an array containing the registered NSImageRep classes.

unregisterImageRepClass:

+ (void)unregisterImageRepClass:(Class)imageRepClass

Removes imageRepClass from the registry of available NSImageRep classes. This method posts the NSImageRepRegistryChangedNotification notification, along with the receiving object, to the default notification center.

Instance Methods

bitsPerSample

− (int)bitsPerSample

Returns the number of bits used to specify a single pixel in each component of the data.

colorSpaceName

− (NSString *)colorSpaceName

Returns the name if the image’s color space, or NSCalibratedRGBColorSpace if no name has been assigned.

draw

− (BOOL)draw

Implemented by subclasses to draw the image at location (0.0, 0.0) in the current coordinate system. Subclass methods return YES if the image is successfully drawn, and NO if it isn’t. This version of the method simply returns YES.

drawAtPoint:

− (BOOL)drawAtPoint:(NSPoint)aPoint

Sets the current coordinates to those indicated by aPoint, invokes the receiver’s draw method draw the image at that point, then restores the current coordinates to their original setting. If aPoint is (0.0, 0.0), drawAtPoint: simply invokes draw.

This method returns NO without translating, scaling, or drawing if the size of the image has not been set. Otherwise it returns the value returned by the draw method, which indicates whether the image is successfully drawn.

See also:	− setSize:

drawInRect:

− (BOOL)drawInRect:(NSRect)rect

Draws the image so that it fits inside the rectangle referred to by rect. The current coordinates are set to the point specified in the rectangle and are scaled so the image will fit within the rectangle. The receiver’s draw method is then invoked to draw the image. After draw has been invoked, the current coordinates and scale factors are restored to their original settings.

This method returns NO without translating, scaling, or drawing if the size of the image has not been set. Otherwise it returns the value returned by the draw method, which indicates whether the image is successfully drawn.

See also:	− setSize:

hasAlpha

− (BOOL)hasAlpha

Returns YES if the receiver has been informed that the image has a coverage component (alpha), and NO if not.

isOpaque

− (BOOL)isOpaque

Returns YES if the receiver is opaque; NO otherwise. Use this method to test whether an NSImageRep completely covers the area within the rectangle returned by size:. Use the method setOpaque: to set the value returned by this method.

pixelsHigh

− (int)pixelsHigh

Returns the height of the image in pixels, as specified in the image data.

See also:	− size:

pixelsWide

− (int)pixelsWide

Returns the width of the image in pixels, as specified in the image data.

See also:	− size:

setAlpha:

− (void)setAlpha:(BOOL)flag

Informs the NSImageRep whether the image has an alpha component. flag should be YES if it does, and NO if it doesn’t.

setBitsPerSample:

− (void)setBitsPerSample:(int)anInt

Informs the NSImageRep that the image has anInt bits of data for each pixel in each component.

setColorSpaceName:

− (void)setColorSpaceName:(NSString *)string

Informs the receiver of the image’s color space. By default, an NSImageRep’s color space name is NSCalibratedRGBColorSpace. Color space names are defined as part of the NSColor class, in NSGraphics.h. The following are valid color space names:

NSCalibratedWhiteColorSpace

NSCalibratedBlackColorSpace

NSCalibratedRGBColorSpace

NSDeviceWhiteColorSpace

NSDeviceBlackColorSpace

NSDeviceRGBColorSpace

NSDeviceCMYKColorSpace

NSNamedColorSpace

NSCustomColorSpace

setOpaque:

− (void)setOpaque:(BOOL)flag

Sets opacity of the NSImageRep’s image. If flag is YES, the image is opaque.

setPixelsHigh:

− (void)setPixelsHigh:(int)anInt

Informs the NSImageRep that the data specifies an image anInt pixels high.

See also:	− setSize:

setPixelsWide:

− (void)setPixelsWide:(int)anInt

Informs the NSImageRep that the data specifies an image anInt pixels wide.

See also:	− setSize:

setSize:

− (void)setSize:(NSSize)aSize

Sets the size of the image in units of the base coordinate system. This determines the size of the image when it’s rendered; it’s not necessarily the same as the width and height of the image in pixels as specified in the image data. You must set the image size before you can render it.

See also:	− draw, − setPixelsHigh:, − setPixelsWide:

size

− (NSSize)size

Returns the size of the image in units of the base coordinate system. This is the size of the image when it’s rendered; it’s not necessarily the same as the width and height of the image in pixels as specified in the image data.

See also:	− pixelsHigh:, − pixelsWide:

Notifications

NSImageRep declares and posts the following notification. In addition, it posts notifications that are declared by its superclass, NSObject. See the NSObject class specification for more information.

NSImageRepRegistryDidChangeNotification

Notification Object	The notifying NSImageRep.

Userinfo	none

Posted when the NSImageRep class registry changes, either through the use of registerImageRepClass: or unregisterImageRepClass:.


NSImageView
p NSImageView

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSControl: NSView: NSResponder: NSObject

Conforms To:	NSCoding (from NSResponder)

NSObject (from NSObject)

Declared In:	AppKit/NSImageView.h

Class Description

An NSImageView displays a single NSImage in a frame. The NSImageView class provides methods for choosing the image, choosing the frame, and for aligning and scaling the image to fit the frame.

For an NSControl, NSImageView is quite limited in its ability to respond to user events: the only thing a user can do is drag in a new image. When it receives the new image, the NSImageView replaces its old image and sends its action message to its target. Even this low level of interactivity can be disabled: you can send the NSImageView the message setEditable:NO.

For more information, see the class specification for NSImageCell.

Method Types

Choosing the image	− image

− setImage:

Choosing the frame	− imageFrameStyle

− setImageFrameStyle:

Aligning and scaling the image	− imageAlignment

− setImageAlignment:

− imageScaling

− setImageScaling:

Responding to user events	− isEditable

− setEditable:

Instance Methods

p	image

− (NSImage *)image

Returns the NSImage displayed by the NSImageView.

See also:	 − setImage:

p	imageAlignment

− (NSImageAlignment)imageAlignment

Returns the position of the cell’s image in the frame. For a list of possible alignments, see setImageAlignment:.

p	imageFrameStyle

− (NSImageFrameStyle)imageFrameStyle

Returns the style of frame that appears around the image. For a list of frame styles, see setImageFrameStyle:.

p	imageScaling

− (NSImageScaling)imageScaling

Returns the way that the cell’s image alters to fit the frame. For a list of possible values, see setImageScaling:.

p	isEditable

− (BOOL)isEditable

Returns whether the user can drag a new image into the frame. The default is YES.

See also:	 − setEditable:

p	setEditable:

− (void)setEditable:(BOOL)flag

Specifies whether the user can drag a new image into the frame.

See also:	− isEditable

p	setImage:

− (void)setImage:(NSImage *)image

Lets you specify the image that the NSImageView displays.

See also:	 − image

p	setImageAlignment:

− (void)setImageAlignment:(NSImageAlignment)alignment

Lets you specify the position of the image in the frame. The possible alignments are:

•	NSImageAlignLeft

•	NSImageAlignRight

•	NSImageAlignCenter

•	NSImageAlignTop

•	NSImageAlignBottom

•	NSImageAlignTopLeft

•	NSImageAlignTopRight

•	NSImageAlignBottomLeft

•	NSImageAlignBottomRight

The default alignment is NSImageAlignCenter.

See also:	− imageAlignment

p	setImageFrameStyle:

− (void)setImageFrameStyle:(NSImageFrameStyle)frameStyle

Lets you specify the kind of frame that borders the image . The possible styles are:

•	NSImageFrameNone—an invisible frame

•	NSImageFramePhoto—a thin black outline and a dropped shadow

•	NSImageFrameGrayBezel—a gray, concave bezel that makes the image look sunken

•	NSImageGroove—a thin groove that looks etched around the image

•	NSImageFrameButton—a convex bezel that makes the image stand out in relief, like a button

The default frameStyle is NSImageFrameNone.

See also:	− imageFrameStyle

p	setImageScaling:

− (void)setImageScaling:(NSImageScaling)scaling

Lets you specify the way that the image alters to fit the frame. The possible values are:

•	NSScaleProportionally. If the image is too large, it shrinks to fit inside the frame. If the image is too small, it expands. The proportions of the image are preserved.

•	NSScaleToFit. The image shrinks or expands, and its proportions distort, until it exactly fits the frame.

•	NSScaleNone. The size and proportions of the image don’t change. If the frame is too small to display the whole image, the edges of the image are trimmed off.

The default scaling is NSScaleProportionally.

See also:	− imageScaling


NSLayoutManager
p NSLayoutManager

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSLayoutManager.h

Class Description

An NSLayoutManager coordinates the layout and display of characters held in an NSTextStorage object. It maps Unicode character codes to glyphs, sets the glyphs in a series of NSTextContainers, and displays them in a series of NSTextViews. In addition to its core function of laying out text, an NSLayoutManager coordinates its NSTextViews, provides services to those NSTextViews to support NSRulerViews for editing paragraph styles, and handles the layout and display of text attributes not inherent in glyphs (such as underline or strikethrough). You can create a subclass of NSLayoutManager to handle additional text attributes, whether inherent or not.

Method Types

Creating an instance	− init

Setting the text storage	− setTextStorage:

− textStorage

− replaceTextStorage:

Setting text containers	− textContainers

− addTextContainer:

− insertTextContainer:atIndex:

− removeTextContainerAtIndex:

Invalidating glyphs and layout	− invalidateGlyphsForCharacterRange:changeInLength:

actualCharacterRange:

− invalidateLayoutForCharacterRange:isSoft:

actualCharacterRange:

− invalidateDisplayForGlyphRange:

− textContainerChangedGeometry:

− textStorage:edited:range:changeInLength:

invalidatedRange:

Turning background layout on/off	− setBackgroundLayoutEnabled:

− backgroundLayoutEnabled

Accessing glyphs	− insertGlyph:atGlyphIndex:characterIndex:

− glyphAtIndex:

− glyphAtIndex:isValidIndex:

− replaceGlyphAtIndex:withGlyph:

− getGlyphs:range:

− deleteGlyphsInRange:

− numberOfGlyphs

Mapping characters to glyphs	− setCharacterIndex:forGlyphAtIndex:

− characterIndexForGlyphAtIndex:

− characterRangeForGlyphRange:actualGlyphRange:

− glyphRangeForCharacterRange:actualCharacterRange:

Setting glyph attributes	− setIntAttribute:value:forGlyphAtIndex:

− intAttribute:forGlyphAtIndex:

Handling layout for text containers	− setTextContainer:forGlyphRange:

− glyphRangeForTextContainer:

− textContainerForGlyphAtIndex:effectiveRange:

− usedRectForTextContainer:

Handling line fragment rectangles	− setLineFragmentRect:forGlyphRange:usedRect:

− lineFragmentRectForGlyphAtIndex:effectiveRange:

− lineFragmentUsedRectForGlyphAtIndex:effectiveRange:

− setExtraLineFragmentRect:usedRect:textContainer:

− extraLineFragmentRect

− extraLineFragmentUsedRect

− extraLineFragmentTextContainer

− setDrawsOutsideLineFragment:forGlyphAtIndex:

− drawsOutsideLineFragmentForGlyphAtIndex:

Layout of glyphs	− setLocation:forStartOfGlyphRange:

− locationForGlyphAtIndex:

 − rangeOfNominallySpacedGlyphsContainingIndex:

− rectArrayForCharacterRange:

withinSelectedCharacterRange:

inTextContainer:rectCount:

− rectArrayForGlyphRange:withinSelectedGlyphRange:

 inTextContainer:rectCount:

− boundingRectForGlyphRange:inTextContainer:

− glyphRangeForBoundingRect:inTextContainer:

− glyphRangeForBoundingRectWithoutAdditionalLayout:

inTextContainer:

− glyphIndexForPoint:inTextContainer:

fractionOfDistanceThroughGlyph:

Display of special glyphs	− setNotShownAttribute:forGlyphAtIndex:

− notShownAttributeForGlyphAtIndex:

− setShowsInvisibleCharacters:

− showsInvisibleCharacters

− setShowsControlCharacters:

− showsControlCharacters

Finding unlaid characters/glyphs	− getFirstUnlaidCharacterIndex:glyphIndex:

Using screen fonts	− setUsesScreenFonts:

− usesScreenFonts

− substituteFontForFont:

Handling rulers	− rulerAccessoryViewForTextView:paragraphStyle:ruler:enabled:

− rulerMarkersForTextView:paragraphStyle:ruler:

Managing the responder chain	− layoutManagerOwnsFirstResponderInWindow:

− firstTextView

− textViewForBeginningOfSelection

Drawing	− drawBackgroundForGlyphRange:atPoint:

− drawGlyphsForGlyphRange:atPoint:

− drawUnderlineForGlyphRange:underlineType:baselineOffset:

lineFragmentRect:lineFragmentGlyphRange:containerOrigin:

− underlineGlyphRange:underlineType:lineFragmentRect:

lineFragmentGlyphRange:containerOrigin:

Setting the delegate	− setDelegate:

− delegate

Instance Methods

p	addTextContainer:

− (void)addTextContainer:(NSTextContainer *)aTextContainer

Appends aTextContainer to the series of NSTextContainers where the receiver arranges text. Invalidates glyphs and layout as needed, but doesn’t perform glyph generation or layout.

See also:	− insertTextContainer:atIndex:, − removeTextContainerAtIndex:, − textContainers, − invalidateGlyphsForCharacterRange:changeInLength:actualCharacterRange:, − invalidateLayoutForCharacterRange:isSoft:actualCharacterRange:

p	backgroundLayoutEnabled

− (BOOL)backgroundLayoutEnabled

Returns YES if the receiver generates glyphs and lays out text when the application’s run loop is idle, NO if it only performs glyph generation and layout when necessary.

See also:	− setBackgroundLayoutEnabled:

p	boundingRectForGlyphRange:inTextContainer:

− (NSRect)boundingRectForGlyphRange:(NSRange)glyphRange inTextContainer:(NSTextContainer *)aTextContainer

Returns a single bounding rectangle enclosing all glyphs and other marks drawn in aTextContainer for glyphRange, including glyphs that draw outside their line fragment rectangles and text attributes such as underlining. This method is useful for determining the area that needs to be redrawn when a range of glyphs changes.

Performs glyph generation and layout if needed.

See also:	− glyphRangeForTextContainer:, − drawsOutsideLineFragmentForGlyphAtIndex:

p	characterIndexForGlyphAtIndex:

− (unsigned int)characterIndexForGlyphAtIndex:(unsigned int)glyphIndex

Returns the index in the NSTextStorage for the first character mapped to the glyph at glyphIndex within the receiver. In many cases it’s better to use the range-mapping methods, characterRangeForGlyphRange:actualGlyphRange: and glyphRangeForCharacterRange:actualCharacterRange:, which provide more comprehensive information.

Performs glyph generation if needed.

p	characterRangeForGlyphRange:actualGlyphRange:

− (NSRange)characterRangeForGlyphRange:(NSRange)glyphRange actualGlyphRange:(NSRange *)actualGlyphRange

Returns the range for the characters in the receiver’s text store that are mapped to the glyphs in glyphRange. If actualGlyphRange is non-NULL, expands the requested range as needed so that it identifies all glyphs mapped to those characters and returns the new range by reference in actualGlyphRange.

Suppose the text store begins with the character “Ö” and the glyph cache contains “O” and “¨”. If you get the character range for the glyph range {0, 1} or {1, 1}, actualGlyphRange is returned as {0, 2}, indicating that both of the glyphs are mapped to the character “Ö”.

Performs glyph generation if needed.

See also:	− characterIndexForGlyphAtIndex:, − glyphRangeForCharacterRange:actualCharacterRange:

p	delegate

− (id)delegate

Returns the receiver’s delegate.

See also:	− setDelegate:

p	deleteGlyphsInRange:

− (void)deleteGlyphsInRange:(NSRange)glyphRange

Deletes the glyphs in glyphRange.

This method is for use by the glyph generation mechanism, and doesn’t perform any invalidation or generation of the glyphs or layout. You should never directly invoke this method.

See also:	− insertGlyph:atGlyphIndex:characterIndex:

p	drawBackgroundForGlyphRange:atPoint:

− (void)drawBackgroundForGlyphRange:(NSRange)glyphRange atPoint:(NSPoint)containerOrigin

Draws background marks for glyphRange, which must lie completely within a single NSTextContainer. containerOrigin indicates the position of the NSTextContainer in the coordinate system of the NSView being drawn. This method must be invoked with the graphics focus locked on that NSView.

Background marks are such things as selection highlighting, text background color, and any background for marked text.

Performs glyph generation and layout if needed.

See also:	− drawGlyphsForGlyphRange:atPoint:, − glyphRangeForTextContainer:, − textContainerOrigin (NSTextView)

p	drawGlyphsForGlyphRange:atPoint:

− (void)drawGlyphsForGlyphRange:(NSRange)glyphRange atPoint:(NSPoint)containerOrigin

Draws the glyphs in glyphRange, which must lie completely within a single NSTextContainer. containerOrigin indicates the position of the NSTextContainer in the coordinate system of the NSView being drawn. This method must be invoked with the graphics focus locked on that NSView.

Performs glyph generation and layout if needed.

See also:	− drawBackgroundForGlyphRange:atPoint:, − glyphRangeForTextContainer:, − textContainerOrigin (NSTextView)

p	drawsOutsideLineFragmentForGlyphAtIndex:

− (BOOL)drawsOutsideLineFragmentForGlyphAtIndex:(unsigned int)glyphIndex

Returns YES if the glyph at glyphIndex exceeds the bounds of the line fragment where it’s laid out, NO otherwise. This can happen when text is set at a fixed line height. For example, if the user specifies a fixed line height of 12 points and sets the font size to 24 points, the glyphs will exceed their layout rectangles.

Glyphs that draw outside their line fragment rectangles aren’t considered when calculating enclosing rectangles with the rectArrayForCharacterRange:withinSelectedCharacterRange:inTextContainer:rectCount: and rectArrayForGlyphRange:withinSelectedGlyphRange:inTextContainer:rectCount: methods. They are, however, considered by boundingRectForGlyphRange:inTextContainer:

Performs glyph generation and layout if needed.

p	drawUnderlineForGlyphRange:underlineType:baselineOffset:lineFragmentRect:

lineFragmentGlyphRange:containerOrigin:

− (void)drawUnderlineForGlyphRange:(NSRange)glyphRange

underlineType:(int)underlineType

baselineOffset:(float)baselineOffset

lineFragmentRect:(NSRect)lineRect

lineFragmentGlyphRange:(NSRange)lineGlyphRange

containerOrigin:(NSPoint)containerOrigin

Draws underlining for the glyphs in glyphRange, which must belong to a single line fragment rectangle (as returned by lineFragmentRectForGlyphAtIndex:effectiveRange:). underlineType indicates the style of underlining to draw; NSLayoutManager accepts only NSSingleUnderlineStyle, but subclasses can define their own underline styles. baselineOffset indicates how far below the text baseline the underline should be drawn; it’s usually a positive value. lineRect is the line fragment rectangle containing the glyphs to draw underlining for, and lineGlyphRange is the range of all glyphs within that line fragment rectangle. containerOrigin is the origin of the line fragment rectangle’s NSTextContainer in its NSTextView.

This method is invoked automatically by underlineGlyphRange:...; you should rarely need to invoke it directly.

See also:	− textContainerForGlyphAtIndex:effectiveRange:, − textContainerOrigin (NSTextView)

p	extraLineFragmentRect

− (NSRect)extraLineFragmentRect

Returns the rectangle defining the extra line fragment for the insertion point at the end of a text (either in an empty text or after a final paragraph separator). The rectangle is defined in the coordinate system of its NSTextContainer. Returns NSZeroRect if there is no such rectangle.

See also:	− extraLineFragmentUsedRect, − extraLineFragmentTextContainer, − setExtraLineFragmentRect:usedRect:textContainer:

p	extraLineFragmentTextContainer

− (NSTextContainer *)extraLineFragmentTextContainer

Returns the NSTextContainer that contains the extra line fragment rectangle, or nil if there is no extra line fragment rectangle. This rectangle is used to display the insertion point for the insertion point at the end of a text (either in an empty text or after a final paragraph separator).

See also:	− extraLineFragmentRect, − extraLineFragmentUsedRect, − setExtraLineFragmentRect:usedRect:textContainer:

p	extraLineFragmentUsedRect

− (NSRect)extraLineFragmentUsedRect

Returns the rectangle enclosing the insertion point drawn in the extra line fragment rectangle. The rectangle is defined in the coordinate system of its NSTextContainer. Returns NSZeroRect if there is no extra line fragment rectangle.

The extra line fragment used rectangle is twice as wide (or tall) as the NSTextContainer’s line fragment padding, with the insertion point itself in the middle.

See also:	− extraLineFragmentRect, − extraLineFragmentTextConainer, − setExtraLineFragmentRect:usedRect:textContainer:

p	firstTextView

− (NSTextView *)firstTextView

Returns the first NSTextView in the receiver’s series of text views. This is the object of various NSText and NSTextView notifications posted.

p	getFirstUnlaidCharacterIndex:glyphIndex:

− (void)getFirstUnlaidCharacterIndex:(unsigned int *)charIndex glyphIndex:(unsigned int *)glyphIndex

Returns by reference in charIndex and glyphIndex the indexes for the first character and glyph that have invalid layout information. Either parameter may be NULL, in which case the receiver simply ignores it.

p	getGlyphs:range:

− (unsigned int)getGlyphs:(NSGlyph *)glyphArray range:(NSRange)glyphRange

Fills glyphArray with displayable glyphs from glyphRange and returns the actual number of glyphs filled (which may be smaller than glyphRange’s length if some glyphs aren’t drawn—for example, tab and newline characters). Raises an NSRangeException if the range specified exceeds the bounds of the actual glyph range for the receiver.

Performs glyph generation if needed.

See also:	− glyphAtIndex:, − glyphAtIndex:isValidIndex:, − notShownAttributeForGlyphAtIndex:

p	glyphAtIndex:

− (NSGlyph)glyphAtIndex:(unsigned int)glyphIndex

Returns the glyph at glyphIndex. Raises an NSRangeException if glyphIndex is out of bounds.

Performs glyph generation if needed. To avoid an exception with glyphAtIndex: you must first check the glyph index against the number of glyphs, which requires generating all glyphs. Another method, glyphAtIndex:isValidIndex:, generates glyphs only up to the one requested, so using it can be more efficient.

See also:	− getGlyphs:range:

p	glyphAtIndex:isValidIndex:

− (NSGlyph)glyphAtIndex:(unsigned int)glyphIndex isValidIndex:(BOOL *)flag

If glyphIndex is valid, returns the glyph at glyphIndex and sets flag to YES. Otherwise sets flag to NO (in which case the return value is meaningless).

Performs glyph generation if needed.

See also:	− getGlyphs:range:, − glyphAtIndex:

p	glyphIndexForPoint:inTextContainer:fractionOfDistanceThroughGlyph:

− (unsigned int)glyphIndexForPoint:(NSPoint)aPoint

inTextContainer:(NSTextContainer *)aTextContainer

fractionOfDistanceThroughGlyph:(float *)partialFraction

Returns the index for the glyph nearest aPoint within aTextContainer. aPoint is expressed in aTextContainer’s coordinate system. If partialFraction is non-NULL the ratio of the distance into the glyph relative to the next glyph (in the appropriate sweep direction) is returned by reference in partialFraction.

Note:	NSLayoutManager currently supports only left-to-right sweep.

For purposes such as dragging out a selection or placing the insertion point, a partial percentage less than or equal to 0.5 indicates that aPoint should be considered as falling before the glyph index returned; a partial percentage greater than 0.5 indicates that it should be considered as falling after the glyph index returned. If the nearest glyph doesn’t lie under aPoint at all (for example, if aPoint is beyond the beginning or end of a line) this ratio will be 0 or 1.

Suppose the glyph stream contains the glyphs “A” and “b”, with the width of “A” being 13 points. If the user clicks at a location 8 points into “A”, partialFraction is 8 ÷ 13, or 0.615. In this case, the point given should be considered as falling between “A” and “b” for purposes such as dragging out a selection or placing the insertion point.

Performs glyph generation and layout if needed.

p	glyphRangeForBoundingRect:inTextContainer:

− (NSRange)glyphRangeForBoundingRect:(NSRect)aRect inTextContainer:(NSTextContainer *)aTextContainer

Returns the smallest contiguous range for glyphs that are laid out wholly or partially within aRect in aTextContainer. The range returned can include glyphs that don’t fall inside or intersect aRect, though the first and last glyphs in the range always do. This method is used to determine which glyphs need to be displayed within a given rectangle.

Performs glyph generation and layout if needed.

See also:	− glyphRangeForBoundingRectWithoutAdditionalLayout:inTextContainer:

p	glyphRangeForBoundingRectWithoutAdditionalLayout:inTextContainer:

− (NSRange)glyphRangeForBoundingRectWithoutAdditionalLayout:(NSRect)bounds inTextContainer:(NSTextContainer *)container

Returns the smallest contiguous range for glyphs that are laid out wholly or partially within aRect in aTextContainer. The range returned can include glyphs which don’t fall inside or intersect aRect, though the first and last glyphs in the range always do.

Unlike glyphRangeForBoundingRect:inTextContainer:, this method doesn’t perform glyph generation or layout. Its results, though faster, can be incorrect. This method is primarily for use by NSTextView; you should rarely need to use it yourself.

See also:	− glyphRangeForBoundingRect:inTextContainer:

p	glyphRangeForCharacterRange:actualCharacterRange:

− (NSRange)glyphRangeForCharacterRange:(NSRange)charRange actualCharacterRange:(NSRange *)actualCharRange

Returns the range for the glyphs mapped to the characters of the text store in charRange. If actualCharRange is non-NULL, expands the requested range as needed so that it identifies all characters mapped to those glyphs and returns the new range by reference in actualCharRange.

Suppose the text store contains the characters “n˜” and the glyph cache contains “ñ”. If you get the glyph range for the character range {0, 1} or {1, 1}, actualCharRange is returned as {0, 2}, indicating both of the characters mapped to the glyph “ñ”.

Performs glyph generation if needed.

See also:	− characterIndexForGlyphAtIndex:, − glyphRangeForCharacterRange:actualCharacterRange

p	glyphRangeForTextContainer:

− (NSRange)glyphRangeForTextContainer:(NSTextContainer *)aTextContainer

Returns the range for glyphs laid out within aTextContainer.

Performs glyph generation and layout if needed.

p	init

− (id)init

Initializes the receiver, a newly created NSLayoutManager object. This is the designated initializer for the NSLayoutManager class. Returns self.

See also:	− addLayoutManager: (NSTextStorage), − addTextContainer:

p	insertGlyph:atGlyphIndex:characterIndex:

− (void)insertGlyph:(NSGlyph)aGlyph

atGlyphIndex:(unsigned int)glyphIndex

characterIndex:(unsigned int)charIndex

Inserts aGlyph into the glyph cache at glyphIndex and maps it to the character at charIndex. If the glyph is mapped to several characters, charIndex should indicate the first character that it’s mapped to.

This method is for use by the glyph generation mechanism, and doesn’t perform any invalidation or generation of the glyphs or layout. You should never directly invoke this method.

See also:	− deleteGlyphsInRange:, − replaceGlyphAtIndex:withGlyph:

p	insertTextContainer:atIndex:

− (void)insertTextContainer:(NSTextContainer *)aTextContainer atIndex:(unsigned int)index

Inserts aTextContainer into the series of text containers at index, and invalidates layout for all subsequent NSTextContainer’s. Also invalidates glyph information as needed.

See also:	− addTextContainer:, − removeTextContainerAtIndex:, − textContainers

p	intAttribute:forGlyphAtIndex:

− (int)intAttribute:(int)attributeTag forGlyphAtIndex:(unsigned int)glyphIndex

Returns the value of the attribute identified by attributeTag for the glyph at glyphIndex.

Subclasses that define their own custom attributes must override this method to access their own storage for the attribute values. Non-negative tags are reserved by NeXT; you can define your own attributes with negative tags and set values using setIntAttribute:value:forGlyphAtIndex:.

p	invalidateDisplayForGlyphRange:

− (void)invalidateDisplayForGlyphRange:(NSRange)glyphRange

Marks the glyphs in glyphRange as needing display, as well as the appropriate regions of the NSTextViews that display those glyphs (using NSView’s setNeedsDisplayInRect:). You should rarely need to invoke this method.

p	invalidateGlyphsForCharacterRange:changeInLength:actualCharacterRange:

− (void)invalidateGlyphsForCharacterRange:(NSRange)charRange

changeInLength:(int)lengthChange

actualCharacterRange:(NSRange *)actualCharRange

Invalidates the cached glyphs for the characters in charRange and adjusts the remaining glyph-to-character mapping according to lengthChange, which indicates the number of characters added to or removed from the text store. If non-NULL, actualCharRange is set to the range of characters mapped to the glyphs just invalidated. This can be larger than the range of characters given due to the effect of context on glyphs and layout.

You should rarely need to invoke this method. It only invalidates glyph information, and performs no glyph generation or layout. Because invalidating glyphs also invalidates layout, after invoking this method you should also invoke invalidateLayoutForCharacterRange:isSoft:actualCharacterRange:, passing charRange as the first argument and NO as the flag to the isSoft: keyword.

p	invalidateLayoutForCharacterRange:isSoft:actualCharacterRange:

− (void)invalidateLayoutForCharacterRange:(NSRange)charRange

isSoft:(BOOL)flag

actualCharacterRange:(NSRange *)actualCharRange

Invalidates the layout information for the glyphs mapped to the characters in charRange. If flag is YES, attempts to save some layout information to avoid recalculation; if flag is NO, saves no layout information. You should typically pass NO for flag. If non-NULL, actualCharRange is set to the range of characters mapped to the glyphs whose layout information has been invalidated. This can be larger than the range of characters given due to the effect of context on glyphs and layout.

This method only invalidates information; it performs no glyph generation or layout. You should rarely need to invoke this method.

See also:	− invalidateGlyphsForCharacterRange:changeInLength:actualCharacterRange:

p	layoutManagerOwnsFirstResponderInWindow:

− (BOOL)layoutManagerOwnsFirstResponderInWindow:(NSWindow *)aWindow

Returns YES if the first responder in aWindow is an NSTextView associated with the receiver, NO otherwise.

p	lineFragmentRectForGlyphAtIndex:effectiveRange:

− (NSRect)lineFragmentRectForGlyphAtIndex:(unsigned int)glyphIndex effectiveRange:(NSRange *)lineFragmentRange

Returns the line fragment rectangle containing the glyph at glyphIndex. The rectangle is defined in the coordinate system of its NSTextContainer. If non-NULL, lineFragmentRange is set to contain the range for all glyphs in that line fragment.

Performs glyph generation and layout if needed.

See also:	− lineFragmentUsedRectForGlyphAtIndex:effectiveRange:, − setLineFragmentRect:forGlyphRange:usedRect:

p	lineFragmentUsedRectForGlyphAtIndex:effectiveRange:

− (NSRect)lineFragmentUsedRectForGlyphAtIndex:(unsigned int)glyphIndex effectiveRange:(NSRange *)lineFragmentRange

Returns the portion of the line fragment rectangle containing glyphAtIndex that actually contains glyphs (such as for a partial or wrapped line), plus the line fragment padding defined by the NSTextContainer where the glyphs reside. This rectangle is defined in the coordinate system of its NSTextContainer, and is based on line calculation only—that is, it isn’t a bounding box for the glyphs in the line fragment.

If non-NULL, lineFragmentRange is set to contain the range for all glyphs in the line fragment.

Performs glyph generation and layout if needed.

See also:	− lineFragmentRectForGlyphAtIndex:effectiveRange:, − setLineFragmentRect:forGlyphRange:usedRect:

p	locationForGlyphAtIndex:

− (NSPoint)locationForGlyphAtIndex:(unsigned int)glyphIndex

Returns the location, in terms of its line fragment rectangle, for the glyph at glyphIndex. The line fragment rectangle in turn is defined in the coordinate system of the text container where it resides.

Performs glyph generation and layout if needed.

See also:	− lineFragmentRectForGlyphAtIndex:effectiveRange:, − lineFragmentUsedRectForGlyphAtIndex:effectiveRange:

p	notShownAttributeForGlyphAtIndex:

− (BOOL)notShownAttributeForGlyphAtIndex:(unsigned int)glyphIndex

Returns YES if the glyph at glyphIndex isn’t shown (in the sense of the PostScript show operator), NO if it is. For example, a tab, newline, or attachment glyph doesn’t get shown; it just affects the layout of following glyphs or locates the attachment graphic. Space characters, however, typically are shown as glyphs with a displacement, though they leave no visible marks. Raises an NSRangeException if glyphIndex is out of bounds.

Performs glyph generation and layout if needed.

See also:	− setNotShownAttribute:forGlyphAtIndex:

p	numberOfGlyphs

− (unsigned int)numberOfGlyphs

Returns the number of glyphs in the receiver, performing glyph generation if needed to determine this number.

p	rangeOfNominallySpacedGlyphsContainingIndex:

− (NSRange)rangeOfNominallySpacedGlyphsContainingIndex:(unsigned int)glyphIndex

Returns the range for the glyphs around glyphIndex that can be displayed with a single PostScript show operation; in other words, glyphs with no pairwise kerning or other adjustments to spacing.

Performs glyph generation and layout if needed.

p	rectArrayForCharacterRange:withinSelectedCharacterRange:inTextContainer:

rectCount:

− (NSRect *)rectArrayForCharacterRange:(NSRange)charRange

withinSelectedCharacterRange:(NSRange)selCharRange

inTextContainer:(NSTextContainer *)aTextContainer

rectCount:(unsigned int *)rectCount

Returns a C array of rectangles for the glyphs in aTextContainer that correspond to charRange, and by reference in rectCount the number of such rectangles. These rectangles can be used to draw the background or highlight for the given range of characters. selCharRange indicates selected characters, which can affect the size of the rectangles; it must be equal to or contain charRange. To calculate the rectangles for drawing the background, use a selected character range whose location is NSNotFound. To calculate the rectangles for drawing highlighting for charRange, use a selected character range that contains charRange.

The number of rectangles returned isn’t necessarily the number of lines enclosing the specified range. Contiguous lines can share an enclosing rectangle, and lines broken into several fragments have a separate enclosing rectangle for each fragment.

The array of rectangles returned is owned by the receiver, and is overwritten by various NSLayoutManager methods. You should never free it, and should copy it if you need to keep the values or use them after sending other messages to the layout manager.

The purpose of this method is to calculate line rectangles for drawing the text background and highlighting. These rectangles don’t necessarily enclose glyphs that draw outside their line fragment rectangles; use boundingRectForGlyphRange:inTextContainer: to determine the area that contains all drawing performed for a range of glyphs.

Performs glyph generation and layout if needed.

See also:	− glyphRangeForTextContainer:, − characterRangeForGlyphRange:actualGlyphRange:, − drawsOutsideLineFragmentForGlyphAtIndex:

p	rectArrayForGlyphRange:withinSelectedGlyphRange:inTextContainer:

rectCount:

− (NSRect *)rectArrayForGlyphRange:(NSRange)glyphRange

withinSelectedGlyphRange:(NSRange)selGlyphRange

inTextContainer:(NSTextContainer *)aTextContainer

rectCount:(unsigned *)rectCount

Returns a C array of rectangles for the glyphs in aTextContainer in glyphRange, and by reference in rectCount the number of such rectangles. These rectangles can be used to draw the background or highlight for the given range of glyphs. selGlyphRange indicates selected glyphs. To calculate the rectangles for drawing the background, use a selected glyph range whose location is NSNotFound. To calculate the rectangles for highlighting, use a selected glyph range that contains glyphRange.

The number of rectangles returned isn’t necessarily the number of lines enclosing the specified range. Contiguous lines can share an enclosing rectangle, and lines broken into several fragments have a separate enclosing rectangle for each fragment.

The array of rectangles returned is owned by the receiver, and is overwritten by various NSLayoutManager methods. You should never free it, and should copy it if you need to keep the values or use them after sending other messages to the layout manager.

The purpose of this method is to calculate line rectangles for drawing the text background and highlighting. These rectangles don’t necessarily enclose glyphs that draw outside their line fragment rectangles; use boundingRectForGlyphRange:inTextContainer: to determine the area that contains all drawing performed for a range of glyphs.

Performs glyph generation and layout if needed.

See also:	− glyphRangeForTextContainer:, − drawsOutsideLineFragmentForGlyphAtIndex:

p	removeTextContainerAtIndex:

− (void)removeTextContainerAtIndex:(unsigned int)index

Removes the NSTextContainer at index and invalidates the layout as needed.Also invalidates glyph information as needed.

See also:	− addTextContainer:, − insertTextContainer:atIndex:, − textContainers, − invalidateGlyphsForCharacterRange:changeInLength:actualCharacterRange:, − invalidateLayoutForCharacterRange:isSoft:actualCharacterRange:

p	replaceGlyphAtIndex:withGlyph:

− (void)replaceGlyphAtIndex:(unsigned int)glyphIndex withGlyph:(NSGlyph)newGlyph

Replaces the glyph at glyphIndex with newGlyph. Doesn’t alter the glyph-to-character mapping or invalidate layout information.

This method is for use by the glyph generation mechanism, and doesn’t perform any invalidation or generation of the glyphs or layout. You should never directly invoke this method.

See also:	− setCharacterIndex:forGlyphAtIndex:, − invalidateGlyphsForCharacterRange:changeInLength:actualCharacterRange:, − invalidateLayoutForCharacterRange:isSoft:actualCharacterRange:

p	replaceTextStorage:

− (void)replaceTextStorage:(NSTextStorage *)newTextStorage

Replaces the NSTextStorage for the group of text-system objects containing the receiver with newTextStorage. All NSLayoutManagers sharing the original NSTextStorage then share the new one. This method makes all the adjustments necessary to keep these relationships intact, unlike setTextStorage:.

p	rulerAccessoryViewForTextView:paragraphStyle:ruler:enabled:

− (NSView *)rulerAccessoryViewForTextView:(NSTextView *)aTextView

paragraphStyle:(NSParagraphStyle *)paraStyle

ruler:(NSRulerView *)aRulerView

enabled:(BOOL)flag

Returns the accessory NSView for aRulerView. This accessory contains tab wells, text alignment buttons, and so on. paraStyle is used to set the state of the controls in the accessory NSView; it must not be nil. If flag is YES the accessory view is enabled and accepts mouse and keyboard events; if NO it’s disabled.

This method is invoked automatically by the NSTextView object using the layout manager. You should rarely need to invoke it, but you can override it to customize ruler support. If you do this method directly, not that it neither installs the ruler accessory view nor sets the markers for the NSRulerView. You must install the accessory view into the ruler using NSRulerView’s setAccessoryView: method. To set the markers, use rulerMarkersForTextView:paragraphSyle:ruler: to get the markers needed and then send setMarkers: to the ruler.

See also:	− horizontalRulerView (NSScrollView)

p	rulerMarkersForTextView:paragraphStyle:ruler:

− (NSArray *)rulerMarkersForTextView:(NSTextView *)aTextView

paragraphStyle:(NSParagraphStyle *)paraStyle

ruler:(NSRulerView *)aRulerView

Returns the NSRulerMarkers for aRulerView in aTextView, based on paraStyle. These markers represent such things as left and right margins, first-line indent, and tab stops. You can set these markers immediately with NSRulerView’s setMarkers: method.

This method is invoked automatically by the NSTextView object using the layout manager. You should rarely need to invoke it; but you can override it to add new kinds of markers or otherwise customize ruler support.

See also:	− rulerAccessoryViewForTextView:paragraphStyle:ruler:enabled:

p	setBackgroundLayoutEnabled:

− (void)setBackgroundLayoutEnabled:(BOOL)flag

Sets according to flag whether the receiver generates glyphs and lays them out when the application’s run loop is idle.

See also:	− backgroundLayoutEnabled

p	setCharacterIndex:forGlyphAtIndex:

− (void)setCharacterIndex:(unsigned int)charIndex forGlyphAtIndex:(unsigned int)glyphIndex

Maps the character at charIndex to the glyph at glyphIndex.

This method is for use by the glyph generation mechanism, and doesn’t perform any invalidation or generation of the glyphs or layout. You should never directly invoke this method.

See also:	− characterIndexForGlyphAtIndex:, − characterRangeForGlyphRange:actualGlyphRange:, − glyphRangeForCharacterRange:actualCharacterRange:

p	setDelegate:

− (void)setDelegate:(id)anObject

Sets the receiver’s delegate to anObject, without retaining it.

See also:	− delegate

p	setDrawsOutsideLineFragment:forGlyphAtIndex:

− (void)setDrawsOutsideLineFragment:(BOOL)flag forGlyphAtIndex:(unsigned int)glyphIndex

Sets according to flag whether the glyph at glyphIndex exceeds the bounds of the line fragment where it’s laid out. This can happen when text is set at a fixed line height. For example, if the user specifies a fixed line height of 12 points and sets the font size to 24 points, the glyphs will exceed their layout rectangles.

This method is used by the layout mechanism; you should never invoke it directly.

See also:	− drawsOutsideLineFragmentForGlyphAtIndex

p	setExtraLineFragmentRect:usedRect:textContainer:

− (void)setExtraLineFragmentRect:(NSRect)aRect

usedRect:(NSRect)usedRect

textContainer:(NSTextContainer *)aTextContainer

Sets a line fragment rectangle for displaying an empty last line in a body of text. aRect is the rectangle to set, and aTextContainer is the NSTextContainer where the rectangle should be laid out. usedRect indicates where the insertion point is drawn.

This method is used by the layout mechanism; you should never invoke it directly.

See also:	− extraLineFragmentRect, − extraLineFragmentUsedRect, − textContainer

p	setIntAttribute:value:forGlyphAtIndex:

− (void)setIntAttribute:(int)attributeTag

value:(int)anInt

forGlyphAtIndex:(unsigned int)glyphIndex

Sets a custom attribute value for the glyph at glyphIndex. attributeTag identifies the custom attribute, and anInt is its new value.

Subclasses that define their own custom attributes must override this method and provide their own storage for the attribute values. Non-negative tags are reserved by NeXT; you can define your own attributes with negative tags and set values using this method.

This method doesn’t perform glyph generation or layout. The glyph at glyphIndex must already have been generated.

See also:	− intAttribute:forGlyphAtIndex:

p	setLineFragmentRect:forGlyphRange:usedRect:

− (void)setLineFragmentRect:(NSRect)fragmentRect

forGlyphRange:(NSRange)glyphRange

usedRect:(NSRect)usedRect

Sets to fragmentRect the line fragment rectangle where the glyphs in glyphRange are laid out. The text container must be specified first with setTextContainer:forGlyphRange:, and the exact positions of the glyphs must be set after the line fragment rectangle with setLocation:forStartOfGlyphRange:. usedRect indicates the portion of fragmentRect, in the NSTextContainer’s coordinate system, that actually contains glyphs or other marks that are drawn (including the text container’s line fragment padding). usedRect must be equal to or contained within fragmentRect.

This method is used by the layout mechanism; you should never invoke it directly.

See also:	− lineFragmentRectForGlyphRange:effectiveRange:, − lineFragmentUsedRectForGlyphRange:effectiveRange:

p	setLocation:forStartOfGlyphRange:

− (void)setLocation:(NSPoint)aPoint forStartOfGlyphRange:(NSRange)glyphRange

Sets the location where the glyphs in glyphRange are laid out to aPoint, which is expressed relative to the origin of the line fragment rectangle for glyphRange. glyphRange defines a series of glyphs that can be displayed with a single PostScript show operation (a nominal range). Setting the location for a series of glyphs implies that the glyphs preceding it can’t be included in a single show operation.

Before setting the location for a glyph range, you must specify the text container with setTextContainer:forGlyphRange: and the line fragment rectangle with setLineFragmentRect:forGlyphRange:usedRect:.

This method is used by the layout mechanism; you should never invoke it directly.

See also:	− rangeOfNominallySpacedGlyphsContainingIndex:

p	setNotShownAttribute:forGlyphAtIndex:

− (void)setNotShownAttribute:(BOOL)flag forGlyphAtIndex:(unsigned int)glyphIndex

Sets according to flag whether the glyph at glyphIndex is one that isn’t shown. For example, a tab or newline character doesn’t leave any marks; it just indicates where following glyphs are laid out. Raises an NSRangeException if glyphIndex is out of bounds.

This method is used by the layout mechanism; you should never invoke it directly.

See also:	− notShownAttributeForGlyphAtIndex

p	setShowsControlCharacters:

− (void)setShowsControlCharacters:(BOOL)flag

Controls whether the receiver makes control characters visible in layout where possible. If flag is YES, it substitutes visible glyphs for control characters if the font and script support it; if flag is NO it doesn’t.

See also:	− setShowsInvisibleCharacters:, − showsControlCharacters

p	setShowsInvisibleCharacters:

− (void)setShowsInvisibleCharacters:(BOOL)flag

Controls whether the receiver makes whitespace and other typically nonvisible characters visible in layout where possible. If flag is YES, it substitutes visible glyphs for invisible characters if the font and script support it; if flag is NO it doesn’t.

See also:	− setShowsControlCharacters:, − showsInvisibleCharacters

p	setTextContainer:forGlyphRange:

− (void)setTextContainer:(NSTextContainer *)aTextContainer forGlyphRange:(NSRange)glyphRange

Sets to aTextContainer the NSTextContainer where the glyphs in glyphRange are laid out. You specify the layout within the container with the setLineFragmentRect:forGlyphRange:usedRect: and setLocation:forStartOfGlyphRange: methods.

This method is used by the layout mechanism; you should never invoke it directly.

See also:	− textContainerForGlyphRange:effectiveRange:

p	setTextStorage:

− (void)setTextStorage:(NSTextStorage *)textStorage

Sets the receiver’s NSTextStorage to textStorage. This method is invoked automatically when you add an NSLayoutManager to an NSTextStorage object; you should never need to invoke it directly, but might want to override it. If you want to replace the NSTextStorage for an established group of text-system objects containing the receiver, use replaceTextStorage:.

See also:	− addLayoutManager: (NSTextStorage)

p	setUsesScreenFonts:

−(void)setUsesScreenFonts:(BOOL)flag

Sets according to flag whether the receiver calculates layout and displays text using screen fonts when possible.

See also:	− usesScreenFonts, − substituteFontForFont:

p	showsControlCharacters

− (BOOL)showsControlCharacters

Returns YES if the receiver substitutes visible glyphs for control characters if the font and script support it, NO if it doesn’t.

See also:	− showsInvisibleCharacters, − setShowsControlCharacters:

p	showsInvisibleCharacters

− (BOOL)showsInvisibleCharacters

Returns YES if the receiver substitutes visible glyphs for invisible characters if the font and script support it, NO if it doesn’t.

See also:	− showsControlCharacters, − setShowsInvisibleCharacters:

p	substituteFontForFont:

− (NSFont *)substituteFontForFont:(NSFont *)originalFont

Returns a screen font suitable for use in place of originalFont, or simply returns originalFont if a screen font can’t be used or isn’t available. A screen font can be substituted if the receiver is set to use screen fonts and if no NSTextView associated with the receiver are scaled or rotated.

See also:	− usesScreenFonts

p	textContainerChangedGeometry:

− (void)textContainerChangedGeometry:(NSTextContainer *)aTextContainer

Invalidates the layout information, and possibly glyphs, for aTextContainer and all subsequent NSTextContainers. This method is invoked automatically by other components of the text system; you should rarely need to invoke it directly. Subclasses of NSTextContainer, however, must invoke this method any time their size of shape changes (a text container that dynamically adjusts its shape to wrap text around placed graphics, for example, must do so when a graphic is added, moved, or removed).

p	textContainerChangedTextView:

− (void)textContainerChangedTextView:(NSTextContainer *)aTextContainer

Updates information needed to manage NSTextView objects. This method is invoked automatically by other components of the text system; you should rarely need to invoke it directly.

p	textContainerForGlyphAtIndex:effectiveRange:

− (NSTextContainer *)textContainerForGlyphAtIndex:(unsigned int)glyphIndex effectiveRange:(NSRange *)effectiveGlyphRange

Returns the NSTextContainer where the glyph at glyphIndex is laid out. If non-NULL, effectiveGlyphRange is set to the range for all glyphs laid out in that text container.

Performs glyph generation and layout if needed.

See also:	− setTextContainer:forGlyphAtIndex:

p	textContainers

− (NSArray *)textContainers

Returns the receiver’s NSTextContainers.

See also:	− addTextContainer:, − insertTextContainer:atIndex:, − removeTextContainerAtIndex:

p	textStorage

− (NSTextStorage *)textStorage

Returns the receiver’s NSTextStorage.

See also:	− setTextStorage:, − replaceTextStorage:

p	textStorage:edited:range:changeInLength:invalidatedRange:

− (void)textStorage:(NSTextStorage *)aTextStorage

edited:(unsigned int)mask

range:(NSRange)range

changeInLength:(int)lengthChange

invalidatedRange:(NSRange)invalidatedCharRange

Invalidates glyph and layout information for a portion of text in aTextStorage. This message is sent from NSTextStorage’s processEditing method to indicate that its characters or attributes have been changed. This method invalidates glyphs and layout for the affected characters, and performs a soft invalidation of the layout information for all subsequent characters. mask specifies the nature of the changes. Its value is made by combining these options with the C bitwise OR operator:

Option	Meaning

NSTextStorageEditedAttributes	Attributes were added, removed, or changed.

NSTextStorageEditedCharacters	Characters were added, removed, or replaced.

range indicates the extent of characters resulting from the edits. If the NSTextStorageEditedCharacters bit of mask is set, lengthChange gives the number of characters added to or removed from the original range (otherwise its value is irrelevant). For example, after replacing “The” with “Several” to produce the string “Several files couldn’t be saved”, range is {0, 7} and lengthChange is 4. The receiver uses this information to update its character-to-glyph mapping and to update the selection range based on the change.

invalidatedRange represents the range of characters affected after attributes have been fixed. For example, deleting a paragraph separator character invalidates the layout information for all characters in the paragraphs that precede and follow the separator.

textStorage:edited:range:changeInLength:invalidatedRange: messages are sent in a series to each NSLayoutManager associated with the text storage object, so the NSLayoutManagers receiving them shouldn’t edit aTextStorage. If one of them does, the range, lengthChange, and invalidatedRange arguments will be incorrect for all following NSLayoutManagers that receive the message.

See also:	− invalidateLayoutForCharacterRange:isSoft:actualCharacterRange:

p	textViewForBeginningOfSelection

− (NSTextView *)textViewForBeginningOfSelection

Returns the NSTextView containing the first glyph in the selection, or nil if there’s no selection or if there isn’t enough layout information to determine the text view.

p	underlineGlyphRange:underlineType:lineFragmentRect:

lineFragmentGlyphRange:containerOrigin:

− (void)underlineGlyphRange:(NSRange)glyphRange

underlineType:(int)underlineType

lineFragmentRect:(NSRect)lineRect

lineFragmentGlyphRange:(NSRange)lineGlyphRange

containerOrigin:(NSPoint)containerOrigin

Calculates and draws underlining for the glyphs in glyphRange, which must belong to a single line fragment rectangle (as returned by lineFragmentRectForGlyphAtIndex:effectiveRange:). underlineType indicates the style of underlining to draw; NSLayoutManager accepts only NSSingleUnderlineStyle, but subclasses can define their own underline styles. lineRect is the line fragment rectangle containing the glyphs to draw underlining for, and lineGlyphRange is the range of all glyphs within that line fragment rectangle. containerOrigin is the origin of the line fragment rectangle’s NSTextContainer in its NSTextView.

This method determines which glyphs actually need to be underlined based on underlineType. With NSSingleUnderlineStyle, for example, leading and trailing whitespace isn’t underlined, but whitespace between visible glyphs is. A potential word-underline style would omit underlining on any whitespace. After determining which glyphs to draw underlining on, this method invokes drawUnderlineForGlyphRange:... for each contiguous range of glyphs that requires it.

See also:	− textContainerForGlyphAtIndex:effectiveRange:, − textContainerOrigin (NSTextView)

p	usedRectForTextContainer:

− (NSSize)usedRectForTextContainer:(NSTextContainer *)aTextContainer

Returns the bounding rectangle for the glyphs laid out in aTextContainer, which tells “how full” it is. This rectangle is given in the aTextContainer’s coordinate system.

See also:	− containerSize (NSTextContainer)

p	usesScreenFonts

− (BOOL)usesScreenFonts

Returns YES if the receiver calculates layout and displays text using screen fonts when possible, NO otherwise.

See also:	− setUsesScreenFonts:, − substituteFontForFont:

Methods Implemented by the Delegate

p	layoutManager:didCompleteLayoutForTextContainer:atEnd:

− (void)layoutManager:(NSLayoutManager *)aLayoutManager didCompleteLayoutForTextContainer:(NSTextContainer *)aTextContainer

atEnd:(BOOL)flag

Informs the delegate that aLayoutManager has finished laying out text in aTextContainer. aTextContainer is nil if there aren’t enough containers to hold all the text; the delegate can use this information as a cue to add another container. If flag is YES, aLayoutManager is finished laying out its text—this also means that aTextContainer is the final text container used by the layout manager. Delegates can use this information to show an indicator or background or to enable or disable a button that forces immediate layout of text.

p	layoutManagerDidInvalidateLayout:

− (void)layoutManagerDidInvalidateLayout:(NSLayoutManager *)aLayoutManager

Informs the delegate that aLayoutManager has invalidated layout information (not glyph information). This method is invoked only when layout was complete and then became invalidated for some reason. Delegates can use this information to show an indicator or background layout or to enable a button that forces immediate layout of text.


NSMatrix

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSControl : NSView : NSResponder : NSObject

Conforms To:	NSCoding (from NSResponder)

NSObject (from NSObject)

Declared In:	AppKit/NSMatrix.h

Class Description

NSMatrix is a class used for creating groups of NSCells that work together in various ways. It includes methods for arranging NSCells in rows and columns, either with or without space between them. NSCells in an NSMatrix are numbered by row and column, each starting with 0; for example, the top left NSCell would be at (0, 0), and the NSCell that’s second down and third across would be at (1, 2).

The cell objects that an NSMatrix contains are usually of a single subclass of NSCell, but they can be of multiple subclasses of NSCell. The only restriction is that all cell objects must be the same size. An NSMatrix can be set up to create new NSCells by copying a prototype object, or by allocating and initializing instances of a specific NSCell class. Cells created by or added to an NSMatrix are retained by the matrix.

An NSMatrix adds to NSControl’s target/action paradigm by allowing a separate target and action for each of its NSCells in addition to its own target and action. It also allows for an action message that’s sent when the user double-clicks an NSCell, which is sent in addition to the single-click action message. If an NSCell doesn’t have an action, the NSMatrix sends its own action to its own target. If an NSCell doesn’t have a target, the NSMatrix sends the NSCell’s action to its own target. The double-click action of an NSMatrix is always sent to the target of the NSMatrix.

Since the user might press the mouse button while the cursor is within the NSMatrix and then drag the mouse around, NSMatrix offers four “selection modes” that determine how NSCells behave when the NSMatrix is tracking the mouse:

•	NSTrackModeMatrix is the most basic mode of operation. In this mode the NSCells are asked to track the mouse with trackMouse:inRect:ofView:untilMouseUp: whenever the mouse is inside their bounds. No highlighting is performed. An example of this mode might be a “graphic equalizer” NSMatrix of sliders, where moving the mouse around causes the sliders to move under the mouse.

•	NSHighlightModeMatrix is a modification of NSTrackModeMatrix. In this mode, an NSCell is highlighted before it’s asked to track the mouse, then unhighlighted when it’s done tracking. This is useful for multiple unconnected NSCells that use highlighting to inform the user that they are being tracked (like push-buttons and switches).

•	NSRadioModeMatrix is used when you want no more than one NSCell to be selected at a time. It can be used to create a set of buttons of which one and only one is selected (there’s the option of allowing no button to be selected). Any time an NSCell is selected, the previously selected NSCell is unselected. The canonical example of this mode is a set of radio buttons.

•	NSListModeMatrix is the opposite of NSTrackModeMatrix. NSCells are highlighted, but don’t track the mouse. This mode can be used to select a range of text values, for example. NSMatrix supports the standard multiple-selection paradigms of dragging to select, using the shift key to make discontinuous selections, and using the alternate key to extend selections. Browsers (as used, for instance, in NeXT’s File Viewer) use this mode.

Method Types

Initializing the NSMatrix class	+ cellClass

+ setCellClass

Initializing an NSMatrix object	− initWithFrame:

− initWithFrame:mode:cellClass:numberOfRows:numberOfColums:

− initWithFrame:mode:prototype:numberOfRows:numberOfColumns:

Setting the selection mode	− mode

− setMode:

Configuring the NSMatrix	− allowsEmptySelection

− isSelectionByRect

− setAllowsEmptySelection

− setSelectionByRect:

Setting the cell class	− cellClass

− prototype

− setCellClass:

− setPrototype:

Laying out the NSMatrix	− addColumn

− addColumnWithCells:

− addRow

− addRowWithCells:

− cellFrameAtRow:column:

− cellSize

− getNumberOfRows:columns:

− insertColumn:

− insertColumn:withCells:

− insertRow:

− insertRow:withCells:

− intercellSpacing

− makeCellAtRow:column:

− numberOfColumns

− numberOfRows:

− putCell:atRow:column:

− removeColumn:

− removeRow:

− renewRows:columns:

− setCellSize:

− setIntercellSpacing:

− sortUsingFunction:context:

− sortUsingSelector:

Finding matrix coordinates	− getRow:column:forPoint:

− getRow:column:ofCell:

Modifying individual cells	− setState:atRow:column:

Selecting cells	− deselectAllCells

− deselectSelectedCell

− keyCell

− selectAll:

− selectCellAtRow:column:

− selectCellWithTag:

− selectedCell

− selectedCells

− selectedColumn

− selectedRow

− setKeyCell:

− setSelectionFrom:to:anchor:highlight:

Finding cells	− cellAtRow:column:

− cellWithTag:

− cells

Modifying graphic attributes	− backgroundColor

− cellBackgroundColor

− drawsBackground

− drawsCellBackground

− setBackgroundColor:

− setCellBackgroundColor:

− setDrawsBackground:

− setDrawsCellBackground:

Editing text in cells	− selectText:

− selectTextAtRow:column:

− textDidBeginEditing:

− textDidChange:

− textDidEndEditing:

− textShouldBeginEditing:

− textShouldEndEditing:

Setting tab key behavior	− nextText

− previousText

− setNextText:

− setPreviousText:

− setTabKeyTraversesCells:

− tabKeyTraversesCells

Assigning a delegate	− delegate

− setDelegate:

Resizing the matrix and its cells	− autosizesCells

− setAutosizesCells:

− setValidateSize:

− sizeToCells

Scrolling	− isAutoscroll

− scrollCellToVisibleAtRow:column:

− setAutoscroll:

− setScrollable:

Displaying	− drawCellAtRow:column:

− highlightCell:atRow:column:

Target and action	− doubleAction

− errorAction

− sendAction

− sendAction:to:forAllCells:

− sendDoubleAction

− setDoubleAction:

− setErrorAction:

Handling event and action messages	− acceptsFirstMouse:

− mouseDown:

− mouseDownFlags

− performKeyEquivalent:

Managing the cursor	− resetCursorRects

Class Methods

cellClass

+ (Class)cellClass

Returns the default class that the NSMatrix class will use to make cells.

See also:	− cellClass, − makeCellAtRow:column:, − prototype

setCellClass:

+ (void)setCellClass:(Class)factoryId

Sets the default class that the NSMatrix class will use to make cells. factoryId should be the id of a subclass of NSCell (usually NSActionCell), obtained by sending the class message to either the NSCell subclass object or to an instance of that subclass. The default NSCell class is NSActionCell.

Your code should rarely need to invoke this method, since each instance of NSMatrix can be configured to use its own NSCell class (or a prototype that gets copied). The NSCell class set with this method is simply a fall-back for matrices initialized with initWithFrame:.

See also:	− setCellClass:, − setPrototype:, − makeCellAtRow:column:, − initWithFrame:mode:cellClass:numberOfRows:numberOfColumns:, − initWithFrame:mode:prototype:numberOfRows:numberOfColumns:

Instance Methods

acceptsFirstMouse:

− (BOOL)acceptsFirstMouse:(NSEvent *)theEvent

Returns NO if the selection mode of the NSMatrix is NSListModeMatrix, YES if the NSMatrix is in any other selection mode. The NSMatrix does not accept first mouse in NSListModeMatrix to prevent the loss of multiple selections. The NSEvent parameter, theEvent, is ignored.

See also:	− mode

addColumn

− (void)addColumn

Adds a new column of cells to the right of the last column, creating new cells as needed with makeCellAtRow:column:.

If the number of rows or columns in the NSMatrix has been changed with renewRows:columns:, new cells are created only if they are needed. This allows you to grow and shrink an NSMatrix without repeatedly creating and freeing the cells.

This method doesn’t redraw the NSMatrix. Accordingly, after calling this method you should send setNeedsDisplay:YES to the NSMatrix. Your code may also need to use sizeToCells after sending this method to resize the NSMatrix to fit the newly added cells.

See also:	− cellClass, − insertColumn:, − prototype

addColumnWithCells:

− (void)addColumnWithCells:(NSArray *)newCells

Adds a new column of cells to the right of the last column. The new column is filled with objects from newCells, starting with the object at index 0. Each object in newCells should be a an NSCell or one of its subclasses (usually NSActionCell). newCells should have a sufficient number of cells to fill the entire column; extra cells are ignored.

This method doesn’t redraw the NSMatrix. Accordingly, after calling this method you should send setNeedsDisplay:YES to the NSMatrix. Your code may also need to use sizeToCells after sending this method to resize the NSMatrix to fit the newly added cells.

See also:	− insertColumn:withCells:

addRow

− (void)addRow

Adds a new row of cells below the last row, creating new cells as needed with makeCellAtRow:column:.

If the number of rows or columns in the NSMatrix has been changed with renewRows:columns:, then new cells are created only if they are needed. This allows you to grow and shrink an NSMatrix without repeatedly creating and freeing the cells.

This method doesn’t redraw the NSMatrix. Accordingly, after calling this method you should send setNeedsDisplay:YES to the NSMatrix. Your code may also need to use sizeToCells after sending this method to resize the NSMatrix to fit the newly added cells.

See also:	− cellClass, − insertRow:, − prototype

addRowWithCells:

− (void)addRowWithCells:(NSArray *)newCells

Adds a new row of cells below the last row. The new row is filled with objects from newCells, starting with the object at index 0. Each object in newCells should be a an NSCell or one of its subclasses (usually NSActionCell). newCells should have a sufficient number of cells to fill the entire row; extra cells are ignored.

This method doesn’t redraw the NSMatrix. Accordingly, after calling this method you should send setNeedsDisplay:YES to the NSMatrix. Your code may also need to use sizeToCells after sending this method to resize the NSMatrix to fit the newly added cells.

See also:	− insertRow:withCells:

allowsEmptySelection

− (BOOL)allowsEmptySelection

Returns whether its possible to have no cells selected in a radio-mode matrix.

See also:	− mode

autosizesCells

− (BOOL)autosizesCells

Returns YES if cells are resized proportionally to the NSMatrix when its size changes (and inter-cell spacing is kept constant). Returns NO if the cell size remains constant (and inter-cell spacing changes).

backgroundColor

− (NSColor *)backgroundColor

Returns the color used to draw the background of the NSMatrix (the space between the cells).

See also:	− cellBackgroundColor, − drawsBackground

cellAtRow:column:

− (id)cellAtRow:(int)row column:(int)column

Returns the NSCell object at row and column, or nil if either row or column are outside the bounds of the NSMatrix.

See also:	− getRow:column:ofCell:

cellBackgroundColor

− (NSColor *)cellBackgroundColor

Returns the color used to fill the background of the NSMatrix’s cells.

See also:	− backgroundColor, − drawsCellBackground

cellClass

− (Class)cellClass

Returns the subclass of NSCell that the NSMatrix uses when creating new (empty) cells.

See also:	− prototype, − makeCellAtRow:column:

cellFrameAtRow:column:

− (NSRect)cellFrameAtRow:(int)row column:(int)column

Returns the frame rectangle of the cell that would be drawn at the specified row and column (whether or not the specified cell actually exists).

See also:	− cellSize

cellSize

− (NSSize)cellSize

Returns the width and the height of each cell in the NSMatrix (all cells in an NSMatrix are the same size).

See also:	− cellFrame:atRow:column:, − intercellSpacing

cellWithTag:

− (id)cellWithTag:(int)anInt

Searches the NSMatrix and returns the last (when viewing the matrix as a row-ordered array) NSCell object which has a tag matching anInt, or nil if no such cell exists.

See also:	− selectCellWithTag:, − setTag: (NSActionCell)

cells

− (NSArray *)cells

Returns an NSArray that contains the NSMatrix’s cells. The cells in the array are row-ordered; that is, the first row of cells appear first in the array, followed by the second row, and so forth.

See also:	− cellAtRow:column:

delegate

− (id)delegate

Returns the delegate for messages from the field editor.

See also:	− textShouldBeginEditing:, − textShouldEndEditing:

deselectAllCells

− (void)deselectAllCells

Deselects all cells in the NSMatrix and, if necessary, redisplays the NSMatrix. If the selection mode is NSRadioModeMatrix and empty selection is not allowed, this method does nothing.

See also:	− allowsEmptySelection, − mode, − selectAll:

deselectSelectedCell

− (void)deselectSelectedCell

Deselects the selected cell or cells. If the selection mode is NSRadioModeMatrix and empty selection is not allowed, or if nothing is currently selected, this method does nothing. This method doesn’t redisplay the NSMatrix.

See also:	− allowsEmptySelection, − mode, − selectCellAtRow:column:

doubleAction

− (SEL)doubleAction

Returns the action method sent by the NSMatrix to its target when the user double-clicks an entry, or NULL if there’s no double-click action. The double-click action of an NSMatrix is sent after the appropriate single-click action (for the NSCell clicked or for the NSMatrix if the NSCell doesn’t have its own action). If there is no double-click action and the NSMatrix doesn’t ignore multiple clicks, the single-click action is sent twice.

See also:	− action (NSControl), − target (NSControl), − sendDoubleAction, − ignoresMultiClick (NSControl)

drawCellAtRow:column:

− (void)drawCellAtRow:(int)row column:(int)column

Displays the cell at the specified row and column, providing that row and column reference a cell that’s within the NSMatrix.

See also:	− drawCell: (NSControl), − drawCellInside: (NSControl)

drawsBackground

− (BOOL)drawsBackground

Returns whether the receiver draws its background (the space between the cells).

See also:	− backgroundColor, − drawsCellBackground

drawsCellBackground

− (BOOL)drawsCellBackground

Returns whether the receiver draws the background within each of its cells.

See also:	− cellBackgroundColor, − drawsBackground

errorAction

− (SEL)errorAction

Returns the action that’s sent to the target of the NSMatrix when the user enters an illegal value for the selected cell.

See also:	− action (NSControl), − target (NSControl), − textShouldEndEditing:

getNumberOfRows:columns:

− (void)getNumberOfRows:(int *)rowCount columns:(int *)columnCount

Returns by reference the number of rows and columns in the NSMatrix.

See also:	− numberOfColumns, − numberOfRows

getRow:column:forPoint:

− (BOOL)getRow:(int *)row column:(int *)column forPoint:(NSPoint)aPoint

Returns YES if aPoint lies within one of the cells in the NSMatrix, and returns by reference the row and column for the cell within which the specified point lies. If aPoint falls outside the bounds of the Matrix or lies within an intercell spacing, getRow:column:forPoint: returns NO.

Make sure that aPoint is in the coordinate system of the NSMatrix.

See also:	− getRow:column:ofCell:

getRow:column:ofCell:

− (BOOL)getRow:(int *)row column:(int *)column ofCell:(NSCell *)aCell

Searches the NSMatrix and returns YES if aCell is one of the cells in the NSMatrix, and returns by reference the row and column of the cell. If aCell is not found within the Matrix, getRow:column:ofCell: returns NO.

See also:	− getRow:column:forPoint:

highlightCell:atRow:column:

− (void)highlightCell:(BOOL)flag atRow:(int)row column:(int)column

Assuming that row and column indicate a valid cell within the NSMatrix, highlightCell:atRow:column: highlights (if flag is YES) or unhighlights (if flag is NO) the specified cell.

initWithFrame:

− (id)initWithFrame:(NSRect)frameRect

Initializes and returns the receiver, a newly-allocated instance of NSMatrix, with default parameters in the frame specified by frameRect. The new NSMatrix contains no rows or columns. The default mode is NSRadioModeMatrix. The default cell class is NSActionCell.

initWithFrame:mode:cellClass:numberOfRows:numberOfColumns:

− (id)initWithFrame:(NSRect)frameRect mode:(int)aMode cellClass:(Class)factoryId numberOfRows:(int)numRows numberOfColumns:(int)numColumns

Initializes and returns the receiver, a newly-allocated instance of NSMatrix, in the frame specified by frameRect. The new NSMatrix contains numRows rows and numColumns columns. aMode is set as the tracking mode for the NSMatrix, and can be one of the following four constants, all of which are described in the class description:

NSTrackModeMatrix	Cells track the mouse, but do not highlight

NSHighlightModeMatrix	Cells highlight as they track the mouse

NSRadioModeMatrix	Allows no more than one selected cell

NSListModeMatrix	Cells are highlighted, but don’t track the mouse

The new NSMatrix creates and uses cells of class classId, which can be obtained by sending a class message to the desired subclass of NSCell.

This method is the designated initializer for matrices that add cells by creating instances of an NSCell subclass.

initWithFrame:mode:prototype:numberOfRows:numberOfColumns:

− (id)initWithFrame:(NSRect)frameRect mode:(int)aMode prototype:(NSCell *)aCell numberOfRows:(int)numRows numberOfColumns:(int)numColumns

Initializes and returns the receiver, a newly-allocated instance of NSMatrix, in the frame specified by frameRect. The new NSMatrix contains numRows rows and numColumns columns. aMode is set as the tracking mode for the NSMatrix, and can be one of the following four constants, all of which are described in the class description:

NSTrackModeMatrix	Cells track the mouse, but do not highlight

NSHighlightModeMatrix	Cells highlight as they track the mouse

NSRadioModeMatrix	Allows no more than one selected cell

NSListModeMatrix	Cells are highlighted, but don’t track the mouse

The new Matrix creates cells by copying aCell, which should be an instance of a subclass of NSCell.

This method is the designated initializer for matrices that add cells by copying an instance of an NSCell subclass.

insertColumn:

− (void)insertColumn:(int)column

Inserts a new column of cells before column, creating new cells if needed with makeCellAtRow:column:. If column is greater than the number of columns in the NSMatrix, enough columns are created to expand the NSMatrix to be column columns wide. This method doesn’t redraw the NSMatrix. Accordingly, after calling this method you should send setNeedsDisplay:YES to the NSMatrix. Your code may also need to use sizeToCells after sending this method to resize the NSMatrix to fit the newly added cells.

If the number of rows or columns in the NSMatrix has been changed with renewRows:columns:, then new cells are created only if they’re needed. This allows you to grow and shrink an NSMatrix without repeatedly creating and freeing the cells.

See also:	− addColumn, − insertRow:

insertColumn:withCells:

− (void)insertColumn:(int)column withCells:(NSArray *)newCells

Inserts a new column of cells before column. The new column is filled with objects from newCells, starting with the object at index 0. Each object in newCells should be a an NSCell or one of its subclasses (usually NSActionCell). If column is greater than the number of columns in the NSMatrix, enough columns are created to expand the NSMatrix to be column columns wide. newCells should have a sufficient number of cells to fill each new column; extra cells are ignored.

This method doesn’t redraw the NSMatrix. Accordingly, after calling this method you should send setNeedsDisplay:YES to the NSMatrix. Your code may also need to use sizeToCells after sending this method to resize the NSMatrix to fit the newly added cells.

See also:	− addColumnWithCells:, − insertRow:withCells:

insertRow:

− (void)insertRow:(int)row

Inserts a new row of cells before row, creating new cells if needed with makeCellAtRow:column:. If row is greater than the number of rows in the NSMatrix, enough rows are created to expand the NSMatrix to be row rows high. This method doesn’t redraw the NSMatrix. Accordingly, after calling this method you should send setNeedsDisplay:YES to the NSMatrix. Your code may also need to use sizeToCells after sending this method to resize the NSMatrix to fit the newly added cells.

If the number of rows or columns in the NSMatrix has been changed with renewRows:columns:, then new cells are created only if they’re needed. This allows you to grow and shrink an NSMatrix without repeatedly creating and freeing the cells.

See also:	− addRow, − insertColumn:

insertRow:withCells:

− (void)insertRow:(int)row withCells:(NSArray *)newCells

Inserts a new row of cells before row. The new row is filled with objects from newCells, starting with the object at index 0. Each object in newCells should be an NSCell or one of its subclasses (usually NSActionCell). If row is greater than the number of rows in the NSMatrix, enough rows are created to expand the NSMatrix to be row rows high. newCells should have a sufficient number of cells to fill each new row ([newCells count] must be greater than or equal to [self numberOfColumns]); extra cells are ignored.

This method doesn’t redraw the NSMatrix. Accordingly, after calling this method you should send setNeedsDisplay:YES to the NSMatrix. Your code may also need to use sizeToCells after sending this method to resize the NSMatrix to fit the newly added cells.

See also:	− addRowWithCells:, − insertColumn:withCells:

intercellSpacing

− (NSSize)intercellSpacing

Returns the vertical and horizontal spacing between cells in the NSMatrix.

See also:	− cellSize

isAutoscroll

− (BOOL)isAutoscroll

Returns whether the NSMatrix will be automatically scrolled whenever the mouse is dragged outside the NSMatrix after a mouse-down event within its bounds.

See also:	− scrollCellToVisibleAtRow:column:, − setScrollable:

isSelectionByRect

− (BOOL)isSelectionByRect

Returns YES if a the user can select a rectangle of cells in the NSMatrix by dragging the cursor, NO otherwise.

See also:	− setSelectionFrom:to:anchor:highlight:

p	keyCell

− (id)keyCell

Returns the cell that will be clicked when the user presses the Return key.

See also:	− nextText, − tabKeyTraversesCells

makeCellAtRow:column:

− (NSCell *)makeCellAtRow:(int)row column:(int)column

Creates a new cell at the specified location in the NSMatrix. If the NSMatrix has a prototype cell, it’s copied to create the new cell. If not, and if the NSMatrix has a cell class set, it allocates and initializes (with init) an instance of that class. If the NSMatrix hasn’t had either a prototype cell or a cell class set, makeCellAtRow:column: creates an NSActionCell. Returns the newly created cell.

Your code should never invoke this method directly; it’s used by addRow and other methods when a cell must be created. It may be overridden to provide more specific initialization of cells.

See also:	− addColumn, − addRow, − insertColumn:, − insertRow:, − setCellClass:, − setPrototype:

mode

− (NSMatrixMode)mode

Returns the selection mode of the NSMatrix. Possible return values are defined in NSMatrix.h, and are also listed here:

NSTrackModeMatrix	Cells track the mouse, but do not highlight

NSHighlightModeMatrix	Cells highlight as they track the mouse

NSRadioModeMatrix	Allows no more than one selected cell

NSListModeMatrix	Cells are highlighted, but don’t track the mouse

These modes are explained in detail in the class description.

See also:	− initWithFrame:mode:cellClass:numberOfRows:numberOfColumns:, − initWithFrame:mode:prototype:numberOfRows:numberOfColumns:

mouseDown:

− (void)mouseDown:(NSEvent *)theEvent

Responds to a mouse-down event. A mouse-down event in a text cell initiates editing mode. A double-click in any cell type except a text cell sends the double-click action of the NSMatrix (if there is one) in addition to the single-click action.

Your code should never invoke this method, but you may override it to implement different mouse tracking than NSMatrix does. The response of the NSMatrix depends on its selection mode, as explained in the class description.

See also:	− sendAction, − sendDoubleAction

mouseDownFlags

− (int)mouseDownFlags

Returns the flags that were in effect at the mouse-down event that started the current tracking session (NSMatrix’s mouseDown: method obtains these flags by sending a modifierFlags message to the event passed into mouseDown:). Use this method if you want to access these flags. This method is valid only during tracking; it isn’t useful if the target of the NSMatrix initiates another tracking loop as part of its action method (as a cell that pops up a PopUpList does, for example).

See also:	− sendActionOn: (NSCell)

nextText

− (id)nextText

Returns the object that would be selected if the user presses Tab while editing the last text cell in the NSMatrix.

See also:	− nextKeyView (NSView), − previousText, − setNextText:

numberOfColumns

− (int)numberOfColumns

Returns the number of columns in the NSMatrix.

See also:	− getNumberOfRows:columns:

numberOfRows

− (int)numberOfRows

Returns the number of rows in the NSMatrix.

See also:	− getNumberOfRows:columns:

performKeyEquivalent:

− (BOOL)performKeyEquivalent:(NSEvent *)theEvent

If there’s a cell in the NSMatrix that has a key equivalent equal to the character in [theEvent charactersIgnoringModifiers] (taking into account any key modifier flags) and that cell is enabled, that cell is made to react as if the user had clicked it: by highlighting, changing its state as appropriate, sending its action if it has one, and then unhighlighting. Returns YES if a cell in the NSMatrix responds to the key equivalent in theEvent, NO if no cell responds.

Your code should never send this message; it is sent when the NSMatrix or one of its superviews is the first responder and the user presses a key. You may want to override this method to change the way key equivalents are performed or displayed, or to disable them in your subclass.

previousText

− (id)previousText

Returns the object that would be selected if the user presses Shift-Tab while editing the first text cell in the NSMatrix.

See also:	− nextKeyView (NSView), − nextText, − setPreviousText:

prototype

− (id)prototype

Returns the prototype cell that’s copied whenever a new cell needs to be created, or nil if there is none.

See also:	− initWithFrame:mode:prototype:numberOfRows:numberOfColumns:, − makeCellAtRow:column:

putCell:atRow:column:

− (void)putCell:(NSCell *)newCell atRow:(int)row column:(int)column

Replaces the cell at the specified row and column with newCell, and redraws the cell.

removeColumn:

− (void)removeColumn:(int)column

Removes the column at position column from the NSMatrix and autoreleases the column’s cells. Doesn’t redraw the NSMatrix. Your code should normally send sizeToCells after invoking this method to resize the NSMatrix so that it fits the reduced cell count.

See also:	− removeRow:, − addColumn, − insertColumn:

removeRow:

− (void)removeRow:(int)row

Removes the row at position row from the NSMatrix and autoreleases the row’s cells. Doesn’t redraw the NSMatrix. Your code should normally send sizeToCells after invoking this method to resize the NSMatrix so that it fits the reduced cell count.

See also:	− removeColumn:, − addRow, − insertRow:

renewRows:columns:

− (void)renewRows:(int)newRows columns:(int)newCols

Changes the number of rows and columns in the NSMatrix. This method uses the same cells as before, creating new cells only if the new size is larger; it never frees cells. Doesn’t redisplay the NSMatrix. Your code should normally send sizeToCells after invoking this method to resize the NSMatrix so that it fits the changed cell arrangement. This method deselects all cells in the NSMatrix.

See also:	− addColumn, − addRow, − removeColumn:, − removeRow:

resetCursorRects

− (void)resetCursorRects

Resets cursor rectangles so that the cursor becomes an I-beam over text cells. It does this by sending resetCursorRect:inView: to each cell in the NSMatrix. Any cell that has a cursor rectangle to set up should then send addCursorRect:cursor: back to the NSMatrix.

See also:	− resetCursorRect:inView: (NSCell), − addCursorRect:cursor: (NSView)

scrollCellToVisibleAtRow:column:

− (void)scrollCellToVisibleAtRow:(int)row column:(int)column

If the NSMatrix is in a scrolling view, and row and column represent a valid cell within the NSMatrix, this method scrolls the NSMatrix so that the specified cell is visible.

See also:	− scrollRectToVisible: (NSView)

selectAll:

− (void)selectAll:(id)sender

Selects and highlights all of the cells in the NSMatrix, except for editable text cells and disabled cells. Redisplays the NSMatrix. sender is ignored.

See also:	− selectCell: (NSControl)

selectCellAtRow:column:

− (void)selectCellAtRow:(int)row column:(int)column

Selects the cell at the specified row and column within the NSMatrix. If the specified cell is an editable text cell, its text is selected. If either row or column is −1, then the current selection is cleared (unless the NSMatrix is in NSRadioModeMatrix and doesn’t allow empty selection). Redraws the affected cells.

See also:	− allowsEmptySelection, − mode, − selectCell: (NSControl)

selectCellWithTag:

− (BOOL)selectCellWithTag:(int)anInt

If the NSMatrix has at least one cell whose tag is equal to anInt, the last cell (when viewing the matrix as a row-ordered array) is selected. If the specified cell is an editable text Cell, its text is selected. Returns YES if the NSMatrix contains a cell whose tag matches anInt, or NO if no such cell exists.

See also:	− cellWithTag:, − selectCell: (NSControl)

selectText:

− (void)selectText:(id)sender

If the currently selected cell is editable and enabled, its text is selected. Otherwise, the key cell is selected.

See also:	− keyCell, − selectText: (NSTextField)

selectTextAtRow:column:

− (id)selectTextAtRow:(int)row column:(int)column

If row and column indicate a valid cell within the NSMatrix, and that cell is both editable and selectable, selectTextAtRow:column: selects and then returns the specified cell. If the cell specified by row and column is either not editable or not selectable, selectTextAtRow:column: does nothing, and returns nil. Finally, if row and column indicate a cell that is outside the NSMatrix, selectTextAtRow:column: does nothing and returns the receiver.

See also:	− selectText:

selectedCell

− (id)selectedCell

Returns the most recently selected cell, or nil if no cell is selected. If more than one cell is selected, selectedCell returns the cell that is lowest and furthest to the right in the NSMatrix.

selectedCells

− (NSArray *)selectedCells

Returns an array containing each of the cells in the receiver that is currently highlighted.

See also:	− selectedCell

selectedColumn

− (int)selectedColumn

Returns the column number of the selected cell, or −1 if no cells are selected. If cells in multiple columns are selected, this method returns the number of the last (right-most) column containing a selected cell.

selectedRow

− (int)selectedRow

Returns the row number of the selected cell, or −1 if no cells are selected. If cells in multiple rows are selected, this method returns the number of the last row containing a selected cell.

sendAction

− (BOOL)sendAction

If the selected cell has both an action and a target, its action is sent to its target. If the cell has an action but no target, its action is sent to the target of the NSMatrix. If the cell doesn’t have an action, or if there is no selected cell, the NSMatrix sends its own action to its target. Returns YES if an action was successfully sent to a target.

If the selected cell is disabled, this method does nothing and returns NO.

See also:	− sendDoubleAction, − action (NSCell), − target (NSCell)

sendAction:to:forAllCells:

− (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag

Iterates through all of the cells in the NSMatrix (if flag is YES), or just the selected cells in the NSMatrix (if flag is NO), sending aSelector to anObject for each. Iteration begins with the cell in the upper-left corner of the NSMatrix, proceeding through the appropriate entries in the first row, then on to the next.

aSelector must represent a method that takes a single argument: the id of the current cell in the iteration. aSelector’s return value must be a BOOL. If aSelector returns NO for any cell, sendAction:to:forAllCells: terminates immediately, without sending the message to the remaining cells. If it returns YES, endAction:to:forAllCells: proceeds on to the next cell.

This method is not invoked to send action messages to target objects in response to mouse-down events in the NSMatrix. Instead, you can invoke it if you want to have multiple cells in an NSMatrix interact with an object. For example you could use it to verify the titles in a list of items, or to enable a series of radio buttons based on their purpose in relation to anObject.

sendDoubleAction

− (void)sendDoubleAction

If the NSMatrix has a double-click action, sendDoubleAction sends that message to the target of the NSMatrix. If not, then if the selected cell (as returned by selectedCell) has an action, that message is sent to the selected cell’s target. Finally, if the selected cell also has no action, then the single-click action of the NSMatrix is sent to the target of the NSMatrix.

If the selected cell is disabled, this method does nothing.

Your code shouldn’t invoke this method; it’s sent in response to a double-click event in the NSMatrix. Override it if you need to change the search order for an action to send.

See also:	− sendAction, − ignoresMultiClick: (NSControl)

setAllowsEmptySelection:

− (void)setAllowsEmptySelection:(BOOL)flag

If flag is YES, then the NSMatrix will allow one or zero cells to be selected. If flag is NO, then the NSMatrix will allow one and only one cell (not zero cells) to be selected. This setting has effect only in the NSRadioModeMatrix selection mode.

setAutoscroll:

− (void)setAutoscroll:(BOOL)flag

If flag is YES and the NSMatrix is in a scrolling view, it will be automatically scrolled whenever a the mouse is dragged outside the NSMatrix after a mouse-down event within the bounds of the NSMatrix.

setAutosizesCells:

− (void)setAutosizesCells:(BOOL)flag

If flag is YES, then whenever the NSMatrix is resized, the sizes of the cells change in proportion, keeping the inter-cell space constant; further, this method verifies that the cell sizes and inter-cell spacing add up to the exact size of the NSMatrix, adjusting the size of the cells and updating the NSMatrix if they don’t. If flag is NO, then the inter-cell space changes when the NSMatrix is resized, with the cell size remaining constant.

setBackgroundColor:

− (void)setBackgroundColor:(NSColor *)aColor

Sets the background color for the NSMatrix to aColor, and redraws the NSMatrix. This color is used to fill the space between cells or the space behind any non-opaque cells. The default background color is NSColor’s controlColor.

See also:	− drawsBackground, − setCellBackgroundColor:

setCellBackgroundColor:

− (void)setCellBackgroundColor:(NSColor *)aColor

Sets the background color for the cells in the NSMatrix to aColor. This color is used to fill the space behind non-opaque cells. The default cell background color is NSColor’s controlColor.

See also:	− drawsCellBackground, − setBackgroundColor:

setCellClass:

− (void)setCellClass:(Class)factoryId

Configures the receiver to use instances of factoryId when creating new cells. factoryId should be the id of a subclass of NSCell, which can be obtained by sending the class message to either the NSCell subclass object or to an instance of that subclass. The default cell class is that set with the class method setCellClass:, or NSActionCell if no other default cell class has been specified.

You only need to use this method with matrices initialized with initWithFrame:, since the other initializers allow you to specify an instance-specific cell class or cell prototype.

See also:	− addColumn, − addRow, − insertColumn:, − insertRow:, − makeCellAtRow:column:, − setPrototype:

setCellSize:

− (void)setCellSize:(NSSize)aSize

Sets the width and the height of each of the cells in the NSMatrix to those in aSize. This may change the size of the NSMatrix. Does not redraw the NSMatrix.

See also:	− calcSize (NSControl)

setDelegate:

− (void)setDelegate:(id)anObject

Sets the delegate for messages from the field editor.

See also:	− textShouldBeginEditing:, − textShouldEndEditing:

setDoubleAction:

− (void)setDoubleAction:(SEL)aSelector

Makes aSelector the action sent to the target of the NSMatrix when the user double-clicks a cell. A double-click action is always sent after the appropriate single-click action; the cell’s if it has one, otherwise the single-click action of the NSMatrix.

If an NSMatrix has no double-click action set, then by default a double-click is treated as a single-click.

See also:	− sendDoubleAction, − setAction: (NSControl), − setTarget: (NSControl)

setDrawsBackground:

− (void)setDrawsBackground:(BOOL)flag

Sets whether the receiver draws its background (the space between the cells).

See also:	− backgroundColor, − setDrawsCellBackground

setDrawsCellBackground:

− (void)setDrawsCellBackground:(BOOL)flag

Sets whether the receiver draws the background within each of its cells.

See also:	− cellBackgroundColor, − setDrawsBackground

setErrorAction:

− (void)setErrorAction:(SEL)aSelector

Sets the action that’s sent to the target of the NSMatrix when the user enters an illegal value for the selected cell.

See also:	− action (NSControl), − target (NSControl)

setIntercellSpacing:

− (void)setIntercellSpacing:(NSSize)aSize

Sets the vertical and horizontal spacing between cells in the NSMatrix. By default, both values are 1.0 in the NSMatrix’s coordinate system.

See also:	− cellSize

p	setKeyCell:

− (void)setKeyCell:(NSCell *)aCell

Sets to aCell the cell that will be clicked when the user presses the Return key.

See also:	− setNextText:, − setTabKeyTraversesCells:

setMode:

− (void)setMode:(NSMatrixMode)aMode

Sets the selection mode of the NSMatrix. Possible values for aMode are defined in NSMatrix.h, and include:

NSTrackModeMatrix	Cells track the mouse, but do not highlight

NSHighlightModeMatrix	Cells highlight as they track the mouse

NSRadioModeMatrix	Allows no more than one selected cell

NSListModeMatrix	Cells are highlighted, but don’t track the mouse

These modes are explained in detail in the class description.

See also:	− initWithFrame:mode:cellClass:numberOfRows:numberOfColumns:, − initWithFrame:mode:prototype:numberOfRows:numberOfColumns:

setNextText:

− (void)setNextText:(id)anObject

If the NSMatrix doesn’t already have a next key view, inserts anObject after the receiver in the key view loop of the receiver’s NSWindow. anObject thus becomes the object that would be selected if the user presses Tab while editing the last text cell in the NSMatrix. If the NSMatrix already has a next key view, this method does nothing.

See also:	− setNextKeyView: (NSView), − setTabKeyTraversesCells:

setPreviousText:

− (void)setPreviousText:(id)anObject

If anObject doesn’t already have a next key view, inserts the receiver after anObject in the key view loop of anObject’s NSWindow. If anObject already has a next key view, this method does nothing.

See also:	− setNextKeyView: (NSView)

setPrototype:

− (void)setPrototype:(NSCell *)aCell

Sets the prototype cell that’s copied whenever a new cell needs to be created.

See also:	− initWithFrame:mode:prototype:numberOfRows:numberOfColumns:, − makeCellAtRow:column:

setScrollable:

− (void)setScrollable:(BOOL)flag

If flag is YES, sets all the cells to be scrollable, so that the text they contain scrolls to remain in view if the user types past the edge of the cell. If flag is NO, all cells are made to be non-scrolling. The prototype cell, if there is one, is also set accordingly.

See also:	− prototype, − setScrollable: (NSCell)

setSelectionByRect:

− (void)setSelectionByRect:(BOOL)flag

Sets whether the user can select a rectangle of cells in the NSMatrix by dragging the cursor. If flag is NO, selection is on a row-by-row basis. The default is YES.

See also:	− setSelectionFrom:to:anchor:highlight:

setSelectionFrom:to:anchor:highlight:

− (void)setSelectionFrom:(int)startPos to:(int)endPos anchor:(int)anchorPos highlight:(BOOL)lit

Programmatically selects a range of cells. startPos, endPos, and anchorPos are cell positions, counting from 0 at the upper left cell of the NSMatrix, in row order. For example, the third cell in the top row would be number 2.

startPos and endPos are used to mark where the user would have pressed the mouse button and released it, respectively. anchorPos locates the “last selected cell” with regard to extending the selection by Shift- or Alternate-clicking. Finally, lit determines whether cells selected by this method should be highlighted.

See also:	− isSelectionByRect, − selectedCells:

setState:atRow:column:

− (void)setState:(int)value atRow:(int)row column:(int)column

Sets the state of the cell at row and column to value. For radio-mode matrices, if value is non-zero the specified cell is selected before its state is set to value. If value is zero and the receiver is a radio-mode matrix, then the currently-selected cell is deselected (providing that empty selection is allowed).

This method redraws the affected cell.

See also:	− allowsEmptySelection:, − setState: (NSCell), − selectCellAtRow:column:

p	setTabKeyTraversesCells:

− (void)setTabKeyTraversesCells:(BOOL)flag

Sets whether pressing the Tab key advances the key cell to the next selectable cell in the NSMatrix. If flag is NO, or if there aren’t any selectable cells after the current one, when the user presses the Tab key the next view in the window becomes key. Pressing Shift-Tab causes the key cell to advance in the opposite direction (if flag is NO, or if there aren’t any selectable cells before the current one, the previous view in the window becomes key).

See also:	− selectKeyViewFollowingView: (NSWindow), − selectNextKeyView: (NSWindow), − setKeyCell:, − setNextText:

setValidateSize:

− (void)setValidateSize:(BOOL)flag

If flag is YES, then the size information in the NSMatrix is assumed to be correct. If flag is NO, then calcSize will be invoked before any further drawing is done.

See also:	− calcSize (NSControl)

sizeToCells

− (void)sizeToCells

Changes the width and the height of the NSMatrix frame so that it exactly contains the cells. Does not redraw the NSMatrix.

See also:	− setFrameSize: (NSView), − sizeToFit (NSControl)

sortUsingFunction:context:

− (void)sortUsingFunction:(int (*)(id, id ,void *))comparator context:(void *)context

Sorts the receiver’s cells in ascending order as defined by the comparison function comparator. The comparison function is used to compare two elements at a time and should return NSOrderedAscending if the first element is smaller than the second, NSOrderedDescending if the first element is larger than the second, and NSOrderedSame if the elements are equal. Each time the comparison function is called, it’s passed context as its third argument. This allows the comparison to be based on some outside parameter, such as whether character sorting is case-sensitive or case-insensitive.

See also:	− sortUsingFunction:context: (NSMutableArray)

sortUsingSelector:

− (void)sortUsingSelector:(SEL)comparator

Sorts the receiver’s cells in ascending order as defined by the comparison method comparator. The comparator message is sent to each object in the matrix, and has as its single argument another object in the array. The comparison method is used to compare two elements at a time and should return NSOrderedAscending if the receiver is smaller than the argument, NSOrderedDescending if the receiver is larger than the argument, and NSOrderedSame if they are equal.

See also:	− sortUsingSelector: (NSMutableArray)

p	tabKeyTraversesCells

− (BOOL)tabKeyTraversesCells

Returns whether pressing the Tab key advances the key cell to the next selectable cell in the NSMatrix.

See also:	− keyCell:, − setTabKeyTraversesCells:

textDidBeginEditing:

− (void)textDidBeginEditing:(NSNotification *)notification

Invoked when there’s a change in the text after the receiver gains first responder status. This method’s default behavior is to post an NSControlTextDidBeginEditingNotification along with the receiving object to the default notification center. The posted notification’s user info contains the contents of notification’s user info dictionary, plus an additional key/value pair. The additional key is “NSFieldEditor”; the value for this key is the text object that began editing.

See also:	− textDidChange:, − textDidEndEditing:, − textShouldBeginEditing:

textDidChange:

− (void)textDidChange:(NSNotification *)notification

Invoked upon a key-down event or paste operation that changes the receiver’s contents. This method’s default behavior is to pass this message on to the selected cell (if the selected cell responds to textDidChange:), and then to post an NSControlTextDidChangeNotification along with the receiving object to the default notification center. The posted notification’s user info contains the contents of notification’s user info dictionary, plus an additional key/value pair. The additional key is “NSFieldEditor”; the value for this key is the text object that changed.

See also:	− textDidBeginEditing:, − textDidEndEditing:

textDidEndEditing:

− (void)textDidEndEditing:(NSNotification *)notification

Invoked when text editing ends. This method’s default behavior is to post an NSControlTextDidEndEditingNotification along with the receiving object to the default notification center. The posted notification’s user info contains the contents of notification’s user info dictionary, plus an additional key/value pair. The additional key is “NSFieldEditor”; the value for this key is the text object that began editing. After posting the notification, textDidEndEditing: sends an endEditing: message to the selected cell, draws and makes the selected cell key, and then takes the appropriate action based on which key was used to end editing (Return, Tab, or Back-Tab).

See also:	− textDidBeginEditing:, − textDidChange:, − textShouldEndEditing:

textShouldBeginEditing:

− (BOOL)textShouldBeginEditing:(NSText *)textObject

Invoked to let the NSTextField respond to impending changes to its text. This method’s default behavior is to send control:textShouldBeginEditing: to the receiver’s delegate (passing the receiver and textObject as parameters). textShouldBeginEditing: returns the value obtained from control:textShouldBeginEditing:, unless the delegate doesn’t respond to that method, in which case it returns YES, thereby allowing text editing to proceed.

See also:	− delegate

textShouldEndEditing:

− (BOOL)textShouldEndEditing:(NSText *)textObject

Invoked to let the NSTextField respond to impending loss of first-responder status. This method’s default behavior checks the text field for validity; providing that the field contents are deemed valid, and providing that the delegate responds, control:textShouldEndEditing: is sent to the receiver’s delegate (passing the receiver and textObject as parameters). If the contents of the text field aren’t valid, textShouldEndEditing: sends the error action to the selected cell’s target.

textShouldEndEditing: returns NO if the text field contains invalid contents, otherwise it returns the value passed back from control:textShouldEndEditing:.

See also:	− delegate, − errorAction


NSMenu

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSObject (NSObject)

Declared In:	AppKit/NSMenu.h

Class Description

This class defines an object that manages an application’s menus. An NSMenu object displays a list of items that a user can choose from. When an item is clicked, it may either issue a command directly or bring up another menu (a submenu) that offers further choices. An NSMenu object’s choices are implemented with NSMenuItem objects. Each menu item can be configured either to send its action message to a target or to open a submenu.

It’s typically more convenient to use Interface Builder to construct your application’s menus—see Interface Builder’s Help for more information about using this application. NSMenu and NSMenuItem provide you with additional flexibility to dynamically contruct or modify your application’s menus at run time.

Exactly one NSMenu created by the application is designated as the main menu for the application (with NSApplication’s setMainMenu: method). Depending on the user interface of the host system, the main menu displays itself as a free standing window with a title bar and a list of menu items, as a menu bar with no title, or in some other form. The form a menu takes in the user interface may limit which methods in the class’s interface actually have an effect; for example, on Microsoft Windows submenus can’t be detached. In all cases, however, methods return values that reflect their actual state or ability (isTornOff always returns NO on Microsoft Windows, for example).

A free standing main menu is displayed on top of all other windows whenever the application is active, and can be moved by the user by dragging its title bar. When a submenu is opened, it appears attached to the right of its supermenu with a title bar, allowing the user to drag it away from its supermenu so that it remains on the screen. A detached submenu displays a close button to allow the user to dismiss it (the main menu, of course, never displays a close button). If the user moves a menu window while a submenu is attached, the submenu follows its supermenu. If a menu window lies partly off-screen, when the user tracks the mouse pointer to the edge of the screen, by holding down the mouse button and dragging the mouse pointer, the menu temporarily shifts onto the screen (along with any attached super- or submenus), allowing the user to access all of its items.

Where the main menu appears as a menu bar, it doesn’t display a title, nor do its submenus. The submenus of a menu bar are typical drop-down menus, and submenus of these appear to the right or left, depending on the available screen space. Submenus of a menu bar typically can’t be detached by the user.

NSMenu supports the assignment of keyboard equivalents to its menu items. On Microsoft Windows, the class also supports the assignment of mnemonics to menu items. Any menu item, except those that open submenus, can have a key equivalent, but whether they should depends on the host system’s user interface guidelines. Unlike keyboard equivalents, mnemonics only function when their menu is active, and they can be assigned to menu items which open submenus.

See the NSMenuItem protocol, NSMenuItem class, and NSMenuActionResponder protocol specifications for more information.

Method Types

Controlling allocation zones	+ menuZone

+ setMenuZone:

Creating an NSMenu	− initWithTitle:

Setting up menu commands	− addItemWithTitle:action:keyEquivalent:

− insertItemWithTitle:action:keyEquivalent:atIndex:

− removeItem:

− itemArray

Finding menu items	− itemWithTag:

− itemWithTitle:

Managing submenus	− setSubmenu:forItem:

− submenuAction:

− attachedMenu

− isAttached

− isTornOff

− locationForSubmenu:

− supermenu

Enabling and disabling menu items

− autoenablesItems

− setAutoEnablesItems:

− update

Handling keyboard equivalents	− performKeyEquivalent:

Updating menu layout	− menuChangedMessagesEnabled

− setMenuChangedMessagesEnabled:

− sizeToFit

Displaying context-sensitive help	− helpRequested:

Class Methods

menuZone

+ (NSZone *)menuZone

Returns the zone from which NSMenus should be allocated, creating it if necessary.

setMenuZone:

+ (void)setMenuZone:(NSZone *)zone

Sets the zone from which NSMenus should be allocated to zone.

Instance Methods

addItemWithTitle:action:keyEquivalent:

− (id <NSMenuItem>)addItemWithTitle:(NSString *)aString

action:(SEL)aSelector

keyEquivalent:(NSString *)keyEquiv

Adds a new item with title aString, action aSelector, and key equivalent keyEquiv to the end of the menu. Returns the new menu item.

attachedMenu

− (NSMenu *)attachedMenu

Returns the menu currently attached to the receiver or nil if there’s no such object.

autoenablesItems

− (BOOL)autoenablesItems

Returns whether the receiver automatically enables and disables its menu items based on the NSMenuActionResponder informal protocol. By default NSMenus do autoenable their menu items. See that protocol specification for more information.

See also:	− setAutoenablesItems:

p	helpRequested:

− (void)helpRequested:(NSEvent *)event

Overridden by subclasses to implement specialized context-sensitive help behavior by causing the Help manager to display the help associated with the receiver. Never invoke this method directly.

See also:	− showContextHelpForObject:locationHint: (NSHelpManager)

initWithTitle:

− (id)initWithTitle:(NSString *)aTitle

Initializes and returns a new menu using aTitle for its title. This method is the designated initializer for the class. Returns self.

insertItemWithTitle:action:keyEquivalent:atIndex:

− (id <NSMenuItem>)insertItemWithTitle:(NSString *)aString

action:(SEL)aSelector

keyEquivalent:(NSString *)keyEquiv

atIndex:(unsigned int)index

Adds a new item at index having the title aString, action aSelector, and key equivalent keyEquiv. Returns the new menu item.

isAttached

− (BOOL)isAttached

Returns YES if the receiver is currently attached to another menu, NO otherwise. This method always returns NO on Microsoft Windows.

isTornOff

− (BOOL)isTornOff

Returns NO if the receiver is off-screen or attached to another menu (or if it’s the main menu), YES otherwise. This method always returns NO on Microsoft Windows.

itemArray

− (NSArray *)itemArray

Returns the receiver’s menu items.

ItemWithTag:

− (id <NSMenuItem>)itemWithTag:(int)aTag

Returns the first menu item in the receiver that has aTag as its tag.

itemWithTitle:

− (id <NSMenuItem>)itemWithTitle:(NSString *)aString

Returns the first menu item in the receiver that has aString as its title.

locationForSubmenu:

− (NSPoint)locationForSubmenu:(NSMenu *)aSubmenu

On Mach, returns the screen coordinates where aSubmenu will be displayed when it’s opened as a submenu of the receiver (regardless of its current location). On Microsoft Windows, the coordinates that are reutrned are not meaningful.

p	menuChangedMessagesEnabled

− (BOOL)menuChangedMessagesEnabled

Returns YES if messages are being sent to the application’s windows upon each change to the menu, NO otherwise.

See also:	− setMenuChangedMessagesEnabled:

performKeyEquivalent:

− (BOOL)performKeyEquivalent:(NSEvent *)theEvent

Searches for a menu item in the receiver, or on Microsoft Windows in any of its submenus as well, whose key equivalent exactly matches the character, or character sequence, of the keyboard event theEvent and whose modifier flags match the key-equivalent modifier mask in theEvent, and causes that item to send its action message.

removeItem:

− (void)removeItem:(id <NSMenuItem>)anItem

Removes anItem from the receiver.

setAutoenablesItems:

− (void)setAutoenablesItems:(BOOL)flag

Controls whether the receiver automatically enables and disables its menu items based on the NSMenuActionResponder informal protocol. If flag is YES, menu items are automatically enabled and disabled. If flag is NO, menu items are not automatically enabled or disabled. See the NSMenuActionResponder protocol specification for more information.

See also:	− autoenablesItems

p	setMenuChangedMessagesEnabled:

− (void)setMenuChangedMessagesEnabled:(BOOL)flag

Controls whether the receiver sends messages to the application’s windows upon each menu change. To avoid the “flickering” effect of many successive menu changes, invoke this method with NO as flag, make changes to the menu, and invoke the method again with YES as flag. This has the effect of batching changes and having them applied all at once.

See also:	− menuChangedMessagesEnabled

setSubmenu:forItem:

− (void)setSubmenu:(NSMenu *)aMenu forItem:(id <NSMenuItem>)anItem

Makes aMenu a submenu controlled by anItem, automatically setting anItem’s action to submenuAction:.

setTitle:

− (NSString *)setTitle:(NSString *)aString

Sets the receiver’s title to aString.

See also:	− title

sizeToFit

− (void)sizeToFit

Resizes the receiver to exactly fit its items. On Microsoft Windows, this method has no effect.

submenuAction:

− (void)submenuAction:(id)sender

This is the action method assigned to menu items that open submenus. Never invoke this method directly.

supermenu

− (NSMenu *)supermenu

Returns the receiver’s supermenu or nil if it has none.

title

− (NSString *)title

Returns the receiver’s title.

See also:	− setTitle:

update

− (void)update

Enables or disables the receiver’s menu items based on the NSMenuActionResponder informal protocol and sizes the menu to fit its current menu items if necessary. See the NSMenuActionResponder protocol specification for more information.


NSMenuActionResponder
NSMenuActionResponder (informal protocol)

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Category Of:	NSObject

Declared In:	AppKit/NSMenu.h

Protocol Description

This informal protocol allows your application to update the enabled or disabled status of an NSMenuItem. It declares only one method, validateMenuItem:. By default, every time a user event occurs, NSMenu automatically enables and disables each visible menu item based on criteria described in “Automatic Updating of NSMenuItems,” below. Implement validateMenuItem: in cases where you want to override NSMenu’s default enabling scheme.

NSMenuItems can be enabled or disabled in two ways: explicitly, by sending the setEnabled: message, or automatically, as described below. Automatic updating can be turned on and off with NSMenu’s setAutoenablesItems: message.

Automatic Updating of NSMenuItems

Whenever a user event occurs, the NSMenu object updates the status of every one of its visible menu items. To update the status of a menu item, an NSMenu tries to find the object that responds to the NSMenuItem’s action message. It searches the following objects in order until it finds one that responds to the action message (note that it doesn’t actually send the action message):

•	The NSMenuItem’s target. If the target is non-nil, the search ends here whether the target responds or not.

•	The key window’s responder chain, starting with its first responder.

•	The key window itself.

•	The key window’s delegate.

•	The main window’s responder chain, starting with its first responder.

•	The main window itself.

•	The main window’s delegate.

•	The NSApplication object.

•	The NSApplication object’s delegate.

If none of these objects responds to the action message, the menu item is disabled. If NSMenu finds an object that responds to the action message, it then checks to see if that object responds to the validateMenuItem: method (the method declared in this informal protocol). If validateMenuItem: is not implemented in that object, the menu item is enabled. If it is implemented, the return value of validateMenuItem: indicates whether the menu item should be enabled or disabled.

Here is an example of using validateMenuItem: to override automatic enabling. If your application has a Copy menu item that sends the copy: action message to the first responder, that menu item is automatically enabled any time an object that responds to copy:, such as an NSText object, is the first responder of the key or main window. If you create a class whose instances might become the first responder, and which doesn’t support copying of everything it allows the user to select, you should implement validateMenuItem: in that class. validateMenuItem: will then return NO if items that can’t be copied are selected (or if no items are selected) and YES if all items in the selection can be copied. By implementing validateMenuItem:, you can have the Copy menu item disabled even though the target object does implement the copy: method. If your class never permits copying, then you simply omit an implemention of copy: in that class, and the Copy menu item is disabled automatically whenever an instance of that class is the first responder.

If you send a setEnabled: message to enable or disable a menu item when automatic updating is turned on (with NSMenu’s setAutoEnablesItems:), other objects might undo what you have done after another user event occurs. Hence you can never be sure that the menu item will remain the way you set it. If your application must use setEnabled:, turn off the automatic enabling of menu items in order to get predictable results.

Instance Methods

validateMenuItem:

− (BOOL)validateMenuItem:(NSMenuItem *)aMenuItem

Implemented to override the default action of enabling or disabling aMenuItem. The object implementing this method must be the target of aMenuItem.  It returns YES to enable the aMenuItem, NO to disable it. You can determine which menu item aMenuItem is by querying it for its title, tag, or action.

The following example beeps and disables the menu item “Next Record” if the selected line in a table view is the last one; conversely, it beeps and disables the menu item “Prior Record” if the selected row is the first one in the table view. (countryKeys is an array of names appearing in the table view.)

- (BOOL)validateMenuItem:(NSMenuItem *)anItem

{

    int row = [tableView selectedRow];

    if ([[anItem title] isEqualToString:@"Next Record"] &&

        (row == [countryKeys indexOfObject:[countryKeys lastObject]])) {

        NSBeep();

        return NO;

    }

    if ([[anItem title] isEqualToString:@"Prior Record"] && row == 0 ) {

        NSBeep();

        return NO;

    }

    return YES;

}


NSMenuItem

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSMenuItem

NSObject (NSObject)

Declared In:	AppKit/NSMenuItem.h

Class Description

NSMenuItem is the class that OPENSTEP uses to implement the functionality of the NSMenuItem protocol. The NSMenuItem class defines objects that are used as command items in menus. In addition to implementing all of the methods in the NSMenuItem protocol, the NSMenuItem class also includes some additional private functionality that is needed to maintain binary compatibility with other components of NeXT's OPENSTEP software. Because of this, you cannot replace the NSMenuItem class with a different class which conforms to the NSMenuItem protocol. You may, however, subclass the NSMenuItem class if necessary.

The appearance of NSMenuItem objects is tailored to match the user interface of the host system, presently either Mach or Microsoft Windows.

See the NSMenu class specification and the NSMenuItem protocol specification for more information on menus.

Adopted Protocols

NSMenuItem	+ setUsesUserKeyEquivalents:

+ usesUserKeyEquivalents

- action

- hasSubmenu

- isEnabled

- keyEquivalent

- keyEquivalentModifierMask

- mnemonic

- mnemonicLocation

- representedObject

- setAction:

- setEnabled:

- setKeyEquivalent:

- setKeyEquivalentModifierMask:

- setMnemonicLocation:

- setRepresentedObject:

- setTag:

- setTarget:

- setTitle:

- setTitleWithMnemonic:

- tag

- target

- title

- userKeyEquivalent


NSMenuItem Protocol

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Adopted By:	NSMenuItem

Conforms To:	NSCoding, NSCopying

NSObject (NSObject)

Declared In:	AppKit/NSMenuItem.h

Protocol Description

The NSMenuItem protocol declares methods that are used to manipulate command items in menus. With some implementations of the OpenStep specification (including NeXT’s OPENSTEP), you cannot replace the NSMenuItem class with a different class which conforms to the NSMenuItem protocol. You may, however, subclass the NSMenuItem class if necessary.

See the NSMenu and NSMenuItem class specifications for more information on menus.

Keyboard Equivalents

An object conforming to the NSMenuItem protocol can be assigned a keyboard eqivalent, so that when the user types it the menu item’s action is sent. The keyboard eqivalent is defined in two parts. First is the basic key equivalent, which must be a Unicode character that can be generated by a single key press without modifier keys (Shift excepted). It is also possible to use a sequence of Unicode characters so long as the user’s key mapping is able to generate the sequence with a single key press. The basic key equivalent is set using setKeyEquivalent: and returned by keyEquivalent. The second part defines the modifier keys that must also be pressed. This is set using setKeyEquivalentModifierMask: and returned by keyEquivalentModifierMask. The modifier mask by default includes NSCommandKeyMask, and may also include the masks for the Shift, Alternate, or other modifier keys. Specifying keyboard equivalents in two parts allows you to define a modified keyboard equivalent without having to know which character is generated by the basic key plus the modifier. For example, you can define the keyboard equivalent Command-Alt-f without having to know which character is generated by typing Alt-f.

Certain methods in the NSMenuItem protocol can override assigned keyboard equivalents with those the user has specified in the defaults system. The setUsesUserKeyEquivalents: protocol method turns this behavior on or off, and usesUserKeyEquivalents returns its status. To determine the user-defined key equivalent for an NSMenuItem object, invoke the userKeyEquivalent instance method. If user-defined key equivalents are active and an NSMenuItem object has a user-defined key equivalent, its keyEquivalent method returns the user-defined key equivalent and not the one set using setKeyEquivalent:.

Mnemonics

On certain platforms, currently including Microsoft Windows, an object conforming to the NSMenuItem protocol can also be assigned a mnemonic. Mnemonics can be assigned on other platforms as well, however, they won’t have any effect. Mnemonics are represented by an underlined character in the title of a menu item. The mnemonic can be any character that can be generated by a single key press without modifier keys (Shift excepted). When the menu is active, the user can type the underlined character in the menu item in order to activate that menu item. On Microsoft Windows a user activates the menu by pressing the Alternate key. A particular mnemonic character should only be used once within the set of menu items contained either in the same menu as the menu item or in the application’s main menu.

Method Types

Setting the target and action	− setTarget:

− target

− setAction:

− action

Setting the title	− setTitle:

− title

Setting the tag	− setTag:

− tag

Enabling a menu item	− setEnabled:

− isEnabled

Checking for a submenu	− hasSubmenu

Managing key equivalents	− setKeyEquivalent:

− keyEquivalent

− setKeyEquivalentModifierMask:

− keyEquivalentModifierMask

Managing mnemonics	− setMnemonicLocation:

− mnemonicLocation

− setTitleWithMnemonic:

− mnemonic

Managing user key equivalents	+ setUsesUserKeyEquivalents:

+ usesUserKeyEquivalents

− userKeyEquivalent

Representing an object	− setRepresentedObject:

− representedObject

Class Methods

setUsesUserKeyEquivalents:

+ (void)setUsesUserKeyEquivalents:(BOOL)flag

If flag is YES, menu items conform to user preferences for key equivalents; otherwise, the key equivalents originally assigned to the menu items are used.

See also:	+ usesUserKeyEquivalents, − userKeyEquivalent

usesUserKeyEquivalents

+ (BOOL)usesUserKeyEquivalents

Returns YES if menu items conform to user preferences for key equivalents; otherwise, returns NO.

See also:	+ setUsesUserKeyEquivalents:, − userKeyEquivalent

Instance Methods

action

− (SEL)action

Returns the receiver’s action method.

See also:	− target, − setAction:

hasSubmenu

− (BOOL)hasSubmenu

Returns YES if the receiver has a submenu, NO if it doesn’t.

See also:	− setSubmenu:forItem:(NSMenu)

isEnabled

− (BOOL)isEnabled

Returns YES if the receiver is enabled, NO if not.

See also:	− setEnabled:

keyEquivalent

− (NSString *)keyEquivalent

Returns the receiver’s unmodified keyboard equivalent, or the empty string if one hasn’t been defined. Use keyEquivalentModifierMask to determine the modifier mask for the key equivalent.

See also:	− userKeyEquivalent, − mnemonic, − setKeyEquivalent:

keyEquivalentModifierMask

− (unsigned int)keyEquivalentModifierMask

Returns the receiver’s keyboard equivalent modifier mask.

See also:	− setKeyEquivalentModifierMask:

p	mnemonic

− (NSString *)mnemonic

Returns the character in the menu item title that appears underlined for use as a mnemonic. If there is no mnemonic character, returns an empty string.

See also:	− setTitleWithMnemonic:

p	mnemonicLocation

− (unsigned)mnemonicLocation

Returns the position of the underlined character in the menu item title used as a mnemonic. The position is the zero based index of that character in the title string. If the receiver has no mnemonic character, returns NSNotFound.

See also:	− setMnemonicLocation:

p	representedObject

− (id)representedObject

Returns the object that the receiving menu item represents. For example, you might have a menu list the names of views that are swapped into the same panel. The represented objects would be the appropriate NSView objects. The user would then be able to swtich back and forth between the different views that are displayed by selecting the various menu items.

See also:	− tag, − setRepresentedObject:

setAction:

− (void)setAction:(SEL)aSelector

Sets the receiver’s action method to aSelector.

See also:	− setTarget:, − action

setEnabled:

− (void)setEnabled:(BOOL)flag

Sets whether the receiver is enabled based on flag. If a menu item is disabled, it’s keyboard equivalent and mnemonic are also disabled. See the NSMenuActionResponder informal protocol specification for cautions regarding this method.

See also:	− isEnabled

setKeyEquivalent:

− (void)setKeyEquivalent:(NSString *)aString

Sets the receiver’s unmodified key equivalent to aString. Use setKeyEquivalentModifierMask: to set the appropriate mask for the modifier keys for the key equivalent.

See also:	− setMnemonicLocation:, − keyEquivalent

setKeyEquivalentModifierMask:

− (void)setKeyEquivalentModifierMask:(unsigned int)mask

Sets the receiver’s keyboard equivalent modifiers (indicating modifiers such as the Shift or Alternate keys) to those in mask. mask is an integer bit field containing any of these modifier key masks, combined using the C bitwise OR operator:

NSShiftKeyMask

NSAlternateKeyMask

NSCommandKeyMask

On Mach, you should always set NSCommandKeyMask in mask; on Microsoft Windows, this is not required.

NSShiftKeyMask is relevant only for function keys; that is, for key events whose modifier flags include NSFunctionKeyMask. For all other key events NSShiftKeyMask is ignored and characters typed while the Shift key is pressed are interpreted as the shifted versions of those characters; for example, Command-Shift-‘c’ is interpreted as Command-‘C’.

See the NSEvent class specification for more information about modifier mask values.

See also:	− keyEquivalentModifierMask

p	setMnemonicLocation:

− (void)setMnemonicLocation:(unsigned)location

Sets the character of the menu item title at location that is to be underlined. location must be between 0 and 254. This character identifies the access key on Windows by which users can access the menu item.

See also:	− mnemonicLocation

p	setRepresentedObject:

− (void)setRepresentedObject:(id)anObject

Sets the object represented by the receiver to anObject. By setting a represented object for a menu item you make an association between the menu item and that object. The represented object functions as a more specific form of tag that allows you to associate any object, not just an int, with the items in a menu.

For example, an NSView object might be associated with a menu item—when the user selects the menu item, the represented object is fetched and displayed in a panel. Several menu items might control the display of multiple views in the same panel.

See also:	 − setTag:, − representedObject

setTag:

− (void)setTag:(unsigned int)anInt

Sets the receiver’s tag to anInt.

See also:	− setRepresentedObject:, − tag

setTarget:

− (void)setTarget:(id)anObject

Sets the receiver’s target to anObject.

See also:	− setAction:, − target

setTitle:

− (void)setTitle:(NSString *)aString

Sets the receiver’s title to aString.

See also:	− title

p	setTitleWithMnemonic:

− (void)setTitleWithMnemonic:(NSString *)aString

Sets the title of a menu item with a character underlined to denote an access key (Windows only). Use an ampersand character to mark the character (the one following the ampersand) to be underlined. For example, the following message causes the ‘c’ in ‘Receive’ to be underlined:

[aMenuItem setTitleWithMnemonic:NSLocalizedString(@"Re&ceive")];

See also:	− mnemonic, − setMnemonicLocation:

tag

− (unsigned int)tag

Returns the receiver’s tag.

See also:	− representedObject, − setTag:

target

− (id)target

Returns the receiver’s target.

See also:	− action, − setTarget:

title

− (NSString *)title

Returns the receiver’s title.

See also:	− setTitle:

userKeyEquivalent

− (NSString *)userKeyEquivalent

Returns the user-assigned key equivalent for the receiver.

See also:	− keyEquivalent


NSMutableParagraphStyle
p NSMutableParagraphStyle

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSParagraphStyle : NSObject

Conforms To:	NSCoding (NSParagraphStyle)

NSCopying (NSParagraphStyle)

NSMutableCopying (NSParagraphStyle)

NSObject (NSObject)

Declared In:	AppKit/NSParagraphStyle.h

Class Description

NSMutableParagraphStyle adds methods to its superclass, NSParagraphStyle, for changing the values of the sub-attributes in a paragraph style attribute. See the NSParagraphStyle and NSAttributedString specifications for more information.

Method Types

Setting tab stops	− setTabStops:

− addTabStop:

− removeTabStop:

Setting other style information	− setParagraphStyle:

− setAlignment:

− setFirstLineHeadIndent:

− setHeadIndent:

− setTailIndent:

− setLineBreakMode:

− setMaximumLineHeight:

− setMinimumLineHeight:

− setLineSpacing:

− setParagraphSpacing:

Instance Methods

p	addTabStop:

− (void)addTabStop:(NSTextTab *)tabStop

Adds tabStop to the receiver.

See also:	− removeTabStop:, − setTabStops:, − tabStops (NSParagraphStyle)

p	removeTabStop:

− (void)removeTabStop:(NSTextTab *)tabStop

Removes the first text tab whose location and type are equal to those of tabStop.

See also:	− addTabStop:, − setTabStops:, − tabStops (NSParagraphStyle)

p	setAlignment:

− (void)setAlignment:(NSTextAlignment)alignment

Sets the alignment of the receiver to alignment, which may be one of:

    NSLeftTextAlignment

    NSRightTextAlignment

    NSCenterTextAlignment

    NSJustifiedTextAlignment

    NSNaturalTextAlignment

See also:	− alignment (NSParagraphStyle)

p	setFirstLineHeadIndent:

− (void)setFirstLineHeadIndent:(float)aFloat

Sets the distance in points from the leading margin of a text container to the beginning of the paragraph’s first line to aFloat. This value must be nonnegative.

See also:	− setHeadIndent:, − setTailIndent:, − firstLineHeadIndent (NSParagraphStyle)

p	setHeadIndent:

− (void)setHeadIndent:(float)aFloat

Sets the distance in points from the leading margin of a text container to the beginning of lines other than the first to aFloat. This value must be nonnegative.

See also:	− setFirstLineHeadIndent:, − setTailIndent:, − headIndent (NSParagraphStyle)

p	setLineBreakMode:

− (void)setLineBreakMode:(NSLineBreakMode)mode

Sets the mode used to break lines in a layout container to mode, which may be one of:

NSLineBreakByWordWrapping

NSLineBreakByCharWrapping

NSLineBreakByClipping

NSLineBreakByTruncatingHead

NSLineBreakByTruncatingTail

NSLineBreakByTruncatingMiddle

See the description of lineBreakMode in the NSParagraphStyle class specification for descriptions of these values.

p	setLineSpacing:

− (void)setLineSpacing:(float)aFloat

Sets the space in points added between lines within the paragraph to aFloat. This value must be nonnegative.

See also:	− setMaximumLineHeight:, − setMinimumLineHeight:, − setParagraphSpacing:, − lineSpacing (NSParagraphStyle)

p	setMaximumLineHeight:

− (void)setMaximumLineHeight:(float)aFloat

Sets the maximum height that any line in the paragraph style will occupy, regardless of the font size or size of any attached graphic, to aFloat. Glyphs and graphics exceeding this height will overlap neighboring lines; however, a maximum height of zero implies no line height limit. This value must be nonnegative.

Note:	Although this limit applies to the line itself, line spacing adds extra space between adjacent lines.

See also:	− setMinimumLineHeight:, − setLineSpacing:, − maximumLineHeight (NSParagraphStyle)

p	setMinimumLineHeight:

− (void)setMinimumLineHeight:(float)aFloat

Sets the minimum height that any line in the paragraph style will occupy, regardless of the font size or size of any attached graphic, to aFloat. This value must be nonnegative.

See also:	− setMaximumLineHeight:, − setLineSpacing:, − minimumLineHeight (NSParagraphStyle)

p	setParagraphSpacing:

− (void)setParagraphSpacing:(float)aFloat

Sets the space added at the end of the paragraph to separate it from the following paragraph to aFloat. This value must be nonnegative.

See also:	− setLineSpacing:, − paragraphSpacing (NSParagraphStyle)

p	setParagraphStyle:

− (void)setParagraphStyle:(NSParagraphStyle *)aStyle

Replaces the sub-attributes of the receiver with those in aStyle.

p	setTabStops:

− (void)setTabStops:(NSArray *)tabStops

Replaces the tab stops in the receiver with tabStops.

See also:	− addTabStop:, − removeTabStop:, − tabStops (NSParagraphStyle)

p	setTailIndent:

− (void)setTailIndent:(float)aFloat

Sets the distance in points from the margin of a text container to the end of lines to aFloat. If positive, this is the distance from the leading margin (for example, the left margin in left-to-right text). If zero or negative, it’s the distance from the trailing margin.

For example, to create a paragraph style that fits exactly in a 2-inch wide container, set its head indent to 0.0 and its tail indent to 0.0. To create a paragraph style with quarter-inch margins, set its head indent to 0.25 and its tail indent to −0.25.

See also:	− setHeadIndent:, − setFirstLineHeadIndent:, − tailIndent (NSParagraphStyle)


NSNibAwaking

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Category Of:	NSObject

Declared In:	AppKit/NSNibLoading.h

Protocol Description

This informal protocol consists of a single method, awakeFromNib. Classes can implement this method to perform final initialization of state after objects have been loaded from an Interface Builder archive.

Instance Methods

awakeFromNib

− (void)awakeFromNib

Implemented to prepare the receiver for service after it has been loaded from an Interface Builder archive, or nib file. An awakeFromNib message is sent to each object loaded from the archive, but only if it can respond to the message, and only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it’s guaranteed to have all its outlet instance variables set.

Note:	This method is also sent during Interface Builder’s test mode to objects instantiated from loaded palettes, which include executable code for the objects. It isn’t sent to objects defined solely by using the Classes display of the nib file window in Interface Builder.

When an Interface Builder archive is loaded into an application, each custom object from the archive is first initialized with an init message, or initWithFrame: if the object is a kind of NSView. It’s then more specifically initialized with the properties that it was configured with using Interface Builder. This part of the initialization process uses any setVariable: methods that are available (where variable is the name of an instance variable whose value was set in Interface Builder). Finally, after all the objects are fully initialized, each receives an awakeFromNib message.

The order in which objects are loaded from the archive is not guaranteed. Therefore, it’s possible for a setVariable: message to be sent to an object before its companion objects have been unarchived. For this reason, setVariable: methods should not send messages to other objects in the archive. However, messages to other objects can safely be sent from within awakeFromNib—by which time it’s assured that all the objects are unarchived and initialized (though not necessarily awakened, of course).

Typically, awakeFromNib is implemented for classes whose instances are used as the owners of a loaded nib file (shown as “File’s Owner” in Interface Builder). Such a class has the express purpose of connecting the loaded objects with objects in the application, and can thereafter be disposed of, or remain in the capacity of a controller or coordinator for the loaded objects. For example, suppose that a nib file contains two custom views that must be positioned relative to each other at run time. Trying to position them when either one of the views is initialized (in initWithCoder: or a setVariable: method) might fail, since the other views might not be unarchived and initialized yet. However, it can be done in the nib file owner’s awakeFromNib method (firstView and secondView are outlets of the file’s owner):

- (void)awakeFromNib

{

    NSRect viewFrame;

    if ([[self superclass] instancesRespondToSelector:@selector(awakeFromNib)]) {

        [super awakeFromNib];

    }

    viewFrame = [firstView frame];

    viewFrame.origin.x += viewFrame.size.width;

    [secondView setFrame:viewFrame];

    return;

}

Note the testing of the superclass before invoking its implementation of awakeFromNib. The Application Kit declares a prototype for this method, but doesn’t implement it. Because there’s no default implementation of awakeFromNib, be sure to invoke it only when the object does in fact respond.

See also:	+ loadNibNamed:owner: (NSBundle Additions),

− awakeAfterUsingCoder (NSObject class of the Foundation Kit),

− initWithCoder: (NSCoding protocol of the Foundation Kit)

+ initialize (NSObject class of the Foundation Kit)


NSOpenPanel

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSSavePanel : NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSOpenPanel.h

Note:	The inheritance and conformance information shown above applies only to NSOpenPanel on OpenStep for Windows. On Mach, NSOpenPanel inherits from (in this order) NSSavePanel, NSPanel, NSWindow, NSResponder, and NSObject.

Class Description

NSOpenPanel provides the Open dialog on OpenStep for Windows or the Open panel on the OpenStep for Mach user interface. Applications use the Open panel (or dialog) as a convenient way to query the user for the name of a file to open. The Open panel can only be run modally.

Most of this class’s behavior is defined by its superclass, NSSavePanel. NSOpenPanel adds to this behavior by:

•	Letting you specify the types (by file-name extension) of the items that will appear in the panel

•	Letting the user select files, directories, or both

•	Letting the user select multiple items at a time

Typically, you access an NSOpenPanel by invoking the openPanel method. When the class receives an openPanel message, it tries to reuse an existing panel rather than create a new one. If a panel is reused, its attributes are reset to the default values so that the effect is the same as receiving a new panel. Because Open dialogs and panels may be reused, you shouldn’t modify the instance returned by openPanel except through the methods listed below (and through those inherited from NSSavePanel). For example, you can set the panel’s title and whether it allows multiple selection, but not the arrangement of the buttons within the panel. If you must modify the Open panel substantially, create and manage your own instance using the alloc... and init... methods rather than the openPanel method.

The following code example shows the NSOpenPanel displaying only files with extensions of ".td" and allowing multiple selection. If the user makes a selection and clicks the OK button (that is, runModalForDirectory:file:types: returns NSOKButton), this method opens each selected file:

- (void)openDoc:(id)sender

{

    int result;

    NSArray *fileTypes = [NSArray arrayWithObject:@"td"];

    NSOpenPanel *oPanel = [NSOpenPanel openPanel];

    [oPanel setAllowsMultipleSelection:YES];

    result = [oPanel runModalForDirectory:NSHomeDirectory() file:nil

 types:fileTypes];

    if (result == NSOKButton) {

        NSArray *filesToOpen = [oPanel filenames];

        int i, count = [filesToOpen count];

        for (i=0; i<count; i++) {

              NSString *aFile = [filesToOpen objectAtIndex:i];

              id currentDoc = [[ToDoDoc alloc] initWithFile:aFile];

        }

    }

}

Method Types

Obtaining the shared instance	+ openPanel

Running the panel modally	− runModalForDirectory:file:types:

− runModalForTypes:

Getting the user selection	− filenames

Allowing browser selections	− setCanChooseFiles:

− canChooseFiles

− setCanChooseDirectories:

− canChooseDirectories

Allowing multiple selections	− setAllowsMultipleSelection:

− allowsMultipleSelections

Class Methods

openPanel

+ (NSOpenPanel *)openPanel

Returns a "recycled" NSOpenPanel or, if one doesn’t yet exist, creates it before returning it. New and recycled NSOpenPanels are reset to default values, which include selection of single files only.

Instance Methods

allowsMultipleSelection

− (BOOL)allowsMultipleSelection

Returns whether the NSOpenPanel’s browser allows the user to open multiple files (and directories) at a time. If multiple files or directories are allowed, then the filename method—inherited from NSSavePanel—returns a non-nil value only if one and only one file is selected. By contrast, NSOpenPanel’s filenames method always returns the selected files, even if only one file is selected.

See also:	− filename(NSSavePanel), − filenames, − setAllowsMultipleSelection:

canChooseDirectories

− (BOOL)canChooseDirectories

Returns whether the Open dialog or panel allows the user to choose directories to open.

See also:	− setCanChooseDirectories:

canChooseFiles

− (BOOL)canChooseFiles

Returns whether the Open dialog or panel allows the user to choose files to open.

See also:	− setCanChooseFiles:

filenames

− (NSArray *)filenames

Returns an array containing the absolute paths (as NSString objects) of the selected files and directories. If multiple selections aren’t allowed, the array contains a single name. The filenames method is preferable over NSSavePanel’s filename to get the name or names of files and directories that the user has selected.

runModalForDirectory:file:types:

− (int)runModalForDirectory:(NSString *)path

file:(NSString *)name

types:(NSArray *)fileTypes

Displays the NSOpenPanel and begins its event loop. The NSOpenPanel displays the files in path that match the types in fileTypes (an NSArray of file extensions as NSString objects). If path is nil the directory the application is "currently in" is substituted (on Mach, this is the user’s home directory); in later invocations of the shared NSOpenPanel, the directory is by default the last directory where a file was opened, unless specified otherwise with setDirectory:.  If all files and subdirectories should be included in the next column of a browser, fileTypes should be nil. If filename specifies a particular file, it is selected when the Open dialog or panel is presented to the user; otherwise, filename should be nil. This method returns NSOKButton (if the user clicks the OK button) or NSCancelButton (if the user clicks the Cancel button).

See also:	− runModalForTypes:

runModalForTypes:

− (int)runModalForTypes:(NSArray *)fileTypes

Invokes the runModalForDirectory:file:types: method, using nil for file and directory (see description of  runModalForDirectory:file:types:). Returns the value returned by that method.

setAllowsMultipleSelection:

− (void)setAllowsMultipleSelection:(BOOL)flag

Sets whether the user can select multiple files (and directories) at one time for opening.

See also:	− allowsMultipleSelection

setCanChooseDirectories:

− (void)setCanChooseDirectories:(BOOL)flag

Sets whether the user can select directories in the NSOpenPanel’s browser. When a directory is selected, the OK button is enabled only if flag is YES.

See also:	− canChooseDirectories

setCanChooseFiles:

− (void)setCanChooseFiles:(BOOL)flag

Sets whether the user can select files in the NSOpenPanel’s browser or type the files to be accepted.

See also:	− canChooseFiles


NSPageLayout

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSPageLayout.h

Note:	On Mach platforms, NSPageLayout inherits from NSPanel and conforms to NSCoding.

Class Description

NSPageLayout is a panel that queries the user for information such as paper type and orientation. This information is stored in an NSPrintInfo object, and is later used when printing. The NSPageLayout panel is created, displayed, and run (in a modal loop) when a runPageLayout: message is sent to the NSApplication object. By default, this message is sent up the responder chain when the user chooses the Page Setup menu item (on Mach platforms the menu item is called Page Layout).

Typically, you access an NSPageLayout panel by invoking the pageLayout method. When the class receives a pageLayout message, it returns an existing panel rather than create a new one. If a panel is reused, its attributes are reset to the default values so that the effect is the same as receiving a new panel. Because an NSPageLayout object may be reused, you shouldn’t modify the instance returned by pageLayout, except using the methods below. If you must modify an NSPageLayout object in other ways than those allowed by its methods, create and manage your own instance using the alloc... and init... methods rather than modify the object returned by pageLayout.

In most cases it is unnecessary to subclass NSPageLayout—you can customize an NSPageLayout by specifying your own accessory view. You can add your own controls to an NSPageLayout through the setAccessoryView: method. The panel is automatically resized to accommodate the NSView that you’ve added. Note that NSPageLayout does not have accessor methods to obtain the state of its controls. If controls you add through an accessory view need to know the values of  existing controls  (or vice versa) use the viewWithTag: method. You obtain a specific control object by sending viewWithTag: to the NSPageLayout object passing one of the tags defined in AppKit/NSPageLayout.h. The value can then be obtained by sending an appropriate accessor message to the returned control object.

Method Types

Creating an NSPageLayout	+ pageLayout

Running an NSPageLayout	− runModal

− runModalWithPrintInfo:

Customizing an NSPageLayout	− accessoryView

− setAccessoryView:

Accessing the NSPrintInfo	− printInfo

− readPrintInfo

− writePrintInfo

Updating the display	− convertOldFactor:newFactor:

− pickedButton:

− pickedOrientation:

− pickedPaperSize:

− pickedUnits:

Class Methods

pageLayout

+ (NSPageLayout *)pageLayout

Returns a shared NSPageLayout object or a newly created one if it doesn’t already exist.

Instance Methods

accessoryView

− (NSView *)accessoryView

Returns the receiver’s accessory view (used to customize the receiver).

See also:	− setAccessoryView:

p	convertOldFactor:newFactor:

− (void)convertOldFactor:(float *)old newFactor:(float *)new

This method is for Mach platforms only—it is not defined for other platforms. The standard unit used to measure a paper’s dimensions is a point (for example, NSPrintInfo defines a paper’s size in points). However, the user can select a different unit of measurement from the NSPageLayout panel. Use this method to get the ratio between a point and the currently selected unit of measurement. Unless this method is invoked by pickedUnits: both old and new will be set to the same ratio value.

The pickedUnits: method is invoked when the user selects a new unit of measurement from the NSPageLayout panel. Subclasses should override the pickedUnits: method to update any controls, located on the accessory view, that display dimensional values. Use this method to get the old and new ratios. See pickedUnits: for details.

p	pickedButton:

− (void)pickedButton:(id)sender

This method is for Mach platforms only—it is not defined for other platforms. Invoked when either the OK or Cancel buttons are clicked, and stops the receiver’s modal loop. If the OK button was clicked, this method verifies that the height, width and scale entries are acceptable (they must hold positive numbers). If not, the unacceptable entry is selected and the panel isn’t stopped. Subclasses should override this method to verify that the controls on the accessory view contain acceptable values.

See also:	− pickedOrientation:, − pickedPaperSize:, − pickedUnits:

p	pickedOrientation:

− (void)pickedOrientation:(id)sender

This method is for Mach platforms only—it is not defined for other platforms. Invoked when the user selects a page orientation (i.e., protrait or landscape). This method updates the height and width fields, and redraws the paper view.

See also:	− pickedButton:, − pickedPaperSize:, − pickedUnits:

p	pickedPaperSize:

− (void)pickedPaperSize:(id)sender

This method is for Mach platforms only—it is not defined for other platforms. Invoked when the user selects a paper size from the paper size list. Updates the height and width fields, redraws the paper view, and may switch the protrait/landscape orientation.

See also:	− pickedButton:, − pickedOrientation:, − pickedUnits:

p	pickedUnits:

− (void)pickedUnits:(id)sender

This method is for Mach platforms only—it is not defined for other platforms. Invoked when the user selects a new unit of measurement from the Units list. The height and width fields are updated.

Subclasses should override this method to update controls in the accessory view that contain unit values. The ratios returned by the convertOldFactor:newFactor: method should be used to calculate the new values as shown below, where myField is an NSTextField located on the accessory view that needs to be updated:

- pickedUnitsLsender

{

float old, new;

/* At this point the units have been selected but not set. */

[self convertOldFactor:&old newFactor:&new];

/* Update myField based on the conversion factors. */

[myField setFloatValue:([myField floatValue]*new/old)];

/* Set the selected units. */

return [super pickedUnits:sender];

}

See also:	− pickedButton:, − pickedOrientation:, − pickedPaperSize:

printInfo

− (NSPrintInfo *)printInfo

Returns the NSPrintInfo object that is used when the receiver is run (set using the runModal or runModalWithPrintInfo: methods).

See also:	− readPrintInfo, − writePrintInfo

readPrintInfo

− (void)readPrintInfo

Sets the receiver’s values to those stored in the NSPrintInfo object used when the receiver is run.

See also:	− printInfo, − writePrintInfo, − runModal, − runModalWithPrintInfo:

runModal

− (int)runModal

Displays the receiver and begins the modal loop. The receiver’s values are recorded in the shared NSPrintInfo object. Returns NSCancelButton if the user clicks the Cancel button, otherwise returns NSOKButton.

See also:	− pickedButton:, − runModalWithPrintInfo:

runModalWithPrintInfo:

− (int)runModalWithPrintInfo:(NSPrintInfo *)printInfo

Displays the receiver and begins the modal loop. The receiver’s values are recorded in printInfo. Returns NSCancelButton if the user clicks the Cancel button, otherwise returns NSOKButton.

See also:	− pickedButton:, − runModal:

setAccessoryView:

− (void)setAccessoryView:(NSView *)aView

Adds an NSView to the receiver. Invoke this method to add a custom view containing your controls. The receiver is automatically resized to accommodate aView. This method can be invoked repeatedly to change the accessory view depending on the situation. If aView is nil, then the receiver’s current accessory view, if any, is removed.

See also:	− accessoryView

writePrintInfo

− (void)writePrintInfo

Writes the receiver’s values to the NSPrintInfo object used when the receiver is run.

See also:	− printInfo, − readPrintInfo, − runModal, − runModalWithPrintInfo:


NSPanel

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSWindow : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSPanel.h

Class Description

A panel is a special kind of window, typically serving an auxiliary function in an application. NSPanel adds a few special behaviors to NSWindow in support of the role panels play:

•	Panels are by default not released when they’re closed, since they’re usually lightweight and often reused.

•	On-screen panels, except for attention panels, are removed from the screen when the application isn’t active, and are restored when the application again becomes active. This reduces screen clutter.

•	Panels can become the key window, but not the main window.

•	If a panel is the key window and has a close button, it closes itself when the user presses the Escape key.

In addition to these automatic behaviors, NSPanel allows you to configure certain other behaviors common to some kinds of panels:

•	A panel can be precluded from becoming the key window unless the user clicks in a view that responds to typing. This prevents key window from shifting to the panel unnecessarily. The setBecomesKeyOnlyIfNeeded: method controls this behavior.

•	Palettes and similar panels can be made to float above standard windows and other panels. This prevents them from being covered and keeps them readily available to the user. The setFloatingPanel: method controls this behavior.

•	A panel can be made to receive mouse and keyboard events even when another window or panel is being run modally or run in a modal session. This permits actions in the panel to affect the modal window or panel. The setWorksWhenModal: method controls this behavior. See “Modal Windows” in the NSWindow class specification for more information on modal windows and panels.

Method Types

Configuring panel behavior	− setFloatingPanel:

− isFloatingPanel

− setBecomesKeyOnlyIfNeeded:

− becomesKeyOnlyIfNeeded

− setWorksWhenModal:

− worksWhenModal

Instance Methods

becomesKeyOnlyIfNeeded

− (BOOL)becomesKeyOnlyIfNeeded

Returns YES if the receiver becomes the key window only when the user clicks a view object that needs to be first responder to receive event and action messages; for example if it edits text or otherwise accepts keyboard input. Returns NO if it becomes the key window whenever clicked. NSPanel by default returns NO, indicating that panels become key as other windows do.

See also:	− setBecomesKeyOnlyIfNeeded:, − needsPanelToBecomeKey (NSView)

isFloatingPanel

− (BOOL)isFloatingPanel

Returns YES if the receiver is set to float above normal windows, NO otherwise. A floating panel’s window level is NSFloatingWindowLevel. NSPanels by default returns NO, indicating that they inhabit the normal window level.

See also:	− setFloatingPanel:, − level (NSWindow)

setBecomesKeyOnlyIfNeeded:

− (void)setBecomesKeyOnlyIfNeeded:(BOOL)flag

Controls whether the receiver only becomes the key window when the user clicks a view object that edits text or otherwise accepts keyboard input. If flag is YES, the receiver only becomes the key window when keyboard input is needed; if flag is NO, it becomes the key window whenever clicked. This behavior is by default not set. You should consider setting it only if most controls in the NSPanel aren’t text fields, and if the choices that can be made by entering text can also be made in another way (such as by clicking an item in a pick list).

See also:	− becomesKeyOnlyIfNeeded, − needsPanelToBecomeKey (NSView)

setFloatingPanel:

− (void)setFloatingPanel:(BOOL)flag

Controls whether the receiver floats above normal windows. If flag is YES, sets the receiver’s window level to NSFloatingWindowLevel; if flag is NO, sets the receiver’s window level to NSNormalWindowLevel. The default is NO. It’s appropriate for an NSPanel to float above other windows only if all of the following conditions are true:

•	It’s small enough not to obscure whatever’s behind it.

•	It’s oriented more to the mouse than to the keyboard—that is, if it doesn’t become the key window or becomes so only when needed.

•	It needs to remain visible while the user works in the application’s normal windows; for example, if the user must frequently move the cursor back and forth between a normal window and the panel (such as a tool palette), or if the panel gives information relevant to the user’s actions in a normal window.

•	It hides when the application is deactivated (the default behavior for panels).

See also:	− isFloatingPanel, − setWindowLevel: (NSWindow)

setWorksWhenModal:

− (void)setWorksWhenModal:(BOOL)flag

Controls whether the receiver receives keyboard and mouse events even when some other window is being run modally. If flag is YES, the application object sends events to the receiver even during a modal loop or session; if flag is NO, the receiver gets no events while a modal loop or session is running. See “Modal Windows” in the NSWindow class specification for more information on modal windows and panels.

See also:	− worksWhenModal, − runModalForWindow: (NSApplication), − runModalSession: (NSApplication)

worksWhenModal

− (BOOL)worksWhenModal

Returns YES if the receiver is able to receive keyboard and mouse events even when some other window is being run modally, NO otherwise. NSPanels by default returns NO, indicating their ineligibility for events during a modal loop or session. See “Modal Windows” in the NSWindow class specification for more information on modal windows and panels.

See also:	− setWorksWhenModal:, − runModalForWindow: (NSApplication), − runModalSession: (NSApplication)


NSParagraphStyle
p NSParagraphStyle

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSCopying

NSMutableCopying

NSObject (NSObject)

Declared In:	AppKit/NSParagraphStyle.h

Class Description

NSParagraphStyle and its subclass NSMutableParagraphStyle encapsulate the paragraph or ruler attributes used by the NSAttributedString classes. Instances of these classes are often referred to as paragraph style objects, or when no confusion will result, as paragraph styles.

A paragraph style object represents a complex attribute value in an attributed string, storing a number of sub-attributes that affect paragraph layout for the characters of the string. Among these sub-attributes are alignment, tab stops, and indents. See the method descriptions for more information on each sub-attribute.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

NSCopying	− copyWithZone:

NSMutableCopying	− mutableCopyWithZone:

Method Types

Creating an NSParagraphStyle	+ defaultParagraphStyle

Accessing style information	− alignment

− firstLineHeadIndent

− headIndent

− tailIndent

− tabStops

− lineBreakMode

− maximumLineHeight

− minimumLineHeight

− lineSpacing

− paragraphSpacing

Class Methods

p	defaultParagraphStyle

+ (NSParagraphStyle *)defaultParagraphStyle

Returns the default paragraph style, which contains these values:

Sub-Attribute	Default Value

Alignment	NSNaturalTextAlignment

Tab stops	12 left-aligned tabs, spaced by 28.0 points

Line break mode	NSLineBreakByWordWrapping

All others	0.0

See individual method descriptions for explanations of each sub-attribute.

See also:	− init

Instance Methods

p	alignment

− (NSTextAlignment)alignment

Returns the text alignment of the paragraph style, one of:

    NSLeftTextAlignment

    NSRightTextAlignment

    NSCenterTextAlignment

    NSJustifiedTextAlignment

    NSNaturalTextAlignment

Natural text alignment is realized as left or right alignment depending on the line sweep direction of the first script contained in the paragraph.

See also:	− setAlignment: (NSMutableParagraphStyle)

p	firstLineHeadIndent

− (float)firstLineHeadIndent

Returns the distance in points from the leading margin of a text container to the beginning of the paragraph’s first line. This value is always nonnegative.

See also:	− headIndent, − tailIndent, − setFirstLineHeadIndent: (NSMutableParagraphStyle)

p	headIndent

− (float)headIndent

Returns the distance in points from the leading margin of a text container to the beginning of lines other than the first. This value is always nonnegative.

See also:	− firstLineHeadIndent, − tailIndent, − setHeadIndent: (NSMutableParagraphStyle)

p	lineBreakMode

− (NSLineBreakMode)lineBreakMode

Returns the mode that should be used to break lines when laying out the paragraph’s text. This is one of:

Value	Meaning

NSLineBreakByWordWrapping	Wrapping occurs at word boundaries, unless the word itself doesn’t fit on a single line.

NSLineBreakByCharWrapping	Wrapping occurs before the first character that doesn’t fit.

NSLineBreakByClipping	Lines are simply not drawn past the edge of the text container.

NSLineBreakByTruncatingHead	Each line is displayed so that the end fits in the container and the missing text is indicated by some kind of ellipsis glyph.

NSLineBreakByTruncatingTail	Each line is displayed so that the beginning fits in the container and the missing text is indicated by some kind of ellipsis glyph.

NSLineBreakByTruncatingMiddle	Each line is displayed so that the beginning and end fit in the container and the missing text is indicated by some kind of ellipsis glyph in the middle.

See also:	− setLineBreakMode: (NSMutableParagraphStyle)

p	lineSpacing

− (float)lineSpacing

Returns the space in points added between lines within the paragraph (commonly known as leading). This value is always nonnegative.

See also:	− maximumLineHeight, − minimumLineHeight, − paragraphSpacing, − setLineSpacing: (NSMutableParagraphStyle)

p	maximumLineHeight

− (float)maximumLineHeight

Returns the maximum height that any line in the paragraph style will occupy, regardless of the font size or size of any attached graphic. Glyphs and graphics exceeding this height will overlap neighboring lines; however, a maximum height of zero implies no line height limit. This value is always nonnegative. The default value is zero.

Note:	Although this limit applies to the line itself, line spacing adds extra space between adjacent lines.

See also:	− minimumLineHeight, − lineSpacing, − setMaximumLineHeight: (NSMutableParagraphStyle)

p	minimumLineHeight

− (float)minimumLineHeight

Returns the minimum height that any line in the paragraph style will occupy, regardless of the font size or size of any attached graphic. This value is always nonnegative.

See also:	− maximumLineHeight, − lineSpacing, − setMinimumLineHeight: (NSMutableParagraphStyle)

p	paragraphSpacing

− (float)paragraphSpacing

Returns the space added at the end of the paragraph to separate it from the following paragraph. This value is always nonnegative.

See also:	− lineSpacing, − setParagraphSpacing: (NSMutableParagraphStyle)

p	tabStops

− (NSArray *)tabStops

Returns the NSTextTab objects, sorted by location, that define the tab stops for the paragraph style.

See also:	− location (NSTextTab), − setTabStops: (NSMutableParagraphStyle), − addTabStop: (NSMutableParagraphStyle), − removeTabStop: (NSMutableParagraphStyle)

p	tailIndent

− (float)tailIndent

Returns the distance in points from the margin of a text container to the end of lines. If positive, this is the distance from the leading margin (for example, the left margin in left-to-right text). If zero or negative, it’s the distance from the trailing margin.

For example, a paragraph style designed to fit exactly in a 2-inch wide container has a head indent of 0.0 and a tail indent of 0.0. One designed to fit with a quarter-inch margin has a head indent of 0.25 and a tail indent of −0.25.

See also:	− headIndent, − firstLineHeadIndent, − setTailIndent: (NSMutableParagraphStyle)


NSPasteboard

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSPasteboard.h

Purpose

An NSPasteboard object is an interface to a pasteboard server that allows you to transfer data between applications, as in copy, cut, and paste operations. The data can be placed in the pasteboard server in a variety of representations.

Principal Attributes

•	Owners	•	Change count

•	Data types	•	Name

Creation

+ generalPasteboard

+ pasteboardWithName:

Commonly Used Methods

− types	Returns an NSArray of pasteboard data types.

− declareTypes:owner:	Prepares NSPasteboard to receive new data.

− dataForType:	Reads data from a pasteboard.

− setData:forType: 	Writes data to a pasteboard.

− stringForType:	Reads an NSString from a pasteboard.

− setStringForType:	Writes an NSString to a pasteboard.

Class Description

NSPasteboard objects transfer data to and from the pasteboard server. The server is shared by all running applications. It contains data that the user has cut or copied, as well as other data that one application wants to transfer to another. NSPasteboard objects are an application’s sole interface to the server and to all pasteboard operations.

Named Pasteboards

Data in the pasteboard server is associated with a name that indicates how it’s to be used. Each set of data and its associated name is, in effect, a separate pasteboard, distinct from the others. An application keeps a separate NSPasteboard object for each named pasteboard that it uses. There are five standard pasteboards in common use:

General pasteboard	The pasteboard that’s used for ordinary cut, copy, and paste operations. It holds the contents of the last selection that’s been cut or copied.

Font pasteboard	The pasteboard that holds font and character information and supports Copy Font and Paste Font commands that my be implemented in a text editor.

Ruler pasteboard	The pasteboard that holds information about paragraph formats in support of the Copy Ruler and Paste Ruler commands that may be implemented in a text editor.

Find pasteboard	The pasteboard that holds information about the current state of the active application’s Find panel. This information permits users to enter a search string into the Find panel, then switch to another application to conduct another search.

Drag pasteboard	The pasteboard that stores data to be moved as the result of a drag operation.

Each standard pasteboard is identified by a unique name (stored in global string objects):

NSGeneralPboard

NSFontPboard

NSRulerPboard

NSFindPboard

NSDragPboard

You can create private pasteboards by asking for an NSPasteboard object with any name other than those listed above. Data in a private pasteboard may then be shared by passing its name between applications.

The NSPasteboard class makes sure there’s never more than one object for each named pasteboard on the computer. If you ask for a new object when one has already been created for the pasteboard with that name, the existing object will be returned.

Data Types

Data can be placed in the pasteboard server in more than one representation. For example, an image might be provided both in Tag Image File Format (TIFF) and as encapsulated PostScript code (EPS). Multiple representations give pasting applications the option of choosing which data type to use. In general, an application taking data from the pasteboard should choose the richest representation it can handle—rich text over plain ASCII, for example. An application putting data in the pasteboard should promise to supply it in as many data types as possible, so that as many different applications as possible can use it.

Filtering services transform the data from one representation to another. Typically, these services aren’t invoked until data is read from a pasteboard.

Data types are identified by NSString objects containing the full type name. These global variables identify the string objects for the standard pasteboard types:

Type	Description

NSColorPboardType	NSColor data

NSDataLinkPboardType	Defines a link between documents

NSFileContentsPboardType	A representation of a file’s contents

NSFilenamesPboardType	NSString designating one or more file names

NSFontPboardType	Font and character information

NSPostScriptPboardType	Encapsulated PostScript code (EPS)

NSRulerPboardType	Paragraph formatting information

NSRTFPboardType	Rich Text Format (RTF)

NSRTFDPboardType	RTFD formatted file contents

NSSelectionPboardType	Describes a selection for use with data linking

NSStringPboardType	NSString data

NSTabularTextPboardType	NSString containing tab-separated fields of text

NSTIFFPboardType	Tag Image File Format (TIFF)

Typically, data is written to the pasteboard using setData:forType: and read using dataForType:. Some of these types can only be written with certain methods. For instance, NSFilenamesPboardType’s form is an array of NSStrings and requires special handling. Use these methods to write these types:

Type	Writing Method	Reading Method

NSColorPboardType	NSColor class methods	NSColor class methods

NSFileContentsPboardType	writeFileContents:	readFileContentsType:toFile:

NSFilenamesPboardType	setPropertyList:forType:	propertyListForType:

NSStringPboardType	setString:forType:	stringForType:

You don’t have to write the data (using setData:forType:) in all types that you’ve declared for the pasteboard: This avoids unneeded conversions. If data is requested from a pasteboard in a format that’s not present, the owner of the pasteboard receives a pasteboard:provideDataForType: message notifying it that it needs to supply the data in that format. It then supplies data in the requested type by invoking one of the setData:forType:, setString:forType:, or setPropertyList:forType: methods on the pasteboard.

The class methods pasteboardByFilteringData:ofType:, pasteboardByFilteringFile:, and pasteboardByFilteringTypesInPasteboard: return a pasteboard with data that is filtered into all types derivable from the current types using available filter services. (For more information on filter services see /NextLibrary/Documentation/NextDev/TasksAndConcepts/ProgrammingTopics/Services.rtf.) The pasteboards returned by these methods are autoreleased instances of NSPasteboard.

Types other than those listed above can also be used. For example, your application may keep data in a private format that’s richer than any of the existing types. That format can also be used as a pasteboard type.

Reading and Writing RTFD Data

The NSRTFDPboardType is used for the contents of an RTFD file package (a directory containing an RTF text file and one or many EPS and TIFF image files). There are several ways to work with RTFD data. If you have an NSFileWrapper object that represents an RTFD file wrapper, you can send it the serializedRepresentation method to return the RTFD data and write that to the pasteboard as follows:

NSFileWrapper *tempRTFDData = [[[NSFileWrapper alloc]

initWithPath:@"/tmp/foo.rtfd"] autorelease];

[pboard setData:[tempRTFDData serializedRepresentation]

forType:NSRTFDPboardType];

In addition to NSFileWrapper, classes such as NSAttributedString and NSText can return RTFD data. If you’re using one of these classes, you would do the following to write RTFD data to the pasteboard:

NSAttributedString *attrString;

...

[pboard setData:[attrString RTFDFromRange:NSMakeRange(0, [attrString length])]

forType:NSRTFDPboardType];

Change Count

The change count is a computer-wide variable that increments every time the contents of the pasteboard changes (a new owner is declared). An independent change count is maintained for each named pasteboard. By examining the change count, an application can determine whether the current data in the pasteboard is the same as the data it last received.

The changeCount, addTypes:owner:, and declareTypes:owner: methods return the change count. A types or availableTypeFromArray: message should be sent by the pasteboard before reading data so that the change count is valid.

Errors

Except where errors are specifically mentioned in the method descriptions, any communications error with the pasteboard server raises an NSPasteboardCommunicationException.

Method Types

Creating and releasing an NSPasteboard object

+ generalPasteboard

+ pasteboardByFilteringData:ofType:

+ pasteboardByFilteringFile:

+ pasteboardByFilteringTypesInPasteboard:

+ pasteboardWithName:

+ pasteboardWithUniqueName

+ typesFilterableTo:

− releaseGlobally

Referring to a pasteboard by name 	− name

Writing data	− addTypes:owner:

− declareTypes:owner:

− setData:forType:

− setPropertyList:forType:

− setString:forType:

− writeFileContents:

Determining Types 	− availableTypeFromArray:

− types

Reading Data 	− changeCount

− dataForType:

− propertyListForType:

− readFileContentsType:toFile:

− stringForType:

Methods Implemented by the Owner

− pasteboardChangedOwner:

− pasteboard:provideDataForType:

Class Methods

generalPasteboard

+ (NSPasteboard *)generalPasteboard

Returns the general NSPasteboard. This invokes pasteboardWithName: to obtain the pasteboard.

pasteboardByFilteringData:ofType:

+ (NSPasteboard *)pasteboardByFilteringData:(NSData *)data ofType:(NSString *)type

Creates and returns a new pasteboard with a unique name that supplies data in as many types as possible given the available filter services. The returned pasteboard also declares data of the supplied type type.

No filter service is invoked until the data is actually requested, so invoking this method is reasonably inexpensive.

pasteboardByFilteringFile:

+ (NSPasteboard *)pasteboardByFilteringFile:(NSString *)filename

Creates and returns a new pasteboard with a unique name that supplies the data in filename in as many types as possible given the available filter services. No filter service is invoked until the data is actually requested, so invoking this method is reasonably inexpensive.

pasteboardByFilteringTypesInPasteboard:

+ (NSPasteboard *)pasteboardByFilteringTypesInPasteboard:(NSPasteboard *)pasteboard

Creates and returns a new pasteboard with a unique name that supplies the data on pasteboard in as many types as possible given the available filter services. This process can be thought of as expanding the pasteboard, since the new pasteboard generally will contain more representations of the data than pasteboard.

This method returns pasteboard if pasteboard was returned by one of the pasteboardByFiltering... methods, so a pasteboard can’t be expanded multiple times. This method only returns the original types and the types that can be created as a result of a single filter; the pasteboard will not have defined types that are the result of translation by multiple filters.

No filter service is invoked until the data is actually requested, so invoking this method is reasonably inexpensive.

pasteboardWithName:

+ (NSPasteboard *)pasteboardWithName:(NSString *)name

Returns the pasteboard for the name pasteboard. A new object is created only if the application doesn’t yet have a NSPasteboard object for the specified name; otherwise, the existing one is returned. To get a standard pasteboard, name should be one of the following variables:

NSGeneralPboard

NSFontPboard

NSRulerPboard

NSFindPboard

NSDragPboard

Other names can be assigned to create private pasteboards for other purposes.

pasteboardWithUniqueName

+ (NSPasteboard *)pasteboardWithUniqueName

Creates and returns a new pasteboard with a name that is guaranteed to be unique with respect to other pasteboards on the computer. This method is useful for applications that implement their own interprocess communication using pasteboards.

typesFilterableTo:

+ (NSArray *)typesFilterableTo:(NSString *)type

Returns an autoreleased array listing the types of data that type can be converted to by available filter services. The array contains the original type.

Instance Methods

addTypes:owner:

− (int)addTypes:(NSArray *)newTypes owner:(id)newOwner

Adds the data types in newTypes to the NSPasteboard and declares a new owner newOwner. This method can be useful when multiple entities (such as a combination of application and library methods) contribute data for a single copy command. It should only be invoked after a declareTypes:owner: message has been sent for the same types. The owner for the new types may be different from the owner(s) of the previously declared types.

Returns the new change count, or 0 in case of an error.

See also:	− changeCount

availableTypeFromArray:

− (NSString *)availableTypeFromArray:(NSArray *)types

Scans the types defined by types and returns the first type that matches a type declared on the receiving NSPasteboard.

A types or availableTypeFromArray: message should be sent before reading any data from the NSPasteboard.

changeCount

− (int)changeCount

Returns the NSPasteboard’s change count.

See also:	− declareTypes:owner:

dataForType:

− (NSData *)dataForType:(NSString *)dataType

Reads the dataType representation of the current contents of the NSPasteboard. dataType should be one of the types returned by the types method. A types or availableTypeFromArray: message should be sent before invoking dataForType:.

If the data is successfully read, this method returns the data. It returns nil if the contents of the pasteboard have changed (if the change count has been incremented by a declareTypes:owner: message) since they were last checked with the types method. It also returns nil if the pasteboard server can’t supply the data in time—for example, if the NSPasteboard’s owner is slow in responding to a pasteboard:provideDataForType: message and the interprocess communication times out. All other errors raise an NSPasteboardCommunicationException exception.

If nil is returned, the application should put up a panel informing the user that it was unable to carry out the paste operation.

The NSData object that this method returns is autoreleased.

declareTypes:owner:

− (int)declareTypes:(NSArray *)newTypes owner:(id)newOwner

Prepares the NSPasteboard for a change in its contents by declaring the new types of data it will contain and a new owner. This is the first step in responding to a user’s copy or cut command and must precede the messages that actually write the data. A declareTypes:owner: message essentially changes the contents of the pasteboard: It invalidates the current contents of the pasteboard and increments its change count.

newTypes is an array of NSStrings that name types the new contents of the pasteboard may assume. The types should be ordered according to the preference of the source application, with the most preferred type coming first (typically, the richest representation).

The newOwner is the object responsible for writing data to the pasteboard in all the types listed in newTypes. You can write the data immediately after declaring the types, or wait until it’s required for a paste operation. If you wait, the owner will receive a pasteboard:provideDataForType: message requesting the data in a particular type when it’s needed. You might choose to write data immediately for the most preferred type, but wait for the others to see whether they’ll be requested.

The newOwner can be NULL if data is provided for all types immediately. Otherwise, the owner should be an object that won’t be released. It should not, for example, be the NSView that displays the data if that NSView is in a window that might be closed.

Returns the pasteboard’s new change count.

See also:	− setString:forType:, − addTypes:owner:, − changeCount

name

− (NSString *)name

Returns the NSPasteboard’s name.

See also:	+ pasteboardWithName:

propertyListForType:

− (id)propertyListForType:(NSString *)dataType

Returns a property list object using the type specified by dataType.

 A property list is an object of the NSArray, NSData, NSDictionary, or NSString classes—or any combination thereof.

A types or availableTypeFromArray: message should be sent before invoking propertyListForType:.

This method invokes dataForType:.

See also:	− setPropertyList:forType:

readFileContentsType:toFile:

− (NSString *)readFileContentsType:(NSString *)type toFile:(NSString *)filename

Reads data representing a file’s contents from the NSPasteboard, and writes it to the file filename. An availableTypeFromArray: or types message should be sent before invoking readFileContentsType:toFile:.

Data of any file contents type should only be read using this method. type should generally be specified; if type is NULL, a type based on filename’s extension (as returned by NSCreateFileContentsPboardType()) is substituted. If data matching type isn’t found on the NSPasteboard, data of type NSFileContentsPboardType is requested. Returns the name of the file that the data was actually written to.

See also:	− writeFileContents:

releaseGlobally

− (void)releaseGlobally

Releases the NSPasteboard’s resources in the pasteboard server. Since an NSPasteboard object is an autoreleased instance of NSPasteboard, it isn’t released by this method, and its retain count isn’t changed.

After this method is invoked, no other application will be able to use the named NSPasteboard. A temporary, privately named pasteboard can be released this way when it’s no longer needed, but a standard NSPasteboard should never be released globally.

setData:forType:

− (BOOL)setData:(NSData *)data forType:(NSString *)dataType

Writes data to the pasteboard server. dataType gives the type of data being written; it must be a type that was declared in the previous declareTypes:owner: message. data points to the data to be sent to the pasteboard server.

Returns YES if the data is successfully written or returns NO if ownership of the pasteboard has changed. Any other error raises an NSPasteboardCommunicationException.

See also:	− setPropertyList:forType:, − setString:forType:

setPropertyList:forType:

− (BOOL)setPropertyList:(id)propertyList forType:(NSString *)dataType

Writes data to the pasteboard server. dataType gives the type of data being written; it must be a type that was declared in the previous declareTypes:owner: message. propertyList points to the data to be sent to the pasteboard server.

This method invokes setData:forType: with a serialized property list parameter.

Returns YES if the data is successfully written or returns NO if ownership of the pasteboard has changed. Any other error raises an NSPasteboardCommunicationException.

See also:	− setString:forType:

setString:forType:

− (BOOL)setString:(NSString *)string forType:(NSString *)dataType

Writes data to the pasteboard server. dataType gives the type of data being written; it must be a type that was declared in the previous declareTypes:owner: message. string points to the data to be sent to the pasteboard server.

This method invokes setPropertyList:forType: to perform the write.

Returns YES if the data is successfully written or returns NO if ownership of the pasteboard has changed. Any other error raises an NSPasteboardCommunicationException.

See also:	− setData:forType:, − setString:forType:

stringForType:

− (NSString *)stringForType:(NSString *)dataType

Returns an NSString using the type specified by dataType. A types or availableTypeFromArray: message should be sent before invoking stringForType:.

This method invokes propertyListForType: to obtain the string.

types

− (NSArray *)types

Returns an array of the NSPasteboard’s data types.

Returns an array of the types that were declared for the current contents of the NSPasteboard. The array is an array of NSStrings holding the type names. Types are listed in the same order that they were declared.

A types or availableTypeFromArray: message should be sent before reading any data from the NSPasteboard.

See also:	− declareTypes:owner:, − dataForType:, NSUniqueString()

writeFileContents:

− (BOOL)writeFileContents:(NSString *)filename

Writes the contents of the file filename to the NSPasteboard object and declares the data to be of type NSFileContentsPboardType and also of a type appropriate for the file’s extension (as returned by NSCreateFileContentsPboardType() when passed the files extension), if it has one. Returns YES if the data from filename was successfully written to the NSPasteboard and NO otherwise.

See also:	− readFileContentsType:toFile:

Methods Implemented by the Owner

pasteboardChangedOwner:

− (void)pasteboardChangedOwner:(NSPasteboard *)sender

Notifies a prior owner of the sender pasteboard (and owners of representations on the pasteboard) that the pasteboard has changed owners. This method is optional and need only be implemented by pasteboard owners that need to know when they have lost ownership. The owner is not able to read the contents of the pasteboard when responding to this method. The owner should be prepared to receive this method at any time, even from within the declareTypes:owner: used to declare ownership.

See also:	− changeCount

pasteboard:provideDataForType:

− (void)pasteboard:(NSPasteboard *)sender

provideDataForType:(NSString *)type

Implemented by the owner (previously declared in a declareTypes:owner: message) to provide promised data. The owner receives a pasteboard:provideDataForType: message from the sender pasteboard when the data is required for a paste operation; type gives the type of data being requested. The requested data should be written to sender using the setData:forType:, setPropertyList:forType:, or setString:forType: methods.

pasteboard:provideDataForType: messages may also be sent to the owner when the application is shut down through Application's terminate: method. This is the method that’s invoked in response to a Quit command. Thus the user can copy something to the pasteboard, quit the application, and still paste the data that was copied.

A pasteboard:provideDataForType: message is sent only if type data hasn’t already been supplied. Instead of writing all data types when the cut or copy operation is done, an application can choose to implement this method to provide the data for certain types only when they’re requested.

If an application writes data to the NSPasteboard in the richest, and therefore most preferred, type at the time of a cut or copy operation, its pasteboard:provideDataForType: method can simply read that data from the pasteboard, convert it to the requested type, and write it back to the pasteboard as the new type.


NSPopUpButton

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSButton : NSControl : NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSPopUpButton.h

Purpose

An NSPopUpButton object controls a pop-up list or a pull-down list, from which a user can select an item.

Principal Attribute

A list of objects that conform to the NSMenuItem protocol.

Creation

Interface Builder

Commonly Used Methods

− selectedItem	Returns the currently selected item.

− indexOfSelectedItem	Returns an integer identifying the currently selected item.

− titleOfSelectedItem	Returns a string identifying the currently selected item.

Class Description

The NSPopUpButton class defines objects that implement the pop-up and pull-down lists of the OpenStep graphical user interface. You normally create an NSPopUpButton using Interface Builder.

When configured to display a pop-up list, an NSPopUpButton contains a number of options and displays as its title the option that was last selected. A pop-up list is often used for selecting items from a small- to medium-sized set of options (like the zoom factor for a document window). It’s a useful alternative to a matrix of radio buttons or an NSBrowser when screen space is at a premium; a zoom factor pop-up can easily fit next to a scroll bar at the bottom of a window, for example.

When configured to display a pull-down list, an NSPopUpButton is generally used for selecting commands in a very specific context. You can think of a pull-down list as a compact form of menu. A pull-down list’s title isn’t affected by the user’s actions, and a pull-down list always displays a title that identifies the type of commands it contains. When the commands only make sense in the context of a particular display, a pull-down list can be used in that display to keep the related actions nearby and to keep them out of the way when that display isn’t visible. For example, Interface Builder has a set of commands that only apply to the Classes view of the nib file window. Those commands are contained in a pull-down list in that view.

The items in the pop-up list or pull-down list (referred to simply as a list in this class description) are objects that conform to the NSMenuItem protocol. Thus, you can send any message defined in that protocol to any item in the list.

Using an NSPopUpButton

Although the NSPopUpButton class defines an initialization method and methods that set up the list created by this class, you usually don’t invoke these methods in your program. The typical way to create an NSPopUpButton is to use Interface Builder. You also define the NSPopUpButton’s target and action, as well as the targets and actions of each item in the NSPopUpButton’s list, using Interface Builder. The NSPopUpButton methods you use most often are the methods that tell you which item is selected.

For example, suppose you want to create a pop-up list from which your user may select a language. Your want your controller object to set an instance variable named language to an enum constant that corresponds to the value that the user has chosen. You use Interface Builder to create the NSPopUpButton object, name it (languagePopUp in this example) add items to it, and configure it as a pop-up list. The actual code you write might look like this:

typedef enum _languageValue {

    English,

    French,

    German

} languageValue;

- (void)setLanguage:(id)sender

{

    NSString *title = [languagePopUp titleOfSelectedItem];

    if ([title isEqualToString:@"English"])

        language = English;

    else if ([title isEqualToString:@"French"])

        language = French;

    else if ([title isEqualToString:@"German"])

        language = German;

}

Method Types

Initializing an NSPopUpButton	− initWithFrame:pullsDown:

Setting the Type of List	− setPullsDown:

− pullsDown

− setAutoenablesItems:

− autoenablesItems

Inserting and Deleting Items	− addItemWithTitle:

− addItemsWithTitles:

− insertItemWithTitle:atIndex:

− removeAllItems

− removeItemWithTitle:

− removeItemAtIndex:

Modifying an Item	− setFont:

− font

Getting the User’s Selection	− selectedItem

− titleOfSelectedItem

− indexOfSelectedItem

− stringValue

Setting the Current Selection	− selectItemAtIndex:

− selectItemWithTitle:

− setTitle:

Querying the NSPopUpButton	− indexOfItemWithTitle:

− numberOfItems

− itemArray

− itemAtIndex:

− itemTitleAtIndex:

− itemTitles

− itemWithTitle:

− lastItem

Target and Action	− setAction

− action

− setTarget:

− target

Setting the State	− synchronizeTitleAndSelectedItem

Instance Methods

action

− (SEL)action

Returns the action to be sent to the NSPopUpButton’s target when an item is selected from the list.

See also:	− setAction:, − target

addItemWithTitle:

− (void)addItemWithTitle:(NSString *)title

Adds an item named title to the end of the list. This method then calls synchronizeTitleAndSelectedItem to make sure that the title displayed matches the currently selected item.

See also:	− insertItemWithTitle:atIndex:, − removeItemWithTitle:, − setTitle:

addItemsWithTitles:

− (void)addItemsWithTitles:(NSArray *)itemTitles

Adds multiple items to the end of the list. The titles for the new items are taken from the itemTitles array. Once the items are added, this method uses synchronizeTitleAndSelectedItem to make sure that the title displayed matches the currently selected item.

See also:	− insertItemWithTitle:atIndex:, − removeAllItems, − removeItemWithTitle:

autoenablesItems

− (BOOL)autoenablesItems

Returns whether the NSPopUpButton automatically enables and disables its items every time a user event occurs. Autoenabling is turned on unless you send the message setAutoenablesItems:NO to the NSPopUpButton. See the NSMenuActionResponder informal protocol for more information on autoenabling menu items.

See also:	− setAutoenablesItems:

font

− (NSFont *)font

Returns the NSFont used for the items’ titles.

See also:	− setFont:

indexOfItemWithTitle:

− (int)indexOfItemWithTitle:(NSString *)title

Returns the index of the item whose title matches title or −1 if no match is found.

indexOfSelectedItem

− (int)indexOfSelectedItem

Returns the index of the item last selected by the user or −1 if there’s no selected item.

See also:	− selectedItem, − titleOfSelectedItem

initWithFrame:pullsDown:

− (id)initWithFrame:(NSRect)frameRect pullsDown:(BOOL)flag

Initializes a newly allocated NSPopUpButton, giving it the dimensions specified by frameRect. If flag is YES, the receiver is initialized to operate as a pull-down list; otherwise, it operates as a pop-up list. If you allocate and initialize an NSPopUpButton in code, you are responsible for releasing it.

See also:	− pullsDown, − setPullsDown:

insertItemWithTitle:atIndex:

− (void)insertItemWithTitle:(NSString *)title atIndex:(int)index

Inserts an item with the name title at position index in the list. Index 0 indicates the top item. Once the item is inserted, this method uses synchronizeTitleAndSelectedItem to make sure that the title displayed matches the currently selected item.

If an item with the name title already exists in the list, it’s removed and the new one is added. This essentially moves title to a new position. If you want to move an item, it’s better to invoke removeItemWithTitle: explicitly and then send this method.

See also:	− addItemWithTitle:, − addItemsWithTitles:, − indexOfItemWithTitle:, − removeItemWithTitle:

itemArray

− (NSArray *)itemArray

Returns the NSArray that holds the list’s items. The NSPopUpButton’s list is actually an NSArray of objects conforming to the NSMenuItem protocol. Usually you access the list’s items and modify the list by sending messages directly to the NSPopUpButton rather than accessing the NSArray.

See also:	− itemAtIndex:, − insertItemWithTitle:atIndex:, − removeItemAtIndex:

itemAtIndex:

− (id <NSMenuItem>)itemAtIndex:(int)index

Returns the list item at index. If there is no item at index, this method returns nil.

See also:	− itemWithTitle:, − lastItem

itemTitleAtIndex:

− (NSString *)itemTitleAtIndex:(int)index

Returns the title of the item at index. If there is no item at index, this method returns the empty string.

See also:	− itemTitles

itemTitles

− (NSArray *)itemTitles

Returns an NSArray object that holds the titles of all of the items in the list. The titles appear in the order in which the items appear in the list.

See also:	− itemTitleAtIndex:, − itemWithTitle:, − numberOfItems

itemWithTitle:

− (id <NSMenuItem>)itemWithTitle:(NSString *)title

Returns the item whose title is title. If there is no item with this title, this method returns nil.

See also:	− addItemWithTitle:, − selectItemWithTitle:, − itemAtIndex:, − indexOfItemWithTitle:

lastItem

− (id <NSMenuItem>)lastItem

Returns the last item in the list.

See also:	− itemAtIndex:

numberOfItems

− (int)numberOfItems

Returns the number of items in the list.

See also:	− lastItem

pullsDown

− (BOOL)pullsDown

Returns YES if the receiver is configured as a pull-down list or NO if it’s configured as a pop-up list.

See also:	− setPullsDown:

removeAllItems

− (void)removeAllItems

Removes all items in the receiver’s item list. This method then uses synchronizeTitleAndSelectedItem to refresh the list.

See also:	− numberOfItems, − removeItemAtIndex:, − removeItemWithTitle:

removeItemAtIndex:

− (void)removeItemAtIndex:(int)index

Removes the item at index. This method then uses synchronizeTitlesAndSelectedItem to make sure the title displayed matches the currently selected item.

See also:	− insertItemWithTitle:atIndex:, − removeAllItems, − removeItemWithTitle:

removeItemWithTitle:

− (void)removeItemWithTitle:(NSString *)title

Removes the item named title. This method then uses synchronizeTitleAndSelectedItem to refresh the list.

See also:	− addItemWithTitle:, − removeAllItems, − removeItemAtIndex:

selectedItem

− (id <NSMenuItem>)selectedItem

Returns the item last selected by the user (the item that was highlighted when the user released the mouse button). If there is no selected item, this method returns nil. It is possible for a pop-up list’s selected item to be its title item.

See also:	− stringValue

selectItemAtIndex:

− (void)selectItemAtIndex:(int)index

Selects the item at index and invokes synchronizeTitleAndSelectedItem to make sure the title displayed matches the currently selected item.

See also:	− indexOfSelectedItem

selectItemWithTitle:

− (void)selectItemWithTitle:(NSString *)title

Selects the item named title and invokes synchronizeTitleAndSelectedItem to make sure the title displayed matches the currently selected item.

See also:	− indexOfItemWithTitle:, − addItemWithTitle:, − setTitle:

setAction:

− (void)setAction:(SEL)aSelector

Sets the NSPopUpButton’s action method to aSelector. The action message is sent to the NSPopUpButton’s target when an item is selected from the list.

See also:	− action, − setTarget:

setAutoenablesItems:

− (void)setAutoenablesItems:(BOOL)flag

Sets whether the NSPopUpButton automatically enables and disables its items every time a user event occurs. Autoenabling is turned on unless you specify NO as the value for flag. See the NSMenuActionResponder informal protocol for more information on autoenabling menu items.

See also:	− autoenablesItems

setFont:

− (void)setFont:(NSFont *)fontObject

Sets the font used for the items’ titles to fontObject. The NSPopUpButton redraws itself at this point, but since it normally won’t be on the screen when it receives this message, this shouldn’t cause any undesirable side-effects.

See also:	− font

setPullsDown:

− (void)setPullsDown:(BOOL)flag

If flag is YES, the receiver is configured as a pull-down list. If flag is NO, the receiver is configured as a pop-up list.

See also:	− initWithFrame:pullsDown:, − pullsDown

setTarget:

− (void)setTarget:(id)anObject

Sets the target for action messages to anObject.

See also:	− target, − setAction:

setTitle:

− (void)setTitle:(NSString *)title

Selects the item named title if such an item exists. If the item does not exist, it first adds the item to the end of the list, then selects it and invokes the method synchronizeTitleAndSelectedItem.

See also:	− addItemWithTitle:, − selectItemWithTitle:

stringValue

− (NSString *)stringValue

Returns the title of the selected item by invoking titleOfSelectedItem.

See also:	− selectedItem

synchronizeTitleAndSelectedItem

− (void)synchronizeTitleAndSelectedItem

Ensures that the receiver’s title agrees with the title of the selected item (see indexOfSelectedItem). If there’s no selected item, this method selects the first item in the item list and sets the receiver’s title to match. This method is useful in subclasses that directly select items in the item matrix or that override setTitle:. This method has no effect on pull-down lists.

See also:	− itemArray

target

− (id)target

Returns the target for action messages.

See also:	− action

titleOfSelectedItem

− (NSString *)titleOfSelectedItem

Returns the title of the item last selected by the user or the empty string if there’s no such item.

See also:	− indexOfSelectedItem, − stringValue

Notifications

NSPopUpButtonWillPopUpNotification

Posted when the NSPopUpButton receives a mouse-down event; that is, when the user is about to select an item from the list. The notification contains:

Notification Object	the selected NSPopUpButton

Userinfo	None


NSPrintInfo

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSCopying

NSObject (NSObject)

Declared In:	AppKit/NSPrintInfo.h

Class Description

An NSPrintInfo object stores information that’s used to generate PostScript output. A shared NSPrintInfo object is automatically created for an application and is used by default for all printing jobs for that application. You can create any number of additional NSPrintInfo objects; however, only one can be “active” at a time, set using the setSharedPrintInfo: class method. You get the shared NSPrintInfo object using the sharedPrintInfo class method.

An NSPrintInfo object is used by NSPrintOperation objects to control printing (it is passed to a NSPrintOperation object which makes a copy of it to use during an operation). If you create special instances of NSPrintInfo objects for a specific printing task, you must ensure that your NSPrintInfo object is the shared one, or instantiate an NSPrintOperation object specifying your NSPrintInfo object.

Normally you don’t set NSPrintInfo attributes directly—this is done by instances of NSPageLayout and NSPrintPanel. The NSView that’s being printed may also supercede some NSPrintInfo settings. In particular, an NSView can supply the range of pages in the document and can provide its own pagination mechanism through the knowsPagesFirst:last: and rect:forPage: methods (see the documentation of these methods in the NSView class for details).

If the NSView doesn’t supply pagination information, the NSPrintInfo’s vertical and horizontal pagination constants are used to trigger these built-in pagination mechanisms:

Pagination Constant	Meaning

NSAutoPagination 	The image is diced into equal-sized rectangles and placed in one column

of pages.

NSFitPagination 	The image is scaled to produce one column or one row of pages.

NSClipPagination	The image is clipped to produce one column or row of pages.

Vertical and horizontal pagination needn’t be the same. However, if either dimension is scaled (NSFitPagination), the other dimension is scaled by the same amount to avoid stretching the image. If both dimensions are scaled, the scaling factor that produces the smallest image is used. Note that NSPrintInfo’s scaling factor is independent of the scaling that’s imposed by pagination and is applied after the document has been paginated.

NSPrintInfo uses points as the unit of measurement for paper size and margin width in the methods described below. See the NSFont specification for a discussion of points.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

NSCopying	− copyWithZone:

Method Types

Initializing an NSPrintInfo	− initWithDictionary:

Managing the shared NSPrintInfo	+ setSharedPrintInfo:

+ sharedPrintInfo

Managing the printing rectangle	+ sizeForPaperName:

− bottomMargin

− leftMargin

− orientation

− paperName

− paperSize

− rightMargin

− setBottomMargin:

− setLeftMargin:

− setOrientation:

− setPaperName:

− setPaperSize:

− setRightMargin:

− setTopMargin:

− topMargin

Pagination	− horizontalPagination

− setHorizontalPagination:

− setVerticalPagination:

− verticalPagination

Positioning the image on the page	− isHorizontallyCentered

− isVerticallyCentered

− setHorizontallyCentered:

− setVerticallyCentered:

Specifying the printer	+ defaultPrinter

+ setDefaultPrinter:

− printer

− setPrinter:

Controlling printing	− jobDisposition

− setJobDisposition:

− setUpPrintOperationDefaultValues

Accessing the dictionary	− dictionary

Class Methods

defaultPrinter

+ (NSPrinter *)defaultPrinter

Returns the user’s default printer. Returns nil if the printer can not be found.

See also:	+ setDefaultPrinter:

setDefaultPrinter:

+ (void)setDefaultPrinter:(NSPrinter *)aPrinter

Sets the user’s default printer to aPrinter. Unless the receiver’s printer was specified using setPrinter:, this default printer is used.

See also:	+ defaultPrinter,  − printer

setSharedPrintInfo:

+ (void)setSharedPrintInfo:(NSPrintInfo *)printInfo

Sets the shared NSPrintInfo object to printInfo. The shared NSPrintInfo object defines the settings for the NSPageLayout panel and print operations that will be used if no NSPrintInfo object is specified for those operataions.  printInfo should never be nil.

See also:	+ sharedPrintInfo

sharedPrintInfo

+ (NSPrintInfo *)sharedPrintInfo

Returns the shared NSPrintInfo object.

See also:	+ setSharedPrintInfo:

sizeForPaperName:

+ (NSSize)sizeForPaperName:(NSString *)name

Returns the size for the specified type of paper in points. name identifies the type of paper, such as Letter or Legal. Paper names are implementation specific.

Instance Methods

bottomMargin

− (float)bottomMargin

Returns the height of the bottom margin in points.

See also:	− setBottomMargin:

dictionary

− (NSMutableDictionary *)dictionary

Returns the receiver’s dictionary that stores its attribute settings. The key/value pairs contained in the dictionary are described in initWithDictionary:. Note, modifying the returned dictionary will change the receiver’s attributes.

horizontalPagination

− (NSPrintingPaginationMode)horizontalPagination

Returns the horizontal pagination mode, see setHorizontalPagination: for description of return values.

See also:	− setVerticalPagination:, − verticalPagination

initWithDictionary:

− (id)initWithDictionary:(NSDictionary *)aDictionary

Initializes a newly allocated NSPrintInfo object by assigning it the parameters specified in aDictionary. This is the designated initializer for this class. The possible key/value pairs contained in aDictionary are listed below. Non-object values should be stored as NSValues in the dictionary.

Key	Type	Description

NSPrintPaperName	NSString	The paper name.

NSPrintPaperSize	NSSize	Height and width of paper in points.

NSPrintMustCollate	BOOL	If YES, collates output.

NSPrintFormName	NSString	Form name such as "Letter" or "Letter

Small".

NSPrintOrientation	NSPrintingOrientation	NSPortraitOrientation or

NSLandscapeOrientation

NSPrintLeftMargin	float	The left margin in points.

NSPrintRightmargin	float	The right margin in points.

NSPrintTopMargin	float	The top margin in points.

NSPrintBottomMargin	float	The bottom margin in points.

NSPrintHorizontallyCentered	BOOL	If YES, pages are centered horizontally.

NSPrintVerticallyCentered	BOOL	If YES, pages are centered vertically.

NSPrintHorizontalPagination	NSPrintingPaginationMode	NSAutoPagination, NSFitPagination,

or NSClipPagination. See

setHorizontalPagination: for details.

NSPrintVerticalPagination	NSPrintingPaginationMode	NSAutoPagination, NSFitPagination,

or NSClipPagination. See

setVerticalPagination: for details.

NSPrintScalingFactor	float	Scale factor before pagination.

NSPrintAllPages	BOOL	If YES, includes all pages in output.

NSPrintReversePageOrder	BOOL	If YES, prints last page first.

NSPrintFirstPage	int	The first page in the print job.

NSPrintLastPage	int	The last page in the print job.

NSPrintCopies	int	Number of copies to spool.

NSPrintPagesPerSheet	int	The number of pages of the document

that are printed on a single sheet of paper.

This number is rounded up to the power

of two when used by the system.

NSPrintJobFeatures	NSMutableDictionary	Features from the NSPrinter object

where keys are the feature name and

values are the settings. For example, the

key NSPrintPaperFeed might have the

value *InputSlot/Upper. See the

NSPrinter class description.

NSPrintPaperFeed	NSString	The printer slot. For example,

InputSlot/Upper or NSPrintManualFeed.

NSPrintPrinter	NSPrinter	The printer to use.

NSPrintJobDisposition	NSString	NSPrintSpoolJob, NSPrintFaxJob,

NSPrintPreviewJob, NSPrintSaveJob, or

NSPrintCancelJob. See

setJobDisposition: for details.

NSPrintSavePath	NSString	Pathname to save as a file if job

disposition is NSPrintSaveJob.

NSPrintFaxReceiverNames	NSArray	Array of NSStrings containing receiver

names for a fax job.

NSPrintFaxReceiverNumbers	NSArray	Array of NSStrings containing the

receiver phone numbers for a fax job.

NSPrintFaxSendTime	NSDate	When to send the fax.

NSPrintFaxUseCoverSheet	BOOL	If YES, send cover sheet.

NSPrintFaxCoverSheetName	NSString	The filename containing the cover sheet.

NSPrintFaxReturnReceipt	BOOL	If YES, sends confirmation email when

fax is sent.

NSPrintFaxHighResolution	BOOL	If YES, sends fax at high resolution.

NSPrintFaxTrimPageEnds	BOOL	If YES, trims page ends, otherwise sends

complete pages.

NSPrintFaxModem	NSPrinter	The fax modem to use.

See also:	− dictionary

isHorizontallyCentered

− (BOOL)isHorizontallyCentered

Returns YES if the image is centered horizontally, otherwise returns NO.

See also:	− isVerticallyCentered, − setHorizontallyCentered:

isVerticallyCentered

− (BOOL)isVerticallyCentered

Returns YES if the image is centered vertically, otherwise returns NO.

See also:	− isHorizontallyCentered, − setVerticallyCentered:

jobDisposition

− (NSString *)jobDisposition

Returns the action specified for the job. See setJobDisposition: for description of return values.

leftMargin

− (float)leftMargin

Returns the width of the left margin in points.

See also:	− setLeftMargin:

orientation

− (NSPrintingOrientation)orientation

Returns the orientation attribute. See setOrientation: for description of return values.

paperName

− (NSString *)paperName

Returns the paper name such as "Letter" or "Legal". Paper names are implementation specific.

See also:	− setPaperName:

paperSize

− (NSSize)paperSize

Returns the size of the paper in points.

See also:	− setPaperSize:

printer

− (NSPrinter *)printer

Returns the NSPrinter to be used for printing.

See also:	− setPrinter:

rightMargin

− (float)rightMargin

Returns the width of the right margin in points.

See also:	− setRightMargin:

setBottomMargin:

− (void)setBottomMargin:(float)margin

Sets the bottom margin to margin specified in points.

See also:	− bottomMargin

setHorizontalPagination:

− (void)setHorizontalPagination:(NSPrintingPaginationMode)mode

Sets the horizontal pagination to mode where mode is one of:

NSAutoPagination 	The image is diced into equal-sized rectangles and placed in one column

of pages.

NSFitPagination 	The image is scaled to produce one column or one row of pages.

NSClipPagination	The image is clipped to produce one column or row of pages.

See also:	− horizontalPagination, − setVerticalPagination:, − verticalPagination

setHorizontallyCentered:

− (void)setHorizontallyCentered:(BOOL)flag

If flag is YES the image will be centered horizontally.

See also:	− isHorizontallyCentered, − isVerticallyCentered, − setVerticallyCentered:

setJobDisposition:

− (void)setJobDisposition:(NSString *)disposition

Sets the action specified for the job to disposition, where disposition is one of:

NSPrintSpoolJob	Normal print job.

NSPrintFaxJob	Fax job.

NSPrintPreviewJob	Send to Preview application.

NSPrintSaveJob	Save to a file.

NSPrintCancelJob	Cancel print job.

See also:	− jobDisposition

setLeftMargin:

− (void)setLeftMargin:(float)margin

Sets the left margin to margin specified in points.

See also:	− leftMargin

setOrientation:

− (void)setOrientation:(NSPrintingOrientation)orientation

Sets the page orientation to orientation where orientation is one of:

NSPortraitOrientation

NSLandscapeOrientation

This method may change either the paper name or size for consistency. To avoid this side effect set the values in the dictionary directly.

See also:	− dictionary, − initWithDictionary:, − orientation

setPaperName:

− (void)setPaperName:(NSString *)name

Sets the paper name to name (i.e., Letter or Legal). Paper names are implementation specific.This method may change either the size or orientation for consistency. To avoid this side effect set the values in the dictionary directly.

See also:	− dictionary, − initWithDictionary:, − paperName

setPaperSize:

− (void)setPaperSize:(NSSize)aSize

Sets the width and height of the paper to aSize specified in points. This method may change either the paper name or orientation for consistency. To avoid this side effect set the values in the dictionary directly.

See also:	− dictionary, − initWithDictionary:, − paperSize

setPrinter:

− (void)setPrinter:(NSPrinter *)aPrinter

Sets the printer used in subsequent printing jobs to aPrinter. This method iterates through the dictionary. If a feature in the dictionary is not supported by this new printer (this is determined by a query to the PPD file), then that feature is removed from the dictionary

See also:	− printer

setRightMargin:

− (void)setRightMargin:(float)margin

Sets the right margin to margin specified in points.

See also:	− rightMargin

setTopMargin:

− (void)setTopMargin:(float)margin

Sets the top margin to margin specified in points.

See also:	− topMargin

setUpPrintOperationDefaultValues

− (void)setUpPrintOperationDefaultValues

Invoked when the print operation is about to start. Subclasses may override this method to set default values for any attributes that are not set.

setVerticalPagination:

− (void)setVerticalPagination:(NSPrintingPaginationMode)mode

Sets the vertical pagination to mode where mode is one of:

NSAutoPagination 	The image is diced into equal-sized rectangles and placed in one column

of pages.

NSFitPagination 	The image is scaled to produce one column or one row of pages.

NSClipPagination	The image is clipped to produce one column or row of pages.

See also:	− horizontalPagination, − setHorizontalPagination:, − verticalPagination

setVerticallyCentered:

− (void)setVerticallyCentered:(BOOL)flag

If flag is YES, the image will be vertically centered.

See also:	− isHorizontallyCentered, − isVerticallyCentered, − setHorizontallyCentered:

topMargin

− (float)topMargin

Returns the top margin in points.

See also:	− setTopMargin:

verticalPagination

− (NSPrintingPaginationMode)verticalPagination

Returns the vertical pagination mode, see setVerticalPagination: for description of return values.

See also:	− horizontalPagination, − setHorizontalPagination:


NSPrintOperation

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSPrintOperation.h

Class Description

An NSPrintOperation object controls operations that generate Encapsulated PostScript (EPS) code or PostScript print jobs. Generally, EPS code is used to transfer images between applications, which happens when the user copies and pastes graphics, uses a Service, or uses ObjectLinks. PostScript is generated when the user prints and faxes documents. An NSPrintOperation object does not generate PostScript code itself; it just controls the overall process, relying on an NSView object to generate the actual code.

NSPrintOperation works in conjunction with two other objects: an NSPrintInfo object, which specifies how the code should be generated, and an NSView object, which performs the actual code generation. You specify these two objects in the method you use to create an NSPrintOperation object. If no NSPrintInfo is specified, NSPrintOperation uses the shared NSPrintInfo, which contains default values. (A shared NSPrintInfo object is automatically created for an application.) The shared NSPrintInfo works well for applications that are not document-based. However, document-based applications should create an NSPrintInfo for each document that might be printed or copied and use that object instead. This will allow  users to set printing attributes on a per-document basis.

You create NSPrintOperation objects in any method that is invoked when a user chooses a Print or Copy command. That method must also send runOperation to the NSPrintOperation object to start the actual operation. For example, applications that are not document-based have a simple print: method as in:

- (void)print:sender {

[[NSPrintOperation printOperatationWithView:self] runOperation];

}

However, document-based applications should use their own instances of NSPrintInfo as in:

- (void)print:sender {

[[NSPrintOperation printOperationWithView:[self myView] printInfo:[document

docPrintInfo]] runOperation];

}

This method creates an NSPrintOperation for a print job that uses the document’s NSPrintInfo object—not the shared NSPrintInfo object.

In both examples, because this is a print job, the NSPrintOperation object will display an NSPrintPanel object allowing the user to select  printing options (i.e., number of pages to print and range of pages to print). The NSPrintOperation object copies the NSPrintInfo object, updates this copy with information from the NSPrintPanel object, and uses the specified NSView to perform the operation. Some of the information stored in an NSPrintInfo object is constant for a particular document, such as its page size. Other information that is likely to change between print operations is set to default values before the operation begins.  In this way, even though NSPrintOperation updates the NSPrintInfo with information from the NSPrintPanel for a specific print job, that information is reset back to the default values for each print job. Because NSPrintOperation keeps a copy of the NSPrintInfo it uses, you could duplicate a specific print job by storing and reusing that copy.

When repeating a print job, you can suppress the display of the NSPrintPanel object by sending setShowPanels:, passing NO as the argument, to the NSPrintOperation object before sending it runOperation. However, make sure that any non-default settings in the NSPrintInfo object that would normally be selected from a NSPrintPanel object are set to reasonable values—a copy of an NSPrintInfo object used in a previous print job will have the correct values.

You can also customize the NSPrintPanel object using the setAccessoryView: method or specify your own NSPrintPanel object using setPrintPanel: (an OpenStep addition).

If you want the PostScript code generated for EPS and printing to be the same but different from the code generated for the screen, you can test for this case by sending isDrawingToScreen to the current NSDPSContext as in:

if (![[NSDPSContext currentContext] isDrawingToScreen]){

/* Insert EPS and printing code here */

}

If you want to generate different PostScript code when printing vs. creating EPS, you can test for this case by sending  isEPSOperation to the current operation as follows:

if ((![[NSDPSContext currentContext] isDrawingToScreen] &&

![[NSPrintOperation currentOperation] isEPSOperation])){

/* Insert printing code here */

}

Method Types

Creating an NSPrintOperation	+ EPSOperationWithView:insideRect:toData:

+ EPSOperationWithView:insideRect:toData:printInfo:

+ EPSOperationWithView:insideRect:toPath:printInfo:

+ printOperationWithView:

+ printOperationWithView:printInfo:

− initEPSOperationWithView:insideRect:toData:printInfo:

− initWithView:printInfo:

Setting the current NSPrintOperation for this thread

+ currentOperation

+ setCurrentOperation:

Determining the type of operation	− isEPSOperation

Modifying the NSPrintInfo object	− printInfo

− setPrintInfo:

Getting the NSView object	− view

Running a print operation	− runOperation

− cleanUpOperation

− deliverResult

Modifying the user interface	− showPanels

− setShowPanels:

− accessoryView

− setAccessoryView:

− printPanel

− setPrintPanel:

Managing the DPS context	− context

− createContext

− destroyContext

Modifying page information	− currentPage

− pageOrder

− setpageOrder:

Class Methods

EPSOperationWithView:insideRect:toData:

+ (NSPrintOperation *)EPSOperationWithView:(NSView *)aView insideRect:(NSRect)rect toData:(NSMutableData *)data

Returns a new NSPrintOperation object that controls the copying of EPS graphics from the area specified by rect in aView. The new NSPrintOperation object will use the default NSPrintInfo object. The EPS code is written to data. Raises an NSPrintOperationExistsException if there is already a print operation in progress, otherwise the returned object is made the current print operation for this thread.

See also:	+ EPSOperationWithView:insideRect:toData:printInfo:, + EPSOperationWithView:insideRect:toPath:printInfo:

EPSOperationWithView:insideRect:toData:printInfo:

+ (NSPrintOperation *)EPSOperationWithView:(NSView *)aView insideRect:(NSRect)rect toData:(NSMutableData *)data printInfo:(NSPrintInfo *)aPrintInfo

Returns a new NSPrintOperation object that controls the copying of EPS graphics from the area specified by rect in aView. The new NSPrintOperation object will use the settings stored in aPrintInfo. The code is written to data. Raises an NSPrintOperationExistsException if there is already a print operation in progress, otherwise the returned object is made the current print operation for this thread.

See also:	+ EPSOperationWithView:insideRect:toData:, + EPSOperationWithView:insideRect:toPath:printInfo:

EPSOperationWithView:insideRect:toPath:printInfo:

+ (NSPrintOperation *)EPSOperationWithView:(NSView *)aView insideRect:(NSRect)rect toPath:(NSString *)path printInfo:(NSPrintInfo *)aPrintInfo

Creates and returns a new NSPrintOperation object that controls the copying of EPS graphics from the area specified by rect in aView. The new NSPrintOperation object will use the settings stored in aPrintInfo. The code is written to path. Raises an NSPrintOperationExistsException if there is already a print operation in progress, otherwise the returned object is made the current print operation for this thread.

See also:	+ EPSOperationWithView:insideRect:toData:, + EPSOperationWithView:insideRect:toData:printInfo:

currentOperation

+ (NSPrintOperation *)currentOperation

Returns the current print operation for this thread. Returns nil if there isn’t a current operation.

See also:	+ setCurrentOperation:

printOperationWithView:

+ (NSPrintOperation *)printOperationWithView:(NSView *)aView

Returns a new NSPrintOperation that controls the printing of aView. The new NSPrintOperation object will use the settings stored in the shared NSPrintInfo object. Raises an NSPrintOperationExistsException if there is already a print operation in progress, otherwise the returned object is made the current print operation for this thread.

See also:	+ printOperationWithView:printInfo:

printOperationWithView:printInfo:

+ (NSPrintOperation *)printOperationWithView:(NSView *)aView printInfo:(NSPrintInfo *)aPrintInfo

Returns a new NSPrintOperation that controls the printing of aView. The new NSPrintOperation object will use the settings stored  in aPrintInfo. Raises an NSPrintOperationExistsException if there is already a print operation in progress, otherwise the returned object is made the current print operation for this thread.

See also:	+ printOperationWithView:

setCurrentOperation:

+ (void)setCurrentOperation:(NSPrintOperation *)operation

Sets the current print operation for this thread to operation. If operation is nil, then there is no current print operation.

See also:	+ currentOperation

Instance Methods

accessoryView

− (NSView *)accessoryView

Returns the accessory view used by the NSPrintPanel object. You use setAccessoryView: to customize the default NSPrintPanel object without having to subclass NSPrintPanel or specify your own NSPrintPanel object.

See also:	 − printPanel, − setPrintPanel:, − setShowPanels:, − showPanels

cleanUpOperation

− (void)cleanUpOperation

Invoked by runOperation at the end of an operation to remove the receiver as the current operation. You typically do not invoke this method directly.

context

− (NSDPSContext *)context

Returns the receiver’s  DPS context used for generating output.

See also:	− createContext, − destroyContext

createContext

− (NSDPSContext *)createContext

Creates the DPS context for output generation, using the receiver’s NSPrintInfo settings. Do not invoke this method directly—it’s invoked before any output is generated.

See also:	− context, − destroyContext

currentPage

− (int)currentPage

Returns the page number of the page that is currently being printed.

See also:	− pageOrder, − setPageOrder:

deliverResult

− (BOOL)deliverResult

Delivers the results generated by runOperation to the intended destination (i.e., the printer spool, or preview application). Returns YES if the operation was successful, otherwise NO. Do not invoke this method directly—it’s invoked automatically when the operation is done generating the output.

destroyContext

− (void)destroyContext

Destroys the receiver’s DPS context. Do not invoke this method directly—it’s invoked at the end of a print operation.

See also:	− context, − createContext

initEPSOperationWithView:insideRect:toData:printInfo:

− (id)initEPSOperationWithView:(NSView *)aView insideRect:(NSRect)rect toData:(NSMutableData *)data printInfo:(NSPrintInfo *)aPrintInfo

Initializes and returns a newly allocated NSPrintOperation object to control the copying of EPS graphics from the area specified by rect in aView, using the settings stored in aPrintInfo. This method makes a copy of aPrintInfo —aPrintInfo is not used in the actual operation. The EPS code is written to data.

See also:	− initWithView:printInfo:

initWithView:printInfo:

− (id)initWithView:(NSView *)aView printInfo:(NSPrintInfo *)aPrintInfo

Initializes and returns a newly allocated NSPrintOperation object to control the printing of aView, using the settings stored in aPrintInfo. This method makes a copy of aPrintInfo —aPrintInfo is not used in the actual operation. This method is the designated initializer for this class.

See also:	− initEPSOperationWithView:insideRect:toData:printInfo:

isEPSOperation

− (BOOL)isEPSOperation

Returns YES if the receiver controls an EPS operation (initiated by a copy command), and NO if the receiver controls a printing operation (initiated by a print command).

pageOrder

− (NSPrintingPageOrder)pageOrder

Returns the order in which pages will be printed. See setPageOrder: for possible return values.

See also:	− currentPage

printInfo

− (NSPrintInfo *)printInfo

Returns the receiver’s NSPrintInfo object.

See also:	− setPrintInfo:

p	printPanel

− (NSPrintPanel *)printPanel

Returns the NSPrintPanel object used when running the operation.

See also:	 − accessoryView, − setAccessoryView:, − setPrintPanel:, − setShowPanels:, − showPanels

runOperation

− (BOOL)runOperation

Runs the operation (i.e., copys an EPS graphic or prints a job). Returns YES if successful, otherwise NO.

See also:	− cleanUpOperation, − deliverResult

setAccessoryView:

− (void)setAccessoryView:(NSView *)aView

Allows you to augment the NSPrintPanel object by adding a custom NSView (by using this method you do not need to subclass NSPrintPanel or specify your own NSPrintPanel object). The NSPrintPanel is automatically resized to accommodate the new accessory view aView.

See also:	− accessoryView, − printPanel, − setPrintPanel:, − setShowPanels:, − showPanels

setPageOrder:

− (void)setPageOrder:(NSPrintingPageOrder)order

Sets the order in which pages will be printed to order where order is one of:

NSAscendingPageOrder	Ascending (back to front) page order.

NSDescendingPageOrder	Descending (front to back) page order.

NSSpecialPageOrder	The spooler will not rearrange pages—they are print in the order

received by the spooler.

NSUnknownPageOrder	No page order specified.

See also:	− currentPage, − pageOrder

setPrintInfo:

− (void)setPrintInfo:(NSPrintInfo *)aPrintInfo

Sets the receiver’s NSPrintInfo object to aPrintInfo.

See also:	− printInfo

p	setPrintPanel:

− (void)setPrintPanel:(NSPrintPanel *)panel

Sets the receiver’s NSPrintPanel used in the operation to panel.

See also:	 − accessoryView, − printPanel, − setAccessoryView:, − setShowPanels:, − showPanels

setShowPanels:

− (void)setShowPanels:(BOOL)flag

If flag is YES then the NSPrintPanel will be used in the operation, otherwise it will not.

See also:	− accessoryView, − printPanel, − setAccessoryView:, − setPrintPanel:, − showPanels

showPanels

− (BOOL)showPanels

Returns YES if the NSPrintPanel will be used in the operation, otherwise NO.

See also:	 − accessoryView, − printPanel, − setAccessoryView:, − setPrintPanel:, − setShowPanels:

view

− (NSView *)view

Returns the NSView object that generates the actual EPS or PostScript code controlled by the receiver.


NSPrintPanel
p NSPrintPanel

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSPanel : NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSPrintPanel.h

Note:	On Mach platforms, NSPrintPanel inherits from NSPanel and conforms to NSCoding.

Class Description

NSPrintPanel creates a Print panel used to query the user for information about a print job, such as which pages to print and how many copies, and execute the Print command.

When a print: message is sent to an NSView or NSWindow, an NSPrintOperation object is created to control the print operation (see the NSPrintOperation class description for details). By default an NSPrintOperation object uses an NSPrintPanel unless it is sent the setShowPanels: message passing NO as the argument. Also, if you subclass NSPrintPanel, send the setPrintPanel: message to the NSPrintOperation object passing an instance of your subclass to ensure that it  is used as the Print panel for that operation.

However, you rarely need to subclass NSPrintPanel since you can augment its display by adding a custom NSView using the setAccessoryView: method. The accessory view is displayed when the user clicks the Options button. (On Mach platforms, the panel is  resized to accommodate the NSView that you add.) Note, however, that you don’t have to create controls for special printer features. If a printer includes features in the “OpenUI” field of its PostScript Printer Description (PPD) table, these features will appear in the panel. For more information on a printer’s PPD table, see the NSPrinter class description.

Typically, you get an NSPrintPanel by invoking the printPanel class method. When the class receives a printPanel message, it tries to reuse an existing panel rather than create a new one. When a panel is reused, its attributes are reset to the default values so that the effect is the same as returning a new panel. Because a Print panel may be reused, you shouldn’t modify the instance returned by printPanel, except through the methods listed below. For example, you can set the accessory view, but not the arrangement of the buttons within the panel. If you must modify the Print panel substantially, create and manage your own instance using the alloc... and init... methods rather than the printPanel method.

An application stores printing information in an NSPrintInfo object. When an NSPrintOperation object is created it is given a specific NSPrintInfo object from the application or assigned a default. You can get the current operation by sending the currentOperation class method to  NSPrintOperation.

Use the  updateFromPrintInfo method to read the NSPrintInfo object’s information into the Print panel. Conversely, the finalWritePrintInfo method updates the NSPrintInfo object if the user changes the information on the Print panel.  The NSPrintOperation object creates a copy of the NSPrintInfo object, so that  finalWritePrintInfo actually writes to that copy, not the original.

Method Types

Creating an NSPrintPanel	+ printPanel

Customizing the panel	− accessoryView

− setAccessoryView:

Running the panel	− runModal

Communicating with the NSPrintInfo object

− updateFromPrintInfo

− finalWritePrintInfo

Updating the panel’s display

− pickedButton:

− pickedAllPages:

− pickedLayoutList:

Class Methods

p	printPanel

+ (NSPrintPanel *)printPanel

Returns a shared NSPrintPanel object or a newly created one if it doesn’t already exist.

Instance Methods

p	accessoryView

− (NSView *)accessoryView

Returns the receiver’s accessory view (used to customize the receiver).

See also:	− setAccessoryView:

p	finalWritePrintInfo

− (void)finalWritePrintInfo

Writes the values of the receiver’s printing attributes to the NSPrintInfo object belonging to the current NSPrintOperation.

See also:	− updateFromPrintInfo, − currentOperation (NSPrintOperation)

p	pickedAllPages:

− (void)pickedAllPages:(id)sender

This method is for Mach platforms only—it is not defined for other platforms. Invoked when the user chooses the All (Pages) radio button. If the All button is clicked the From and To (Pages) fields are empty, otherwise their default values are set to "first" and "last". Override this method to change these defaults.

See also:	− pickedButton:, − pickedLayoutList:

p	pickedButton:

− (void)pickedButton:(id)sender

This method is for Mach platforms only—it is not defined for other platforms. Invoked when the user clicks either the Cancel, Fax, Preview, Print or Save buttons. If a button other than the Cancel button is clicked, then the receiver’s Copies, From (Pages) and To (Pages) fields must contain acceptable values (positive numbers), otherwise the unacceptable entry is selected. If the fields are acceptable the  modal loop is stopped. If the Cancel button is selected the modal loop is stopped regardless of the field values.

See also:	− pickedAllPages:, − pickedLayoutList:, − runModal

p	pickedLayoutList:

− (void)pickedLayoutList:(id)sender

This method is for Mach platforms only—it is not defined for other platforms. Invoked when the user chooses a new layout to update the receiver.

See also:	− pickedAllPages:, − pickedButton:

p	runModal

− (int)runModal

Displays the receiver and begins the modal loop. Returns NSCancelButton if the user clicks the Cancel button, otherwise returns NSOkButton.

See also:	− pickedButton:

p	setAccessoryView:

− (void)setAccessoryView:(NSView *)aView

Adds an NSView to the receiver. Invoke this method to add a custom view containing your controls. The accessory view is displayed when the user clicks the Options button. (On Mach platforms, the receiver is automatically resized to accommodate aView.) This method can be invoked repeatedly to change the accessory view depending on the situation. If aView is nil, then the receiver’s current accessory view, if any, is removed.

See also:	− accessoryView

p	updateFromPrintInfo

− (void)updateFromPrintInfo

Reads the receiver’s values from the NSPrintInfo object belonging to the current NSPrintOperation, and updates the receiver accordingly.

See also:	− finalWritePrintInfo, − currentOperation (NSPrintOperation)


NSPrinter

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSCopying

NSObject (NSObject)

Declared In:	AppKit/NSPrinter.h

Class Description

An NSPrinter object describes a printer's capabilities, such as whether the printer can print in color and whether it provides a particular font. An NSPrinter object represents either a particular make or type of printer, or an actual printer available to the computer. You use NSPrinter to get information about printers, not modify printer attributes or control a printing job.

There are two ways to create an NSPrinter:

•	To create an abstract object that provides information about a type of printer rather than an object that represents an actual printer device, use the printerWithType: class method, passing a printer type (an NSString) as the argument. The printerTypes class method provides a list of printer types,  model names recognized by the computer. Printer types are described in files written in PostScript Printer Description (PPD) format. The location of these files is platform dependent.

•	Use the printerWithName: class method to create or find an NSPrinter that corresponds to an actual printer device. Use the printerNames class method to get a list of recognized printer names.

Once you have an NSPrinter, there's only one thing you can do with it: retrieve information regarding the type of printer or regarding the actual printer the object represents.

When you create an NSPrinter object, the object reads the file that corresponds to the type of printer, a model name, you specified and stores the data it finds there in named tables. Printer types are described in files written in the PostScript Printer Description (PPD) format. Any piece of information in the PPD tables can be retrieved through the methods stringForKey:inTable: and stringListForKey:inTable:, as explained later. Commonly needed items, such as whether a printer supports color or the size of the page on which it prints, are available through more direct methods (methods such as isColor and pageSizeForPaper:).

Note:	To understand what the NSPrinter tables contain, you need to be acquainted with the PPD file format. This is described in PostScript Printer Description File Format Specification, version 4.0, available from Adobe Systems Incorporated. The rest of this class description assumes a familiarity with the concepts and terminology presented in the Adobe manual. A brief summary of the PPD format is given below; PPD terms defined in the Adobe manual are shown in italic.

PPD Format

A PPD file statement, or entry, associates a value with a main keyword:

*mainKeyword: value

The asterisk is literal; it indicates the beginning of a new entry.

For example:

*ModelName: "MMimeo Machine"

*3dDevice: False

A main keyword can be qualified by an option keyword:

*mainKeyword optionKeyword: value

For example:

*PaperDensity Letter: "0.1"

*PaperDensity Legal: "0.2"

*PaperDensity A4: "0.3"

*PaperDensity B5: "0.4"

In addition, any number of entries may have the same main keyword with no option keyword yet give different values:

*InkName: ProcessBlack/Process Black

*InkName: CustomColor/Custom Color

*InkName: ProcessCyan/Process Cyan

*InkName: ProcessMagenta/Process Magenta

*InkName: ProcessYellow/Process Yellow

Option keywords and values can sport translation strings. A translation string is a textual description, appropriate for display in a user interface, of the option or value. An option or value is separated from its translation string by a slash:

*Resolution 300dpi/300 dpi: " ... "

*InkName: ProcessBlack/Process Black

In the first example, the 300dpi option would be presented in a user interface as “300 dpi.” In the second example, the translation string for the ProcessBlack value is set to “Process Black”.

NSPrinter treats entries that have an *OrderDependency or *UIConstraint main keyword specially. Such entries take the following forms (the bracketed elements are optional):

*OrderDependency: real section mainKeyword [optionKeyword]

*UIConstraint: mainKeyword1 [optionKeyword1] mainKeyword2 [optionKeyword2]

There may be more than one UIConstraint entry with the same mainKeyword1 or mainKeyword1/optionKeyword1 value. Below are some examples of *OrderDependency and *UIConstraint entries:

*OrderDependency: 10 AnySetup *Resolution

*UIConstraint: *Option3 None *PageSize Legal

*UIConstraint: *Option3 None *PageRegion Legal

Explaining these entries is beyond the scope of this documentation; however, it's important to note their forms in order to understand how they're represented in the NSPrinter tables.

NSPrinter Tables

NSPrinter defines five key-value tables to store PPD information. The tables are identified by the names given below:

Name	Contents

PPD	General information about a printer type. This table contains the values

for all entries in a PPD file except those with the *OrderDependency

and *UIConstraint main keywords. The values in this table don't

include the translation strings.

PPDOptionTranslation	Option keyword translation strings.

PPDArgumentTranslation	Value translation strings.

PPDOrderDependency	*OrderDependency values.

PPDUIConstraints	*UIConstraint values.

There are two principle methods for retrieving data from the NSPrinter tables:

•	stringForKey:inTable: returns the value for the first occurrence of a given key in the given table.

•	stringListForKey:inTable: returns an array of values, one for each occurrence of the key.

For both methods, the first argument is an NSString that names a key—which part of a PPD file entry the key corresponds to depends on the table (as explained in the following sections). The second argument names the table that you want to search. The values that are returned by these methods, whether singular or in an array, are always NSStrings, even if the value wasn't a quoted string in the PPD file.

The NSPrinter tables store data as ASCII text, thus the two methods described above are sufficient for retrieving any value from any table. NSPrinter provides a number of other methods, such as booleanForKey:inTable: and intForKey:inTable:, that retrieve single values and coerce them, if possible, into particular data types. The coercion doesn't affect the data that's stored in the table (it remains in ASCII format).

To check the integrity of a table, use the isKey:forTable: and statusForTable: methods. The former returns a boolean that indicates whether the given key is valid for the given table; the latter returns an error code that describes the general state of a table (in particular, whether it actually exists).

Retrieving Values from the PPD Table

Keys for the PPD table are strings that name a main keyword or main keyword/option keyword pairing (formatted as “mainKeyword/optionKeyword”). In both cases, you exclude the main keyword asterisk. The following example creates an NSPrinter and invokes stringForKey:inTable: to retrieve the value for an un-optioned main keyword:

/* Create an NSPrinter object for a printer type. */

NSPrinter *prType = [NSPrinter printerWithType:@"My_Mimeo_Machine"]

/* Sets sValue to FALSE. */

NSString *sValue = [prType stringForKey:@"3dDevice" inTable:@"PPD"];

To retrieve the value for a main keyword/option keyword pair, pass the keywords formatted as “mainKeyword/optionKeyword”:

/* Sets sValue to "0.3". */

NSString *sValue = [prType stringForKey:@"PaperDensity/A4" inTable:@"PPD"];

stringForKey:inTable: can determine if a main keyword has options. If you pass a main keyword (only) as the first argument to the method, and if that keyword has options in the PPD file, the method returns an empty string. If it doesn't have options, it returns the value of the first occurrence of the main keyword:

/* Sets sValue to an empty string. */

NSString *sValue = [prType stringForKey:@"PaperDensity" inTable:@"PPD"];

/* Sets sValue to "ProcessBlack". */

NSString *sValue = [prType stringForKey:@"InkName" inTable:@"PPD"];

To retrieve the values for all occurrences of a main keyword, use the stringListForKey:inTable: method giving the main keyword only:

/* Sets sList to an array containing "ProcessBlack","CustomColor", etc. */

NSArray *sList = [prType stringListForKey:@"InkName" inTable:@"PPD"];

In addition, stringListForKey:inTable: can be used to retrieve all the options for a main keyword (given that the main keyword has options):

/* Sets sList to an array containing "Letter", "Legal","A4", etc. */

NSArray *sList = [prType stringListForKey:@"PaperDensity" inTable:@"PPD"];

Retrieving Values from the Option and Argument Translation Tables

A key to a translation table is similiar to a key  to the PPD table: It's a main keyword or main/option keyword pair (again excluding the asterisk). However, the values that are returned from the translation tables are the translation strings for the option or argument (value) portions of the PPD file entry. For example:

/* Sets sValue to "300 dpi". */

NSString *sValue = [prType stringForKey:@"Resolution/300dpi"

                                inTable:@"PPDOptionTranslation"];

/* Sets sList to an array containing "Process Black", "Custom Color", etc. */

NSArray *sList = [prType stringListForKey:@"InkName"

                                  inTable:@"PPDArgumentTranslation"];

As with the PPD table, use stringListForKey:inTable: to request an array of all occurances of a main keyword.

Retrieving Values from the Order Dependency Table

As mentioned earlier, an order dependency entry takes this form:

*OrderDependency: real section mainKeyword [optionKeyword]

These entries are stored in the PPDOrderDependency table. To retrieve a value from this table, always use stringListForKey:inTable:. The value passed as the key is, again, a main keyword or main keyword/option keyword pair; however, these values correspond to the mainKeyword and optionKeyword parts of an order dependency entry's value. As with the other tables, the main keyword's asterisk is excluded. The method returns an NSArray of two NSStrings that correspond to the real and section values for the entry. For example:

/* Sets sList to an array containing "10" and "AnySetup". */

NSArray *sList = [prType stringListForKey:@"Resolution"

                                  inTable:@"PPDOrderDependency"]

Retrieving Values from the UIConstraints Table

Retrieving a value from the PPDUIConstraints table is similar to retrieving a value from the PPDOrderDependency table: always use stringListForKey:inTable: and the key corresponds to elements in the entry's value. Given the following form (as described earlier), the key corresponds to mainKeyword1/optionKeyword1:

*UIConstraint: mainKeyword1 [optionKeyword1] mainKeyword2 [optionKeyword2]

The NSArray that's returned by stringListForKey:inTable: contains the mainKeyword2 and optionKeyword2 values (with the keywords stored as separate elements in the NSArray) for every *UIConstraints entry that has the given mainKeyword1/optionKeyword1 value. For example:

/* Sets sList to an array containing:

   "PageSize", "Legal", "PageRegion", and "Legal" */

NSArray *sList = [prType stringListForKey:@"Option3/None"

                                  inTable:@"PPDUIConstraints"]

Note that the main keywords that are returned in the NSArray don't have asterisks. Also, the NSArray that's returned always alternates main and option keywords. If a particular main keyword doesn't have an option associated with it, the string for the option will be empty (but the entry in the NSArray for the option will exist).

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

NSCopying	− copyWithZone:

Method Types

 Creating an NSPrinter	+ printerWithName:

+ printerWithName:domain:includeUnavailable:

+ printerWithType:

Getting general printer information	+ printerNames

+ printerTypes

Getting attributes	− domain

− host

− name

− note

− type

Getting specific information	− acceptsBinary

− imageRectForPaper:

− pageSizeForPaper:

− isColor

− isFontAvailable:

− isOutputStackInReverseOrder

− languageLevel

Querying the tables	− isKey:inTable:

− stringForKey:inTable:

− stringListForKey:inTable:

− booleanForKey:inTable:

− floatForKey:inTable:

− intForKey:inTable:

− rectForKey:inTable:

− sizeForKey:inTable:

− statusForTable:

− deviceDescription

Class Methods

printerNames

+ (NSArray *)printerNames

Returns an array of recognized printer names.

See also:	 +printerTypes, − name

printerTypes

+ (NSArray *)printerTypes

Returns an array of recognized model names.

See also:	 +printerNames, − type

printerWithName:

+ (NSPrinter *)printerWithName:(NSString *)name

Returns an NSPrinter that represents an actual printer with the given name. Returns nil if the specified printer is not available.

See also:	+ printerWithType:, + printerNames, − name

p	printerWithName:domain:includeUnavailable:

+ (NSPrinter *)printerWithName:(NSString *)name domain:(NSString *)domain includeUnavailable:(BOOL)flag

This method is for Mach platforms only—it is not defined for other platforms. Returns an NSPrinter that represents an actual printer with the given name and domain.  If domain is nil, the first printer (matching name) found on any host or domain is used.  Returns nil if the specified printer is not available and  flag is NO.  If flag is YES, the availability of the printer is ignored.

See also:	+ printerWithName:, + printerWithType:, + printerNames, − domain, − name

printerWithType:

+ (NSPrinter *)printerWithType:(NSString *)type

Returns an NSPrinter with the given printer type.

See also:	+ printerWithName:,  + printerTypes, − type

Instance Methods

acceptsBinary

− (BOOL)acceptsBinary

Returns YES if the receiver accepts binary PostScript, otherwise NO.

booleanForKey:inTable:

− (BOOL)booleanForKey:(NSString *)key inTable:(NSString *)table

Returns a boolean value associated with key in table. Will also return NO if key is not in table.

See also:	− isKey:inTable:, − stringForKey:inTable:

copyWithZone:

@protocol NSCopying

− (id)copyWithZone:(NSZone *)zone

Doesn’t return a copy of the receiver. Returns the receiver with its reference count incremented (sends retain to the receiver).

deviceDescription

− (NSDictionary *)deviceDescription

Returns a dictionary of keys and values describing the device. See NSGraphics.h for possible keys.

p	domain

− (NSString *)domain

This method is for Mach platforms only—it is not defined for other platforms. Returns the name of the domain in which the receiver's printer resides. Returns nil if the receiver doesn't represent an actual printer.

See also:	+ printerWithName:domain:includeUnavailable:

floatForKey:inTable:

− (float)floatForKey:(NSString *)key inTable:(NSString *)table

Returns a floating-point value associated with key in table. Returns 0.0 if key is not in table.

See also:	− isKey:inTable:, − stringForKey:inTable:

host

− (NSString *)host

Returns the name of the receiver's host computer.

imageRectForPaper:

− (NSRect)imageRectForPaper:(NSString *)paperName

Returns the printing rectangle for the paper paperName. Possible values for paperName are contained in the printer's PPD file. Typical values are Letter and Legal.

See also:	− pageSizeForPaper:

intForKey:inTable:

− (int)intForKey:(NSString *)key inTable:(NSString *)table

Returns an integer value associated with key in table. Returns 0 if key is not in table.

See also:	− isKey:inTable:, − stringForKey:inTable:

isColor

− (BOOL)isColor

Returns YES if the receiver can print color, otherwise NO.

isFontAvailable:

− (BOOL)isFontAvailable:(NSString *)faceName

Returns YES if font faceName is available to the receiver, otherwise NO.

isKey:inTable:

− (BOOL)isKey:(NSString *)key inTable:(NSString *)table

Returns YES if  key is in table, otherwise NO.

isOutputStackInReverseOrder

− (BOOL)isOutputStackInReverseOrder

Returns YES if  the receiver outputs pages in reverse page order, otherwise NO.

languageLevel

− (int)languageLevel

Returns the PostScript Language Level recognized by the receiver.

name

− (NSString *)name

Returns the receiver's name.

See also:	+ printerNames, + printerWithName:

note

− (NSString *)note

Returns the note associated with the receiver.

pageSizeForPaper:

− (NSSize)pageSizeForPaper:(NSString *)paperName

Returns the size of the page for the  paper type paperName. Possible values for paperName are contained in the printer's PPD file. Typical values are Letter and Legal.

See also:	 − imageRectForPaper:

rectForKey:inTable:

− (NSRect)rectForKey:(NSString *)key inTable:(NSString *)table

Returns the rectangle associated with key in table. Returns NSZeroRect if key is not in table.

See also:	− isKey:inTable:, − stringForKey:inTable:

sizeForKey:inTable:

− (NSSize)sizeForKey:(NSString *)key inTable:(NSString *)table

Returns the size associated with key in table. The returned width and height is  0.0 if key is not in table.

See also:	− isKey:inTable:, − stringForKey:inTable:

statusForTable:

− (NSPrinterTableStatus)statusForTable:(NSString *)table

Returns the status of table:

NSPrinterTableOK

NSPrinterTableNotFound

NSPrinterTableError

stringForKey:inTable:

− (NSString *)stringForKey:(NSString *)key inTable:(NSString *)table

Returns the first occurence of a value associated with key in table. If key is a main keyword only, and if that keyword has options in the PPD file, this method returns an empty string. Use stringListForKey:inTable: to retrieve the values for all occurrences of a main keyword. Returns nil if key is not in table.

See also:	− isKey:inTable:, − booleanForKey:inTable:, − floatForKey:inTable:, − intForKey:inTable:, − rectForKey:inTable:, − sizeForKey:in:Table:

stringListForKey:inTable:

− (NSArray *)stringListForKey:(NSString *)key inTable:(NSString *)table

Returns an array of strings, one for each occurrence, associated with key in table. Returns nil if key is not in table.

See also:	− isKey:inTable:, −  stringForKey:inTable:

type

− (NSString *)type

Returns the name of the receiver's type.

See also:	 + printerTypes


NSResponder

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	 NSObject

Conforms To:	NSCoding

NSObject (NSObject)

Declared In:	AppKit/NSResponder.h

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 one of these objects doesn’t return the delegate). Given all these components, then, the full responder chain comprises these objects:

•	The key window’s first responder and successors, including objects added with setNextResponder:

•	The key window itself

•	The key window’s delegate (which need not inherit from NSResponder)

•	The main window’s first responder and successors, including objects added with setNextResponder:

•	The main window itself

•	The main window’s delegate (which need not inherit from NSResponder)

•	The application object, NSApp

•	The application object’s delegate (which need not inherit from NSResponder)

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 its ready to resign its status, using resignFirstResponder. If the current first responder returns NO when sent this message, makeFirstResponder: fails and likewise returns NO. If the current first responder returns YES then the new one is sent a becomeFirstResponder message to inform it that it can be the first responder. This object can return NO 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 NO; responder subclasses that need to be first responder must override it to return YES. 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 YES. 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 sendAction:to:from: 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’s sendAction:to:from:. 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 sendAction:to:from:, thus indicating which object instigated the action message. If the intended target isn’t nil, 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 nil, sendAction:to:from: 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:with:. This method checks the receiver to see if it responds to the selector provided, if so invoking the message. If not, it sends tryToPerform:with: 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 sendAction:to:from: does. Similar to tryToPerform:with: 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 sendAction:to:from:, NSResponder’s tryToPerform:with: 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 that 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 that ever happens. Reserved key combinations are often trapped 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 below under “Key Equivalents and Mnemonics.” 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 that the typing couldn’t be processed:

•	A mnemonic matching the character(s) typed, not requiring the Alternate key to be pressed

•	A key equivalent, not requiring the Command (or Control) key to be pressed

•	A keyboard interface control event

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 YES. 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 YES, returning NO 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.

Note:	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.

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. 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 character’s 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 below, “Standard Action Methods for Selecting and Editing,” describes the messages that your object might get sent.

Standard Action Methods for Selecting and Editing

NSResponder declares prototypes for a number of standard action methods, nearly all related to manipulating selections and editing text. These methods are typically invoked through doCommandBySelector: as a result of interpretation by the input manager. They fall into the following general groups:

•	Selection movement and expansion

•	Text insertion

•	General deletion of elements

•	Modifying selected text

•	Scrolling a document

In most cases the intent of the action method is clear from its name. The individual method descriptions in this specification also provide detailed information about what such a method should normally do. However, a few general concepts apply to many of these methods, and are explained here.

Selection Direction. Some methods refer to spatial directions; left, right, up, down. These are meant to be taken literally, especially in text. To accommodate writing systems with directionality different from Latin script, the terms forward, beginning, backward, and end are used.

Selection and insertion point. Methods that refer to moving, deleting, or inserting imply that some elements in the responder are selected, or that there’s a zero-length selection at some location (the insertion point). These two things must always be treated consistently. For example, the insertText: method is defined as replacing the selection with the text provided. moveForwardAndModifySelection: extends or contracts a selection, even if the selection is merely an insertion point. When a selection is modified for the first time, it must always be extended. So a moveForward... message extends the selection from its end, while a moveBackward... message extends it from its beginning.

Marks. A number of action methods for editing text imitate the Emacs concepts of point (the insertion point), and mark (an anchor for larger operations normally handled by selections in graphical interfaces). setMark: establishes the mark at the current selection, which then remains in effect until the mark is changed again. selectToMark: extends the selection to include the mark and all characters between the selection and the mark.

The kill buffer. Also like Emacs, deletion methods affecting lines, paragraphs, and the mark implicitly place the deleted text into a buffer, separate from the pasteboard, from which you can later retrieve it. Methods such as deleteToBeginningOfLine: add text to this buffer, and yank: replaces the selection with the item in the kill buffer.

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 validRequestorForSendType:returnType: 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:with:

Terminating the responder chain	− noResponderFor:

Services menu updating	− validRequestorForSendType:returnType:

Setting the menu	− setMenu:

− menu

Instance Methods

acceptsFirstResponder

− (BOOL)acceptsFirstResponder

Overridden by subclasses to return YES if the receiver can handle key events and action messages sent up the responder chain. NSResponder’s implementation returns NO, 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

− (BOOL)becomeFirstResponder

Notifies the receiver that it’s about to become first responder in its NSWindow. NSResponder’s implementation returns YES, accepting first responder status. Subclasses can override this method to update state or perform some action such as highlighting the selection, or to return NO, 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

p	capitalizeWord:

− (void)capitalizeWord:(id)sender

Implemented by subclasses to capitalize the word or words surrounding the insertion point or selection, though without expanding the selection. If either end of the selection partially covers a word, that entire word is made lowercase. NSResponder declares, but doesn’t implement this method.

See also:	− lowercaseWord:, − uppercaseWord:, − changeCaseOfLetter:

p	centerSelectionInVisibleArea:

− (void)centerSelectionInVisibleArea:(id)sender

Implemented by subclasses to scroll the selection, whatever it is, inside its visible area. NSResponder declares, but doesn’t implement this method.

See also:	− scrollLineDown:, − scrollLineUp:, − scrollPageDown:, − scrollPageUp:

p	changeCaseOfLetter:

− (void)changeCaseOfLetter:(id)sender

Implemented by subclasses to change the case of a letter or letters in the selection, perhaps by opening a panel with capitalization options or by cycling through possible case combinations. NSResponder declares, but doesn’t implement this method.

See also:	− lowercaseWord:, − uppercaseWord:, − capitalizeWord:

p	complete:

− (void)complete:(id)sender

Implemented by subclasses to complete an operation in progress or a partially constructed element. This can be interpreted, for example, as a request to attempt expansion of a partial word, such as for expanding a glossary shortcut, or to close a graphic item being drawn. NSResponder declares, but doesn’t implement this method.

p	deleteBackward:

− (void)deleteBackward:(id)sender

Implemented by subclasses to delete the selection if there is one, or a single element backward from the insertion point (a letter or character in text, for example). NSResponder declares, but doesn’t implement this method.

p	deleteForward:

− (void)deleteForward:(id)sender

Implemented by subclasses to delete the selection if there is one, or a single element forward from the insertion point (a letter or character in text, for example). NSResponder declares, but doesn’t implement this method.

p	deleteToBeginningOfLine:

− (void)deleteToBeginningOfLine:(id)sender

Implemented by subclasses to delete the selection if there is one, or all text from the insertion point to the beginning of a line (typically of text). Also places the deleted text into the kill buffer. NSResponder declares, but doesn’t implement this method.

See also:	− yank:

p	deleteToBeginningOfParagraph:

− (void)deleteToBeginningOfParagraph:(id)sender

Implemented by subclasses to delete the selection if there is one, or all text from the insertion point to the beginning of a paragraph of text. Also places the deleted text into the kill buffer. NSResponder declares, but doesn’t implement this method.

See also:	− yank:

p	deleteToEndOfLine:

− (void)deleteToEndOfLine:(id)sender

Implemented by subclasses to delete the selection if there is one, or all text from the insertion point to the end of a line (typically of text). Also places the deleted text into the kill buffer. NSResponder declares, but doesn’t implement this method.

p	deleteToEndOfParagraph:

− (void)deleteToEndOfParagraph:(id)sender

Implemented by subclasses to delete the selection if there is one, or all text from the insertion point to the end of a paragraph of text. Also places the deleted text into the kill buffer. NSResponder declares, but doesn’t implement this method.

See also:	− yank:

p	deleteToMark:

− (void)deleteToMark:(id)sender

Implemented by subclasses to delete the selection if there is one, or all items from the insertion point to a previously placed mark, including the selection itself if not empty. Also places the deleted text into the kill buffer. NSResponder declares, but doesn’t implement this method.

See also:	− setMark:, − selectToMark:, − yank:

p	deleteWordBackward:

− (void)deleteWordBackward:(id)sender

Implemented by subclasses to delete the selection if there is one, or a single word backward from the insertion point. NSResponder declares, but doesn’t implement this method.

p	deleteWordForward:

− (void)deleteWordForward:(id)sender

Implemented by subclasses to delete the selection if there is one, or a single character or element forward from the insertion point. NSResponder declares, but doesn’t implement this method.

p	doCommandBySelector:

− (void)doCommandBySelector:(SEL)aSelector

Attempts to perform the method indicated by aSelector. The method should take a single argument of type id and return void. If the receiver responds to aSelector, it invokes the method with nil as the argument. If the receiver doesn’t respond, it sends this message to its next responder with the same selector. NSWindow and NSApplication also send the message to their delegates. If the receiver has no next responder or delegate, it beeps.

See also:	− tryToPerform:with:, − sendAction:to:from: (NSApplication)

flagsChanged:

− (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.

p	flushBufferedKeyEvents

− (void)flushBufferedKeyEvents

Overridden by subclasses to clear any unprocessed key events.

helpRequested:

− (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:

p	indent:

− (void)indent:(id)sender

Implemented by subclasses to indent the selection or the insertion point if there is no selection. NSResponder declares, but doesn’t implement this method.

p	insertBacktab:

− (void)insertBacktab:(id)sender

Implemented by subclasses to handle a “backward tab.” A field editor might respond to this by selecting the field before it, while a regular text object either doesn’t respond to, or ignores such a message. NSResponder declares, but doesn’t implement this method.

p	insertNewline:

− (void)insertNewline:(id)sender

Implemented by subclasses to insert a line-break character at the insertion point or selection, deleting the selection if there is one, or to end editing if the receiver is a text field or other field editor. NSResponder declares, but doesn’t implement this method.

p	insertNewlineIgnoringFieldEditor:

− (void)insertNewlineIgnoringFieldEditor:(id)sender

Implemented by subclasses to insert a line-break character at the insertion point or selection, deleting the selection if there is one. Unlike insertNewline:, this method always inserts a line-break character and doesn’t cause the receiver to end editing. NSResponder declares, but doesn’t implement this method.

p	insertParagraphSeparator:

− (void)insertParagraphSeparator:(id)sender

Implemented by subclasses to insert a paragraph separator at the insertion point or selection, deleting the selection if there is one. NSResponder declares, but doesn’t implement this method.

p	insertTab:

− (void)insertTab:(id)sender

Implemented by subclasses to insert a tab character at the insertion point or selection, deleting the selection if there is one, or to end editing if the receiver is a text field or other field editor. NSResponder declares, but doesn’t implement this method.

p	insertTabIgnoringFieldEditor:

− (void)insertTabIgnoringFieldEditor:(id)sender

Implemented by subclasses to insert a tab character at the insertion point or selection, deleting the selection if there is one. Unlike insertNewline:, this method always inserts a tab character and doesn’t cause the receiver to end editing. NSResponder declares, but doesn’t implement this method.

p	insertText:

− (void)insertText:(NSString *)aString

Overridden by subclasses to insert aString at the insertion point or selection, deleting the selection if there is one. NSResponder’s implementation simply passes this message to the next responder, or beeps if there is no next responder.

p	interpretKeyEvents:

− (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:

− (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:

− (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.

p	lowercaseWord:

− (void)lowercaseWord:(id)sender

Implemented by subclasses to make lowercase every letter in the word or words surrounding the insertion point or selection, though without expanding the selection. If either end of the selection partially covers a word, that entire word is made lowercase. NSResponder declares, but doesn’t implement this method.

See also:	− uppercaseWord:, − capitalizeWord:, − changeCaseOfLetter:

p	menu

− (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:

− (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:

− (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:

− (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:

− (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:

− (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:

− (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.

p	moveBackward:

− (void)moveBackward:(id)sender

Implemented by subclasses to move the selection or insertion point one element or character backward. In text, if there is a selection it should be deselected, and the insertion point should be placed at the beginning of the former selection. NSResponder declares, but doesn’t implement this method.

p	moveBackwardAndModifySelection:

− (void)moveBackwardAndModifySelection:(id)sender

Implemented by subclasses to expand or reduce either end of the selection backward by one element or character. If the end being modified is the backward end, this method expands the selection; if the end being modified is the forward end, it reduces the selection. The first moveBackwardAndModifySelection: or moveForwardAndModifySelection: method in a series determines the end being modified by always expanding. Hence, this method results in the backward end becoming the mobile one if invoked first.

NSResponder declares, but doesn’t implement this method.

p	moveDown:

− (void)moveDown:(id)sender

Implemented by subclasses to move the selection or insertion point one element or character down. In text, if there is a selection it should be deselected, and the insertion point should be placed below the beginning of the former selection. NSResponder declares, but doesn’t implement this method.

p	moveDownAndModifySelection:

− (void)moveDownAndModifySelection:(id)sender

Implemented by subclasses to expand or reduce the top or bottom end of the selection downward by one element, character, or line (whichever is appropriate for text direction). If the end being modified is the bottom, this method expands the selection; if the end being modified is the top, it reduces the selection. The first moveDownAndModifySelection: or moveUpAndModifySelection: method in a series determines the end being modified by always expanding. Hence, this method results in the bottom end becoming the mobile one if invoked first.

NSResponder declares, but doesn’t implement this method.

p	moveForward:

− (void)moveForward:(id)sender

Implemented by subclasses to move the selection or insertion point one element or character forward. In text, if there is a selection it should be deselected, and the insertion point should be placed at the end of the former selection. NSResponder declares, but doesn’t implement this method.

p	moveForwardAndModifySelection:

− (void)moveForwardAndModifySelection:(id)sender

Implemented by subclasses to expand or reduce either end of the selection forward by one element or character. If the end being modified is the backward end, this method reduces the selection; if the end being modified is the forward end, it expands the selection. The first moveBackwardAndModifySelection: or moveForwardAndModifySelection: method in a series determines the end being modified by always expanding. Hence, this method results in the forward end becoming the mobile one if invoked first.

NSResponder declares, but doesn’t implement this method.

p	moveLeft:

− (void)moveLeft:(id)sender

Implemented by subclasses to move the selection or insertion point one element or character to the left. In text, if there is a selection it should be deselected, and the insertion point should be placed at the left end of the former selection. NSResponder declares, but doesn’t implement this method.

p	moveRight:

− (void)moveRight:(id)sender

Implemented by subclasses to move the selection or insertion point one element or character to the right. In text, if there is a selection it should be deselected, and the insertion point should be placed at the right end of the former selection. NSResponder declares, but doesn’t implement this method.

p	moveToBeginningOfDocument:

− (void)moveToBeginningOfDocument:(id)sender

Implemented by subclasses to move the selection to the first element of the document, or the insertion point to the beginning. NSResponder declares, but doesn’t implement this method.

p	moveToBeginningOfLine:

− (void)moveToBeginningOfLine:(id)sender

Implemented by subclasses to move the selection to the first element of the selected line, or the insertion point to the beginning of the line. NSResponder declares, but doesn’t implement this method.

p	moveToBeginningOfParagraph:

− (void)moveToBeginningOfParagraph:(id)sender

Implemented by subclasses to move the insertion point to the beginning of the selected paragraph. NSResponder declares, but doesn’t implement this method.

p	moveToEndOfDocument:

− (void)moveToEndOfDocument:(id)sender

Implemented by subclasses to move the selection to the last element of the document, or the insertion point to the end. NSResponder declares, but doesn’t implement this method.

p	moveToEndOfLine:

− (void)moveToEndOfLine:(id)sender

Implemented by subclasses to move the selection to the last element of the selected line, or the insertion point to the end of the line. NSResponder declares, but doesn’t implement this method.

p	moveToEndOfParagraph:

− (void)moveToEndOfParagraph:(id)sender

Implemented by subclasses to move the insertion point to the end of the selected paragraph. NSResponder declares, but doesn’t implement this method.

p	moveUp:

− (void)moveUp:(id)sender

Implemented by subclasses to move the selection or insertion point one element or character up. In text, if there is a selection it should be deselected, and the insertion point should be placed above the beginning of the former selection. NSResponder declares, but doesn’t implement this method.

p	moveUpAndModifySelection:

− (void)moveUpAndModifySelection:(id)sender

Implemented by subclasses to expand or reduce the top or bottom end of the selection upward by one element, character, or line (whichever is appropriate for text direction). If the end being modified is the bottom, this method reduces the selection; if the end being modified is the top, it expands the selection. The first moveDownAndModifySelection: or moveUpAndModifySelection: method in a series determines the end being modified by always expanding. Hence, this method results in the top end becoming the mobile one if invoked first.

NSResponder declares, but doesn’t implement this method.

p	moveWordBackward:

− (void)moveWordBackward:(id)sender

Implemented by subclasses to move the selection or insertion point one word backward. If there is a selection it should be deselected, and the insertion point should be placed at the end of the first word preceding the former selection. NSResponder declares, but doesn’t implement this method.

p	moveWordBackwardAndModifySelection:

− (void)moveWordBackwardAndModifySelection:(id)sender

Implemented by subclasses to expand or reduce either end of the selection backward by one whole word. If the end being modified is the backward end, this method expands the selection; if the end being modified is the forward end, it reduces the selection. The first moveWordBackwardAndModifySelection: or moveWordForwardAndModifySelection: method in a series determines the end being modified by always expanding. Hence, this method results in the backward end becoming the mobile one if invoked first.

NSResponder declares, but doesn’t implement this method.

p	moveWordForward:

− (void)moveWordForward:(id)sender

Implemented by subclasses to move the selection or insertion point one word forward. If there is a selection it should be deselected, and the insertion point should be placed at the beginning of the first word following the former selection. NSResponder declares, but doesn’t implement this method.

p	moveWordForwardAndModifySelection:

− (void)moveWordForwardAndModifySelection:(id)sender

Implemented by subclasses to expand or reduce either end of the selection forward by one whole word. If the end being modified is the backward end, this method reduces the selection; if the end being modified is the forward end, it expands the selection. The first moveWordBackwardAndModifySelection: or moveWordForwardAndModifySelection: method in a series determines the end being modified by always expanding. Hence, this method results in the forward end becoming the mobile one if invoked first.

NSResponder declares, but doesn’t implement this method.

nextResponder

− (NSResponder *)nextResponder

Returns the receiver’s next responder, or nil if it has none.

See also:	− setNextResponder:, − noResponderFor:

noResponderFor:

− (void)noResponderFor:(SEL)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:.

p	pageDown:

− (void)pageDown:(id)sender

Implemented by subclasses to scroll the receiver down (or back) one page in its scroll view, also moving the insertion point to the top of the newly-displayed page. NSResponder declares, but doesn’t implement this method.

See also:	− scrollPageDown:, − scrollPageUp:

p	pageUp:

− (void)pageUp:(id)sender

Implemented by subclasses to scroll the receiver up (or forward) one page in its scroll view, also moving the insertion point to the top of the newly-displayed page. NSResponder declares, but doesn’t implement this method.

See also:	− scrollPageDown:, − scrollPageUp:

performKeyEquivalent:

− (BOOL)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 YES. NSResponder’s implementation does nothing and returns NO.

Note:	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, NSWindow, NSButton)

p	performMnemonic:

− (BOOL)performMnemonic:(NSString *)aString

Overridden by subclasses to handle a mnemonic. If the character code or codes in theEvent match the receiver’s key equivalent, the receiver should respond to the event and return YES. NSResponder’s implementation does nothing and returns NO.

See also:	− performMnemonic: (NSView)

resignFirstResponder

− (BOOL)resignFirstResponder

Notifies the receiver that it’s been asked to relinquish its status as first responder in its NSWindow. NSResponder’s implementation returns YES, resigning first responder status. Subclasses can override this method to update state or perform some action such as unhighlighting the selection, or to return NO, 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:

− (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:

− (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:

− (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.

p	scrollLineDown:

− (void)scrollLineDown:(id)sender

Implemented by subclasses to scroll the receiver one line down in its scroll view, without changing the selection. NSResponder declares, but doesn’t implement this method.

See also:	− scrollPageDown:, − lineScroll (NSScrollView)

p	scrollLineUp:

− (void)scrollLineUp:(id)sender

Implemented by subclasses to scroll the receiver one line up in its scroll view, without changing the selection. NSResponder declares, but doesn’t implement this method.

See also:	− scrollPageUp:, − lineScroll (NSScrollView)

p	scrollPageDown:

− (void)scrollPageDown:(id)sender

Implemented by subclasses to scroll the receiver one page down in its scroll view, without changing the selection. NSResponder declares, but doesn’t implement this method.

See also:	− pageDown:, − pageUp:, − pageScroll (NSScrollView)

p	scrollPageUp:

− (void)scrollPageUp:(id)sender

Implemented by subclasses to scroll the receiver one page up in its scroll view, without changing the selection. NSResponder declares, but doesn’t implement this method.

See also:	− pageDown:, − pageUp:, − pageScroll (NSScrollView)

p	selectAll:

− (void)selectAll:(id)sender

Implemented by subclasses to select all selectable elements. NSResponder declares, but doesn’t implement this method.

p	selectLine:

− (void)selectLine:(id)sender

Implemented by subclasses to select all elements in the line or lines containing the selection or insertion point. NSResponder declares, but doesn’t implement this method.

p	selectParagraph:

− (void)selectParagraph:(id)sender

Implemented by subclasses to select all paragraphs containing the selection or insertion point. NSResponder declares, but doesn’t implement this method.

p	selectToMark:

− (void)selectToMark:(id)sender

Implemented by subclasses to select all items from the insertion point or selection to a previously placed mark, including the selection itself if not empty. NSResponder declares, but doesn’t implement this method.

See also:	− setMark:, − deleteToMark:

p	selectWord:

− (void)selectWord:(id)sender

Implemented by subclasses to extend the selection to the nearest word boundaries outside it (up to, but not including, word delimiters). NSResponder declares, but doesn’t implement this method.

p	setMark:

− (void)setMark:(id)sender

Implemented by subclasses to set a mark at the insertion point or selection, which is used by deleteToMark: and selectToMark:. NSResponder declares, but doesn’t implement this method.

See also:	− swapWithMark:

p	setMenu:

− (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:

− (void)setNextResponder:(NSResponder *)aResponder

Sets the receiver’s next responder to aResponder.

See also:	− nextResponder

p	showContextHelp:

− (void)showContextHelp:(id)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:

p	swapWithMark:

− (void)swapWithMark:(id)sender

Swaps the mark and the selection or insertion point, so that what was marked is now the selection or insertion point, and what was the insertion point or selection is now the mark. NSResponder declares, but doesn’t implement this method.

See also:	− setMark:

p	transpose:

− (void)transpose:(id)sender

Transposes the characters to either side of the insertion point and advances the insertion point past both of them. Does nothing to a selected range of text. NSResponder declares, but doesn’t implement this method.

p	transposeWords:

− (void)transposeWords:(id)sender

NSResponder declares, but doesn’t implement this method.

tryToPerform:with:

− (BOOL)tryToPerform:(SEL)anAction with:(id)anObject

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

See also:	− doCommandBySelector:, − sendAction:to:from: (NSApplication)

p	uppercaseWord:

− (void)uppercaseWord:(id)sender

Implemented by subclasses to make uppercase every letter in the word or words surrounding the insertion point or selection, though without expanding the selection. If either end of the selection partially covers a word, that entire word is made uppercase. NSResponder declares, but doesn’t implement this method.

See also:	− lowercaseWord:, − capitalizeWord:, − changeCaseOfLetter:

validRequestorForSendType:returnType:

− (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)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 receiver data of returnType, it should return self; otherwise it should return nil. NSResponder’s implementation simply forwards this message to the next responder, ultimately returning nil.

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:	− registerServicesMenuSendType:returnTypes: (NSApplication), − writeSelectionToPasteboard:types: (NSApplication), − readSelectionFromPasteboard: (NSApplication)

p	yank:

− (void)yank:(id)sender

Replaces the insertion point or selection with text from the kill buffer and selects that text. If invoked sequentially, cycles through the kill buffer in reverse order. See “Standard Action Methods for Selecting and Editing” in the class description for more information on the kill buffer. NSResponder declares, but doesn’t implement this method.


NSRulerMarker
p NSRulerMarker

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCopying

NSObject (NSObject)

Declared In:	AppKit/NSRulerMarker.h

Class Description

An NSRulerMarker displays a symbol on an NSRulerView, indicating a location for whatever graphic element it represents in the client of the NSRulerView (for example, a margin or tab setting, or the edges of a graphic on the page). A ruler marker comprises three primary attributes: the image it displays on the NSRulerView, the location of that image, and the object it represents. The setImage:, setMarkerLocation: and setRepresentedObject: methods set each of these attributes, respectively. In addition, a ruler marker records an offset for the image, allowing it to be placed relative to the marker location much in the way a cursor’s hot spot relates a cursor image to the mouse location; the setImageOrigin: method establishes this offset.

Most of these attributes are set upon initialization by the initWithRulerView:markerLocation:image:imageOrigin: method. New ruler markers don’t have represented objects; the client typically establishes the represented object in its rulerView:didAddMarker: method. A new NSRulerMarker can be moved around in its NSRulerView, but not removed from it. The setMovable: and setRemovable: methods alter these default settings.

Represented objects allow the NSRulerView’s client to distinguish among different attributes of the selection. In the NSRulerView client methods, the client can retrieve the marker’s represented object to determine what attribute to alter. Generic attributes can be represented by string or other value objects, such as the edge names “Left”, “Right”, “Top”, and “Bottom”. Attributes already implemented as objects can be represented by those objects. For example, the OPENSTEP text system records tab stops as NSTextTab objects, which include the tab location and its alignment. When an NSTextView is the client view of a ruler, it simply makes the NSTextTabs the represented objects of the ruler markers.

Adopted Protocols

NSCopying	− copyWithZone:

Method Types

Creating instances	− initWithRulerView:markerLocation:image:imageOrigin:

Getting the ruler view	− ruler

Setting the image	− setImage:

− image

− setImageOrigin:

− imageOrigin

− imageRectInRuler

− thicknessRequiredInRuler

Setting movability	− setMovable:

− isMovable

− setRemovable:

− isRemovable

Setting the location	− setMarkerLocation:

− markerLocation

Setting the represented object	− setRepresentedObject:

− representedObject

Drawing and event handling	− drawRect:

− isDragging

− trackMouse:adding:

Instance Methods

p	drawRect:

− (void)drawRect:(NSRect)aRect

Draws the part of the receiver’s image that intersects aRect in the NSRulerView’s coordinate system.

See also:	− imageRectInRuler

p	image

− (NSImage *)image

Returns the NSImage object displayed by the receiver.

See also:	− setImage:

p	imageOrigin

− (NSPoint)imageOrigin

Returns the point in the receiver’s image that’s positioned at the receiver’s location on the NSRulerView, expressed in the image’s coordinate system.

For a horizontal ruler, the x coordinate of the image origin is aligned with the location of the marker, and the y coordinate lies on the baseline of the ruler. For vertical rulers, the y coordinate of the image origin is the location, and the x coordinate lies on the baseline.

See also:	− setImageOrigin:, − imageRectInRuler

p	imageRectInRuler

− (NSRect)imageRectInRuler

Returns the rectangle occupied by the marker’s image, in the NSRulerView’s coordinate system, accounting for whether the NSRulerView’s coordinate system is flipped.

See also:	− drawRect:, − thicknessRequiredInRuler

p	initWithRulerView:markerLocation:image:imageOrigin:

− (id)initWithRulerView:(NSRulerView *)aRulerView

markerLocation:(float)location

image:(NSImage *)anImage

imageOrigin:(NSPoint)imageOrigin

Initializes a newly allocated NSRulerMarker object, associating it with (but not adding it to) aRulerView and assigning the attributes provided. location is the x or y position of the marker in the client view’s coordinate system, depending on whether the NSRulerView is horizontal or vertical. anImage is the image displayed at the marker location, and imageOrigin is the point within the image that’s positioned at the marker location, expressed in pixels relative to the lower-left corner of the image. This method raises an NSInvalidArgumentException if aRulerView or anImage is nil.

Note:	The image used to draw the marker must be appropriate for the orientation of the ruler. Markers may need to look different on a horizontal ruler than on a vertical ruler, and the NSRulerView neither scales nor rotates the images.

To add the new ruler marker to aRulerView, use either of NSRulerView’s addMarker: or trackMarker:withMouseEvent: methods. addMarker: immediately puts the marker on the ruler, while trackMarker:withMousEvent: allows the client view to intercede in the addition and placement of the marker.

A new ruler marker is can be moved on its NSRulerView, but not removed. Use setMovable: and setRemovable: to change these attributes. The new ruler marker also has no represented object; use setRepresentedObject: to provide or change it.

This method retains anImage, since it’s an essential part of the ruler marker, but doesn’t retain aRulerView (the NSRulerView instead retains the new marker when it’s added). This method is the designated initializer for the NSRulerMarker class. Returns self.

See also:	− setMarkerLocation:, − setImage:, − setImageOrigin:

p	isDragging

− (BOOL)isDragging

Returns YES if the receiver is being dragged, NO otherwise.

See also:	− trackMouse:adding:

p	isMovable

− (BOOL)isMovable

Returns YES if the user can move the receiver on its NSRulerView, NO otherwise. NSRulerMarkers are by default movable.

See also:	− setMovable:, − isRemovable

p	isRemovable

− (BOOL)isRemovable

Returns YES if the user can remove the receiver from its NSRulerView, NO otherwise. NSRulerMarkers cannot by default be removed from their NSRulerViews.

See also:	− setRemovable:, − isMovable

p	markerLocation

− (float)makerLocation

Returns the location of the receiver in the coordinate system of the NSRulerView’s client view. This is an x position for a horizontal ruler, a y position for a vertical ruler.

See also:	− setMarkerLocation:

p	representedObject

− (id <NSCopying>)representedObject

Returns the object that the receiver represents, as explained in the class description.

See also:	− setRepresentedObject:

p	ruler

− (NSRulerView *)ruler

Returns the NSRulerView that the receiver belongs to.

See also:	− addMarker: (NSRulerView)

p	setImage:

− (void)setImage:(NSImage *)anImage

Sets the receiver’s image to anImage.

See also:	− image, − setImageOrigin:

p	setImageOrigin:

− (void)setImageOrigin:(NSPoint)aPoint

Sets the point in the receiver’s image that’s positioned at the receiver’s location on the NSRulerView to that at aPoint. This point is always expressed in pixels relative to the lower-left corner of the image.

For a horizontal ruler, the x coordinate of the image origin is aligned with the location of the marker, and the y coordinate lies on the baseline of the ruler. For vertical rulers, the y coordinate of the image origin is the location, and the x coordinate lies on the baseline.

See also:	− imageOrigin, − setImage:, − setMarkerLocation:

p	setMarkerLocation:

− (void)setMarkerLocation:(float)location

Sets the location of the receiver in the coordinate system of the NSRulerView’s client view to location. This is an x position for a horizontal ruler, a y position for a vertical ruler.

See also:	− markerLocation, − setImageOrigin:

p	setMovable:

− (void)setMovable:(BOOL)flag

Controls whether the user can move the receiver in its NSRulerView. If flag is YES, the user can drag the marker image in the ruler. If flag is NO, the receiver is immovable. NSRulerMarkers are by default movable.

See also:	− isMovable, − setRemovable:

p	setRemovable:

− (void)setRemovable:(BOOL)flag

Controls whether the user can remove the receiver from its NSRulerView. If flag is YES, the user can drag the marker image off of the ruler. If flag is NO, the receiver can’t be removed. NSRulerMarkers are by default not removable.

See also:	− isRemovable, − setMovable:

p	setRepresentedObject:

− (void)setRepresentedObject:(id <NSCopying>)anObject

Sets the object that the receiver represents to anObject. See the class description for more information on the represented object.

See also:	− representedObject

p	thicknessRequiredInRuler

− (float)thicknessRequiredInRuler

Returns the amount of the receiver’s image that’s displayed above or to the left of the NSRulerView’s baseline, the height for a horizontal ruler or width for a vertical ruler.

See also:	− imageOrigin

p	trackMouse:adding:

− (BOOL)trackMouse:(NSEvent *)theEvent adding:(BOOL)flag

Handles user manipulation of the receiver in its NSRulerView. NSRulerView invokes this method automatically to add a new marker or to move or remove an existing marker. You should never need to invoke it directly.

If flag is YES, the receiver is a new marker being added to its NSRulerView. Before the receiver actually adds itself to the NSRulerView, it queries the NSRulerView’s client view using rulerView:shouldAddMarker:. If the client view responds to this method and returns NO, this method immediately returns NO and the new marker isn’t added.

If flag is NO, this method attempts to move or remove an existing marker, once again based on responses from the NSRulerView’s client view. If the receiver is neither movable nor removable, this method immediately returns NO. Further, if the NSRulerView’s client responds to rulerView:shouldMoveMarker: and returns NO, this method returns NO, indicating that the receiver can’t be moved.

If the receiver is being added or moved, this method queries the client view using rulerView:willAddMarker:atLocation: or rulerView:willMoveMarker:toLocation:, respectively. If the client responds to the method, the return value is used as the receiver’s location. These methods are invoked repeatedly as the receiver is dragged within the NSRulerView.

If the receiver is an existing marker being removed (dragged off the ruler), this method queries the client view using rulerView:shouldRemoveMarker:. If the client responds to this method and returns NO, the marker is pinned to the NSRulerView’s baseline (following the mouse on the baseline if it’s movable).

When the user releases the mouse, this method informs the client view of the marker’s new status using rulerView:didAddMarker:, rulerView:didMoveMarker:, or rulerView:didRemoveMarker: as appropriate. The client view can use this notification to set the marker’s represented object, modify its state and redisplay (for example, adjusting text layout around a new tab stop), or take whatever other action it might need. If flag is YES and the user dragged the new marker away from the ruler, the marker isn’t added, no message is sent, and this method returns NO.

See the NSRulerView class description for more information on these client methods.

See also:	− isMovable, − isRemovable


NSRulerView
p NSRulerView

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSRulerView.h

Purpose

An NSRulerView displays a ruler and markers above or to the side of an NSScrollView’s document view. Views within the NSScrollView can become clients of the ruler view, having it display markers for their elements, and receiving messages from the ruler view when the user manipulates the markers.

Principal Attributes

•	Displays markers that represent elements of the client view

•	Displays in arbitrary units

•	Provides for an accessory view containing extra controls

Creation

− setHasHorizontalRuler: (NSScrollView)

− setHasVerticalRuler: (NSScrollView)

− initWithScrollView:orientation:	Designated initializer.

Commonly Used Methods

− setClientView:	Changes the ruler’s client view.

− setMarkers:	Sets the markers displayed by the ruler view.

− setAccessoryView:	Sets the accessory view.

− trackMarker:withMouseEvent:	Allows the user to add a new marker.

¬

Class Description

An NSRulerView resides in an NSScrollView, displaying a labeled ruler and markers for its client, the document view of the NSScrollView or a subview of the document view. The client view can add and remove markers representing its contents, such as graphic elements, margins, and text tabs. The NSRulerView tracks user manipulation of the markers and informs the client view of those actions. NSRulerView handles both horizontal and vertical rulers, which are tiled in the scroll view above and to the side of the content view, respectively. NSRulerViews are sometimes called simply ruler views or even rulers.

A ruler view comprises three regions. First is the ruler area, where the ruler’s baseline, hash marks, and labels are drawn. The ruler area is largely static, but it scales its hash marks to document view’s coordinate system, and can display the hash marks in arbitrary units. The second region is the marker area, where ruler markers (NSRulerMarker objects) representing elements of the client view are displayed. This is a more dynamic area, changing with the selection and state of the client view. The final region is the accessory view area, which is by default not present but appears when you add an accessory view to the ruler view. An accessory view can contain additional controls for manipulating the ruler’s client view, such as alignment buttons or a set of markers that can be dragged onto the ruler.

A ruler view interacts with its client view in several ways. On appropriating the ruler view, the client view usually sets it up according to its needs. The client view can also dynamically update the ruler view’s markers as its layout changes. In its turn, the ruler view informs the client view of actions the user takes on the ruler markers, allowing the client view to approve or limit the actions and to update its state based on the results of the actions.

The appearance of a ruler is based on both the document view and the client view. The document view, as the backdrop within the scroll view, serves as the canvas on which any client views are laid. Because of the document view’s anchoring role, a ruler always draws its hash marks and labels relative to the document view’s coordinate system. A vertical ruler also checks whether the document view is flipped and acts accordingly. However, the ruler view treats subviews of the document view as items laid out within the coordinate system defined by the document view, and so doesn’t change its hash marks when a client view other than the document view is moved or scaled. For the client view’s convenience it does, however, express marker locations in the client view’s coordinate system. A few other operations that ruler views perform are defined in terms of the ruler’s own coordinate system. The discussion of a feature or method makes clear which coordinate system applies. For reference, this table summarizes all of the coordinate systems involved in using ruler views, and the operations based on them:

Coordinate System	Used for

Client view	Marker locations

Document view	Calculating hash marks based on measurement units and scaling,

origin offset for zero marks

Ruler view	Temporary rulerlines, component layout

Marker image	Image origin (which locates the image relative to the marker location)

Measurement Units

A new ruler view automatically uses the user’s preferred measurement units for drawing hash marks and labels, as stored in the user defaults system under the key “NSMeasurementUnit”. If your application allows the user to change his preferred measurement units, you can change them at run time using setMeasurementUnits:, which takes the name of the units to use, such as “Inches” or “Centimeters”, and causes the ruler view to use that unit definition in spacing its hash marks and labels.

NSRulerView supports the units Inches, Centimeters, Points, and Picas by default. If your application uses other measurement units, your application should define and register them before creating any ruler views. To do, use the class method registerUnitWithName:abbreviation:unitsToPointsConversionFactor: stepUpCycle:stepDownCycle:. Your application can register these wherever it’s most convenient, such as in the NSApplication delegate method applicationDidFinishLaunching:. This code fragment registers a new unit called Grummets, with the abbreviation gt:

NSArray *upArray;

NSArray *downArray;

upArray = [NSArray arrayWithObjects:[NSNumber numberWithFloat:2.0], nil];

downArray = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.5],

    [NSNumber numberWithFloat:0.2], nil];

[NSRulerView registerUnitWithName:@"Grummets"

    abbreviation:NSLocalizedString(@"gt", @"Grummets abbreviation string")

    unitToPointsConversionFactor:100.0

    stepUpCycle:upArray stepDownCycle:downArray];

A Grummet is 100.0 PostScript units (points) in length, so a ruler view using it draws a major hash mark every 100.0 points when its document view is unscaled. If the document view is scaled, the ruler view spaces its hash marks accordingly.

The step-up and step-down cycles control how hash marks are drawn for fractions and multiples of units. NSRulerView attempts to place hash marks so that they’re neither too crowded nor too sparse based on the current scale of the document view. It does so by drawing smaller hash marks for fractions of units where possible, and by removing hash marks for whole units where necessary.

The step-down cycle determines the fractional units checked by the ruler view. For example, with the unit Grummets defined above, the step down cycle is 0.5, then 0.2. With this cycle, the ruler view first checks to see if there’s room for marks every half Grummet, placing them if there is. Then, it checks every fifth of the remaining space, or a tenth of a full Grummet, placing further hash marks there if there’s room. Then it returns to the first step in the cycle to further subdivide the ruler, and so on.

The step-up cycle determines how many full unit marks get dropped when there isn’t room for each one. The example uses a single-step cycle of 2.0, which means that each second Grommet’s hash mark is displayed if there isn’t room for every one, then every fourth if there still isn’t room, and so on.

Preparing a Ruler View for Use

Adding a ruler view to a scroll view can be as simple as invoking NSScrollView’s setHasHorizontalRuler: and setHasVerticalRuler: methods. These create instances of the default ruler view class, which you can change using the NSScrollView class method setRulerViewClass:. You can also set ruler views directly on a per-instance basis using setHorizontalRulerView: and setVerticalRulerView:. Once you’ve added rulers to a scroll view, you can hide and reveal them using setRulersVisible:.

Beyond creating the rulers, you need take only a few steps to set them up properly for use by the views contained within the scroll view: locating the zero marks of the rulers, and reserving room for accessory views. You normally perform these steps only once, when setting up the NSScrollView with rulers. However, if you allow the user to reset document attributes such as margins, you should change the zero mark locations as well. Also, if you reuse the scroll view by swapping in a new document view you may need to set up the rulers again with different settings.

The first step is to determine where you want the zero marks of the rulers to be located relative to the bounds origin of the document view. The zero marks are coincident with the bounds origin by default, but you can change this with the method setOriginOffset:. This method takes an offset specified in the document view’s coordinate system. If you need to set the origin offset based on a point in a subview of the document view, such as a text view that’s inset on a page, use convertPoint:fromView: to realize it in the document view’s coordinate system. This code fragment places the zero marks at the bounds origin of a client view, which lies somewhere inside the document view:

zero = [docView convertPoint:[clientView bounds].origin fromView:clientView];

[horizRuler setOriginOffset:zero.x - [docView bounds].origin.x];

After placing the zero marks, you should set up your rulers so that they don’t change in size as the user works within the document view. For example, if two different subviews of the document view use different accessory views, the ruler view enlarges itself as necessary each time you change the accessory view. Such changes are at best unsightly and at worst confusing to the user. To avoid this problem, calculate ahead of time the sizes of the largest accessory view and the largest markers, and set the ruler view’s required thickness for these elements using setReservedThicknessForAccessoryView: and setReservedThicknessForMarkers:. For example, if you have two accessory views for the horizontal ruler, one 16.0 PostScript units high and the other 24.0, invoke setReservedThicknessForAccessoryView: with an argument of 24.0.

Changing the Client

Once the ruler view is fully set up, the scroll view’s document view, or any subview of the document view, can become its client by sending it a setClientView: message. This method notifies the prior client that it’s losing the ruler view using the rulerView:willSetClientView: method, removes all of the ruler view’s markers, and sets the new client view. A client view normally appropriates the ruler when it becomes first responder and keeps it until some other view appropriates it. After appropriating the ruler view, the client needs to set up its layout and markers.

Adjusting the Layout

If the client has a custom accessory view, it sets that using setAccessoryView:. Clients without accessory views should avoid removing the ruler view’s accessory view when appropriating the ruler, as this can cause unsightly screen flicker as the ruler is redrawn. It’s better in this case for a client view that has an accessory view to implement rulerView:willSetClientView:, disabling the controls in the accessory view so that they’re not active when other clients are using the ruler. Then, when the client view with the accessory view appropriates the ruler, it should set its accessory view again in case another client swapped the accessory view out, and reenable the controls.

Setting Ruler Markers

Aside from the layout of the ruler view itself, the client can also add markers to indicate the positions of its graphic elements, such as tabs and margins in text or the bounding boxes of drawn shapes or images. Each marker is an NSRulerMarker object, which displays a graphic image on the ruler at its given location, and can be associated with an object that identifies the attribute indicated by the marker. You initialize an NSRulerMarker using its initWithRulerView:markerLocation:image:imageOrigin: method, which takes as arguments the NSRulerView where the marker will be displayed, its location on the ruler in the client view’s coordinate system, the image to display, and the point within the image that lies on the ruler’s baseline. Once you’ve created the markers, you can use NSRulerView’s addMarker: or setMarkers: methods to put them on the ruler. This code fragment, for example, sets up markers denoting the left and right edges of the selected object’s frame rectangle:

NSRulerMarker *leftMarker;

NSRulerMarker *rightMarker;

leftMarker = [[NSRulerMarker alloc] initWithRulerView:horizRuler

    markerLocation:NSMinX([selectedItem frame]) image:leftImage

    imageOrigin:NSMakePoint(0.0, 0.0)];

rightMarker = [[NSRulerMarker alloc] initWithRulerView:horizRuler

    markerLocation:NSMaxX([selectedItem frame]) image:rightImage

    imageOrigin:NSMakePoint(8.0, 0.0)];

[horizRuler setMarkers:[NSArray arrayWithObjects:leftMarker, rightMarker, nil]];

The images used for this example are 8 pixels square, and lie just inside of their relevant positions. The figure below shows the left and right marker images, enlarged and with gray bounding boxes. Thus, the left marker’s image must be placed with its lower left corner, or (0.0, 0.0), at the marker location, while the lower right corner of the right marker, at (8.0, 0.0), is used. The image origin is always expressed in the coordinate system of the image itself, just as an NSCursor’s hot spot is.

A new NSRulerMarker allows the user to drag it around on its ruler, but not to remove it. You can change these defaults by sending it setMovable: and setRemovable: messages. For example, you might make markers representing tabs in text removable to allow the user to edit the paragraph settings.

Markers bear one additional attribute, which allows you to distinguish among multiple markers, specifically markers that share the same image. This is the represented object, set with NSRulerMarker’s setRepresentedObject: method. A represented object can simply be a string identifying a generic attribute, such as “Left Margin” or “Right Margin”. It can also be an object stored in the client view or in the selection; for example, the OPENSTEP text system records tab stops as NSTextTab objects, which include the tab location and its alignment. When the user manipulates a tab marker, the client can simply retrieve its represented object to get the tab being affected.

Updating the Ruler View

A single client view may contain many selectable items, such as graphic shapes or paragraphs of text with different ruler settings. When the selection changes, the client must reset the ruler view’s markers based on the new selection. This kind of updating is fairly straightforward and can be performed as described above for situations where the client view itself changes.

Another kind of updating is needed when you wish to support dynamic updating of ruler markers as the user manipulates the elements of the client view. For example, when the user moves a shape, you want the ruler markers to relocate when the user finishes moving it. Any method that changes relevant attributes of the selection should update the ruler markers, whether by replacing them wholesale or by checking each one present and updating its location.

You can even put such updating code within a modal loop that handles dragging items around in the client view, so that the markers track the position of the selected item. This can be a fairly heavyweight operation to perform while also handling movement of the selected item, however. In support of a lighter weight means of showing this information, NSRulerView allows you to draw temporary rulerlines that can be drawn and erased very quickly. One method, moveRulerlineFromLocation:toLocation:, controls the drawing of rulerlines. It takes two locations expressed in the NSRulerView’s coordinate system, erasing the rulerline at the old location and redrawing it at the new. To create a new rulerline, specify −1.0 as the old location; to erase one completely, specify −1.0 as the new location. Although you’re responsible for keeping track of the locations to erase and redraw, this isn’t as cumbersome or inefficient as sifting through or replacing the markers themselves.

User Manipulation of Markers

While a ruler’s client view must perform the work of determining marker locations and placing them on the ruler, the ruler itself handles all the work of tracking user manipulations of the markers, sending messages to the client view that inform it of the changes before they begin, as they occur, and after they finish. The client view can use these messages to update its own state. The following sections describe the individual processes of moving, removing, and adding markers, along with a special method for handling mouse events in the ruler area.

Moving Markers

When the user presses the mouse button over a ruler marker, NSRulerView sends the marker a trackMouse:adding: message. If the marker isn’t movable this method does nothing and immediately returns NO. If it is movable, then it sends the client a series of messages allowing it to determine how the user can move the marker around on the ruler.

First of these messages is rulerView:shouldMoveMarker:, which allows the client view to prevent an otherwise movable marker from being moved. Normally, whether a marker can be moved should be set on the marker itself, but there are situations, such as where items can be locked in place, where this is more properly tracked by the client view instead. If the client view returns YES, allowing the movement, then it receives a series of rulerView:willMoveMarker:toLocation: messages as the user drags the marker around. Each message identifies the marker being moved and its proposed new location in the client view’s coordinate system. The client view can return an altered location to restrict the marker’s movement, or update its display to reflect the new location. Finally, when the user releases the mouse button, the client receives a rulerView:didMoveMarker:, on which it can update its state and clean up any information it may have used while tracking the marker’s movements.

Removing Markers

Removal of markers is handled by a similar set of messages. However, these are always sent during a movement operation, as the user must first be dragging a marker within the ruler to be able to drag it off the ruler. If a marker isn’t set to be removable, the user simply can’t drag it off. If the marker is removable, then when the user drags the mouse far enough away from the ruler’s baseline, it sends the client view a rulerView:shouldRemoveMarker: message, allowing the client to approve or veto the removal. No messages are necessary for new locations, of course, but if the user returns the marker to the ruler then it resumes sending rulerView:willMoveMarker:toLocation: messages as before. If the user releases the mouse with the marker dragged away from the ruler, the marker sends the client view a rulerView:didRemoveMarker: message, so the user can delete the item or attribute represented by the marker.

Adding Markers

User addition of a marker must be initiated by the application, of course, since there is no marker yet for the ruler to track. The first step in adding a marker, then, is to create one, using NSRulerMarker’s initWithRulerView:markerLocation:image:imageOrigin: method. Once the new marker is created, you instruct the ruler view to handle dragging it onto itself by sending it a trackMarker:withMouseEvent: message. One means of doing this is to use the mouse event from the client view method rulerView:handleMouseDown:, as described below under “Handling Mouse Events in the Ruler Area.” Another is to create a custom view object—which typically resides in the ruler’s accessory view—that displays prototype markers, and that handles a mouse-down event by creating a new marker for the ruler and invoking trackMarker:withMouseEvent: with the new marker and that mouse-down event.

Once you’ve initiated the addition process, things proceed in the same manner as for moving a marker. The ruler view sends the new marker a trackMouse:adding: message, with YES as the second argument to indicate that the marker isn’t merely being moved. The marker being added then sends the client view a rulerView:shouldAddMarker: message, and if the client approves then it repeatedly sends rulerView:willAddMarker:atLocation: messages as the user moves the marker around on the ruler. The user can drag the marker away to avoid adding it, or release the mouse button over the ruler, in which case the client receives a rulerView:didAddMarker: message.

As with moving a marker, you should consider enabling and disabling in a more immediate fashion than by the client view method if possible. If the user shouldn’t be able to drag a marker from the accessory view, for example, the view containing the prototype marker should disable itself and indicate this in its appearance, rather than allowing the user to drag a marker out only to discover that the ruler won’t accept it.

Handling Mouse Events in the Ruler Area

In addition to handling user manipulation of markers, a ruler informs its client view when the user presses the mouse button while the mouse is inside the ruler area (where hash marks are drawn), by sending it a rulerView:handleMouseDown: message. This allows the client view to take some special action, such as adding a new marker to the ruler, as described above. This approach works well when it’s quite clear what kind of marker will be created. The client view can also use this message as a cue to change its display in some way; for example to add or remove a guideline that assists the user in laying out and aligning items in the view.

Method Types

Creating instances	− initWithScrollView:orientation:

Altering measurement units	+ registerUnitWithName:abbreviation:

unitToPointsConversionFactor:

stepUpCycle:stepDownCycle:

− setMeasurementUnits:

− measurementUnits

Setting the client view	− setClientView:

− clientView

Setting an accessory view	− setAccessoryView:

− accessoryView

Setting the zero mark position	− setOriginOffset:

− originOffset

Adding and removing markers	− setMarkers:

− markers

− addMarker:

− removeMarker:

− trackMarker:withMouseEvent:

Drawing temporary rulerlines	− moveRulerlineFromLocation:toLocation:

Drawing	− drawHashMarksAndLabelsInRect:

− drawMarkersInRect:

− invalidateHashMarks

Ruler layout	− setScrollView:

− scrollView

− setOrientation:

− orientation

− setReservedThicknessForAccessoryView:

− reservedThicknessForAccessoryView

− setReservedThicknessForMarkers:

− reservedThicknessForMarkers

− setRuleThickness:

− ruleThickness

− requiredThickness

− baselineLocation

− isFlipped

Class Methods

p	registerUnitWithName:abbreviation:unitToPointsConversionFactor:

stepUpCycle:stepDownCycle:

+ (void)registerUnitWithName:(NSString *)unitName

abbreviation:(NSString *)abbreviation

unitToPointsConversionFactor:(float)conversionFactor

stepUpCycle:(NSArray *)stepUpCycle

stepDownCycle:(NSArray *)stepDownCycle

Registers a new unit of measurement with the NSRulerView class, making it available to all instances of NSRulerView. unitName is the name of the unit in English, in plural form and capitalized by convention; “Inches”, for example. The unit name is used as a key to identify the measurement units, and so shouldn’t be localized. abbreviation is a localized short form of the unit name, such as “in” for Inches. conversionFactor is the number of PostScript points in the specified unit; there are 72.0 points per inch, for example. stepUpCycle and stepDownCycle are arrays of NSNumbers that specify how hash marks are calculated, as explained in the class description under “Preparing a Ruler View for Use.” All numbers in stepUpCycle should be greater than 1.0, those in stepDownCycle should be less than 1.0.

NSRulerView supports these units by default:

Unit Name	Abbreviation	Points/Unit	Step-up Cycle	Step-down Cycle

Inches	in	72.0	2.0	0.5

Centimeters	cm	28.35	2.0	0.5, 0.2

Points	pt	1.0	10.0	0.5

Picas	pc	12.0	10.0	0.5

See also:	− setMeasurementUnits:

Instance Methods

p	accessoryView

− (NSView *)accessoryView

Returns the receiver’s accessory view, if it has one.

See also:	 − setAccessoryView:, − reservedThicknessForAccessoryView:

p	addMarker:

− (void)addMarker:(NSRulerMarker *)aMarker

Adds aMarker to the receiver, without consulting the client view for approval. Raises NSInternalInconsistencyException if the receiver has no client view.

See also:	− setMarkers:, − removeMarker:, − markers, − trackMarker:withMouseEvent:

p	baselineLocation

− (float)baselineLocation

Returns the location of the receiver’s baseline, in its own coordinate system. This is a y position for horizontal rulers and an x position for vertical ones.

See also:	− ruleThickness

p	clientView

− (NSView *)clientView

Returns the receiver’s client view, if it has one.

See also:	− setClientView:

p	drawHashMarksAndLabelsInRect:

− (void)drawHashMarksAndLabelsInRect:(NSRect)aRect

Draws the receiver’s hash marks and labels in aRect, which is expressed in the receiver’s coordinate system. This method is invoked by drawRect:—you should never need to invoke it directly. You can define custom measurement units using the class method registerUnitWithName:.... Override this method if you want to customize the appearance of the hash marks themselves.

See also:	− invalidateHashMarks, − drawMarkersInRect:

p	drawMarkersInRect:

− (void)drawMarkersInRect:(NSRect)aRect

Draws the receiver’s markers in aRect, which is expressed in the receiver’s coordinate system. This method is invoked by drawRect:; you should never need to invoke it directly, but you might want to override it if you want to do something different when drawing markers.

See also:	− reservedThicknessForMarkers, − drawHashMarksAndLabelsInRect:

p	initWithScrollView:orientation:

− (id)initWithScrollView:(NSScrollView *)aScrollView orientation:(NSRulerOrientation)orientation

Initializes a newly allocated NSRulerView to have orientation (NSHorizontalRuler or NSVerticalRuler) within aScrollView. The new ruler view displays the user’s preferred measurement units, and has no client, markers, or accessory view. Unlike most subclasses of NSView, no initial frame rectangle is given for NSRulerView; its containing NSScrollView adjusts its frame rectangle as needed.

This is the designated initializer for the NSRulerView class. Returns self.

p	invalidateHashMarks

− (void)invalidateHashMarks

Forces recalculation of the hash mark spacing for the next time the receiver is displayed. You should never need to invoke this method directly, but might need to override it if you override drawHashMarksAndLabelsInRect:.

See also:	− drawHashMarksAndLabelsInRect:

p	isFlipped

− (BOOL)isFlipped

Returns YES if the NSRulerView’s coordinate system is flipped, NO otherwise. A vertical ruler takes into account whether the coordinate system of the NSScrollView’s document view—not the receiver’s client view—is flipped. A horizontal ruler is always flipped.

p	markers

− (NSArray *)markers

Returns the receiver’s NSRulerMarkers. The markers aren’t guaranteed to be sorted in any particular order.

See also:	− setMarkers:, − addMarker:, − removeMarker:, − markerLocation (NSRulerMarker)

p	measurementUnits

− (NSString *)measurementUnits

Returns the full name of the measurement units in effect for the receiver.

See also:	− setMeasurementUnits:, + registerUnitWithName:...

p	moveRulerlineFromLocation:toLocation:

− (void)moveRulerlineFromLocation:(float)oldLoc toLocation:(float)newLoc

Draws temporary lines in the ruler area. If oldLoc is zero or greater, erases the rulerline at that location; if newLoc is zero or greater, draws a new rulerline at that location. oldLoc and newLoc are expressed in the coordinate system of the NSRulerView, not of the client or document view, and are x coordinates for horizontal rulers and y coordinates for vertical rulers. Use NSView’s convert... methods to convert coordinates from the client or document view’s coordinate system to that of the NSRulerView.

This method is useful for drawing highlight lines in the ruler to show the position or extent of an object while it’s being dragged in the client view. The sender is responsible for keeping track of the number and positions of temporary lines—the NSRulerView only does the drawing.

p	orientation

− (NSRulerOrientation)orientation

Returns the orientation of the NSRulerView, either NSHorizontalRuler or NSVerticalRuler.

See also:	− setOrientation:

p	originOffset

− (float)originOffset

Returns the distance from the receiver’s zero hash mark to the bounds origin of the NSScrollView’s document view (not the receiver’s client view), in the document view’s coordinate system.

See also:	− setOriginOffset:

p	removeMarker:

− (void)removeMarker:(NSRulerMarker *)aMarker

Removes aMarker from the receiver, without consulting the client view for approval.

See also:	 − setMarkers:, − addMarker:

p	requiredThickness

− (float)requiredThickness

Returns the thickness needed for proper tiling of the receiver within an NSScrollView. This is the height of a horizontal ruler and the width of a vertical ruler. The required thickness is the sum of the thicknesses of the ruler area, the marker area, and the accessory view.

See also:	− rulerThickness, − reservedThicknessForMarkers, − reservedThicknessForAccessoryView

p	reservedThicknessForAccessoryView

− (float)reservedThicknessForAccessoryView

Returns the thickness reserved to contain the receiver’s accessory view, its height or width depending on the receiver’s orientation. This is automatically enlarged as necessary to the accessory view’s thickness (but never automatically reduced). To prevent retiling of a ruler view’s scroll view, you should set its maximal thickness upon creating using setReservedThicknessForAccessoryView:.

p	reservedThicknessForMarkers

− (float)reservedThicknessForMarkers

Returns the thickness reserved to contain the images of the receiver’s ruler markers, the height or width depending on the receiver’s orientation. This is automatically enlarged as necessary to accommodate the thickest ruler marker image (but never automatically reduced). To prevent retiling of a ruler view’s scroll view, you should set its maximal thickness upon creating using setReservedThicknessForMarkers:.

See also:	− thicknessRequiredInRulerView (NSRulerMarker)

p	ruleThickness

− (float)ruleThickness

Returns the thickness of the receiver’s ruler area (the area where hash marks and labels are drawn), its height or width depending on the receiver’s orientation.

See also:	− setRuleThickness:

p	scrollView

− (NSScrollView *)scrollView

Returns the NSScrollView object that contains the receiver.

See also:	− setScrollView:, − setHorizontalRuler: (NSScrollView), − setVerticalRuler: (NSScrollView)

p	setAccessoryView:

− (void)setAccessoryView:(NSView *)aView

Sets the receiver’s accessory view to aView. Raises an NSInternalInconsistencyException if aView is non-nil and the receiver has no client view.

See also:	− accessoryView, − reservedThicknessForAccessoryView

p	setClientView:

− (void)setClientView:(NSView *)aView

Sets the receiver’s client view to aView, without retaining it, and removes its ruler markers, after informing the prior client of the change using rulerView:willSetClientView:. aView must be either the document view of the NSScrollView that contains the receiver, or a subview of the document view.

See also:	− clientView

p	setMarkers:

− (void)setMarkers:(NSArray *)markers

Sets the receiver’s ruler markers to markers, removing any existing ruler markers and not consulting with the client view about the new markers. markers can be nil or empty to remove all ruler markers. Raises an NSInternalInconsistencyException if markers is non-nil and the receiver has no client view.

See also:	− addMarker:, − removeMarker:

p	setMeasurementUnits:

− (void)setMeasurementUnits:(NSString *)unitName

Sets the measurement units used by the ruler to unitName. unitName must have been registered with the NSRulerView class object prior to invoking this method. See the description of the class method registerUnitWithName:... for a list of predefined units.

See also:	− measurementUnits

p	setOrientation:

− (void)setOrientation:(NSRulerOrientation)orientation

Sets the orientation of the receiver to orientation, which may be NSHorizontalRuler or NSVerticalRuler. You should never need to invoke this method directly—it’s automatically invoked by the containing NSScrollView.

See also:	− orientation

p	setOriginOffset:

− (void)setOriginOffset:(float)offset

Sets the distance to the zero hash mark from the bounds origin of the NSScrollView’s document view (not of the receiver’s client view), in the document view’s coordinate system. The default offset is 0.0, meaning that the ruler origin coincides with the bounds origin of the document view.

See also:	− originOffset

p	setReservedThicknessForAccessoryView:

− (void)setReservedThicknessForAccessoryView:(float)thickness

Sets the room available for the NSRulerView’s accessory view to thickness. If the ruler is horizontal, thickness is the height of the accessory view; otherwise, it’s the width. NSRulerViews by default reserve no space for an accessory view.

An NSRulerView automatically increases the reserved thickness as necessary to that of the accessory view. When the accessory view is thinner than the reserved space, it’s centered in that space. If you plan to use several accessory views of different sizes, you should set the reserved thickness beforehand to that of the thickest accessory view, in order to avoid retiling of the NSScrollView.

See also:	− reservedThicknessForAccessoryView, − setAccessoryView:, − setReservedThicknessForMarkers:

p	setReservedThicknessForMarkers:

− (void)setReservedThicknessForMarkers:(float)thickness

Sets the room available for ruler markers to thickness. The default thickness reserved for markers is 15.0 PostScript units for a horizontal ruler and 0.0 PostScript units for a vertical ruler (under the assumption that vertical rulers rarely contain markers). If you don’t expect to have any markers on the ruler, you can set the reserved thickness to 0.0.

An NSRulerView automatically increases the reserved thickness as necessary to that of its thickest marker. If you plan to use markers of varying sizes, you should set the reserved thickness beforehand to that of the thickest one in order to avoid retiling of the NSScrollView.

See also:	− reservedThicknessForMarkers, − setMarkers:, − setReservedThicknessForAccessoryView:, − thicknessRequiredInRulerView (NSRulerMarker)

p	setRuleThickness:

− (void)setRuleThickness:(float)thickness

Sets to thickness the thickness of the area where ruler hash marks and labels are drawn. This value is the height of the ruler area for a horizontal ruler or the width of the ruler area for a vertical ruler. Rulers are by default 16.0 PostScript units thick. You should rarely need to change this layout attribute, but subclasses might do so to accommodate custom drawing.

See also:	− ruleThickness

p	setScrollView:

− (void)setScrollView:(NSScrollView *)scrollView

Sets the NSScrollView that owns the receiver to scrollView, without retaining it. This method is generally invoked only by the ruler’s scroll view; you should rarely need to invoke it directly.

See also:	− scrollView, − setHorizontalRuler: (NSScrollView), − setVerticalRuler: (NSScrollView)

p	trackMarker:withMouseEvent:

− (BOOL)trackMarker:(NSRulerMarker *)aMarker withMouseEvent:(NSEvent *)theEvent

Tracks the mouse to add aMarker based on the initial mouse-down or mouse-dragged event theEvent. Returns YES if the receiver adds aMarker, NO if it doesn’t. This method works by sending trackMouse:adding: to aMarker with theEvent and YES as arguments.

An application typically invokes this method in one of two cases. In the simpler case, the client view can implement rulerView:handleMouseDown: to invoke this method when the user presses the mouse button in the NSRulerView’s ruler area. This technique is appropriate when it’s clear what kind of marker will be added by clicking in the ruler area. The second, more general, case involves the application providing a palette of different kinds of markers that can be dragged onto the ruler, from the ruler’s accessory view or from some other place. With this technique the palette tracks the mouse until it enters the ruler view, at which time it hands over control to the ruler view by invoking trackMarker:withMouseEvent:.

See also:	− addMarker:, − setMarkers:

Methods Implemented by the NSRulerView’s Client

p	rulerView:didAddMarker:

− (void)rulerView:(NSRulerView *)aRulerView didAddMarker:(NSRulerMarker *)aMarker

Informs the client that aRulerView allowed the user to add aMarker. The client can take whatever action it needs based on this message, such as adding a new tab stop to the selected paragraph or creating a layout guideline.

See also:	− representedObject (NSRulerMarker), − markerLocation (NSRulerMarker)

p	rulerView:didMoveMarker:

− (void)rulerView:(NSRulerView *)aRulerView didMoveMarker:(NSRulerMarker *)aMarker

Informs the client that aRulerView allowed the user to move aMarker. The client can take whatever action it needs based on this message, such as updating the location of a tab stop in the selected paragraph, moving a layout guideline, or resizing a graphic element.

See also:	− representedObject (NSRulerMarker), − markerLocation (NSRulerMarker)

p	rulerView:didRemoveMarker:

− (void)rulerView:(NSRulerView *)aRulerView didRemoveMarker:(NSRulerMarker *)aMarker

Informs the client that aRulerView allowed the user to remove aMarker. The client can take whatever action it needs based on this message, such as deleting a tab stop from the paragraph style or removing a layout guideline.

See also:	− representedObject (NSRulerMarker)

p	rulerView:handleMouseDown:

− (void)rulerView:(NSRulerView *)aRulerView handleMouseDown:(NSEvent *)theEvent

Informs the client that the user has pressed the mouse button while the cursor is in the ruler area of aRulerView. theEvent is the mouse-down event that triggered the message. The client view can implement this method to perform an action such as adding a new marker using trackMarker:withMouseEvent: or adding layout guidelines.

p	rulerView:shouldAddMarker:

− (BOOL)rulerView:(NSRulerView *)aRulerView shouldAddMarker:(NSRulerMarker *)aMarker

Requests permission for aRulerView to add aMarker, an NSRulerMarker being dragged onto the ruler by the user. If the client returns YES then the ruler view accepts the new marker and begins tracking its movement; if the client returns NO then the ruler view refuses the new marker.

See also:	− rulerView:willAddMarker:atLocation:

p	rulerView:shouldMoveMarker:

− (BOOL)rulerView:(NSRulerView *)aRulerView shouldMoveMarker:(NSRulerMarker *)aMarker

Requests permission for aRulerView to move aMarker. If the client returns YES then the ruler view allows the user to move the marker; if the client returns NO then the marker doesn’t move.

The user’s ability to move a marker is typically set on the marker itself, using NSRulerMarker’s setMovable: method. You should use this client view method only when the marker’s movability can vary depending on a variable condition (for example, if graphic items can be locked down to prevent them from being inadvertently moved).

See also:	− rulerView:willMoveMarker:toLocation:

p	rulerView:shouldRemoveMarker:

− (BOOL)rulerView:(NSRulerView *)aRulerView shouldRemoveMarker:(NSRulerMarker *)aMarker

Requests permission for aRulerView to remove aMarker. If the client returns YES then the ruler view allows the user to remove the marker; if the client returns NO then the marker is kept pinned to the ruler’s baseline. This message is sent as many times as needed while the user drags the marker.

The user’s ability to remove a marker is typically set on the marker itself, using NSRulerMarker’s setRemovable: method. You should use this client view method only when the marker’s removability can vary while the user drags it (for example, if the user must press the Shift key to remove a marker).

p	rulerView:willAddMarker:atLocation:

− (float)rulerView:(NSRulerView *)aRulerView

willAddMarker:(NSRulerMarker *)aMarker

atLocation:(float)location

Informs the client that aRulerView will add the new NSRulerMarker, aMarker. location is the marker’s tentative new location, expressed in the client view’s coordinate system. The value returned by the client view is actually used; the client can simply return location unchanged, or adjust it as needed. For example, it may snap the location to a grid. This message is sent repeatedly to the client as the user drags the marker.

See also:	− rulerView:willMoveMarker:toLocation:

p	rulerView:willMoveMarker:toLocation:

− (float)rulerView:(NSRulerView *)aRulerView

willMoveMarker:(NSRulerMarker *)aMarker

toLocation:(float)location

Informs the client that aRulerView will move aMarker, an NSRulerMarker already on the ruler view. location is the marker’s tentative new location, expressed in the client view’s coordinate system. The value returned by the client view is actually used; the client can simply return location unchanged, or adjust it as needed. For example, it may snap the location to a grid. This message is sent repeatedly to the client as the user drags the marker.

See also:	− rulerView:willAddMarker:atLocation:

p	rulerView:willSetClientView:

− (void)rulerView:(NSRulerView *)aRulerView

willSetClientView:(NSView *)newClient

Informs the client view that aRulerView is about to be appropriated by newClient. The client view can use this opportunity to clear any cached information related to the ruler.


NSSavePanel

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSSavePanel.h

Purpose

An NSSavePanel object manages a panel that allows users to specify the directory and name under which a file is saved. It supports browsing of the file system and it accommodates custom accessory views. An NSSavePanel is a recycled object: when you request a Save panel, NSSavePanel tries to reuse an existing Save panel rather than create a new one.

Principal Attributes

•	Delegate	•	Browser

•	Form	•	Prompt

•	Title	•	File name

•	Directory	•	Accessory view

Creation

+ savePanel	(class method)

Commonly Used Methods

runModal	Displays the panel and begins the event loop.

filename	Returns the selected or entered file name.

directory	Returns the full path of the selected file.

ok: 	Invoked when users click OK.

Class Description

NSSavePanel creates and manages a Save panel, and allows you to run the panel in a modal loop. The Save panel provides a simple way for a user to specify a file to use when saving a document or other data. It can restrict the user to files of a certain type, as specified by a file name extension.

When the user decides on a file name, the message panel:isValidFilename: is sent to the NSSavePanel’s delegate. If it responds to that message, the delegate can determine whether the specified file name can be used; it returns YES if the file name is valid, or NO if the Save panel should stay up and wait for the user to type in a different file name.

Typically, you access an NSSavePanel by invoking the savePanel method. When the class receives a savePanel message, it tries to reuse an existing panel rather than create a new one. When a panel is reused its attributes are reset to the default values so that the effect is the same as receiving a new panel. Because a Save panel may be reused, you shouldn't modify the instance returned by savePanel except through the methods listed below. For example, you can set the panel’s title and required file type, but not the arrangement of the buttons within the panel. If you must modify the Save panel substantially, create and manage your own instance using the alloc... and init... methods rather than the savePanel method.

A typical programmatic use of NSavePanel requires you to:

•	Invoke savePanel.

•	Configure the panel (for instance, set its title or add a custom view).

•	Run the panel in a model loop.

•	Test the result; if successful, save the file under the chosen name and in the chosen directory.

The following code fragment demonstrates this sequence. (Two objects in this example, newView and textData, are assumed to be defined and created elsewhere.)

    NSSavePanel *sp;

    int runResult;

    /* create or get the shared instance of NSSavePanel */

    sp = [NSSavePanel savePanel];

    /* set up new attributes */

    [sp setAccessoryView:newView];

    [sp setRequiredFileType:@"txt"];

    /* display the NSSavePanel */

    runResult = [sp runModalForDirectory:NSHomeDirectory() file:@""];

    /* if successful, save file under designated name */

    if (runResult == NSOKButton) {

        if (![textData writeToFile:[sp filename] atomically:YES])

              NSBeep();

    }

Method Types

Creating an NSSavePanel	+ savePanel

Customizing the NSSavePanel	− setAccessoryView:

− accessoryView

− setTitle:

− title

− setPrompt:

− prompt

Setting directory and file type	− setDirectory:

− setRequiredFileType:

− requiredFileType

− treatsFilePackagesAsDirectories

− setTreatsFilePackagesAsDirectories:

− validateVisibleColumns

Running the NSSavePanel	− runModal

− runModalForDirectory:file:

Getting user selections	− directory

− filename

Action methods	− cancel:

− ok:

Responding to user input	− selectText:

Setting the delegate	− setDelegate:

− delegate (NSWindow)

Class Methods

savePanel

+ (NSSavePanel *)savePanel

Returns an instance of NSSavePanel, creating one if necessary. Otherwise, the instance is a recycled NSSavePanel object. The method sets the attributes of the instance to the default values:

•	current working directory as starting point

•	prompt of “Name”

•	no required file types

•	file packages not treated as directories

•	no delegate

•	no accessory view

Instance Methods

accessoryView

− (NSView *)accessoryView

Returns the custom accessory view for the current application. This view is set by setAccessoryView:.

See also:	− setAccessoryView:

cancel:

− (void)cancel:(id)sender

Invoked when the user clicks the panel’s Cancel button.

directory

− (NSString *)directory

Returns the absolute pathname of the directory currently shown in the panel. Do not invoke this method within a modal session (runModal or runModalForDirectory:file:) because the directory information is only updated just before the modal session ends.

See also:	− setDirectory:

encodeWithCoder:

− (void)encodeWithCoder:(NSCoder *)coder

Overrides the superclass implementation of this NSCoding protocol method to raise an exception. The  NSSavePanel does not get encoded.

See also:	− initWithCoder:

filename

− (NSString *)filename

Returns the absolute path name of the file currently shown in the panel. Do not invoke this method within a modal session (runModal or runModalForDirectory:file:) because the filename information is only updated just before the modal session ends.

initWithCoder:

− (id)initWithCoder:(NSCoder *)coder

Overrides the superclass implementation of this NSCoding protocol method to raise an exception. The  NSSavePanel does not get decoded.

See also:	− encodeWithCoder:

ok:

− (void)ok:(id)sender

Invoked when the user clicks the panel’s OK button.

prompt

− (NSString *)prompt

Returns the prompt of the Save panel field that holds the current pathname or file name. By default this prompt is “Name:”.

See also:	− setPrompt:

requiredFileType

− (NSString *)requiredFileType

Returns the required file type (if any). A file specified in the Save panel is saved with the designated file name and this file type as an extension. Examples of common file types are “rtf”, “tiff”, and “ps”. An empty NSString return value indicates that the user can save to any ASCII file.

See also:	− setRequiredFileType:

runModal

− (int)runModal

Displays the panel and begins its event loop with the current working (or last selected) directory as the default starting point. Invokes runModalForDirectory:file: (file argument is an empty NSString), which in turn performs NSApplication’s runModalForWindow: method with self as the argument. Returns NSOKButton (if the user clicks the OK button) or NSCancelButton (if the user clicks the Cancel button). Do not invoke filename or directory within a modal loop because the information that these methods fetch is updated only upon return.

See also:	 − runModalForDirectory:file:, − runModalForWindow: (NSApplication)

runModalForDirectory:file:

− (int)runModalForDirectory:(NSString *)path file:(NSString *)filename

Initializes the panel to the directory specified by path and, optionally, the file specified by filename, then displays it and begins its modal event loop; path and filename can be empty strings, but cannot be nil. The method invokes Application’s runModalForWindow: method with self as the argument.   Returns NSOKButton (if the user clicks the OK button) or NSCancelButton (if the user clicks the Cancel button). Do not invoke filename or directory within a modal loop because the information that these methods fetch is updated only upon return.

See also:	 − runModal, − runModalForWindow: (Application)

selectText:

− (void)selectText:(id)sender

Advances the current browser selection one line when Tab or the up-arrow key is pressed, and goes back one line when Shift-Tab or the down-arrow key is pressed; after it makes the new selection it writes the selected item in the field after the prompt. The argument sender identifies the object invoking this method. This method is primarily of interest to those who want to override it to get different behavior.

setAccessoryView:

− (void)setAccessoryView:(NSView *)aView

Customizes the panel for the application by adding a custom NSView (aView) to the panel. The custom NSView that’s added appears just above the OK and Cancel buttons at the bottom of the panel. The NSSavePanel automatically resizes itself to accommodate aView. You can invoke this method repeatedly to change the accessory view as needed. If aView is nil, the NSSavePanel removes the current accessory view.

See also:	− accessoryView

setDelegate:

− (void)setDelegate:(id)anObject

Makes anObject the NSSavePanel’s delegate, after verifying which delegate methods are implemented. Use NSWindow’s delegate method to retrieve the NSSavePanel’s delegate.

setDirectory:

− (void)setDirectory:(NSString *)path

Sets the current path name in the Save panel’s browser. The path argument must be an absolute path name.

See also:	− directory

setPrompt:

− (void)setPrompt:(NSString *)prompt

Sets the prompt of the field that holds the current pathname or file name. This prompt appears on all NSSavePanels (or all NSOpenPanels if the receiver of this message is an NSOpenPanel) in your application. “Name:” is the default prompt string.

See also:	− prompt

setRequiredFileType:

− (void)setRequiredFileType:(NSString *)type

Specifies the type, a file name extension to be appended to any selected files that don’t already have that extension; “nib” and “rtf” are examples. The argument type should not include the period that begins the extension. You need to invoke this method each time the Save panel is used for another file type within the application.

See also:	− requiredFileType

setTreatsFilePackagesAsDirectories:

− (void)setTreatsFilePackagesAsDirectories:(BOOL)flag

Sets the NSSavePanel’s behavior for displaying file packages (for example, MyApp.app) to the user. If flag is YES, the user is shown files and subdirectories within a file package. If NO, the NSSavePanel shows each file package as a file, thereby giving no indication that it is a directory.

See also:	− treatsFilePackagesAsDirectories

setTitle:

− (void)setTitle:(NSString *)title

Sets the title of the NSSavePanel to title. By default, “Save” is the title string. If you adapt the NSSavePanel for other uses, its title should reflect the user action that brings it to the screen.

See also:	− title

treatsFilePackagesAsDirectories

− (BOOL)treatsFilePackagesAsDirectories

Use to determine whether the Save panel displays file packages to the user as directories. Returns YES if the user is shown files and subdirectories within a file package; returns NO (the default) if the user is shown only file-package names, with no indication that they are directories.

See also:	− setTreatsFilePackagesAsDirectories:

validateVisibleColumns

− (void)validateVisibleColumns

Validates and possibly reloads the browser columns visible in the Save panel by causing the delegate method panel:shouldShowFilename: to be invoked. One situation in which this method would find use is whey you want the browser show only files with certain extensions based on the selection made in an accessory-view pop-up list.  When the user changes the selection, you would invoke this method to revalidate the visible columns.

Methods Implemented by the Delegate

panel:compareFilename:with:caseSensitive:

− (NSComparisonResult)panel:(id)sender

compareFilename:(NSString *)fileName1

with:(NSString *)fileName2

caseSensitive:(BOOL)flag

Controls the ordering of files presented by the NSSavePanel. This method should return:

•	NSOrderedAscending if fileName1 should precede fileName2

•	NSOrderedSame if the two names are equivalent

•	NSOrderedDescending if fileName2 should precede fileName1

The flag argument, if YES, indicates that the ordering is to be case-sensitive.

Don’t reorder file names in the Save panel without good reason, since it may confuse the user to have files in one Save panel or Open panel ordered differently than those in other such panels or in the Workspace Manager. The default behavior of Save and Open panel is to order files as they appear in the Workspace Manager file viewer. Note also that by implementing this method you will reduce the operating performance of the panel.

panel:shouldShowFilename:

− (BOOL)panel:(id)sender

shouldShowFilename:(NSString *)filename

The NSSavePanel sends this message to the panel’s delegate for each file or directory (filename) it is about to load in the browser. This method gives the delegate the opportunity to filter out items that it doesn’t want the user to see or choose. The delegate returns YES if filename should be displayed, and NO if the NSSavePanel should ignore the file or directory.

panel:isValidFilename:

− (BOOL)panel:(id)sender

isValidFilename:(NSString *)filename

The NSSavePanel sends this message just before the end of a modal session for each file name displayed or selected (including file names in multiple selections). The delegate determines whether it wants the file identified by filename; it returns YES if the file name is valid, or NO if the NSSavePanel should stay in its modal loop and wait for the user to type in or select a different file name or names. If the delegate refuses a file name in a multiple selection, none of the file names in the selection are accepted.


NSScreen

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	 NSObject

Conforms To:	 NSObject (NSObject)

Declared In:	 AppKit/NSScreen.h

Class Description

An NSScreen object describes the attributes of a computer’s monitor, or screen. An application may use an NSScreen object to retrieve information about a screen and use this information to decide what to display upon that screen. For example, an application may use the deepestScreen method to find out which of the available screens can best represent color and then may choose to display all of its windows on that screen.

The two main attributes of a screen are its depth and its dimensions. The depth method describes the screen depth (such as two-bit, eight-bit, or twelve-bit) and tells you if the screen can display color. The frame method gives the screen’s dimensions and location as an NSRect.

The device description dictionary contains more complete information about the screen. Use NSScreen’s deviceDescription method to access the dictionary, and use these keys to retrieve information about a screen:

Dictionary Key	Returns

NSDeviceResolution	An NSValue describing the screen’s resolution in dots per inch (dpi).

NSDeviceColorSpaceName	The screen’s color space name. See NSGraphics.h for a list of possible

values.

NSDeviceBitsPerSample	The bit depth of screen images (2-bit, 8-bit, etc.).

NSDeviceIsScreen	YES, indicating the device is a screen.

NSDeviceSize	An NSValue describing the screen’s size in points.

The device description dictionary contains information about not only screens, but all other system devices such as printers and windows. There are other keys into the dictionary that you would use to obtain information about these other devices. For a complete list of device dictionary keys, see NSGraphics.h.

The application object should be created before you use the methods in this class, so that the application object can make the necessary connection to the Window System.  You can make sure the application object exists by calling NSApplication's sharedApplication method, which creates it if necessary.  If you created your application with Project Builder, the application object is automatically created for you in main().

Method Types

 Getting NSScreens	+  mainScreen

+ deepestScreen

+ screens

Reading screen information	− depth

− frame

− supportedWindowDepths

− deviceDescription

Class Methods

deepestScreen

+ (NSScreen *)deepestScreen

Returns an NSScreen object representing the screen that can best represent color. This method always returns an object, even if there is only one screen and it is not a color screen.

mainScreen

+ (NSScreen *)mainScreen

Returns an NSScreen object representing the main screen. The main screen is the screen with the key window.

screens

+ (NSArray *)screens

Returns an array of NSScreen objects representing all of the screens available on the system. Raises NSWindowServerCommunicationException if the screens information can’t be obtained from the window system.

Instance Methods

depth

− (NSWindowDepth)depth

Returns the screen’s depth, including whether the screen can display color.

deviceDescription

− (NSDictionary *)deviceDescription

Returns the device dictionary as described in the class description.

frame

− (NSRect)frame

Returns the dimensions and location of the screen in an NSRect.

supportedWindowDepths

− (const NSWindowDepth *)supportedWindowDepths

Returns a zero-terminated array of the window depths supported by the screen.


NSScrollView

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSScrollView.h

Purpose

An NSScrollView allows the user to scroll a document view that’s too large to display in its entirety. In addition to the document view, it displays horizontal and vertical scrollers and rulers (depending on which it’s configured to have).

Principal Attributes

•	Configurable scrollers	•	Small and large increment scrolling

•	Configurable rulers	•	Dynamic (continuous) scrolling

•	Displays a special cursor over its document view

Creation

Interface Builder

− initWithFrame:	Designated initializer.

Commonly Used Methods

− setDocumentView:	Sets the cursor used over the document view.

− setLineScroll:	Sets the amount by which the document view moves during scrolling.

− setRulersVisible:	Displays or hides rulers.

Class Description

The NSScrollView class is the central coordinator for the Application Kit’s scrolling machinery, composed of this class, NSClipView, and NSScroller. An NSScrollView displays a portion of a document view that’s too large to be displayed whole, and provides NSScrollers that allow the user to move the document view within the NSScrollView. An NSScrollView can be configured with a vertical scroller, a horizontal scroller, or both. In addition to the basic accoutrements, an NSScrollView keeps a cursor that it sets whenever the mouse is over its document view, and maintains both horizontal and vertical ruler objects that can be hidden and displayed.

An NSScrollView encloses its document view within an NSClipView, using this view to actually position and monitor the document view. Because the NSClipView manages the content of the NSScrollView, it’s also called the content view. The content view positions the document view by altering its bounds rectangle, which determines where the document view’s frame lies. The content view also monitors changes in the document view’s size and notifies the NSScrollView so that the scrollers can be updated to reflect the new size. The documentView and contentView methods return an NSScrollView’s major component views.

NSScrollView defines three levels of scrolling: by line, by page, and direct. Scrolling by line moves the document view by a small amount, typically when the user clicks the scroll buttons of a scroller. Scrolling by page moves the document view by a larger amount, typically near the size of the content view, when the user Alternate-clicks the scroll buttons, and on some platforms in the slot of the scroller. You set these amounts using setLineScroll: and setPageScroll:, respectively (Interface Builder also lets you set these directly). Direct scrolling moves the document view to the position of the scroller’s knob as the user drags it. This either displays the document view continuously as it scrolls or displays it only when the user releases the mouse, as configured with the setScrollsDynamically: method.

When created programmatically, an NSScrollView has no scrollers. You can set them up using the setHasVerticalScroller: and setHasHorizontalScroller: methods with an argument of YES, which cause the NSScrollView to allocate and maintain instances of the NSScroller class. You can substitute specialized scrollers using the setVerticalScroller: and setHorizontalScroller: methods. Note that in any case you must use the setHas... methods to make sure the NSScrollView displays its scrollers.

Rulers

An NSScrollView can be set to hold both horizontal and vertical rulers using the setHasHorizontalRuler: and setHasVerticalRuler: methods. These allocate instances of the NSRulerView class, but unlike with scrollers don’t immediately display the rulers. To do this, use the setRulersVisible: method. You can substitute custom ruler objects using setHorizontalRuler: and setVerticalRuler:, and to customize the rulers for all instances of NSScrollView you can set the class used with setRulerViewClass:. This causes all subsequent rulers created by NSScrollViews to be of the class you specify.

An NSScrollView’s rulers don’t automatically establish the document view as their client. The document view itself (or a subview) is responsible, as its selection and other state changes, for retrieving the rulers using NSScrollView’s horizontalRuler and verticalRuler methods and for establishing itself as the client using NSRulerView’s setClientView: method.

How Scrolling Works

As indicated above, an NSScrollView’s document view is actually positioned by the content view, which sets its bounds rectangle in such a way that the document view’s frame moves relative to it. However, the action sequence between the scrollers and the NSScrollView and the manner in which scrolling is performed involve a bit more detail than this.

Scrolling typically occurs because of user actions on an NSScroller object, which sends the NSScrollView a private action message telling it to scroll based on the NSScroller’s state. This process is described in the class description for the NSScroller class under “Interaction with a Container View.” If you plan to implement your own kind of scrolling view or scroller object, you should read that section.

NSClipView’s scrollToPoint: is the method that actually scrolls the document view. It essentially translates the origin of the content view’s bounds rectangle, but it also optimizes redisplay by copying as much of the rendered document view as remains visible, and only asking the document view to draw newly exposed regions. This usually improves scrolling performance, but may not always be appropriate behavior. You can turn it off using NSClipView’s setCopiesOnScroll: method. If you do leave copy-on-scroll active, be sure to scroll the document view programmatically using scrollToPoint: rather than translateOriginToPoint:.

Whether the document view scrolls explicitly through a user action or an NSClipView message, or implicitly through a setFrame: or other such message, the content view monitors it closely. Whenever the document view’s frame or bounds rectangle changes, it informs the NSScrollView of the change with a reflectScrolledClipView: message. This method updates the NSScroller objects to reflect the position and size of the visible portion of the document view. You may find on occasion that you need to invoke this method explicitly when manipulating the document view directly.

Autoscrolling

In addition to user-driven and programmatic scrolling, you can program any NSView to automatically scroll when the user drags the mouse outside the enclosing NSClipView. This allows the user to drag an item in order to move it, and have the document view automatically shift itself in the appropriate direction when the user drags the item past the visible area. NSClipView’s autoscroll: method takes an NSEvent object of the mouse-dragged type and scrolls its document view in the opposite direction from the mouse location, making the portion of the document view that would be under the mouse become visible. NSView also implements autoscroll: to forward the message to its superview. This allows any NSView to simply send the message to itself during a mouse-dragging loop without checking whether it’s contained in an NSClipView (though it does need to check whether the mouse is outside of its visible portion, as returned by visibleRect).

Method Types

Calculating layout	+ contentSizeForFrameSize:hasHorizontalScroller:

hasVerticalScroller:borderType:

+ frameSizeForContentSize:hasHorizontalScroller:

hasVerticalScroller:borderType:

Determining component sizes	− contentSize

− documentVisibleRect

Managing graphic attributes	− setBackgroundColor:

− backgroundColor

− setBorderType:

− borderType

Managing the scrolled views	− setContentView:

− contentView

− setDocumentView:

− documentView

− setDocumentCursor:

Managing scrollers	− setHorizontalScroller:

− horizontalScroller

− setHasHorizontalScroller:

− hasHorizontalScroller

− setVerticalScroller:

− verticalScroller

− setHasVerticalScroller:

− hasVerticalScroller

Managing rulers	+ setRulerViewClass:

+ rulerViewClass

− setHasHorizontalRuler:

− hasHorizontalRuler

− setHorizontalRulerView:

− horizontalRulerView

− setHasVerticalRuler:

− hasVerticalRuler

− setVerticalRulerView:

− verticalRulerView

− setRulersVisible:

− rulersVisible

Setting scrolling behavior	− setLineScroll:

− lineScroll

− setPageScroll:

− pageScroll

− setScrollsDynamically:

− scrollsDynamically

Updating display after scrolling	− reflectScrolledClipView:

Arranging components	− tile

Class Methods

contentSizeForFrameSize:hasHorizontalScroller:hasVerticalScroller:borderType:

+ (NSSize)contentSizeForFrameSize:(NSSize)frameSize

hasHorizontalScroller:(BOOL)hFlag

hasVerticalScroller:(BOOL)vFlag

borderType:(NSBorderType)borderType

Returns the size of a content view for an NSScrollView whose frame size is frameSize. hFlag and vFlag indicate whether a horizontal or vertical scroller, respectively, is present. If the flag is YES then the content size is reduced in the appropriate dimension by the width of an NSScroller. borderType indicates the appearance of the NSScrollView’s edge, which also affects the content size; see the description of setBorderType: for a list of possible values.

For an existing NSScrollView, you can simply use the contentSize method.

See also:	+ frameSizeForContentSize:hasHorizontalScroller:hasVerticalScroller:borderType:, + scrollerWidth (NSScroller)

frameSizeForContentSize:hasHorizontalScroller:hasVerticalScroller:borderType:

+ (NSSize)frameSizeForContentSize:(NSSize)contentSize

hasHorizontalScroller:(BOOL)hFlag

hasVerticalScroller:(BOOL)vFlag

borderType:(NSBorderType)borderType

Returns the frame size of an NSScrollView that contains a content view whose size is contentSize. hFlag and vFlag indicate whether a horizontal or vertical scroller, respectively, is present. If the flag is YES then the frame size is increased in the appropriate dimension by the width of an NSScroller. borderType indicates the appearance of the NSScrollView’s edge, which also affects the frame size; see the description of setBorderType: for a list of possible values.

For an existing NSScrollView, you can simply use the frame method and extract its size.

See also:	+ contentSizeForFrameSize:hasHorizontalScroller:hasVerticalScroller:borderType:, + scrollerWidth (NSScroller)

p	rulerViewClass

+ (Class)rulerViewClass

Returns the default class to be used for ruler objects in NSScrollViews. This is normally NSRulerView.

See also:	+ setRulerViewClass:

p	setRulerViewClass:

+ (void)setRulerViewClass:(Class)aClass

Sets the default class to be used for ruler objects in NSScrollViews to aClass. This is normally NSRulerView, but you can use this method to set it to a custom subclass of NSRulerView.

Note:	This method simply sets a global variable private to NSScrollView.Subclasses of NSScrollView should override both this method and rulerViewClass to store their ruler view classes in private variables.

See also:	+ rulerViewClass

Instance Methods

backgroundColor

− (NSColor *)backgroundColor

Returns the content view’s background color.

See also:	− setBackgroundColor:, − backgroundColor (NSClipView)

borderType

− (NSBorderType)borderType

Returns a value that represents the type of border surrounding the receiver; see the description of setBorderType: for a list of possible values.

contentSize

− (NSSize)contentSize

Returns the size of the receiver’s content view.

See also:	+ contentSizeForFrameSize:hasHorizontalScroller:hasVerticalScroller:borderType:

contentView

− (NSClipView *)contentView

Returns the receiver’s content view, the view that clips the document view.

See also:	− setContentView:, − documentView

documentCursor

− (NSCursor *)documentCursor

Returns the content view’s document cursor.

See also:	− setDocumentCursor:, − documentCursor (NSClipView)

documentView

− (id)documentView

Returns the view that the receiver scrolls within its content view.

See also:	− setDocumentView:, − documentView (NSClipView)

documentVisibleRect

− (NSRect)documentVisibleRect

Returns the portion of the document view, in its own coordinate system, that’s visible through the receiver’s content view.

See also:	− documentVisibleRect (NSClipView), − visibleRect (NSView)

p	hasHorizontalRuler

− (BOOL)hasHorizontalRuler

Returns YES if the receiver maintains a horizontal ruler view, NO if it doesn’t. Display of rulers is controlled using the setRulersVisible: method.

See also:	− horizontalRulerView, − setHasHorizontalRuler:, − hasVerticalRuler, + rulerClass:

hasHorizontalScroller

− (BOOL)hasHorizontalScroller

Returns YES if the receiver displays a horizontal scroller, NO if it doesn’t.

See also:	− horizontalScroller, − setHasHorizontalScroller:, − hasVerticalScroller

p	hasVerticalRuler

− (BOOL)hasVerticalRuler

Returns YES if the receiver maintains a vertical ruler view, NO if it doesn’t. Display of rulers is controlled using the setRulersVisible: method.

See also:	− verticalRulerView, − setHasVerticalRuler:, − hasHorizontalRuler, + rulerClass:

hasVerticalScroller

− (BOOL)hasVerticalScroller

Returns YES if the receiver displays a vertical scroller, NO if it doesn’t.

See also:	− verticalScroller, − setHasVerticalScroller:, − hasHorizontalScroller

p	horizontalRulerView

− (NSRulerView *)horizontalRulerView

Returns the receiver’s horizontal ruler view, whether or not the receiver is currently displaying it, or nil if the receiver has none. If the receiver is set to display a horizontal ruler view and doesn’t yet have one, this method creates an instance of the ruler view class set using the class method setRulerViewClass:. Display of rulers is controlled using the setRulersVisible: method.

See also:	− hasHorizontalRulerView, − verticalRulerView

horizontalScroller

− (NSScroller *)horizontalScroller

Returns the receiver’s horizontal scroller, whether or not the receiver is currently displaying it, or nil if the receiver has none.

See also:	− hasHorizontalScroller, − setHorizontalScroller:, − verticalScroller

lineScroll

− (float)lineScroll

Returns the amount by which the receiver scrolls itself when scrolling line-by-line, expressed in the content view’s coordinate system. This amount is used when the user clicks the scroll arrows without holding a modifier key.

See also:	− setLineScroll:, − pageScroll

pageScroll

− (float)pageScroll

Returns the amount of the document view kept visible when scrolling page-by-page, expressed in the content view’s coordinate system. This amount is used when the user clicks the scroll arrows while holding the Alternate key.

Note:	This amount expresses the context that remains when the receiver scrolls by one page, allowing the user to orient himself to the new display. It differs from the line scroll amount, which indicates how far the document view moves. The page scroll amount is the amount common to the content view before and after the document view is scrolled by one page.

See also:	− setLineScroll:, − pageScroll

reflectScrolledClipView:

− (void)reflectScrolledClipView:(NSClipView *)aClipView

If aClipView is the receiver’s content view, adjusts the receiver’s scrollers to reflect the size and positioning of its document view. Does nothing if aClipView is any other view object (in particular, if it’s an NSClipView that isn’t the content view).

This method is invoked automatically during scrolling and when an NSClipView’s relationship to its document view changes; you should rarely need to invoke it yourself, but may wish to override it for custom updating or other behavior.

See also:	− contentView, − documentView

p	rulersVisible

− (BOOL)rulersVisible

Returns YES if the receiver was set to show rulers using setRulersVisible: (whether or not it has rulers at all), NO if it was set to hide them.

See also:	− hasHorizontalRuler, − hasVerticalRuler

scrollsDynamically

− (BOOL)scrollsDynamically

Returns YES if the receiver redraws its document view while tracking the knob, NO if it redraws only when the scroller knob is released. NSScrollView scrolls dynamically by default.

See also:	− setScrollsDynamically:

setBackgroundColor:

− (void)setBackgroundColor:(NSColor *)aColor

Sets the color of the content view’s background to aColor. This color is used to paint areas inside the content view that aren’t covered by the document view.

See also:	− backgroundColor, − setBackgroundColor: (NSClipView)

setBorderType:

− (void)setBorderType:(NSBorderType)borderType

Sets the border type of the receiver to borderType, which may be one of:

NSNoBorder

NSLineBorder

NSBezelBorder

NSGrooveBorder

See also:	− borderType

setContentView:

− (void)setContentView:(NSClipView *)aView

Sets the receiver’s content view, the view that clips the document view, to aView. aView’s document view, if any, also becomes the receiver’s document view, while the original content view’s document view remains with it.

See also:	− contentView, − setDocumentView:

setDocumentCursor:

− (void)setDocumentCursor:(NSCursor *)aCursor

Sets the cursor used when the mouse is over the content view to aCursor, by sending setDocumentCursor: to the content view.

See also:	− documentCursor

setDocumentView:

− (void)setDocumentView:(NSView *)aView

Sets the receiver’s document view to aView.

See also:	− documentView, − setDocumentView: (NSClipView)

p	setHasHorizontalRuler:

− (void)setHasHorizontalRuler:(BOOL)flag

Determines whether the receiver keeps a horizontal ruler object. If flag is YES, the receiver allocates a horizontal ruler the first time it’s needed. Display of rulers is handled independently with the setRulersVisible: method.

See also:	− hasHorizontalRuler, − horizontalRuler, − setHasVerticalRuler:

setHasHorizontalScroller:

− (void)setHasHorizontalScroller:(BOOL)flag

Determines whether the receiver keeps a horizontal scroller. If flag is YES, the receiver allocates and displays a horizontal scroller as needed. An NSScrollView by default has neither a horizontal nor a vertical scroller.

See also:	− hasHorizontalScroller, − horizontalScroller, − setHasVerticalScroller:

p	setHasVerticalRuler:

− (void)setHasVerticalRuler:(BOOL)flag

Determines whether the receiver keeps a vertical ruler object. If flag is YES, the receiver allocates a vertical ruler the first time it’s needed. Display of rulers is handled independently with the setRulersVisible: method.

See also:	− hasVerticalRuler, − verticalRuler, − setHasHorizontalRuler:, − setRulersVisible:

setHasVerticalScroller:

− (void)setHasVerticalScroller:(BOOL)flag

Determines whether the receiver keeps a vertical scroller. If flag is YES, the receiver allocates and displays a vertical scroller as needed. An NSScrollView by default has neither a vertical nor a horizontal scroller.

See also:	− hasVerticalScroller, − verticalScroller, − setHasHorizontalScroller:

p	setHorizontalRulerView:

− (void)setHorizontalRulerView:(NSRulerView *)aRulerView

Sets the receiver’s horizontal ruler view to aRulerView. You can use this method to override the default ruler class set using the class method setRulerClass:. Display of rulers is controlled using the setRulersVisible: method.

See also:	− horizontalRulerView:,− setHasHorizontalRuler:, − setVerticalRulerView:, − setRulersVisible:

setHorizontalScroller:

− (void)setHorizontalScroller:(NSScroller *)aScroller

Sets the receiver’s horizontal scroller to aScroller, establishing the appropriate target-action relationships between them. To make sure the scroller is visible, invoke the setHasHorizontalScroller: method with an argument of YES.

See also:	− horizontalScroller, − setVerticalScroller:

setLineScroll:

− (void)setLineScroll:(float)aFloat

Sets the amount by which the receiver scrolls itself when scrolling line-by-line to aFloat, expressed in the content view’s coordinate system. This is the amount used when the user clicks the scroll arrows without holding a modifier key. When displaying text in an NSScrollView, for example, you might set this to the height of a single line of text in the default font.

See also:	− lineScroll, − setPageScroll:

setPageScroll:

− (void)setPageScroll:(float)aFloat

Sets the amount of the document view kept visible when scrolling page-by-page to aFloat, expressed in the content view’s coordinate system. This amount is used when the user clicks the scroll arrows while holding the Alternate key.

Note:	This amount expresses the context that remains when the receiver scrolls by one page, allowing the user to orient himself to the new display. It differs from the line scroll amount, which indicates how far the document view moves. The page scroll amount is the amount common to the content view before and after the document view is scrolled by one page. Thus, setting the page scroll amount to 0.0 implies that the entire visible portion of the document view is replaced when a page scroll occurs.

See also:	− pageScroll, − setLineScroll:

p	setRulersVisible:

− (void)setRulersVisible:(BOOL)flag

Determines whether the receiver displays its rulers. If flag is YES, the receiver displays its rulers (creating them if needed). If flag is NO, the receiver doesn’t display its rulers.

See also:	− rulersVisible, − hasHorizontalRuler, − hasVerticalRuler

setScrollsDynamically:

− (void)setScrollsDynamically:(BOOL)flag

Determines whether the receiver redraws its document view while scrolling continuously. If flag is YES it does, if flag is NO it redraws only when the scroller knob is released. NSScrollView scrolls dynamically by default.

See also:	− scrollsDynamically

p	setVerticalRulerView:

− (void)setVerticalRulerView:(NSRulerView *)aRulerView

Sets the receiver’s vertical ruler view to aRulerView. You can use this method to override the default ruler class set using the class method setRulerClass:. Display of rulers is controlled using the setRulersVisible: method.

See also:	− verticalRulerView:, − setHasVerticalRuler:, − setHorizontalRulerView:, − setRulersVisible:

setVerticalScroller:

− (void)setVerticalScroller:(NSScroller *)aScroller

Sets the receiver’s vertical scroller to aScroller, establishing the appropriate target-action relationships between them. To make sure the scroller is visible, invoke the setHasVerticalScroller: method with an argument of YES.

See also:	− verticalScroller, − setHorizontalScroller:

tile

− (void)tile

Lays out the components of the receiver: the content view, the scrollers, and the ruler views. You rarely need to invoke this method, but subclasses may override it to manage additional components.

p	verticalRulerView

− (NSRulerView *)verticalRulerView

Returns the receiver’s vertical ruler view, whether or not the receiver is currently displaying it, or nil if the receiver has none. If the receiver is set to display a vertical ruler view and doesn’t yet have one, this method creates an instance of the ruler view class set using the class method setRulerViewClass:. Display of rulers is controlled using the setRulersVisible: method.

See also:	− hasVerticalRulerView, − horizontalRulerView

verticalScroller

− (NSScroller *)verticalScroller

Returns the receiver’s vertical scroller, whether or not the receiver is currently displaying it, or nil if the receiver has none.

See also:	− hasVerticalScroller, − setVerticalScroller:, − horizontalScroller


NSScroller

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSControl : NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSScroller.h

Purpose

An NSScroller object is a user control for scrolling a document view within a container view. You normally don’t need to program with NSScrollers, as Interface Builder allows you to fully configure them with an NSScrollView.

Principal Attributes

•	Scrolling by small and large increments

•	Proportional knob showing visible amount of document

Creation

Interface Builder

− initWithFrame:	Initializes the NSScroller.

Commonly Used Methods

− hitPart	Indicates where the user clicked the NSScroller.

− floatValue (NSControl)	Returns the position of the NSScroller’s knob.

− setFloatValue:knobProportion:	Sets the position and size of the NSScroller’s knob.

Class Description

An NSScroller controls scrolling of a document view within an NSScrollView’s clip view (or potentially another kind of container view). It typically displays a pair of buttons that the user can click to scroll by a small amount (called a line increment or decrement) and Alternate-click to scroll by a large amount (called a page increment or decrement), plus a slot containing a knob that the user can drag directly to the desired location. The knob indicates both the position within the document view and, by varying in size within the slot, the amount visible relative to the size of the document view. You can configure whether an NSScroller uses scroll buttons, but it always draws the knob when there’s room for it.

Interface Builder automatically associates NSScrollers with an NSScrollView, allowing you to configure most aspects of scrolling behavior without programming. If you create one programmatically using initWithFrame: the new NSScroller automatically collapses the shorter of its two dimensions to the standard scroller width, as returned by the scrollerWidth class method. In this manner a tall, narrow frame results in a vertical NSScroller and a short, wide frame results in a horizontal NSScroller.

Interaction with a Container View

NSScroller is a public class primarily for programmers who decide not to use an NSScrollView but who want to present a consistent user interface. Its use outside of NSScrollViews is discouraged except in cases where the porting of an existing application is made more straightforward. Setting up an NSScroller with a custom container view class (or a completely different kind of target) involves establishing the standard target and action as defined by NSControl, and implementing the target’s action method appropriately.

As an NSScroller tracks the mouse, it sends an action message to its target with itself as the argument. The target then performs the scrolling operation based on these things:

•	The orientation of the NSScroller, vertical or horizontal, which determines the axis to scroll along. This can be done by getting the NSScroller’s frame and determining the longer dimension, or by keeping a reference to designated vertical and horizontal scrollers (as NSScrollView does).

•	The direction and scale of scrolling. NSScroller’s hitPart method returns this information, described in more detail below.

•	If the hit part is the knob or its slot, the NSScroller’s value, which indicates where to position the document view in the container view. The floatValue method provides this information, which the target should interpret relative to the size of the document view’s frame minus the size of the container view’s bounds.

As indicated above, the direction and scale of a scrolling operation is determined by the value returned from a hitPart message, which indicates the various parts of an NSScroller in terms of their intended result (not in terms of their location or appearance):

Value	How to Scroll

NSScrollerKnob	Directly to the NSScroller’s value, as given by floatValue

NSScrollerKnobSlot	Directly to the NSScroller’s value, as given by floatValue

NSScrollerDecrementLine	Up or left by a small amount

NSScrollerDecrementPage	Up or left by a large amount

NSScrollerIncrementLine	Down or right by a small amount

NSScrollerIncrementPage	Down or right by a large amount

NSScrollerNoPart	Don’t scroll at all

Note:	These part codes are interpreted differently depending on the method you use them with. See the individual method descriptions for hitPart, rectForPart:, and testPart: for details.

The four decrement/increment values require the target to calculate an appropriate amount to scroll by. Line and page amounts are up to the target or the container view to define. NSScrollView, for example, allows you to set these in Interface Builder or with its setLineScroll: and setPageScroll: methods. Once the target has scrolled the document view by a decrement or increment, it should update the NSScroller’s position using setFloatValue:.

The container view or target should also keep tabs on its size and on the size and position of its document view. Any time these change it should update its NSScrollers using setFloatValue:knobProportion:. NSClipView, for example, overrides most of NSView’s setBounds... and setFrame... methods to perform this updating.

Method Types

Determining NSScroller size	+ scrollerWidth

Laying out an NSScroller	− setArrowsPosition:

− arrowsPosition

Setting the knob position	− setFloatValue:knobProportion:

− knobProportion

Calculating layout	− rectForPart:

− testPart:

− checkSpaceForParts

− usableParts

Drawing the parts	− drawArrow:highlight:

− drawKnob

− drawParts

− highlight:

Event handling	− hitPart

− trackKnob:

− trackScrollButtons:

Class Methods

scrollerWidth

+ (float)scrollerWidth

Returns the width of instances. NSScrollView uses this value to lay out its components. Subclasses that use a different width should override this method.

Instance Methods

arrowsPosition

− (NSScrollArrowPosition)arrowsPosition

Returns the location of the scroll buttons within the receiver, as described under setArrowsPosition:.

checkSpaceForParts

− (void)checkSpaceForParts

Checks to see if there is enough room in the receiver to display the knob and buttons. usableParts returns the state calculated by this method. You should never need to invoke this method; it’s invoked automatically whenever the NSScroller’s size changes.

drawArrow:highlight:

− (void)drawArrow:(NSScrollerArrow)arrow highlight:(BOOL)flag

Draws the scroll button indicated by arrow, which is either NSScrollerIncrementArrow (the down or right scroll button) or NSScrollerDecrementArrow (up or left). If flag is YES, the button is drawn highlighted, otherwise it’s drawn normally. You should never need to invoke this method directly, but may wish to override it to customize the appearance of scroll buttons.

See also:	− drawKnob, − rectForPart:

drawKnob

− (void)drawKnob

Draws the knob. You should never need to invoke this method directly, but may wish to override it to customize the appearance of the knob.

See also:	− drawArrow:highlight:, − rectForPart:

drawParts

− (void)drawParts

Caches images for the scroll buttons and knob. It’s invoked only once when the NSScroller is created. You may want to override this method if you alter the look of the NSScroller, but you should never invoke it directly.

highlight:

− (void)highlight:(BOOL)flag

Highlights or unhighlights the scroll button that the user clicked. The receiver invokes this method while tracking the mouse; you should not invoke it directly. If flag is YES, the appropriate part is drawn highlighted, otherwise it’s drawn normally.

See also:	− drawArrow:highlight:, − rectForPart:

hitPart

− (NSScrollerPart)hitPart

Returns a part code indicating the manner in which the scrolling should be performed:

Value	How to Scroll

NSScrollerKnob	Directly to the NSScroller’s value, as given by floatValue

NSScrollerKnobSlot	Directly to the NSScroller’s value, as given by floatValue

NSScrollerDecrementLine	Up or left by a small amount

NSScrollerDecrementPage	Up or left by a large amount

NSScrollerIncrementLine	Down or right by a small amount

NSScrollerIncrementPage	Down or right by a large amount

NSScrollerNoPart	Don’t scroll at all

This method is typically invoked by an NSScrollView to determine how to scroll its document view when it receives an action message from the NSScroller.

initWithFrame

− (id)initWithFrame:(NSRect)frameRect

Initializes the receiver as normal, but collapsing frameRect’s narrower dimension to the value returned by the scrollerWidth method. This enforces the appearance of vertical and horizontal NSScrollers. This is the designated initializer for the NSScroller class. Returns self.

knobProportion

− (float)knobProportion

Returns the portion of the knob slot that the knob should fill, as a floating-point value from 0.0 (minimal size) to 1.0 (fills the slot).

rectForPart:

− (NSRect)rectForPart:(NSScrollerPart)aPart

Returns the rectangle occupied by aPart, which for this method is interpreted literally rather than as an indicator of scrolling direction:

Value	Part

NSScrollerKnob	The knob itself

NSScrollerKnobSlot	The slot that the knob moves in

NSScrollerDecrementLine	The up or left scroll button

NSScrollerDecrementPage	The region of the slot above or to the left of the knob

NSScrollerIncrementLine	The down or right scroll button

NSScrollerIncrementPage	The region of the slot below or to the right of the knob

Note the interpretations of NSScrollerDecrementPage and NSScrollerIncrementPage. The actual part of an NSScroller that causes page-by-page scrolling varies from platform to platform, so as a convenience these part codes refer to useful parts different from the scroll buttons.

Returns NSZeroRect if the part requested isn’t present on the receiver.

See also:	− hitPart, − testPart:, − usableParts

setArrowsPosition:

− (void)setArrowsPosition:(NSScrollArrowPosition)location

Sets the location of the scroll buttons within the Scroller to location, or inhibits their display, as follows:

Value	Meaning

NSScrollerArrowsMaxEnd	Buttons at bottom or right

NSScrollerArrowsMinEnd	Buttons at top or left

NSScrollerArrowsNone	No buttons

Note:	On Microsoft Windows scroll buttons appear at either end of the scroller rather than both on one end. A value other than NSScrollerArrowsNone is thus reinterpreted on that platform to display the buttons at either end.

See also:	− arrowsPosition

setFloatValue:knobProportion:

− (void)setFloatValue:(float)aFloat knobProportion:(float)knobProp

Sets the position of the knob to aFloat, which is a value between 0.0 (indicating the top or left end) and 1.0 (the bottom or right end). Also sets the proportion of the knob slot filled by the knob to knobProp, also a value between 0.0 (minimal size) and 1.0 (fills the slot).

See also:	− floatValue (NSControl), − knobProportion

testPart:

− (NSScrollerPart)testPart:(NSPoint)aPoint

Returns the part that would be hit by a mouse-down event at aPoint (expressed in the receiver’s coordinate system):

Return Value	Part Identified

NSScrollerKnob	The knob itself

NSScrollerKnobSlot	The slot that the knob moves in (returned only if there’s no knob)

NSScrollerDecrementLine	The up or left scroll button

NSScrollerDecrementPage	The region of the slot above or to the left of the knob

NSScrollerIncrementLine	The down or right scroll button

NSScrollerIncrementPage	The region of the slot below or to the right of the knob

NSScrollerNoPart	(aPoint isn’t in the NSScroller)

Note the interpretations of NSScrollerDecrementPage and NSScrollerIncrementPage. The actual part of an NSScroller that causes page-by-page scrolling varies from platform to platform, so as a convenience these part codes refer to useful parts different from the scroll buttons.

See also:	− hitPart, − rectForPart:

trackKnob:

− (void)trackKnob:(NSEvent *)theEvent

Tracks the knob and sends action messages to the receiver’s target. This method is invoked automatically when the NSScroller receives a mouse-down event in the knob; you should not invoke it directly.

trackScrollButtons:

− (void)trackScrollButtons:(NSEvent *)theEvent

Tracks the scroll buttons and sends action messages to the receiver’s target. This method is invoked automatically when the NSScroller receives a mouse-down event in a scroll button; you should not invoke this method directly.

usableParts

− (NSUsableScrollerParts)usableParts

Returns a value indicating which parts of the receiver are displayed and usable. This is one of:

Value	Meaning

NSNoScrollerParts	Scroller has neither a knob nor scroll buttons, only the knob slot.

NSOnlyScrollerArrows	Scroller has only scroll buttons, no knob.

NSAllScrollerParts	Scroller has at least a knob, possibly also scroll buttons.

See also:	− checkSpaceForParts, − arrowsPosition


NSSecureTextField
p NSSecureTextField

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSTextField : NSControl : NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSSecureTextField.h

Class Description

NSSecureTextField is a subclass of NSTextField that hides its text from display or other access via the user interface. It’s suitable for use as a password-entry object, or for any item in which a secure value must be kept. An NSSecureTextField uses an NSSecureTextFieldCell, and adds behavior to the OPENSTEP extended text system to protect its text value. Your code can get the text field’s string value using the standard stringValue method, but users can’t extract it themselves. NSSecureTextField overrides many aspects of text editing to prevent passing of the object’s value out by mechanisms available to the user (namely, through Cut, Copy, and Paste commands, and the Services facility). This object also overrides the text system’s drawing routine to draw no text at all.

Class Methods

p	setCellClass:

+ (void)setCellClass:(Class)cellClass

Raises an NSInvalidArgumentException. NSSecureTextFields use NSSecureTextFieldCells only.


NSSecureTextFieldCell
p NSSecureTextFieldCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSTextFieldCell : NSActionCell : NSCell : NSObject

Conforms To:	NSCoding (NSCell)

NSCopying (NSCell)

NSObject (NSObject)

Declared In:	AppKit/NSSecureTextField.h

Class Description

NSSecureTextFieldCell works with NSSecureTextField to provide a text field whose value is guarded from user examination. It overrides the general cell use of the field editor to provide its own field editor, which doesn’t display text or allow the user to Cut, Copy, or Paste its value. See the NSSecureTextField class specification for more information.


NSSelection

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCoding

NSCopying

NSObject (from NSObject)

Declared In:	AppKit/NSSelection.h

Class Description

The NSSelection class defines an object that describes a selection within a document. An NSSelection, or simply, selection, is an immutable description; it may be held by the system or other documents, and it cannot change over time. Selections are typically used by NSDataLink objects to represent the source and destination of a link.

Because a selection description can’t be changed once it’s been exported, it’s a good idea to construct general descriptions that can survive changes to a document and don’t require selection-specific information to be stored in the document. This description may be simple or complex, depending upon the application. For example, a painting application might describe a selection in an image as a simple rectangle. This description doesn’t require that any information be stored in the image’s file, and the description can be expected to remain valid through the life of the image. An object-based drawing application might describe a selection as a list of object identifiers (though not ids), where an object identifier is unique throughout the life of the document. Based on this list, a selection could be meaningfully reconstructed, even if new objects are added to the document or selected objects are deleted. Such a scheme doesn’t require that any selection-specific information be stored in the document’s file, with the benefit that links can be made to read-only documents.

Maintaining a character-range selection in a text document is more problematic. A possible solution is to insert selection-begin and selection-end markers that define a specific selection into the text stream. A selection description would then refer to a specific selection marker. This solution requires that selection state information be stored and maintained within the document. Furthermore, this information generally shouldn’t be purged from the document, because the document can’t know how many references to the selection exist. (References to the selection could be stored with documents on removable media, like floppy disks.) This selection-state information should be maintained as long as it refers to any meaningful data. For this reason, it’s desirable to describe selection in a manner that doesn’t require that selection-state information be maintained in the document whenever possible.

Three well-known selection descriptions can apply to any document: the empty selection, the entire document, and the abstract concept of the current selection. NSSelection objects for these selections are returned by the emptySelection, allSelection, and currentSelection class methods.

Since an NSSelection may be used in a document that is read by machines with different architectures, care should be taken to write machine-independent descriptions. For example, using a binary structure as a selection description will fail on a machine where an identically-defined structure has a different size or is kept in memory with different byte ordering. Exporting (and then parsing) ASCII descriptions is often a good solution. If binary descriptions must be used, it’s prudent to preface the description with a token specifying the description’s byte ordering.

It may also be prudent to version-stamp selection descriptions, so that old selections can be accurately read by updated versions of an application.

Adopted Protocols

NSCoding	− encodeWithCoder:

− initWithCoder:

NSCopying	− copyWithZone:

Method Types

Creating  an NSSelection	+ selectionWithDescriptionData:

− initWithDescriptionData:

− initWithPasteboard:

Returning special selection shared instances

+ allSelection

+ currentSelection

+ emptySelection

Describing a selection	− descriptionData

− isWellKnownSelection

Writing a selection to the pasteboard	− writeToPasteboard:

Class Methods

allSelection

+ (NSSelection *)allSelection

Returns the shared instance of the well-known selection representing an entire document.

currentSelection

+ (NSSelection *)currentSelection

Returns the shared instance of the well-known selection representing the abstract concept of the current selection. The current selection never describes a specific selection; it describes a selection that may change frequently.

emptySelection

+ (NSSelection *)emptySelection

Returns the shared instance of the well-known selection representing no data.

selectionWithDescriptionData:

+ (NSSelection *)selectionWithDescriptionData:(NSData *)newData

Allocates an NSSelection instance and initializes it using a copy of the data indicated by description to describe the selection. As mentioned in the Class Description, the description should ideally be architecture-independent and should contain some sort of version information.

See also:	 − initWithDescriptionData:, − descriptionData

Instance Methods

descriptionData

− (NSData *)descriptionData

Returns the data that describes the selection as set by selectionWithDescriptionData: or initWithDescriptionData:.

initWithDescriptionData:

− (id)initWithDescriptionData:(NSData *)description

Initializes a newly allocated NSSelection instance using a copy of the data indicated by description to describe the selection. As mentioned in the Class Description, the description should ideally be architecture-independent and should contain some sort of version information. Returns self.

See also:	 + selectionWithDescriptionData:, − descriptionData

initWithPasteboard:

− (id)initWithPasteboard:(NSPasteboard *)pasteboard

Initializes a newly allocated NSSelection instance from data on the specified pasteboard. If the NSSelection can’t be initialized for any reason (for example, if data of type NSSelectionPboardType isn’t found on the pasteboard) the new instance is freed and nil is returned. Returns the newly-initialized NSSelection instance (which may be other than self).

See also:	− writeToPasteboard:

isWellKnownSelection

− (BOOL)isWellKnownSelection

Returns YES if the NSSelection is one of the three well-known selection types, and NO otherwise. There are well-known selection types for an entire document, the current selection, and for an empty selection.

See also:	+ allSelection, + currentSelection, + emptySelection

writeToPasteboard:

− (void)writeToPasteboard:(NSPasteboard *)pasteboard

Writes the NSSelection to the pasteboard pasteboard. A copy of the selection can then be retrieved by initializing a new NSSelection from the pasteboard using initWithPasteboard:.


NSServicesRequests

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

 (informal protocol)

Category Of:	NSObject

Declared In:	AppKit/NSApplication.h

Protocol Description

This informal protocol consists of two methods, writeSelectionToPasteboard:types: and readSelectionFromPasteboard:. The first is implemented to provide data to a remote service, and the second to receive any data the remote service might send back. Both respond to messages that are generated when the user chooses a command from the Services menu.

Instance Methods

readSelectionFromPasteboard:

- (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard

Implemented to replace the current selection (that is, the text or objects that are currently selected) with data read from the Pasteboard object pboard. The data would have been placed in the pasteboard by another application in response to a remote message from the Services menu. A readSelectionFromPasteboard: message is sent to the same object that previously received a writeSelectionToPasteboard:types: message.

There’s no default readSelectionFromPasteboard: method. The Application Kit declares a prototype for this method, but doesn’t implement it.

writeSelectionToPasteboard:types:

- (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard types:(NSArray *)types

Implemented to write the current selection to the Pasteboard object pboard. The selection should be written as one or more of the data types listed in types. After writing the data, this method should return YES. If for any reason it can’t write the data, it should return NO.

A writeSelectionToPasteboard:types: message is sent to the first responder when the user chooses a command from the Services menu, but only if the receiver didn’t return nil to a previous validRequestorForSendType:returnType: message.

After this method writes the data to the pasteboard, a remote message is sent to the application that provides the service the user requested. If the service provider supplies return data to replace the selection, the first responder will then receive a readSelectionFromPasteboard: message.

There’s no default writeSelectionToPasteboard:types: method. The Application Kit declares a prototype for this method, but doesn’t implement it.

See also:	 − validRequestorForSendType:returnType: (NSResponder class)


NSSlider

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSControl : NSView : NSResponder : NSObject

Conforms To:	NSCoding (from NSResponder)

NSObject (from NSObject)

Declared In:	AppKit/NSSlider.h

Class Description

An NSSlider has a handle, or “knob,” that can be dragged in a groove, or “bar.” The knob’s position in the bar represents a number between a minimum and a maximum. If the slider is vertical, its minimum is at its bottom; if it is horizontal, its minimum is at its left.

The minimum and maximum can be obtained with the minValue and maxValue methods, and set with the setMinValue: and setMaxValue: methods. To read the value represented by the current position of the knob, you use an NSControl method like floatValue; conversely, to send a value to the slider, you use a NSControl method like setFloatValue:.

By default, an NSSlider is a continuous NSControl: while the user drags the slider’s knob, the slider sends its action message continuously. If, instead, you want the slider to reserve its action message until the mouse is released, invoke setContinuous: (an NSControl method) with an argument of NO.

In its bar, an NSSlider can display an image, a title, or both. The title can be drawn in any color and any font. However, since a title in the bar may be obscured by the slider knob, you will more often label a slider by placing an NSTextField near it.

Like most NSControls, NSSlider relies heavily on a related cell class, NSSliderCell. For more information, see the NSSliderCell class specification.

Method Types

 Asking about the slider’s appearance

− image

− knobThickness

− isVertical

Changing the slider’s appearance	− setImage:

− setKnobThickness:

Asking about the slider’s title	− title

− titleCell

− titleColor

− titleFont

Changing the slider’s title	− setTitle:

− setTitleCell:

− setTitleColor:

− setTitleFont:

Asking about the value limits	− maxValue

− minValue

Changing the value limits	− setMaxValue

− setMinValue

Handling mouse-down events	− acceptsFirstMouse:

Instance Methods

acceptsFirstMouse:

− (BOOL)acceptsFirstMouse:(NSEvent *)mouseDownEvent

Returns YES by default, so that a single mouse-down event can simultaneously activate the window and take hold of the slider’s knob.

If you want the slider to wait for its own mouse-down event, you must override this method.

image

− (NSImage *)image

Returns the image that the slider displays in its bar, or nil if no image has been set.

See also:	 − setImage:

isVertical

− (int)isVertical

Returns 1 if the slider is vertical, 0 if it’s horizontal, and −1 if the orientation can’t be determined (for example, if the slider hasn’t been displayed yet). A slider is defined as vertical if its height is greater than its width.

knobThickness

− (float)knobThickness

Returns the knob’s thickness, in pixels. The thickness is defined to be the extent of the knob along the long dimension of the bar. In a vertical slider, then, a knob’s thickness is its height; in a horizontal slider, a knob’s thickness is its width.

See also:	 − setKnobThickness:

maxValue

− (double)maxValue

Returns the maximum value that the slider can send to its target. A horizontal slider sends its maximum value when the knob is at the right end of the bar; a vertical slider sends it when the knob is at the top.

See also:	 − setMaxValue:

minValue

− (double)minValue

Returns the minimum value that the slider can send to its target. A vertical slider sends its minimum value when its knob is at the bottom; a horizontal slider, when its knob is all the way to the left.

See also:	 − setMinValue:

setImage:

− (void)setImage:(NSImage *)barImage

Sets the image that the slider displays in the bar behind its knob. The slider may scale and distort barImage to fit inside the bar.

The knob may cover part of the image. If you want the image to be visible all the time, you’re better off placing it near the slider.

See also:	 − setImage:

setKnobThickness:

− (void)setKnobThickness:(float)thickness

Lets you set the knob’s thickness, measured in pixels. The thickness is defined to be the extent of the knob along the long dimension of the bar. In a vertical slider, then, a knob’s thickness is its height; in a horizontal slider, a knob’s thickness is its width.

See also:	− knobThickness

setMaxValue:

− (void)setMaxValue:(double)maxValue

Sets the maximum value that the slider can send to its target—the value that a horizontal slider sends when its knob is all the way to the right, or that a vertical slider sends when its knob is at the top.

See also:	 − maxValue

setMinValue:

− (void)setMinValue:(double)minValue

Sets the minimum value that the slider can send to its target. A horizontal slider sends its minimum value when its knob is all the way to the left; a vertical slider sends its minimum value when its knob is at the bottom.

See also:	 − minValue

setTitle:

− (void)setTitle:(NSString *)barTitle

Sets the title that the slider displays in the bar behind its knob.

The knob may cover part or all of the title. If you want the title to be visible all of the time, you’re better off placing a label near the slider.

See also:	 − title

setTitleCell:

− (void)setTitleCell:(NSCell *)titleCell

Sets the cell used to draw the slider’s title. You only need to invoke this method if the default title cell, NSTextFieldCell, doesn’t suit your needs—that is, if you want to display the title in a manner that NSTextFieldCell doesn’t permit. When you do choose to override the default, titleCell should be an instance of a subclass of TextFieldCell.

See also:	− titleCell

setTitleColor:

− (void)setTitleColor:(NSColor *)color

Sets the color used to draw the slider’s title.

See also:	 − titleColor

setTitleFont:

− (void)setTitleFont:(NSFont *)font

Sets the font used to draw the slider’s title.

See also:	 − titleFont

title

− (NSString *)title

Returns the slider’s title. The default title is the empty string (“”).

See also:	 − setTitle:

titleCell

− (id)titleCell

Returns the cell used to draw the title. The default is an NSTextFieldCell.

See also:	 − setTitleCell:

titleColor

− (NSColor *)titleColor

Returns the color used to draw the slider’s title. The default color is NSColor’s controlTextColor.

See also:	 − setTitleColor:

titleFont

− (NSFont *)titleFont

Returns the font used to draw the slider’s title.

See also:	− setTitleColor:


NSSliderCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSActionCell : NSCell : NSObject

Conforms To:	NSCoding, NSCopying (from NSCell)

NSObject (from NSObject)

Declared In:	AppKit/NSSliderCell.h

Class Description

An NSSliderCell controls the appearance and behavior of an NSSlider, or of a single slider in an NSMatrix.

You can customize an NSSliderCell to a certain degree, using its set... methods. If these do not allow you sufficient flexibility, you can create a subclass. In that subclass, you can override any of the following methods: knobRectFlipped:, drawBarInside:flipped:, drawKnob:, or prefersTrackingUntilMouseUp.

Method Types

Asking about the cell’s behavior 	− altIncrementValue

+ prefersTrackingUntilMouseUp

− trackRect

Changing the cell’s behavior	− setAltIncrementValue:

Displaying the cell	− knobRectFlipped:

− drawBarInside:flipped:

− drawKnob

− drawKnob:

Asking about the cell’s appearance	− knobThickness

− isVertical

− title

− titleCell

− titleFont

− titleColor

Changing the cell’s appearance	− setKnobThickness:

− setTitle:

− setTitleCell:

− setTitleColor:

− setTitleFont:

Asking about the value limits	− maxValue

− minValue

Changing the value limits	− setMaxValue

− setMinValue

Class Methods

prefersTrackingUntilMouseUp

+ (BOOL)prefersTrackingUntilMouseUp

By default, this method returns YES, so that an NSSliderCell continues to track the mouse even after the mouse leaves the cell’s tracking rectangle. This means that, once you take hold of a slider’s knob (by putting the mouse inside the cell’s frame rectangle and pressing the mouse button), you retain control of the knob until you release the mouse button, even if you drag the mouse clear to the other side of the screen.

Never call this method explicitly. Override it if you create a subclass of NSSliderCell that you want to track the mouse differently.

Instance Methods

altIncrementValue

− (double)altIncrementValue

Returns the amount that the slider will change its value when the user drags the knob with the Alt key held down.

Unless you call setAltIncrementValue, altIncrementValue returns −1.0, and the slider behaves no differently with the Alt key down than with it up.

See also:	 − setAltIncrementValue:

drawBarInside:flipped:

− (void)drawBarInside:(NSRect)aRect flipped:(BOOL)flipped

Draws the slider’s bar—but not its bezel or knob—in aRect.

flipped indicates whether the cell’s control view—that is, the NSSlider or NSMatrix associated with the NSSliderCell—has a flipped coordinate system.

You should never invoke this method explicitly. It’s included so that you can override it in a subclass.

See also:	 − drawKnob:

drawKnob

− (void)drawKnob

Calculates the rectangle in which the knob should be drawn, then invokes drawKnob: to actually draw the knob. Before this message is sent, a lockFocus method must be sent to the cell’s control view.

You might invoke this method if you override one of the display methods belonging to NSControl or NSCell.

If you create a subclass of NSSliderCell, don’t override this method. Override drawKnob: instead.

drawKnob:

− (void)drawKnob:(NSRect)knobRect

Draws the knob in knobRect. Before this message is sent, a lockFocus message must be sent to the cell’s control view.

You should never invoke this method explicitly. It’s included so that you can override it in a subclass.

isVertical

− (int)isVertical

Returns 1 if the slider is vertical, 0 if it’s horizontal, and −1 if the orientation can’t be determined (for example, if the slider hasn’t been displayed yet). A slider is defined as vertical if its height is greater than its width.

knobRectFlipped:

− (NSRect)knobRectFlipped:(BOOL)flipped

Returns the rectangle in which the knob will be drawn, specified in the coordinate system of the NSSlider or NSMatrix with which the NSSliderCell is associated. flipped indicates whether that coordinate system is flipped, a question you can answer by sending NSView’s isFlipped message to the NSMatrix or NSSlider.

The knob rectangle depends on where in the slider the knob belongs—that is, it depends on the SliderCell’s minimum and maximum values, and on the value which the position of the knob will represent.

You should never invoke this method explicitly. It’s included so that you can override it in a subclass.

knobThickness

− (float)knobThickness

Returns the knob’s thickness, in pixels. The thickness is defined to be the extent of the knob along the long dimension of the bar. In a vertical slider, then, a knob’s thickness is its height; in a horizontal slider, its thickness is its width.

See also:	− setKnobThickness:

maxValue

− (double)maxValue

Returns the maximum value that the slider can send to its target. A horizontal slider sends its maximum value when the knob is at the right end of the slider; a vertical slider sends it when the knob is at the top.

See also:	 − setMaxValue:

minValue

− (double)minValue

Returns the minimum value that the slider can send to its target. A vertical slider sends this value when its knob is at the bottom; a horizontal slider sends it when its knob is all the way to the left.

setAltIncrementValue:

− (void)setAltIncrementValue:(double)increment

Sets the amount by which the NSSliderCell modifies its value when the knob is Alt-dragged. increment should fit the range of values that the slider can represent—for example, if the slider has a minimum value of 5 and a maximum value of 10, increment should be between 0 and 5.

If you don’t call this method, the slider behaves the same with the Alt key down as with it up. This is also the result when you call setAltIncrementValue: with an increment of -1.

See also:	 − maxValue, − minValue

setKnobThickness:

− (void)setKnobThickness:(float)thickness

Lets you set the knob’s thickness, measured in pixels. The thickness is defined to be the extent of the knob along the long dimension of the bar. In a vertical slider, then, a knob’s thickness is its height; in a horizontal slider, its thickness is its width.

See also:	− knobThickness

setMaxValue:

− (void)setMaxValue:(double)aDouble

Sets the maximum value that the slider can send to its target—the value that a horizontal slider will send when its knob is all the way to the right, or that a vertical slider will send when its knob is at the top.

See also:	 − maxValue

setMinValue:

− (void)setMinValue:(double)aDouble

Sets the minimum value that the slider can send to its target. A horizontal slider sends its minimum value when its knob is all the way to the left; a vertical slider sends its minimum value when its knob is at the bottom.

See also:	− minValue

setTitle:

− (void)setTitle:(NSString *)title

Sets the title in the bar behind the slider’s knob to title.

See also:	 − title

setTitleCell:

− (void)setTitleCell:(NSCell *)aCell

Sets the cell used to draw the slider’s title. You only need to invoke this method if the default title cell, NSTextFieldCell, doesn’t suit your needs—that is, if you want to display the title in a manner that NSTextFieldCell doesn’t permit. When you do choose to override the default, aCell should be an instance of a subclass of TextFieldCell.

See also:	− titleCell

setTitleColor:

− (void)setTitleColor:(NSColor *)color

Sets the color used to draw the slider’s title.

See also:	 − titleColor

setTitleFont:

− (void)setTitleFont:(NSFont *)font

Sets the font used to draw the slider’s title.

See also:	 − titleFont

title

− (NSString *)title

Returns the slider’s title. The default title is the empty string (“”).

See also:	 − setTitle:

titleCell

− (id)titleCell

Returns the cell used to draw the title. The default is an NSTextFieldCell.

See also:	− setTitleCell:

titleColor

− (NSColor *)titleColor

Returns the color used to draw the slider’s title. The default color is NSColor’s controlTextColor.

See also:	− setTitleColor:

titleFont

− (NSFont *)titleFont

Returns the font used to draw the slider’s title.

See also:	− setTitleFont:

trackRect

− (NSRect)trackRect

Returns the rectangle within which the cell tracks the mouse while the mouse button is down. This rectangle includes the slider bar, but not the bezel.


NSSpellChecker

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSSpellChecker.h

Class Description

The NSSpellChecker class gives any application an interface to the OpenStep spell-checking service. To handle all its spell checking, an application needs only one instance of NSSpellChecker. It provides a panel in which the user can specify decisions about words that are suspect. To check the spelling of a piece of text, the application:

•	Includes in its user interface a menu item (or a button or command) by which the user will request spell checking.

•	Makes the text available by way of an NSString object.

•	Creates an instance of the NSSpellChecker class and sends it a checkSpellingOfString:startingAt: message.

For example, you might use the following statement to create a spell checker:

range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:aString startingAt:0];

The checkSpellingOfString:startingAt: method checks the spelling of the words in the specified string beginning at the specified offset (this example uses 0 to start at the beginning of the string) until it finds a word that is misspelled. Then it returns an NSRange to indicate the location of the misspelled word.

In a graphical application, whenever a misspelled word is found, you’ll probably want to highlight the word in the document, using the NSRange that checkSpellingOfString:startingAt: returned to determine the text to highlight. Then you should show the misspelled word in the Spelling panel’s misspelled-word field by calling updateSpellingPanelWithMisspelledWord:. If checkSpellingOfString:startingAt: does not find a misspelled word, you should call updateSpellingPanelWithMisspelledWord: with the empty string. This causes the system to beep, letting the user know that the spell check is complete and no misspelled words were found. None of these steps is required, but if you do one, you should do them all.

The object that provides the string being checked should adopt the following protocols:

NSChangeSpelling	A message in this protocol (changeSpelling:) is sent down the

responder chain when the user presses the Correct button.

NSIgnoreMisspelledWords 	When the object being checked responds to this protocol, the spell server

 keeps a list of words that are acceptable in the document and enables the

 Ignore button in the Spelling panel.

The application may choose to split a document’s text into segments and check them separately. This will be necessary when the text has segments in different languages. Spell checking is invoked for one language at a time, so a document that contains portions in three languages will require at least three checks.

Dictionaries and Word Lists

The process of checking spelling makes use of three references:

•	A dictionary registered with the system’s spell-checking service. When the Spelling panel first appears, by default it shows the dictionary for the user’s preferred language. The user may select a different dictionary from the list in the Spelling panel.

•	The user’s “learn” list of correctly-spelled words in the current language. The NSSpellChecker updates the list when the user presses the Learn or Forget buttons in the Spelling panel.

•	The document’s list of words to be ignored while checking it (if the first responder conforms to the NSIgnoreMisspelledWords protocol). The NSSpellChecker updates its copy of this list when the user presses the Ignore button in the Spelling panel.

A word is considered to be misspelled if none of these three accepts it.

Matching a List of Ignored Words with the Document It Belongs To

The NSString being checked isn’t the same as the document. In the course of processing a document, an application might run several checks based on different parts or different versions of the text. But they’d all belong to the same document. The NSSpellChecker keeps a separate “ignored words” list for each document that it checks. To help match “ignored words” lists to documents, you should call uniqueSpellDocumentTag once for each document. This method returns a unique arbitrary integer that will serve to distinguish one document from the others being checked and to match each “ignored words” list to a document. When searching for misspelled words, pass the tag as the fourth argument of checkSpellingOfString:startingAt:language:wrap:inSpellDocumentWithTag:wordCount:. (The convenience method checkSpellingOfString:startingAt: takes no tag. This method is suitable when the first responder does not conform to the NSIgnoreMisspelledWords protocol.)

When the application saves a document, it may choose to retrieve the “ignored words” list and save it along with the document. To get back the right list, it must send the NSSpellChecker an ignoredWordsInSpellDocumentWithTag: message. When the application has closed a document, it should notify the NSSpellChecker that the document’s “ignored words” list can now be discarded, by sending it a closeSpellDocumentWithTag: message. When the application reopens the document, it should restore the “ignored words” list with the message setIgnoredWords:inSpellDocumentWithTag:.

Method Types

Getting the spell checker	+ sharedSpellChecker

+ sharedSpellCheckerExists

Managing the spelling panel	− setAccessoryView:

− accessoryView

− spellingPanel

Checking spelling	− countWordsInString:language:

− checkSpellingOfString:startingAt:

− checkSpellingOfString:startingAt:language:wrap:inSpellDocumentWithTag:wordCount:

Setting the language	− setLanguage:

− language

Managing the Spelling Process	+ uniqueSpellDocumentTag

− closeSpellDocumentWithTag:

− ignoreWord:inSpellDocumentWithTag:

− setIgnoredWordsInSpellDocumentWithTag:

− ignoredWordsInSpellDocumentWithTag:

− setWordFieldStringValue:

− updateSpellingPanelWithMisspelledWord:

Class Methods

sharedSpellChecker

+ (NSSpellChecker *)sharedSpellChecker

Returns the NSSpellChecker (one per application).

See also:	+ sharedSpellCheckerExists

sharedSpellCheckerExists

+ (BOOL)sharedSpellCheckerExists

Returns whether the application’s NSSpellChecker has already been created.

See also:	+ sharedSpellChecker

uniqueSpellDocumentTag

+ (int)uniqueSpellDocumentTag

Returns a guaranteed unique tag to use as the spell-document tag for a document. Use this method to generate tags to avoid collisions with other objects that can be spell-checked.

Instance Methods

accessoryView

− (NSView *)accessoryView

Returns the Spelling panel’s accessory NSView object.

See also:	− setAccessoryView:

checkSpellingOfString:startingAt:

− (NSRange)checkSpellingOfString:(NSString *)stringToCheck

startingAt:(int)startingOffset

Starts the search for a misspelled word in stringToCheck starting at startingOffset within the string object. Returns the range of the first misspelled word. Wrapping occurs but no ignored-words dictionary is used.

checkSpellingOfString:startingAt:language:wrap:inSpellDocumentWithTag:wordCount:

− (NSRange)checkSpellingOfString:(NSString *)stringToCheck

startingAt:(int)startingOffset

language:(NSString *)language

wrap:(BOOL)wrapFlag

 inSpellDocumentWithTag:(int)tag

wordCount:(int *)wordCount

Starts the search for a misspelled word in stringToCheck starting at startingOffset within the string object. Returns the range of the first misspelled word and optionally the word count by reference. tag is an identifier unique within the application used to inform the spell check which document (actually, a dictionary) of ignored words to use. wrapFlag determines whether spell checking continues at the beginning of the string when the end is reached. language is the language used in the string. If language is the empty string, the current selection in the Spelling panel’s pop-up menu is used.

closeSpellDocumentWithTag:

− (void)closeSpellDocumentWithTag:(int)tag

Notifies the spell checker that the user has finished with the ignored-word document identified by tag, causing it to throw that dictionary away.

countWordsInString:language:

− (int)countWordsInString:(NSString *)stringToCount

language:(NSString *)language

Returns the number of words in string. The language argument specifies the language used in the string. If language is the empty string, the current selection in the Spelling panel’s pop-up menu is used.

ignoreWord:inSpellDocumentWithTag:

− (void)ignoreWord:(NSString *)wordToIgnore inSpellDocumentWithTag:(int)tag

Instructs the spell checker to ignore all future occurrences of wordToIgnore in the document identified by tag. You should call this method from within your implementation of the NSIgnoreMisspelledWords protocol’s ignoreSpelling: method.

ignoredWordsInSpellDocumentWithTag:

− (NSArray *)ignoredWordsInSpellDocumentWithTag:(int)tag

Returns the array of ignored words for a document identified by tag. Invoke this before closeSpellDocument: if you want to store the ignored words.

See also:	− setIgnoredWords:inSpellDocumentWithTag:

language

− (NSString *)language

Returns the current language used in spell-checking.

See also:	− setLanguage:

setAccessoryView:

− (void)setAccessoryView:(NSView *)aView

Makes an NSView object an accessory of the Spelling panel by making it a subview of the panel’s content view. This method posts the notification NSWindowDidResizeNotification with the Spelling panel object to the default notification center.

See also:	− accessoryView

setIgnoredWords:inSpellDocumentWithTag:

− (void)setIgnoredWords:(NSArray *)words inSpellDocumentWithTag:(int)tag

Initializes the ignored-words document (i.e., dictionary identified by tag with someWords), an array of words to ignore.

See also:	− ignoredWordsInSpellDocumentWithTag:

setLanguage:

− (BOOL)setLanguage:(NSString *)language

Sets the language to use in spell-checking to aLanguage. Returns whether the Language pop-up list in the Spelling panel lists aLanguage.

See also:	− language

setWordFieldStringValue:

− (void)setWordFieldStringValue:(NSString *)aString

Sets the string that appears in the misspelled word field, using the string object aString.

spellingPanel

− (NSPanel *)spellingPanel

Returns the spell checker’s panel.

updateSpellingPanelWithMisspelledWord:

− (void)updateSpellingPanelWithMisspelledWord:(NSString *)word

Causes the spell checker to update the Spelling panel’s misspelled-word field to reflect word. You are responsible for highlighting word in the document and for extracting it from the document using the range returned by the checkSpelling:... methods. Pass the empty string as word to have the system beep, indicating no misspelled words were found.


NSSpellServer

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSSpellServer.h

Class Description

The NSSpellServer class gives you a way to make your particular spelling checker a service that's available to any application. A service is an application that declares its availability in a standard way, so that any other applications that wish to use it can do so. If you build a spelling checker that makes use of the NSSpellServer class and list it as an available service, then users of any application that makes use of NSSpellChecker or includes a Services menu will see your spelling checker as one of the available dictionaries.

To make use of NSSpellServer, you write a small program that creates an NSSpellServer instance and a delegate that responds to messages asking it to find a misspelled word and to suggest guesses for a misspelled word. Send the NSSpellServer registerLanguage:byVendor: messages to tell it the languages your delegate can handle.

The program that runs your spelling checker should not be built as an Application Kit application, but as a simple program. Suppose you supply spelling checkers under the vendor name “Acme.” Suppose the file containing the code for your delegate is called AcmeEnglishSpellChecker. Then the following might be your program's main:

void main()

{

  NSSpellServer *aServer = [[NSSpellServer alloc] init];

  if ([aServer registerLanguage:"English" byVendor:"Acme"]) {

    [aServer setDelegate:[AcmeEnglishSpellChecker alloc] init]];

    [aServer run];

    fprintf(stderr, "Unexpected death of Acme SpellChecker!\n");

  } else {

    fprintf(stderr, "Unable to check in Acme SpellChecker.\n");

  }

}

Your delegate is an instance of a custom subclass. (It's simplest to make it a subclass of NSObject, but that's not a requirement.) Given an NSString, your delegate must be able to find a misspelled word by implementing the method spellServer:findMisspelledWordInString:language:wordCount:countOnly:. Usually, this method also reports the number of words it has scanned, but that isn't mandatory.

Optionally, the delegate may also suggest corrections for misspelled words. It does so by implementing the method spellServer:suggestGuessesForWord:inLanguage:

Service Availability Notice

When there's more than one spelling checker available, the user selects the one desired. The application that requests a spelling check uses an NSSpellChecker object, and it provides a Spelling panel; in the panel there's a pop-up list of available spelling checkers. Your spelling checker appears in that list if it has a service descriptor.

A service descriptor is an entry in a text file called services. Usually it's located within the bundle that also contains your spelling checker's executable file. The bundle (or directory) that contains the services file must have a name ending in “.service” or “.app”. The system looks for service bundles in a standard set of directories.

A spell checker service availability notice has a standard format, illustrated in the following example for the Acme spelling checker:

Spell Checker:  Acme

Language:  French

Language:  English

Executable:  franglais.daemon

The first line identifies the type of service; for a spelling checker, it must say “Spell Checker:” followed by your vendor name. The next line contains the English name of a language your spelling checker is prepared to check. (The language must be one your system recognizes.) If your program can check more than one language, use an additional line for each additional language. The last line of a descriptor gives the name of the service's executable file. (It requires a complete path if it's in a different directory.)

If there's a service descriptor for your Acme spelling checker and also a service descriptor for the English checker provided by a vendor named Consolidated, a user looking at the Spelling panel's pop-up list would see:

English (Acme)

English (Consolidated)

French (Acme)

Illustrative Sequence of Messages to an NSSpellServer

The act of checking spelling usually involves the interplay of objects in two classes: the user application's NSSpellChecker (which responds to interactions with the user) and your spelling checker's NSSpellServer (which provides the application interface for your spelling checker). You can see the interaction between the two in the following list of steps involved in finding a misspelled word.

•	The user of an application selects a menu item to request a spelling check. The application sends a message to its NSSpellChecker object. The NSSpellChecker in turn sends a corresponding message to the appropriate NSSpellServer.

•	The NSSpellServer receives the message asking it to check the spelling of an NSString. It forwards the message to its delegate.

•	The delegate searches for a misspelled word. If it finds one, it returns an NSRange identifying the word's location in the string.

•	The NSSpellServer receives a message asking it to suggest guesses for the correct spelling of a misspelled word, and forwards the message to its delegate.

•	The delegate returns a list of possible corrections, which the NSSpellServer in turn returns to the NSSpellChecker that initiated the request.

•	The NSSpellServer doesn't know what the user does with the errors its delegate has found or with the guesses its delegate has proposed. (Perhaps the user corrects the document, perhaps by selecting a correction from the NSSpellChecker's display of guesses; but that's not the NSSpellServer's responsibility.) However, if the user presses the Learn or Forget buttons (thereby causing the NSSpellChecker to revise the user's word list), the NSSpellServer receives a notification of the word thus learned or forgotten. It's up to you whether your spell checker acts on this information. If the user presses the Ignore button, the delegate is not notified (but the next time that word occurs in the text, the method isWordInUserDictionaries:caseSensitive: will report YES rather than NO).

•	Once the NSSpellServer delegate has reported a misspelled word, it has completed its search. Of course, it's likely that the user's application will then send a new message, this time asking the NSSpellServer to check a string containing the part of the text it didn't get to earlier.

Method Types

Registering your service	− registerLanguage:byVendor:

Assigning a delegate	− setDelegate:

− delegate

Running the service	− run

Checking user dictionaries	− isWordInUserDictionaries:caseSensitive:

Instance Methods

delegate

− (id)delegate

Returns the NSSpellServer’s delegate.

See also:  − setDelegate:

isWordInUserDictionaries:caseSensitive:

− (BOOL)isWordInUserDictionaries:(NSString *)word caseSensitive:(BOOL)flag

Indicates whether word is in the user's list of learned words or the document's list of words to ignore. If YES, the word is acceptable to the user.  flag indicates whether the comparison is to be case-sensitive.

registerLanguage:byVendor:

− (BOOL)registerLanguage:(NSString *)language byVendor:(NSString *)vendor

Notifies the NSSpellServer of a language your spelling checker can check. language is the English name of a language on NeXT's list of languages. vendor identifies the vendor (to distinguish your spelling checker from those that others may offer for the same language). If your spelling checker supports more than one language, it should invoke this method once for each language. Registering a language/vendor combination causes it to appear in the Spelling Panel's pop-up list of spelling checkers.

Returns YES if the language is registered, NO if for some reason it can't be registered.

run

− (void)run

Causes the NSSpellServer to start listening for spell-checking requests. This method starts a loop that never returns; you need to set the NSSpellServer’s delegate before sending this message.

See also:  − setDelegate:

setDelegate:

− (void)setDelegate:(id)anObject

Assigns a delegate to the NSSpellServer. Since the delegate is where the real work is done, this is an essential step before telling the NSSpellServer to run.

See also:  − delegate, − run

Methods Implemented by the Delegate

spellServer:didForgetWord:inLanguage:

− (void)spellServer:(NSSpellServer *)sender

didForgetWord:(NSString *)word

inLanguage:(NSString *)language

Notifies the delegate that word has been removed from the user’s list of acceptable words. If your delegate maintains a similar auxiliary word list, you may wish to edit the list accordingly.

spellServer:didLearnWord:inLanguage:

− (void)spellServer:(NSSpellServer *)sender

didLearnWord:(NSString *)word

inLanguage:(NSString *)language

Notifies the delegate that word has been added to the user’s list of acceptable words. If your delegate maintains a similar auxiliary word list, you may wish to edit the list accordingly.

spellServer:findMisspelledWordInString:language:wordCount:countOnly:

− (NSRange)spellServer:(NSSpellServer *)sender

findMisspelledWordInString:(NSString *)stringToCheck

language:(NSString *)language

wordCount:(int *)wordCount

countOnly:(BOOL)countOnly

Asks the delegate to search for a misspelled word in stringToCheck, using language, and marking the first misspelled word found by returning its range within the string object. In wordCount return by reference the number of words from the beginning of the string object until the misspelled word (or the end-of-string). If countOnly is YES, just count the words in the string object; do not spell-check. Send isWordInUserDictionaries:caseSensitive: to the spelling server to determine if word exists in the user's language dictionaries.

spellServer:suggestGuessesForWord:inLanguage:

− (NSArray *)spellServer:(NSSpellServer *)sender

suggestGuessesForWord:(NSString *)word

inLanguage:(NSString *)language

Gives the delegate the opportunity to suggest guesses for the correct spelling of the misspelled word. Return the guesses as an array of NSStrings.


NSSplitView

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSView : NSResponder : NSObject

Conforms To:	NSCoding (from NSResponder)

NSObject (from NSObject)

Declared In:	AppKit/NSSplitView.h

Class Description

An NSSplitView object lets several views share a region within a window. The NSSplitView resizes its subviews so that each subview is the same width as the NSSplitView, and the total of the subviews’ heights (plus the total of the dividers’ thicknesses) is equal to the height of the NSSplitView. The NSSplitView positions its subviews so that the first subview is at the top of the NSSplitView, and each successive subview is positioned below the previous one. The user can set the height of two subviews by moving a horizontal bar called the divider, which makes one subview smaller and the other larger. Programmatically, you adjust the relative height of subviews simply by modifying the frame of each of the subviews.

To add a view to an NSSplitView, you use the NSView method addSubview:. When the NSSplitView is displayed, it checks to see if its subviews are properly tiled. If not, it invokes the delegate method splitView:resizeSubviewsWithOldSize:, allowing the delegate to specify the heights of specific subviews. If the delegate doesn’t implement this method, the NSSplitView sends adjustSubviews to itself to yield the default tiling behavior.

When a mouse-down occurs in an NSSplitView’s divider, the NSSplitView determines the limits of the divider’s travel and tracks the mouse to allow the user to drag the divider within these limits. With the following mouse-up, the NSSplitView resizes the two affected subviews, informs the delegate that the subviews were resized, and displays the affected views and divider. The NSSplitView’s delegate can constrain the travel of specific dividers by implementing the method splitView:constrainMinCoordinate:maxCoordinate:ofSubviewAt:.

Method Types

Managing component views	− adjustSubviews

− dividerThickness

− drawDividerInRect:

Assigning a delegate	− delegate

− setDelegate:

*nil* Notifications

When the subviews within a split view have been resized

NSSplitViewDidResizeSubviewsNotification

When the subviews within a split view are about to be resized

NSSplitViewWillResizeSubviewsNotification

Instance Methods

adjustSubviews

− (void)adjustSubviews

Adjusts the heights of the NSSplitView’s subviews so the total height (including the dividers) fills the NSSplitView. The subviews are resized proportionally; the size of a subview relative to the other subviews doesn’t change.

See also:	− setDelegate:, − setFrame: (NSView)

delegate

− (id)delegate

Returns the NSSplitView’s delegate.

dividerThickness

− (float)dividerThickness

Returns the thickness of the divider. By default, this size is the height of the “dimple” + 1.0. You can override this method to change the divider’s height, if necessary.

See also:	− drawDividerInRect:

drawDividerInRect:

− (void)drawDividerInRect:(NSRect)aRect

Draws a divider between two of the NSSplitView’s subviews. aRect describes the entire divider rectangle in the NSSplitView’s coordinates, which are flipped. The default implementation composites a default “dimple” image to the center of aRect; if you override this method and use a different icon to identify the divider, you may want to change the height of the divider.

See also:	− dividerThickness, − composite:toPoint: (NSImage)

setDelegate:

− (void)setDelegate:(id)anObject

Makes anObject the NSSplitView’s delegate. The notification messages that the delegate can expect to receive are listed at the end of the NSSplitView class specification. The delegate doesn’t need to implement all of the delegate methods.

*nil* Methods Implemented by the Delegate

splitView:constrainMinCoordinate:maxCoordinate:ofSubviewAt:

− (void)splitView:(NSSplitView *)sender constrainMinCoordinate:(float *)min maxCoordinate:(float *)max ofSubviewAt:(int)offset

Allows the delegate to constrain the y coordinate limits of a divider when the user drags the mouse. This method is invoked before the NSSplitView begins tracking the mouse to position a divider. When this method is invoked, the limits have already been set and are stored in min (the topmost limit) and max (the bottommost limit). You may further constrain the limits by setting the variables indicated by min and max, but you cannot extend the divider limits. min and max are specified in the NSSplitView’s flipped coordinate system. The divider to be repositioned is indicated by offset, an index that counts the dividers from top to bottom starting with divider 0.

splitView:resizeSubviewsWithOldSize:

− (void)splitView:(NSSplitView *)sender resizeSubviewsWithOldSize:(NSSize)oldSize

Allows the delegate to specify custom sizing behavior for the subviews of the NSSplitView. If the delegate implements this method, splitView:resizeSubviewsWithOldSize: is invoked after the NSSplitView is resized. The size of the NSSplitView before the user resized it is indicated by oldSize; the subviews should be resized such that the sum of the heights of the subviews plus the sum of the thickness of the dividers equals the height of the NSSplitView’s new frame. You can get the height of a divider through the dividerThickness method.

See also:	− adjustSubviews, − setFrame: (NSView)

splitViewDidResizeSubviews:

− (void)splitViewDidResizeSubviews:(NSNotification *)aNotification

Sent by the default notification center to the delegate; aNotification is always an NSSplitViewDidResizeSubviewsNotification. If the delegate implements this method, the delegate is automatically registered to receive this notification. This method is invoked after the NSSplitView resizes two of its subviews in response to the repositioning of a divider.

splitViewWillResizeSubviews:

− (void)splitViewWillResizeSubviews:(NSNotification *)aNotification

Sent by the default notification center to the delegate; aNotification is always an NSSplitViewWillResizeSubviewsNotification. If the delegate implements this method, the delegate is automatically registered to receive this notification. This method is invoked before the NSSplitView resizes two of its subviews in response to the repositioning of a divider.

Notifications

NSSplitView declares and posts the following notifications. In addition, it posts notifications that are declared by its superclass, NSView. See the NSView class specification for more information.

NSSplitViewDidResizeSubviewsNotification

Notification Object	The notifying NSSplitView.

Userinfo	none

Posted after the NSSplitView changes the sizes of some or all of its subviews.

See also:	− splitViewDidResizeSubviews:

NSSplitViewWillResizeSubviewsNotification

Notification Object	The notifying NSSplitView.

Userinfo	none

Posted before the NSSplitView changes the sizes of some or all of its subviews.

See also:	− splitViewWillResizeSubviews:


NSString Additions
p NSString Additions

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Declared In:	AppKit/NSStringDrawing.h

Class Description

The Application Kit adds three methods to support drawing string objects directly in an NSView. These methods, drawAtPoint:withAttributes:, drawInRect:withAttributes:, and sizeWithAttributes:, parallel similar methods defined by NSAttributedString methods. The draw... methods draw a string object with a single set of attributes that apply to the entire string. To draw a string using multiple fonts and other attributes, you must use an NSAttributedString.

Method Types

Drawing an NSString	− drawAtPoint:withAttributes:

− drawInRect:withAttributes:

− sizeWithAttributes:

Instance Methods

p	drawAtPoint:

− (void)drawAtPoint:(NSPoint)aPoint withAttributes:(NSDictionary *)attributes

Draws the receiver with the font and other display attributes of attributes, at aPoint in the currently focused NSView. Don’t invoke this method while no NSView is focused.

See also:	− lockFocus (NSView)

p	drawInRect:

− (void)drawInRect:(NSRect)aRect withAttributes:(NSDictionary *)attributes

Draws the receiver with the font and other display attributes of attributes, within aRect in the currently focused NSView. Don’t invoke this method while no NSView is focused.

See also:	− lockFocus (NSView)

p	size

− (NSSize)sizeWithAttributes:(NSDictionary *)attributes

Returns the bounding box size that the receiver occupies when drawn with attributes.


NSTableColumn

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSTableColumn.h

Class Description

An NSTableColumn stores the display characteristics and attribute identifier for a column in an NSTableView. The NSTableColumn determines the width and width limits, resizability, and editability of its column in the NSTableView. It also stores two NSCell objects: the header cell, which is used to draw the column header, and the data cell, used to draw the values for each row. You can control the display of the column by setting the subclasses of NSCell used and by setting the font and other display characteristics for these NSCells. For example, you can use the default NSTextFieldCell for displaying string values or substitute an NSImageCell to display pictures.

See the NSTableView class specification for a general overview.

Method Types

Creating an NSTableColumn instance

− initWithIdentifier:

Setting the identifier	− setIdentifier:

− identifier

Setting the NSTableView	− setTableView:

− tableView

Controlling size	− setWidth:

− width

− setMinWidth:

− minWidth

− setMaxWidth:

− maxWidth

− setResizable:

− isResizable

− sizeToFit

Controlling editability	− setEditable:

− isEditable

Setting component cells	− setHeaderCell:

− headerCell

− setDataCell:

− dataCell

Instance Methods

dataCell

− (id)dataCell

Returns the NSCell object used by the NSTableView to draw values for the NSTableColumn.

See also:	− setDataCell:

headerCell

− (id)headerCell

Returns the NSTableHeaderCell object used to draw the header of the NSTableColumn. You can set the column title by sending setStringValue: to this object.

See also:	− setHeaderCell:

initWithIdentifier:

− (id)initWithIdentifier:anObject

Initializes a newly created NSTableColumn with anObject as its identifier and with an NSTextFieldCell as its data cell. Send setStringValue: to the header cell to set the column title. This is the designated initializer for the NSTableColumn class. Returns self.

See the NSTableView class specification for information on identifiers.

See also:	− setIdentifier:

identifier

− (id)identifier

Returns the object used by the data source to identify the attribute corresponding to the NSTableColumn.

See also:	− setIdentifier:

isEditable

− (BOOL)isEditable

Returns YES if the user can edit cells associated with the NSTableColumn by double-clicking the column in the NSTableView, NO otherwise. You can initiate editing programmatically regardless of this setting with NSTableView’s editColumn:row:withEvent:select: method.

See also:	− setEditable:

isResizable

− (BOOL)isResizable

Returns YES if the user is allowed to resize the NSTableColumn in its NSTableView, NO otherwise. You can change the size programmatically regardless of this setting.

See also:	− setWidth:, − setMinWidth:, − setMaxWidth:, − setResizable:

maxWidth

− (float)maxWidth

Returns the maximum width for the NSTableColumn. The NSTableColumn’s width can’t be made larger than this either by the user or programmatically.

See also:	− minWidth, − width, − setMaxWidth:, − sizeToFit (NSTableView), − autoresizesAllColumnsToFit (NSTableView)

minWidth

− (float)minWidth

Returns the minimum width for the NSTableColumn. The NSTableColumn’s width can’t be made less than this either by the user or programmatically.

See also:	− maxWidth, − width, − setMinWidth:, − sizeToFit (NSTableView), − autoresizesAllColumnsToFit (NSTableView)

setDataCell:

− (void)setDataCell:(NSCell *)aCell

Sets the NSCell used by the NSTableView to draw individual values for the NSTableColumn to aCell. You can use this method to control the font, alignment, and other text attributes for an NSTableColumn. You can also assign a cell to display things other than text—for example, an NSImageCell to display images.

See also:	− dataCell

setEditable:

− (void)setEditable:(BOOL)flag

Controls whether the user can edit cells in the receiver by double-clicking them. If flag is YES a double click initiates editing; if flag is NO it merely sends the double action to the NSTableView’s target. You can initiate editing programmatically regardless of this setting with NSTableView’s editColumn:row:withEvent:select: method.

See also:	− isEditable

setHeaderCell:

− (void)setHeaderCell:(NSCell *)aCell

Sets the NSCell used to draw the NSTableColumn’s header to aCell. aCell should never be nil.

See also:	− headerCell

setIdentifier:

− (void)setIdentifier:(id)anObject

Sets the NSTableColumn’s identifier to anObject. This object is used by the data source to identify the attribute corresponding to the NSTableColumn.

See also:	− identifier

setMaxWidth:

− (void)setMaxWidth:(float)maxWidth

Sets the NSTableColumn’s maximum width to maxWidth, also adjusting the current width if it’s greater than this value. The NSTableView can be made no wider than this, either by the user or programmatically.

See also:	− setMinWidth:, − setWidth:, − maxWidth, − sizeToFit (NSTableView), − autoresizesAllColumnsToFit (NSTableView)

setMinWidth:

− (void)setMinWidth:(float)minWidth

Sets the NSTableColumn’s minimum width to minWidth, also adjusting the current width if it’s less than this value. The NSTableView can be made no less wide than this, either by the user or programmatically.

See also:	− setMaxWidth:, − setWidth:, − minWidth, − sizeToFit (NSTableView), − autoresizesAllColumnsToFit (NSTableView)

setResizable:

− (void)setResizable:(BOOL)flag

Sets whether the user can resize the receiver in its NSTableView. If flag is YES the user can resize the receiver; if flag is NO the user can’t resize it (though you can set the size programmatically).

See also:	− isResizable, − setWidth:, − setMinWidth:, − setMaxWidth:

setTableView:

− (void)setTableView:(NSTableView *)aTableView

Sets aTableView as the NSTableColumn’s NSTableView. You should never need to invoke this method; it’s invoked automatically when you add an NSTableColumn to an NSTableView.

See also:	− tableView, − addTableColumn: (NSTableView)

setWidth:

− (void)setWidth:(float)newWidth

Sets the NSTableColumn’s width to newWidth. If newWidth exceeds the minimum or maximum width, it’s adjusted to the appropriate limiting value. Marks the NSTableView as needing display.

This method posts NSTableViewColumnDidResizeNotification on behalf of the NSTableColumn’s NSTableView.

See also:	− width, − setMinWidth:, − setMaxWidth:, − sizeToFit (NSTableView), − autoresizesAllColumnsToFit (NSTableView)

sizeToFit

− (void)sizeToFit

Resizes the NSTableColumn to fit the width of its header cell. If the maximum width is less than the width of the header, the maximum is increased to the header’s width. Similarly, if the minimum width is greater than the width of the header, the minimum is reduced to the header’s width. Marks the NSTableView as needing display if the width actually changes.

See also:	− width, − minWidth, − maxWidth, − sizeToFit (NSTableView), − autoresizesAllColumnsToFit (NSTableView)

tableView

− (NSTableView *)tableView

Returns the NSTableView that the NSTableColumn belongs to.

See also:	− setTableView:

width

− (float)width

Returns the width of the NSTableColumn.

See also:	− width


NSTableDataSource

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Category Of:	NSObject

Declared In:	AppKit/NSTableView.h

Category Description

The NSTableDataSource category declares the methods that an NSTableView uses to access the contents of its data source object. It determines how many rows to display by sending a numberOfRowsInTableView: message, and accesses individual values with the tableView:objectValueForTableColumn:row: and tableView:setObjectValue:forTableColumn:row: methods. A data source must implement the first two methods to work with an NSTableView, but if it doesn’t implement the third the NSTableView simply provides read-only access to its contents.

The NSTableView treats objects provided by its data source as values to be displayed in NSCell objects. If these objects aren’t of common value classes—such as NSString, NSNumber, and so on—you’ll need to create a custom NSFormatter to display them. See the NSFormatter class specification for more information.

Suppose that an NSTableView’s column identifiers are set up as NSStrings containing the names of attributes for the column, such as “Last Name”, “City”, and so on, and that the data source stores its records as an NSMutableArray, called records, of NSMutableDictionary objects using those names as keys. Here’s a small example, given as an ASCII property list:

(

  { "Last Name" = Anderson;

    "First Name" = James;

    Abode = apartment;

    City = "San Francisco";

  },

  { "Last Name" = Beresford;

    "First Name" = Keith;

    Abode = apartment;

    City = "Redwood City";

  }

)

With such a record structure, this implementation of tableView:objectValueForTableColumn:row: suffices to retrieve values for the NSTableView:

- (id)tableView:(NSTableView *)aTableView

    objectValueForTableColumn:(NSTableColumn *)aTableColumn

    row:(int)rowIndex

{

    id theRecord, theValue;

    NSParameterAssert(rowIndex >= 0 && rowIndex < [records count]);

    theRecord = [records objectAtIndex:rowIndex];

    theValue = [theRecord objectForKey:[aTableColumn identifier]];

    return theValue;

}

Here’s the corresponding method for setting values:

- (void)tableView:(NSTableView *)aTableView

    setObjectValue:anObject

    forTableColumn:(NSTableColumn *)aTableColumn

    row:(int)rowIndex

{

    id theRecord;

    NSParameterAssert(rowIndex >= 0 && rowIndex < [records count]);

    theRecord = [records objectAtIndex:rowIndex];

    [theRecord setObject:anObject forKey:[aTableColumn identifier]];

    return;

}

Finally, numberOfRowsInTableView: simply returns the count of the NSArray:

- (int)numberOfRowsInTableView:(NSTableView *)aTableView

{

    return [records count];

}

In each case, the NSTableView that sends the message is provided as aTableView. A data source object that manages several sets of data can choose the appropriate set based on which NSTableView sends the message.

Instance Methods

numberOfRowsInTableView:

− (int)numberOfRowsInTableView:(NSTableView *)aTableView

Returns the number of records managed for aTableView by the data source object. An NSTableView uses this method to determine how many rows it should create and display.

tableView:objectValueForTableColumn:row:

− (id)tableView:(NSTableView *)aTableView

objectValueForTableColumn:(NSTableColumn *)aTableColumn

row:(int)rowIndex

Returns an attribute value for the record in aTableView at rowIndex. aTableColumn contains the identifier for the attribute, which you get by using NSTableColumn’s identifier method. For example, if aTableColumn stands for the city that an employee lives in and rowIndex specifies the record for an employee who lives in Portland, this method returns an object with a string value of “Portland”. See the category description for an example.

tableView:setObjectValue:forTableColumn:row:

− (void)tableView:(NSTableView *)aTableView

setObjectValue:(id)anObject

forTableColumn:(NSTableColumn *)aTableColumn

row:(int)rowIndex

Sets an attribute value for the record in aTableView at rowIndex. anObject is the new value, and aTableColumn contains the identifier for the attribute, which you get by using NSTableColumn’s identifier method. See the category description for an example.


NSTableHeaderCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSTextFieldCell : NSActionCell : NSCell : NSObject

Conforms To:	NSCoding (NSCell)

NSCopying (NSCell)

NSObject (NSObject)

Declared In:	AppKit/NSTableHeaderCell.h

Class Description

An NSTableHeaderCell is used by an NSTableHeaderView to draw its column headers. See the NSTableView class specification for more information on how it’s used.

Subclasses of NSTableHeaderCell can override drawInteriorWithFrame:inView:, drawWithFrame:inView:, and highlight:withFrame:inView: to change the way headers appear. See the NSCell class specification, and the description below, for information on these methods.

Instance Methods

drawInteriorWithFrame:inView:

− (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView

Draws the receiver’s interior, as described for this same method in the NSCell class specification. NSTableHeaderCell’s implementation overrides NSTextFieldCell’s to draw the receiver’s image if it has one, instead of its string value. If the receiver has no image, it simply draws its string value. This allows column headers to be labeled with images rather than text.

To make an NSTableHeaderCell display an image, use NSCell’s setImage: method, which changes the receiver’s cell type to NSImageCellType and stores the image provided. To restore it to displaying a text label, supply a new title using setStringValue:, which removes the image and reverts the receiver’s cell type to NSTextCellType.


NSTableHeaderView

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSTableHeaderView.h

Class Description

An NSTableHeaderView is used by an NSTableView to draw headers over its columns and to handle mouse events in those headers. See the NSTableView class specification for more information.

Method Types

Setting the table view	− setTableView:

− tableView

Checking altered columns	− draggedColumn

− draggedDistance

− resizedColumn

Utility methods	− columnAtPoint:

− headerRectOfColumn:

Instance Methods

columnAtPoint:

− (int)columnAtPoint:(NSPoint)aPoint

Returns the index of the column whose header lies under aPoint in the NSTableHeaderView, or −1 if no such column is found. aPoint is expressed in the NSTableHeaderView’s coordinate system.

draggedColumn

− (int)draggedColumn

If the user is dragging a column in the NSTableView, returns the index of that column. Otherwise returns −1.

See also:	− draggedDistance

draggedDistance

− (float)draggedDistance

If the user is dragging a column in the NSTableView, returns the column’s horizontal distance from its original position. Otherwise the return value is meaningless.

See also:	− draggedColumn

headerRectOfColumn:

− (NSRect)headerRectOfColumn:(int)columnIndex

Returns the rectangle containing the header tile for the column at columnIndex. Raises an NSInternalInconistencyException if columnIndex is out of bounds.

See also:	− rectOfColumn: (NSTableView)

resizedColumn

− (int)resizedColumn

If the user is resizing a column in the NSTableView, returns the index of that column. Otherwise returns −1.

setTableView:

− (void)setTableView:(NSTableView *)aTableView

Sets aTableView as the NSTableColumn’s NSTableView. You should never need to invoke this method; it’s invoked automatically when you set the header view for an NSTableView.

See also:	− setHeaderView: (NSTableView)

tableView

− (NSTableView *)tableView

Returns the NSTableView that the NSTableHeaderView belongs to.


NSTableView

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSControl : NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSTableView.h

Purpose

An NSTableView object displays record-oriented data in a table, and allows the user to edit values and resize and rearrange columns.

Principal Attributes

•	Displays record-oriented data	•	Works with NSScrollView

•	Gets data from an object you provide	•	Uses a delegate

•	Lazily retrieves only data that needs to be displayed

Creation

Interface Builder

− initWithFrame:	Designated initializer

Commonly Used Methods

− dataSource	Returns the object providing the data that the NSTableView displays.

− tableColumns	Returns the NSTableColumn objects representing attributes for the NSTableView.

− selectedColumn	Returns the index of the selected column.

− selectedRow	Returns the index of the selected column.

− numberOfRows	Returns the number of rows in the NSTableView.

− reloadData	Informs the NSTableView that data has changed and needs to be retrieved and displayed again.

Class Description

An NSTableView displays data for a set of related records, with rows representing individual records and columns representing the attributes of those records. A record is a set of values for a particular real-world entity, such as an employee or a bank account. For example, in a table of employee records, each row represents one employee, and the columns represent such attributes as the first and last name, address, salary, and so on. An NSTableView is usually displayed in an NSScrollView, like this:

In this illustration, the NSTableView itself is only the portion displaying values. The header is drawn by two auxiliary views: the column headers by the header view, and the blank square above the vertical scroller by the corner view. The roles of these two auxiliary views are discussed in “Auxiliary Components.”

The user selects rows or columns in the table by clicking, and edits individual cells by double-clicking. The user can also rearrange columns by dragging the column headers and can resize the columns by dragging the divider between two column headers. You can configure the table’s parameters so that the user can select more than one row or column (or have none selected), so that the user isn’t allowed to edit particular columns or rearrange them, and so on. You can also specify an action message to be sent when the user double-clicks something other than an editable cell.

Providing Data for Display

Unlike most NSControls, an NSTableView doesn’t store or cache the data it displays. Instead, it gets all of its data from an object that you provide, called its data source. Your data source object can store records in any way, but it must be able to identify them by integer index and must implement methods to provide the following information: how many records the data source contains, and what the value is for a particular record’s attribute. If you want to allow the user to edit the records, you must also provide a method for changing the value of an attribute. These methods are described in the NSTableDataSource informal protocol specification.

A record attribute is indicated by an object called its identifier, which is associated with a column in the NSTableView, as described in “Auxiliary Components.” The data source uses the identifier as a key to retrieve values for the attribute—because columns can be reordered, their indices can’t be used to identify record attributes. The identifier can be any kind of object that uniquely identifies attributes for the data source. For example, if you specify identifiers as NSStrings containing the names of attributes, such as “Last Name”, “Address”, and so on, the data source object can use these strings as keys into NSDictionary objects. See the NSTableDataSource informal protocol specification for example of how to use identifiers.

Auxiliary Components

As indicated earlier, an NSTableView is usually displayed in an NSScrollView along with its two auxiliary views, the corner view and the header view. The corner view is by default a simple view that merely fills in the corner above the vertical scroller. You can replace the default corner view with a custom view; for example, a button that sorts based on the selected column. The header view is usually an instance of the NSTableHeaderView class, which draws the column headers and handles column selection, rearranging, and resizing. NSScrollView queries any document view it’s given for the cornerView and headerView methods, and if the document view responds and returns objects for them, the NSScrollView automatically tiles them along with its scrollers and the document view.

The NSTableView and the NSTableHeaderView both need access to information about columns (such as their width), so this information is encapsulated in NSTableColumn objects. An NSTableColumn stores its column’s width, and determines whether the user can resize the column or edit its cells. It also holds an NSCell object that the NSTableHeaderView uses to draw the column header, and an NSCell object that the NSTableView uses to draw values in the column (it reuses the same NSCell for each row in the column). Finally, the NSTableColumn holds the attribute identifier mentioned in “Providing Data for Display.”

The cell for each column header is by default an instance of the NSTableHeaderCell class; it’s used by the NSTableHeaderView to draw the column’s header. An NSTableHeaderCell contains the title displayed over the column, as well as the font and color for that title. You use the API of its superclasses, NSTextFieldCell and NSCell, to set a column’s title and to specify display attributes for that title (font, alignment, and so on). In addition, you can use the NSCell method setImage: to make the NSTableHeaderCell display an image instead of a title. To remove the image and restore the title, use the NSCell method setStringValue:.

The data cell for the column values is typically an instance of NSTextFieldCell, but can be an instance of any NSCell subclass, such as NSImageCell. This object is used to draw all values in the column and determines the font, alignment, text color, and other such display attributes for those values. You can customize the presentation of various kinds of values by assigning an NSFormatter to the cell. For example, to properly display NSDate values in a column, assign its data cell an NSDateFormatter.

Delegate Messages

NSTableView adds a handful of delegate messages to those defined by its superclass, NSControl. These methods give the delegate control over the appearance of individual cells in the table, over changes in selection, and over editing of cells. The delegate methods that request permission to alter the selection or edit a value are invoked during user actions that affect the NSTableView, but not when you change things programmatically; when making changes programmatically you decide whether you want the delegate to intervene and send the appropriate message (checking that the delegate responds first, of course). Because the delegate methods involve the actual data displayed by the NSTableView, the delegate is typically the same object as the data source.

tableView:willDisplayCell:forTableColumn:row: informs the delegate that the NSTableView is about to draw a particular cell. The delegate can modify the NSCell provided to alter the display attributes for that cell; for example, making uneditable values display in italic or gray text (as in the figure above).

tableView:shouldSelectRow: and tableView:shouldSelectTableColumn: give the delegate control over whether the user can select a particular row or column (though the user can still reorder columns). This is useful for disabling particular rows or columns. For example, in a database client application, when another user is editing a record you might want all other users not to be able to select it.

selectionShouldChangeInTableView: allows the delegate to deny a change in selection; for example, if the user is editing a cell and enters an improper value, the delegate can prevent the user from selecting or editing any other cells until a proper value has been entered into the original cell.

tableView:shouldEditTableColumn:row: asks the delegate whether it’s okay to edit a particular cell. The delegate can approve or deny the request.

In addition to these methods, the delegate is also automatically registered to receive messages corresponding to NSTableView notifications. These inform the delegate when the selection changes and when a column is moved or resized:

Delegate Message	Notification

tableViewColumnDidMove:	NSTableViewColumnDidMoveNotification

tableViewColumnDidResize:	NSTableViewColumnDidResizeNotification

tableViewSelectionDidChange:	NSTableViewSelectionDidChangeNotification

tableViewSelectionIsChanging:	NSTableViewSelectionIsChangingNotification

Method Types

Creating an instance	− initWithFrame:

Setting the data source	− setDataSource:

− dataSource

Loading data	− reloadData

Target-action behavior	− setDoubleAction:

− doubleAction

− clickedColumn

− clickedRow

Configuring behavior	− setAllowsColumnReordering:

− allowsColumnReordering

− setAllowsColumnResizing:

− allowsColumnResizing

− setAllowsMultipleSelection:

− allowsMultipleSelection

− setAllowsEmptySelection:

− allowsEmptySelection

− setAllowsColumnSelection:

− allowsColumnSelection

Setting display attributes	− setIntercellSpacing:

− intercellSpacing

− setRowHeight:

− rowHeight

− setBackgroundColor:

− backgroundColor

Manipulating columns	− addTableColumn:

− removeTableColumn:

− moveColumn:toColumn:

− tableColumns

− columnWithIdentifier:

− tableColumnWithIdentifier:

Selecting columns and rows	− selectColumn:byExtendingSelection:

− selectRow:byExtendingSelection:

− deselectColumn:

− deselectRow:

− numberOfSelectedColumns

− numberOfSelectedRows

− selectedColumn

− selectedRow

− isColumnSelected:

− isRowSelected:

− selectedColumnEnumerator

− selectedRowEnumerator

− selectAll:

− deselectAll:

Getting the dimensions of the table	− numberOfColumns

− numberOfRows

Setting grid attributes	− setDrawsGrid:

− drawsGrid

− setGridColor:

− gridColor

Editing cells	− editColumn:row:withEvent:select:

− editedRow

− editedColumn

Setting auxiliary views	− setHeaderView:

− headerView

− setCornerView:

− cornerView

Layout support	− rectOfColumn:

− rectOfRow:

− columnsInRect:

− rowsInRect:

− columnAtPoint:

− rowAtPoint:

− frameOfCellAtColumn:row:

− setAutoresizesAllColumnsToFit

− autoresizesAllColumnsToFit

− sizeLastColumnToFit

− sizeToFit

− noteNumberOfRowsChanged

− tile

Drawing	− drawRow:clipRect:

− drawGridInClipRect:

− highlightSelectionInClipRect:

Scrolling	− scrollRowToVisible:

− scrollColumnToVisible:

Text delegate methods	− textShouldBeginEditing:

− textDidBeginEditing:

− textDidChange

− textShouldEndEditing:

− textDidEndEditing:

Setting the delegate	− setDelegate:

− delegate

Instance Methods

addTableColumn:

− (void)addTableColumn:(NSTableColumn *)aColumn

Appends aColumn to the receiver.

See also:	− sizeLastColumnToFit, − sizeToFit, − removeTableColumn:

allowsColumnReordering

− (BOOL)allowsColumnReordering

Returns YES if the receiver allows the user to rearrange columns by dragging their headers, NO otherwise. The default is YES. You can rearrange columns programmatically regardless of this setting.

See also:	− moveColumn:toColumn:, − setAllowsColumnReordering:

allowsColumnResizing

− (BOOL)allowsColumnResizing

Returns YES if the receiver allows the user to resize columns by dragging between their headers, NO otherwise. The default is YES. You can resize columns programmatically regardless of this setting.

See also:	− setWidth: (NSTableColumn), − setAllowsColumnResizing:

allowsColumnSelection

− (BOOL)allowsColumnSelection

Returns YES if the receiver allows the user to select columns by clicking their headers, NO otherwise. The default is YES. You can select columns programmatically regardless of this setting.

See also:	− selectColumn:byExtendingSelection:, − allowsColumnReordering, − setAllowsColumnSelection:

allowsEmptySelection

− (BOOL)allowsEmptySelection

Returns YES if the receiver allows the user to select zero columns or rows, NO otherwise. The default is YES.

You can not set an empty selection programmatically if this setting is NO, unlike with the other settings that affect selection behavior.

See also:	− deselectAll:, − deselectColumn:, − deselectRow:, − setAllowsEmptySelection:

allowsMultipleSelection

− (BOOL)allowsMultipleSelection

Returns YES if the receiver allows the user to select more than one column or row at a time, NO otherwise. The default is NO. You can select multiple columns or rows programmatically regardless of this setting.

See also:	− selectColumn:byExtendingSelection:, − selectRow:byExtendingSelection:, − setAllowsMultipleSelection:

autoresizesAllColumnsToFit

− (BOOL)autoresizesAllColumnsToFit

Returns YES if the receiver proportionally resizes its columns to fit when its superview’s frame changes, NO if it only resizes the last column.

See also:	− setAutoresizesAllColumnsToFit:, − sizeLastColumnToFit, − sizeToFit

backgroundColor

− (NSColor *)backgroundColor

Returns the color used to draw the background of the receiver. The default background color is light gray.

See also:	− setBackgroundColor:

clickedColumn

− (int)clickedColumn

Returns the index of the column the user clicked to trigger an action message. The return value of this method is meaningful only in the target’s implementation of the action or double-action method.

See also:	− clickedRow, − setAction: (NSControl), − setDoubleAction:

clickedRow

− (int)clickedRow

Returns the index of the row the user clicked to trigger an action message. The return value of this method is meaningful only in the target’s implementation of the action or double-action method.

See also:	− clickedColumn, − setAction: (NSControl), − setDoubleAction:

columnAtPoint:

− (int)columnAtPoint:(NSPoint)aPoint

Returns the index of the column that aPoint lies in, or −1 if aPoint lies outside the receiver’s bounds.

See also:	− rowAtPoint:

columnsInRect:

− (NSRange)columnsInRect:(NSRect)aRect

Returns a range of indices for the receiver’s columns that lie wholly or partially within the horizontal boundaries of aRect; the location of the range is the first such column’s index, and the length is the number of columns that lie in aRect. Both the width and height of aRect must be nonzero values, or columnsInRect: returns an NSRange whose length is zero.

See also:	− rowsInRect:

columnWithIdentifier:

− (int)columnWithIdentifier:(id)anObject

Returns the index of the first column in the receiver whose identifier is equal to anObject, when compared using isEqual:, or −1 if no columns are found with the specified identifier.

See also:	− tableColumnWithIdentifier:

cornerView

− (NSView *)cornerView

Returns the NSView used to draw the area to the left of the column headers and above the vertical scroller of the enclosing NSScrollView. This is by default a simple view that merely fills in its frame, but you can replace it with a custom view using setCornerView:.

See also:	− headerView

dataSource

− (id)dataSource

Returns the object that provides the data displayed by the receiver. See the class description and the NSTableDataSource informal protocol specification for more information.

See also:	− setDataSource:

delegate

− (id)delegate

Returns the receiver’s delegate.

See also:	− setDelegate:

deselectAll:

− (void)deselectAll:(id)sender

Deselects all selected rows or columns if empty selection is allowed, otherwise does nothing. Posts NSTableViewSelectionDidChangeNotification to the default notification center if the selection does in fact change.

As a target-action method, deselectAll: checks with the delegate before changing the selection, using selectionShouldChangeInTableView:.

See also:	− allowsEmptySelection, − selectAll:, − selectColumn:byExtendingSelection:

deselectColumn:

− (void)deselectColumn:(int)columnIndex

Deselects the column at columnIndex if it’s selected, regardless of whether empty selection is allowed. If the selection does in fact change, posts NSTableViewSelectionDidChangeNotification to the default notification center.

If the indicated column was the last column selected by the user, the column nearest it effectively becomes the last selected column. In case of a tie, priority is given to the column on the left.

This method doesn’t check with the delegate before changing the selection.

See also:	− selectedColumn, − allowsEmptySelection, − selectRow:byExtendingSelection:

deselectRow:

− (void)deselectRow:(int)rowIndex

Deselects the row at rowIndex if it’s selected, regardless of whether empty selection is allowed. If the selection does in fact change, posts NSTableViewSelectionDidChangeNotification to the default notification center.

If the indicated row was the last row selected by the user, the row nearest it effectively becomes the last selected row. In case of a tie, priority is given to the row above.

This method doesn’t check with the delegate before changing the selection.

See also:	− selectedRow, − allowsEmptySelection

doubleAction

− (SEL)doubleAction

Returns the message sent to the target when the user double-clicks a column header or an uneditable cell.

See also:	− action (NSControl), − target (NSControl), − setDoubleAction:

drawGridInClipRect:

− (void)drawGridInClipRect:(NSRect)aRect

Draws the grid lines within aRect, using the grid color set with setGridColor:. This method draws a grid regardless of whether the receiver is set to draw one automatically.

Subclasses can override this method to draw grid lines other than the standard ones.

See also:	− gridColor, − setIntercellSpacing:, − drawsGrid, − drawRow:clipRect:, − highlightSelectionInClipRect:

drawRow:clipRect:

− (void)drawRow:(int)rowIndex clipRect:(NSRect)clipRect

Draws the cells for the row at rowIndex in the columns that intersect clipRect. Sends tableView:willDisplayCell:forTableColum:row: to the delegate before drawing each cell.

Subclasses can override this method to customize their appearance.

See also:	− columnsInRect:, − highlightSelectionInClipRect:, − drawGridInClipRect:

drawsGrid

− (BOOL)drawsGrid

Returns YES if the receiver draws grid lines around cells, NO if it doesn’t. The default is YES.

See also:	− gridColor, − drawGridInClipRect:, − setDrawsGrid

editColumn:row:withEvent:select:

− (void)editColumn:(int)columnIndex

row:(int)rowIndex

withEvent:(NSEvent *)theEvent

select:(BOOL)flag

Edits the cell at columnIndex and rowIndex, selecting its entire contents if flag is YES. This method is invoked automatically in response to user actions; you should rarely need to invoke it directly. theEvent is usually the mouse event that triggered editing; it can be nil when starting an edit programmatically.

This method scrolls the receiver so that the cell is visible, sets up the field editor, and sends selectWithFrame:inView:editor:delegate:start:length: and editWithFrame:inView:editor:delegate:event: to the field editor’s NSCell object with the NSTableView as the text delegate.

See also:	− isEditable, − editedColumn, − editedRow

editedColumn

− (int)editedColumn

If sent during editColumn:row:withEvent:select: returns the index of the column being edited; otherwise returns −1.

editedRow

− (int)editedRow

If sent during editColumn:row:withEvent:select: returns the index of the row being edited; otherwise returns −1.

frameOfCellAtColumn:row:

− (NSRect)frameOfCellAtColumn:(int)columnIndex row:(int)rowIndex

Returns a rectangle locating the cell that lies at the intersection of columnIndex and rowIndex. Returns NSZeroRect if columnIndex or rowIndex are greater than the number of columns or rows in the NSTableView.

The result of this method is used in a drawWithFrame:inView: message to the NSTableColumn’s data cell.

See also:	− rectOfColumn:, − rectOfRow:

gridColor

− (NSColor *)gridColor

Returns the color used to draw grid lines. The default color is gray.

See also:	− drawsGrid, − drawGridInClipRect:, − setGridColor:

headerView

− (NSTableHeaderView *)headerView

Returns the NSTableHeaderView used to draw headers over columns, or nil if the NSTableView has no header view. See the class description and the NSTableHeaderView class specification for more information.

See also:	− setHeaderView:

highlightSelectionInClipRect:

− (void)highlightSelectionInClipRect:(NSRect)clipRect

Highlights the region of the receiver in clipRect. This method is invoked before drawRow:clipRect:.

Subclasses can override this method to change the manner in which they highlight selections.

See also:	− drawGridInClipRect:

initWithFrame:

− (id)initWithFrame:(NSRect)frameRect

Initializes a newly allocated NSTableView with frameRect as its frame rectangle. The new NSTableView has a header view but has no columns; you can create NSTableColumn objects, set their titles and attributes, and add them to the new NSTableView with addTableColumn:. You must also set the NSTableView up in an NSScrollView with NSScrollView’s setDocView: method. This is the designated initializer for the NSTableView class. Returns self.

It’s usually more convenient to create an NSTableView using Interface Builder. Interface Builder lets you create an NSTableView already embedded in an NSScrollView, add and name the columns, and set up a data source.

intercellSpacing

− (NSSize)intercellSpacing

Returns the horizontal and vertical spacing between cells. The default spacing is (3.0, 2.0).

See also:	− setDrawsGrid:, − setIntercellSpacing:

isColumnSelected:

− (BOOL)isColumnSelected:(int)columnIndex

Returns YES if the column at columnIndex is selected, NO otherwise.

See also:	− selectedColumn, − selectedColumnEnumerator, − selectColumn:byExtendingSelection:

isRowSelected:

− (BOOL)isRowSelected:(int)rowIndex

Returns YES if the row at rowIndex is selected, NO otherwise.

See also:	− selectedRow, − selectedRowEnumerator, − selectRow:byExtendingSelection:

moveColumn:toColumn:

− (void)moveColumn:(int)columnIndex toColumn:(int)newIndex

Moves the column and heading at columnIndex to newIndex, inserting the column before the existing column at newIndex.

This method posts NSTableViewColumnDidMoveNotification to the default notification center.

noteNumberOfRowsChanged

− (void)noteNumberOfRowsChanged

Informs the receiver that the number of records in its data source has changed, allowing the receiver to update the scrollers in its NSScrollView without actually reloading data into the receiver. It’s useful for a data source that continually receives data in the background over a period of time, in which case the NSTableView can remain responsive to the user while the data is received.

See the NSTableDataSource informal protocol specification for information on the messages an NSTableView sends to its data source.

See also:	− reloadData, − numberOfRowsInTableView: (NSTableDataSource informal protocol)

numberOfColumns

− (int)numberOfColumns

Returns the number of columns in the receiver.

See also:	− numberOfRows

numberOfRows

− (int)numberOfRows

Returns the number of rows in the receiver.

See also:	− numberOfColumns, − numberOfRowsInTableView: (NSTableDataSource informal protocol)

numberOfSelectedColumns

− (int)numberOfSelectedColumns

Returns the number of selected columns.

See also:	− numberOfSelectedRows, − selectedColumnEnumerator

numberOfSelectedRows

− (int)numberOfSelectedRows

Returns the number of selected rows.

See also:	− numberOfSelectedColumns, − selectedRowEnumerator

rectOfColumn:

− (NSRect)rectOfColumn:(int)columnIndex

Returns the rectangle containing the column at columnIndex. Raises an NSInternalInconsistencyException if columnIndex lies outside the range of valid column indices for the NSTableView.

See also:	− frameOfCellAtColumn:row:, − rectOfRow:, − headerRectOfColumn: (NSTableHeaderView)

rectOfRow:

− (NSRect)rectOfRow:(int)rowIndex

Returns the rectangle containing the row at rowIndex. Raises an NSInternalInconistencyException if columnIndex lies outside the range of valid column indices for the receiver.

See also:	− frameOfCellAtColumn:row:, − rectOfColumn:

reloadData

− (void)reloadData

Marks the receiver as needing redisplay, so that it will reload the data for visible cells and draw the new values.

See also:	− noteNumberOfRowsChanged

removeTableColumn:

− (void)removeTableColumn:(NSTableColumn *)aTableColumn

Deletes aTableColumn from the receiver.

See also:	− sizeLastColumnToFit, − sizeToFit, − addTableColumn:

rowAtPoint:

− (int)rowAtPoint:(NSPoint)aPoint

Returns the index of the row that aPoint lies in, or −1 if aPoint lies outside the receiver’s bounds.

See also:	− columnAtPoint:

rowHeight

− (float)rowHeight

Returns the height of each row in the receiver. The default row height is 16.0.

See also:	− setRowHeight:

rowsInRect:

− (NSRange)rowsInRect:(NSRect)aRect

Returns a range of indices for the rows that lie wholly or partially within the vertical boundaries of aRect; the location of the range is the first such row’s index, and the length is the number of rows that lie in aRect. Both the width and height of aRect must be nonzero values, or columnsInRect: returns an NSRange whose length is zero.

See also:	− columnsInRect:

scrollColumnToVisible:

− (void)scrollColumnToVisible:(int)columnIndex

Scrolls the receiver and header view horizontally in an enclosing NSClipView so that the column specified by columnIndex is visible.

See also:	− scrollRowToVisible:, − scrollToPoint: (NSClipView)

scrollRowToVisible:

− (void)scrollRowToVisible:(int)rowIndex

Scrolls the receiver vertically in an enclosing NSClipView so that the row specified by rowIndex is visible.

See also:	− scrollColumnToVisible:, − scrollToPoint: (NSClipView)

selectAll:

− (void)selectAll:(id)sender

If the table allows multiple selection, selects all rows or all columns, according to whether rows or columns were most recently selected; otherwise does nothing. Posts NSTableViewSelectionDidChangeNotification to the default notification center if the selection does in fact change.

As a target-action method, selectAll: checks with the delegate before changing the selection.

See also:	− allowsMultipleSelection, − deselectAll:, − selectColumn:byExtendingSelection:

selectColumn:byExtendingSelection:

− (void)selectColumn:(int)columnIndex byExtendingSelection:(BOOL)flag

Selects the column at columnIndex, regardless of whether column selection is allowed. If flag is NO, deselects all before selecting the new column. Raises an NSInternalInconistencyException if multiple selection isn’t allowed and flag is YES. Posts NSTableViewSelectionDidChangeNotification to the default notification center if the selection does in fact change.

This method doesn’t check with the delegate before changing the selection. If the user is editing a cell, editing is simply forced to end and the selection is changed.

See also:	− allowsMultipleSelection, − allowsColumnSelection, − deselectColumn:, − selectedColumn, − selectRow:byExtendingSelectoin:

selectedColumn

− (int)selectedColumn

Returns the index of the last column selected or added to the selection, or −1 if no column is selected.

See also:	− selectedColumnEnumerator, − numberOfSelectedColumns, − selectColumn:byExtendingSelection:, − deselectColumn:

selectedColumnEnumerator

− (NSEnumerator *)selectedColumnEnumerator

Returns an object that enumerates the indices of the selected columns as NSNumbers.

See also:	− numberOfSelectedColumns, − selectedColumn, − selectedRowEnumerator

selectedRow

− (int)selectedRow

Returns the index of the last row selected or added to the selection, or −1 if no row is selected.

See also:	− selectedRowEnumerator, − numberOfSelectedRows, − selectRow:byExtendingSelection: − deselectRow:

selectedRowEnumerator

− (NSEnumerator *)selectedRowEnumerator

Returns an object that enumerates the indices of the selected rows as NSNumbers.

See also:	− numberOfSelectedRows, − selectedRow, − selectedColumnEnumerator

selectRow:byExtendingSelection:

− (void)selectRow:(int)rowIndex byExtendingSelection:(BOOL)flag

Selects the row at rowIndex. If flag is NO, deselects all before selecting the new row. Raises an NSInternalInconistencyException if multiple selection isn’t allowed and flag is YES. Posts NSTableViewSelectionDidChangeNotification to the default notification center if the selection does in fact change.

This method doesn’t check with the delegate before changing the selection. If the user is editing a cell, editing is simply forced to end and the selection is changed.

See also:	− allowsMultipleSelection, − allowsRowSelection, − deselectRow:, − selectedRow, − selectColumn:byExtendingSelectoin:

setAllowsColumnReordering:

− (void)setAllowsColumnReordering:(BOOL)flag

Controls whether the user can drag column headers to reorder columns. If flag is YES the user can reorder columns; if flag is NO the user can’t. The default is YES. You can rearrange columns programmatically regardless of this setting.

See also:	− moveColumn:toColumn:, − allowsColumnReordering

setAllowsColumnResizing:

− (void)setAllowsColumnResizing:(BOOL)flag

Controls whether the user can resize columns by dragging between headers. If flag is YES the user can resize columns; if flag is NO the user can’t. The default is YES. You can resize columns programmatically regardless of this setting.

See also:	− setWidth: (NSTableColumn), − allowsColumnResizing

setAllowsColumnSelection:

− (void)setAllowsColumnSelection:(BOOL)flag

Controls whether the user can select an entire column by clicking its header. If flag is YES the user can select columns; if flag is NO the user can’t. The default is YES. You can select columns programmatically regardless of this setting.

See also:	− selectColumn:byExtendingSelection:, − setAllowsColumnReordering:, − allowsColumnSelection

setAllowsEmptySelection:

− (void)setAllowsEmptySelection:(BOOL)flag

Controls whether the receiver allows zero rows or columns to be selected. If flag is YES empty selection is allowed; if flag is NO it isn’t. The default is YES.

You can not set an empty selection programmatically if empty selection is disallowed, unlike with the other settings that affect selection behavior.

See also:	− deselectAll:, − deselectColumn:, − deselectRow:, − allowsEmptySelection

setAllowsMultipleSelection:

− (void)setAllowsMultipleSelection:(BOOL)flag

Controls whether the user can select more than one row or column at a time. If flag is YES the user can select multiple rows or columns; if flag is NO the user can’t. The default is NO. You can select multiple columns or rows programmatically regardless of this setting.

See also:	− selectColumn:byExtendingSelection:, − selectRow:byExtendingSelection:, − allowsMultipleSelection

setAutoresizesAllColumnsToFit

− (void)setAutoresizesAllColumnsToFit:(BOOL)flag

Controls whether the receiver proportionally resizes its columns to fit when its superview’s frame changes. If flag is YES, the difference in width is distributed among the receiver’s table columns; if flag is NO, only the last column is resized to fit.

See also:	− autoresizesAllColumnsToFit, − sizeLastColumnToFit, − sizeToFit

setBackgroundColor:

− (void)setBackgroundColor:(NSColor *)aColor

Sets the receiver’s background color to aColor.

See also:	− setNeedsDisplay: (NSView), − backgroundColor

setCornerView:

− (void)setCornerView:(NSView *)aView

Sets the receiver’s corner view to aView. The default corner view merely draws a bezeled rectangle using a blank NSTableHeaderCell, but you can replace it with a custom view that displays an image or with a control that can handle mouse events, such as a select-all button. Your custom corner view should be as wide as a vertical NSScroller and as tall as the receiver’s header view.

See also:	− setHeaderView:, − cornerView

setDataSource:

− (void)setDataSource:(id)anObject

Sets the receiver’s data source to anObject and invokes tile. anObject should implement the appropriate methods of the NSTableDataSource informal protocol.

This method raises an NSInternalInconistencyException if anObject doesn’t respond to either numberOfRowsInTableView: or tableView:objectValueForTableColumn:row:.

See also:	− dataSource

setDelegate:

− (void)setDelegate:(id)anObject

Sets the receiver’s delegate to anObject.

See also:	− delegate

setDoubleAction:

− (void)setDoubleAction:(SEL)aSelector

Sets to aSelector the message sent to the target when the user double-clicks an uneditable cell or a column header. If the double-clicked cell is editable, this message isn’t sent and the cell is edited instead. You can use this method to implement features such as sorting records according to the column that was double-clicked.

See also:	− setAction: (NSControl), − setTarget: (NSControl), − doubleAction

setDrawsGrid:

− (void)setDrawsGrid:(BOOL)flag

Controls whether the receiver draws grid lines around cells. If flag is YES it does; if flag is NO it doesn’t. The default is YES.

See also:	− setGridColor:, − drawGridInClipRect:, − drawsGrid

setGridColor:

− (void)setGridColor:(NSColor *)aColor

Sets the color used to draw grid lines to aColor. The default color is gray.

See also:	− setDrawsGrid:, − drawGridInClipRect:, − gridColor

setHeaderView:

− (void)setHeaderView:(NSTableHeaderView *)aHeaderView

Sets the receiver’s header view to aHeaderView.

See also:	− setCornerView:, − headerView

setIntercellSpacing:

− (void)setIntercellSpacing:(NSSize)aSize

Sets the width and height between cells to those in aSize and redisplays the receiver. The default intercell spacing is (3.0, 2.0).

See also:	− intercellSpacing

setRowHeight:

− (void)setRowHeight:(float)rowHeight

Sets the height for rows to rowHeight and invokes tile.

See also:	− rowHeight

sizeLastColumnToFit

− (void)sizeLastColumnToFit

Resizes the last column if there’s room so that the receiver fits exactly within its enclosing NSClipView.

See also:	− setAutoresizesAllColumnsToFit:, − minWidth (NSTableColumn), − maxWidth (NSTableColumn)

sizeToFit

− (void)sizeLastColumnToFit

Resizes columns if there’s room so that all fit in the enclosing NSClipView and so all but the last are just wide enough to display their titles and values. This method first sets all columns to their minimum widths; then divides among the columns the space remaining to fill the width of the NSScrollView.

See also:	− setAutoresizesAllColumnsToFit:, − minWidth (NSTableColumn), − maxWidth (NSTableColumn)

tableColumns

− (NSArray *)tableColumns

Returns the NSTableColumns in the receiver.

tableColumnWithIdentifier:

− (NSTableColumn *)tableColumnWithIdentifier:(id)anObject

Returns the NSTableColumn object for the first column whose identifier is equal to anObject, as compared using isEqual:, or nil if no columns are found with the specified identifier.

See also:	− columnWithIdentifier:

textDidBeginEditing:

− (void)textDidBeginEditing:(NSNotification *)aNotification

Posts an NSControlTextDidBeginEditingNotification to the default notification center, as described in the NSControl class specification. aNotification is the NSNotification posted by the field editor; see the NSText class specifications for more information on this text delegate method.

See also:	− textShouldBeginEditing:

textDidChange:

− (void)textDidChange:(NSNotification *)aNotification

Sends textDidChange: to the edited cell, and posts an NSControlTextDidChangeNotification to the default notification center, as described in the NSControl class specification. aNotification is the NSNotification posted by the field editor; see the NSText class specifications for more information on this text delegate method.

textDidEndEditing:

− (void)textDidEndEditing:(NSNotification *)aNotification

Updates the data source based on the newly-edited value and selects another cell for editing if possible according to the character that ended editing (Return, Tab, Backtab). aNotification is the NSNotification posted by the field editor; see the NSText class specifications for more information on this text delegate method.

See also:	− textShouldEndEditing:

textShouldBeginEditing:

− (BOOL)textShouldBeginEditing:(NSNotification *)aNotification

Queries the delegate using control:textShouldBeginEditing:, returning the delegate’s response, or simply returning YES to allow editing if the delegate doesn’t respond to that method. aNotification is the NSNotification posted by the field editor; see the NSText class specifications for more information on this text delegate method.

See also:	− textDidBeginEditing:

textShouldEndEditing:

− (BOOL)textShouldEndEditing:(NSNotification *)aNotification

Validates the cell being edited and queries the delegate using control:textShouldEndEditing:, returning the delegate’s response if it responds to that method. If it doesn’t, it returns YES if the cell’s new value is valid and NO if it isn’t. aNotification is the NSNotification posted by the field editor; see the NSText class specifications for more information on this text delegate method.

See also:	− textDidEndEditing:

tile

− (void)tile

Properly sizes the receiver and its header view, and marks it as needing display. Also resets cursor rectangles for the header view and line scroll amounts for the NSScrollView.

See also:	− setNeedsDisplay: (NSView)

Methods Implemented By the Delegate

selectionShouldChangeInTableView:

− (BOOL)selectionShouldChangeInTableView:(NSTableView *)aTableView

Returns YES to permit aTableView to change its selection (typically a row being edited), NO to deny permission. The user can select and edit different cells within the same row, but can’t select another row unless the delegate approves. The delegate can implement this method for complex validation of edited rows based on the values of any of their cells.

tableView:shouldEditTableColumn:row:

− (BOOL)tableView:(NSTableView *)aTableView

shouldEditTableColumn:(NSTableColumn *)aTableColumn

row:(int)rowIndex

Returns YES to permit aTableView to edit the cell at rowIndex in aTableColumn, NO to deny permission. The delegate can implement this method to disallow editing of specific cells.

tableView:shouldSelectRow:

− (BOOL)tableView:(NSTableView *)aTableView

shouldSelectRow:(int)rowIndex

Returns YES to permit aTableView to select the row at rowIndex, NO to deny permission. The delegate can implement this method to disallow selection of particular rows.

tableView:shouldSelectTableColumn:

− (BOOL)tableView:(NSTableView *)aTableView

shouldSelectTableColumn:(NSTableColumn *)aTableColumn

Returns YES to permit aTableView to select aTableColumn, NO to deny permission. The delegate can implement this method to disallow selection of particular columns.

tableView:willDisplayCell:forTableColumn:row:

− (void)tableView:(NSTableView *)aTableView

willDisplayCell:(id)aCell

forTableColumn:(NSTableColumn *)aTableColumn

row:(int)rowIndex

Informs the delegate that aTableView will display the cell at rowIndex in aTableColumn using aCell. The delegate can modify the display attributes of aCell to alter the appearance of the cell. Since aCell is reused for every row in aTableColumn, the delegate must set the display attributes both when drawing special cells and when drawing normal cells.

tableViewColumnDidMove:

− (void)tableViewColumnDidMove:(NSNotification *)aNotification

Informs the delegate that a column was moved by user action in the NSTableView. aNotification is an NSTableViewColumnDidMoveNotification.

tableViewColumnDidResize:

− (void)tableViewColumnDidResize:(NSNotification *)aNotification

Informs the delegate that a column was resized in the NSTableView. aNotification is an NSTableViewColumnDidResizeNotification.

tableViewSelectionDidChange:

− (void)tableViewSelectionDidChange:(NSNotification *)aNotification

Informs the delegate that the NSTableView’s selection has changed. aNotification is an NSTableViewSelectionDidChangeNotification.

tableViewSelectionIsChanging:

− (void)tableViewSelectionIsChanging:(NSNotification *)aNotification

Informs the delegate that the NSTableView’s selection is in the process of changing (typically because the user is dragging the mouse across a number of rows). aNotification is an NSTableViewSelectionIsChangingNotification.

Notifications

NSTableViewColumnDidMoveNotification

Posted whenever a column is moved by user action in the NSTableView. The notification contains:

Notification Object	The NSTableView in which a column moved.

Userinfo

Key	Value

NSOldColumn	The column’s original index (an NSNumber)

NSNewColumn	The column’s present index (an NSNumber)

See also:	− moveColumn:toColumn:

NSTableViewColumnDidResizeNotification

Posted whenever a column is resized in the NSTableView. The notification contains:

Notification Object	The NSTableView in which a column was resized.

Userinfo

Key	Value

NSOldWidth	The column’s original width (an NSNumber)

NSTableViewSelectionDidChangeNotification

Posted after the NSTableView’s selection changes. The notification contains:

Notification Object	The NSTableView whose selection changed.

Userinfo	None

NSTableViewSelectionIsChangingNotification

Posted as the NSTableView’s selection changes (while the mouse is still down). The notification contains:

Notification Object	The NSTableView whose selection is changing.

Userinfo	None


NSText

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSView : NSResponder : NSObject

Conforms To:	NSChangeSpelling

NSIgnoreMisspelledWords

NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSText.h

Purpose

NSText declares the most general programmatic interface for objects that manage text. You usually use one of its subclasses, NSTextView or NSCStringText, but both share the methods and other definitions of this class.

Principal Attributes

•	Supports rich text and graphics	•	Provides delegation and notification

•	Works with the Font Panel and menu	•	Works with the pasteboard

•	Works with the Services facility	•	Works with the spell-checking service

Creation

See the class description.

Commonly Used Methods

− readRTFDFromFile:	Reads an .rtf or .rtfd file.

− writeRTFDToFile:atomically:	Writes the receiver’s text to a file.

− string	Returns the receiver’s text, without attributes.

− RTFFromRange:	Returns the receiver’s text with attributes.

− RTFDFromRange:	Returns the receiver’s text with attributes and attachments.

Class Description

The NSText class declares the most general programmatic interface to objects that manage text. NSText is an abstract class with two concrete subclasses, NSCStringText and NSTextView. You can create an NSText object when constructing your application’s interface with Interface Builder, or at run time using initWithFrame:. For the most generic and portable use of text, this is the recommended approach. NSCStringText is most suitable for use when backward compatibility with the NEXTSTEP Text object is needed. NSTextView is a NeXT addition to the OpenStep specification that acts as the front end to NeXT’s revised text system. Instances of any of these classes are generically called text objects.

Text objects are used by the Application Kit wherever text appears in interface objects: A text object draws the title of a window, the commands in a menu, the title of a button, and the items in a browser. Your application can also create text objects for its own purposes.

The text classes are unlike most other classes in the Application Kit in the richness and complexity of their interface. One of their design goals is to provide a comprehensive set of text-handling features so that you’ll rarely need to create a subclass. Among other things, a text object can:

•	Control whether the user can select or edit text.

•	Control the font and layout characteristics of its text by working with the Font Panel and menu.

•	Let the user control the format of paragraphs by manipulating a ruler.

•	Control the color of its text and background.

•	Wrap text on a word or character basis.

•	Display graphic images within its text.

•	Write text to or read text from files in the form of RTFD—Rich Text Format files that contain TIFF or EPS images, or attached files.

•	Let another object, the delegate, dynamically control its properties.

•	Let the user copy and paste text within and between applications.

•	Let the user copy and paste font and format information between NSText objects.

•	Let the user check the spelling of words in its text.

Graphical user-interface building tools (such as Interface Builder) may give you access to text objects in several different configurations, such as those found in the NSTextField, NSForm, and NSScrollView objects. These classes configure a text object for their own specific purposes. Additionally, all NSTextFields, NSForms, NSButtons within the same window—in short, all objects that access a text object through associated cells—share the same text object, reducing the memory demands of an application. Thus, it’s generally best to use one of these classes whenever it meets your needs, rather than create text objects yourself. If one of these classes doesn’t provide enough flexibility for your purposes, you can create text objects programmatically.

Text objects typically work closely with various other objects. Some of these—such as the delegate or an embedded graphic object—require a degree of programming on your part. Others—such as the Font Panel, spell checker, or ruler—take no effort other than deciding whether the service should be enabled or disabled. Several of the following sections discuss these interrelationships.

Plain and Rich Text Objects

Text objects are differentiated into two groups: those that allow only one set of text attributes for all of their text, and those that allow multiple fonts, sizes, indents, and other attributes for different sets of characters and paragraphs. Text objects in the former group are called plain text objects, while those in the latter are called rich text objects. You can control whether a text object is plain or rich using the setRichText: method. Rich text objects are also capable of allowing the user to drag images and files into them. This behavior is controlled by the setImportsGraphics: method.

A rich NSText object can use RTF (Rich Text Format) as an interchange format. Not all RTF control words are supported: On input, an NSText object ignores any control word it doesn’t recognize; some of those it can read and interpret it doesn’t write out. The table below lists the RTF control words that any text object recognizes. Subclasses may recognize more.

Control Word	Read	Write

\ansi	yes	yes

\b	yes	yes

\cb	yes	yes

\cf	yes	yes

\colortbl	yes	yes

\dnn	yes	yes

\fin	yes	yes

\fn	yes	yes

\fonttbl	yes	yes

\fsn	yes	yes

\i	yes	yes

\lin	yes	yes

\margrn	yes	yes

\paperwn	yes	yes

\mac	yes	no

\margln	yes	yes

\par	yes	yes

\pard	yes	no

\pca	yes	no

\qc	yes	yes

\ql	yes	yes

\qr	yes	yes

\sn	yes	no

\tab	yes	yes

\upn	yes	yes

Notifying a Text Object’s Delegate

Many of an NSText object’s actions can be controlled through an associated object, the NSText object’s delegate. The delegate can be any object you choose, and one delegate can control multiple NSText objects. If it implements any of the following methods, the delegate receives the corresponding message at the appropriate time:

textShouldBeginEditing:

textDidBeginEditing:

textDidChange:

textShouldEndEditing:

textDidEndEditing:

Of special note are the two “textShould” methods. These methods are requests for permission. Any time a text object begins an operation that would change its text or attributes, it uses textShouldBeginEditing: to request approval for the change. The delegate can return YES to permit the change, or NO to forbid it. Similarly, textShouldEndEditing: enables the delegate to prevent a text object from ending editing, such as when it contains an invalid value.

Adding Graphics and Other Attachments to the Text

A rich text object may allow graphics or other file attachments to be embedded in the text. Each graphic is treated as a single (possibly large) “character”: The text’s line height and character placement are adjusted to accommodate the graphic. Graphics are embedded in the text in either of two ways: programmatically or directly through user actions. In the programmatic approach, graphic objects can be added using replaceRange:WithRTFD:, or through a more specific method defined by a subclass.

An alternate means of adding an image or other attachment to the text is for the user to drag an image or other file directly into the text object. The text object automatically creates an attachment object to manage the display of the image (the implementation of attachment differs between NSTextView and NSCStringText). This feature requires a rich text object that has been configured to receive dragged images using the setImportsGraphics: method.

Images that have been imported can be written as part of an RTFD document. RTFD documents use a file package, or directory, to store the components of the document (the “D” stands for “directory”). The file package has the name of the document plus an .rtfd extension. The file package always contains a file called TXT.rtf for the text of the document, and one or more TIFF or EPS files for the images, plus the files for other attachments. A text object can transfer information in an RTFD document to a file and read it from a file using the writeRTFDToFile:atomically: and readRTFDFromFile: methods.

Working with the Font Panel

Text objects are designed to work with the Application Kit’s font conversion system, defined by the NSFontPanel and NSFontManager classes. By default, a text object keeps the Font Panel updated with the first font in its selection, or of its typing attributes (defined below). It also changes the font in response to messages from the Font Panel and Font menu. Such changes apply to the selected text or typing attributes for a rich text object, or to all the text in a plain text object. You can turn this behavior off using the setUsesFontPanel: method. Doing so is recommended for a text object that serves as a field editor, for example.

Working with Rulers and Paragraph Styles

Text objects also provide for a ruler, by which the user can edit paragraph attributes such as indents and tabs. NSCStringText uses its own ruler object, and defines some methods for altering paragraph attributes. NSTextView works with the public NSRulerView class and uses the NSTextStorage and NSParagraphStyle classes to handle paragraph attributes. To show or hide a text object’s ruler, use the toggleRuler: action method. Similar to the Font Panel, NSTextView can be set not to use a ruler with the setUsesRuler: method.

Adopted Protocols

NSChangeSpelling	− changeSpelling:

NSIgnoreMisspelledWords	− ignoreSpelling:

Method Types

Creating instances	− initWithFrame:

Getting the characters	− string

Setting graphic attributes	− setBackgroundColor:

− backgroundColor

− setDrawsBackground:

− drawsBackground

Setting behavioral attributes	− setEditable:

− isEditable

− setSelectable:

− isSelectable

− setFieldEditor:

− isFieldEditor

− setRichText:

− isRichText

− setImportsGraphics:

− importsGraphics

Using the Font Panel and menu	− setUsesFontPanel:

− usesFontPanel

Using the ruler	− toggleRuler:

− isRulerVisible

Changing the selection	− setSelectedRange:

− selectedRange

Replacing text	− replaceCharactersInRange:withRTF:

− replaceCharactersInRange:withRTFD:

− replaceCharactersInRange:withString:

− setString:

Action methods for editing	− selectAll:

− copy:

− cut:

− paste:

− copyFont:

− pasteFont:

− copyRuler:

− pasteRuler:

− delete:

Changing the font	− changeFont:

− setFont:

− setFont:range:

− font

Setting text alignment	− setAlignment:

− alignCenter:

− alignLeft:

− alignRight:

− alignment

Setting text color	− setTextColor:

− setTextColor:range:

− textColor

Setting super- and subscripting	− superscript:

− subscript:

− unscript:

Underlining text	− underline:

Reading and writing RTF	− readRTFDFromFile:

− writeRTFDToFile:atomically:

− RTFDFromRange:

− RTFFromRange:

Checking spelling	− checkSpelling:

− showGuessPanel:

Constraining size	− setMaxSize:

− maxSize

− setMinSize:

− minSize

− setVerticallyResizable:

− isVerticallyResizable

− setHorizontallyResizable:

− isHorizontallyResizable

− sizeToFit

Scrolling	− scrollRangeToVisible:

Setting the delegate	− setDelegate:

− delegate

Instance Methods

alignCenter:

− (void)alignCenter:(id)sender

This action method applies center alignment to selected paragraphs (or all text if the receiver is a plain text object).

See also:	− alignLeft:, − alignRight:, − alignment, − setAlignment:

alignLeft:

− (void)alignLeft:(id)sender

This action method applies left alignment to selected paragraphs (or all text if the receiver is a plain text object).

See also:	− alignCenter:, − alignRight:, − alignment, − setAlignment:

alignRight:

− (void)alignRight:(id)sender

This action method applies right alignment to selected paragraphs (or all text if the receiver is a plain text object).

See also:	− alignLeft:, − alignCenter:, − alignment, − setAlignment:

alignment

− (NSTextAlignment)alignment

Returns the alignment of the first selected paragraph, or of all text for a plain text object. This value is one of:

NSLeftTextAlignment

NSRightTextAlignment

NSCenterTextAlignment

NSJustifiedTextAlignment

NSNaturalTextAlignment (realized as one of the above depending on the script)

backgroundColor

− (NSColor *)backgroundColor

Returns the receiver’s background color.

See also:	− drawsBackground, − setBackgroundColor:

changeFont:

− (void)changeFont:(id)sender

This action method changes the font of the selection for a rich text object, or of all text for a plain text object. If the receiver doesn’t use the Font Panel, however, this method does nothing.

This method changes the font by sending convertFont: messages to sender (which is presumed to be an NSFontManager or similarly capable object) and applying each NSFont returned to the appropriate text. If a rich text object’s selection contains multiple fonts, convertFont: is invoked for each contiguous range of characters that share a font. See the NSFontManager class specification for more information on font conversion.

See also:	− usesFontPanel

checkSpelling:

− (void)checkSpelling:(id)sender

This action method searches for a misspelled word in the receiver’s text. The search starts at the end of the selection and continues until it reaches a word suspected of being misspelled or the end of the text. If a word isn’t recognized by the spelling server. A showGuessPanel: message then opens the Guess panel and allows the user to make a correction or add the word to the local dictionary.

See also:	− showGuessPanel:

copy:

− (void)copy:(id)sender

This action method copies the selected text onto the general pasteboard, in as many formats as the receiver supports. A plain text object uses NSStringPboardType for plain text, and a rich text object also uses NSRTFPboardType.

See also:	− copyFont:, − copyRuler:, − cut:, − paste:

copyFont:

− (void)copyFont:(id)sender

This action method copies the font information for the first character of the selection (or for the insertion point) onto the font pasteboard, as NSFontPboardType.

See also:	− copy:, − copyRuler:, − cut:, − paste:

copyRuler:

− (void)copyRuler:(id)sender

This action method copies the paragraph style information for first selected paragraph onto the ruler pasteboard, as NSRulerPboardType, and expands the selection to paragraph boundaries.

See also:	− copy:, − copyFont:, − cut:, − paste:

cut:

− (void)cut:(id)sender

This action method deletes the selected text and places it onto the general pasteboard, in as many formats as the receiver supports. A plain text object uses NSStringPboardType for plain text, and a rich text object also uses NSRTFPboardType.

See also:	− delete:, − copy:, − copyFont:, − copyRuler:, − paste:

delegate

− (id)delegate

Returns the receiver’s delegate, or nil if it has none.

See also:	− setDelegate:

delete:

− (void)delete:(id)sender

This action method deletes the selected text.

See also:	− cut:

drawsBackground

− (BOOL)drawsBackground

Returns YES if the receiver draws its background, NO if it doesn’t.

See also:	− backgroundColor, − setDrawsBackground:

font

− (NSFont *)font

Returns the font of the first character in the receiver’s text, or of the insertion point if there’s no text.

See also:	− setFont:, − setFont:range:

importsGraphics

− (BOOL)importsGraphics

Returns YES if the receiver allows the user to import files by dragging, NO if it doesn’t. A text object that accepts dragged files is also a rich text object.

See also:	− isRichText, − setImportsGraphics:

initWithFrame:

− (id)initWithFrame:(NSRect)frameRect

Initializes the receiver with frameRect as its frame rectangle. This method actually substitutes an instance of a concrete subclass of NSText, such as NSCStringText or NSTextView, depending on the platform, and configures that instance to archive itself in a manner portable across OpenStep implementations.

isEditable

− (BOOL)isEditable

Returns YES if the receiver allows the user to edit text, NO if it doesn’t. You can change the receiver’s text programmatically regardless of this setting.

If the receiver is editable, it’s also selectable.

See also:	− isSelectable, − setEditable:

isFieldEditor

− (BOOL)isFieldEditor

Returns YES if the receiver interprets Tab, Shift-Tab, and Return (Enter) as cues to end editing, and possibly to change the first responder; no if it accepts them as text input. See the NSWindow class specification for more information on field editors. By default, NSText objects don’t behave as field editors.

See also:	− setFieldEditor:

isHorizontallyResizable

− (BOOL)isHorizontallyResizable

Returns YES if the receiver automatically changes its width to accommodate the width of its text, NO if it doesn’t.

See also:	− isVerticallyResizable, − setHorizontallyResizable

isRichText

− (BOOL)isRichText

Returns YES if the receiver allows the user to apply attributes to specific ranges of the text, NO if it doesn’t.

See also:	− importsGraphics, − setRichText:

isRulerVisible

− (BOOL)isRulerVisible

Returns YES if the receiver’s enclosing scroll view shows its ruler, NO otherwise.

See also:	− usesRuler, − toggleRuler:

isSelectable

− (BOOL)isSelectable

Returns YES if the receiver allows the user to select text, NO if it doesn’t.

See also:	− isEditable, − setSelectable:

isVerticallyResizable

− (BOOL)isVerticallyResizable

Returns YES if the receiver automatically changes its height to accommodate the height of its text, NO if it doesn’t.

See also:	− isHorizontallyResizable, − setVerticallyResizable

maxSize

− (NSSize)maxSize

Returns the receiver’s maximum size.

See also:	− minSize, − setMaxSize:

minSize

− (NSSize)minSize

Returns the receiver’s minimum size.

See also:	− maxSize, − setMinSize:

paste:

− (void)paste:(id)sender

This action method pastes text from the general pasteboard at the insertion point or over the selection.

See also:	− copy:, − cut:, − pasteFont:, − pasteRuler:

pasteFont:

− (void)pasteFont:(id)sender

This action method pastes font information from the font pasteboard onto the selected text or insertion point of a rich text object, or over all text of a plain text object.

See also:	− copyFont:, − pasteRuler:

pasteRuler:

− (void)pasteRuler:(id)sender

This action method pastes paragraph style information from the ruler pasteboard onto the selected paragraphs of a rich text object. It doesn’t apply to a plain text object.

See also:	− copyFont:, − pasteRuler:

readRTFDFromFile:

− (BOOL)readRTFDFromFile:(NSString *)path

Attempts to read the RTFD file at path, returning YES if successful and NO if not. path should be the path for an .rtf file or an .rtfd file wrapper, not for the RTF file within an .rtfd file wrapper.

See also:	− writeRTFDToFile:atomically:

replaceCharactersInRange:withRTF:

− (void)replaceCharactersInRange:(NSRange)aRange withRTF:(NSData *)rtfData

Replaces the characters in aRange with RTF text interpreted from rtfData. This method applies only to rich text objects.

See also:	− replaceCharactersInRange:withRTFD:, − replaceCharactersInRange:withString:

replaceCharactersInRange:withRTFD:

− (void)replaceCharactersInRange:(NSRange)aRange withRTFD:(NSData *)rtfdData

Replaces the characters in aRange with RTFD text interpreted from rtfdData. This method applies only to rich text objects.

See also:	− replaceCharactersInRange:withRTF:, − replaceCharactersInRange:withString:

replaceCharactersInRange:withString:

− (void)replaceCharactersInRange:(NSRange)aRange withString:(NSString *)aString

Replaces the characters in aRange with aString. For a rich text object, the text of aString is assigned the formatting attributes of the first character of the text it replaces, or of the character immediately before aRange if the range’s length is zero. If the range’s location is zero, the formatting attributes of the first character in the receiver are used.

See also:	− replaceCharactersInRange:withRTF:, − replaceCharactersInRange:withRTFD:

RTFDFromRange:

− (NSData *)RTFDFromRange:(NSRange)aRange

Returns an NSData object that contains an RTFD stream corresponding to the characters and attributes within aRange. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

When writing data to the pasteboard, you can use the NSData object as the first argument to NSPasteboard’s setData:forType: method, with a second argument of NSRTFDPboardType.

See also:	− RTFFromRange:

RTFFromRange:

− (NSData *)RTFFromRange:(NSRange)range

Returns an NSData object that contains an RTF stream corresponding to the characters and attributes within aRange, omitting any attachment characters and attributes. Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters.

When writing data to the pasteboard, you can use the NSData object as the first argument to NSPasteboard’s setData:forType: method, with a second argument of NSRTFPboardType.

See also:	− RTFDFromRange:documentAttributes:

scrollRangeToVisible:

− (void)scrollRangeToVisible:(NSRange)aRange

Scrolls the receiver in its enclosing scroll view so that the first characters of aRange are visible.

selectAll:

− (void)selectAll:(id)sender

This action method selects all of the receiver’s text.

selectedRange

− (NSRange)selectedRange

Returns the range of selected characters.

See also:	− setSelectedRange:

setAlignment:

− (void)setAlignment:(NSTextAlignment)mode

Sets the alignment of all the receiver’s text to mode, which may be one of:

NSLeftTextAlignment

NSRightTextAlignment

NSCenterTextAlignment

NSJustifiedTextAlignment

NSNaturalTextAlignment (realized as one of the above depending on the script)

See also:	− alignment, − alignLeft:, − alignCenter:, − alignRight:

setBackgroundColor:

− (void)setBackgroundColor:(NSColor *)aColor

Sets the receiver’s background color to aColor.

See also:	− setDrawsBackground:, − backgroundColor

setDelegate:

− (void)setDelegate:(id)anObject

Sets the receiver’s delegate to anObject, without retaining it.

See also:	− delegate

setDrawsBackground:

− (void)setDrawsBackground:(BOOL)flag

Controls whether the receiver draws its background. If flag is YES, the receiver fills its background with the background color; if flag is NO, it doesn’t.

See also:	− setBackgroundColor:, − drawsBackground

setEditable:

− (void)setEditable:(BOOL)flag

Controls whether the receiver allows the user to edit its text. If flag is YES, the receiver allows the user to edit text and attributes; if flag is NO, it doesn’t. You can change the receiver’s text programmatically regardless of this setting. If the receiver is made editable, it’s also made selectable. NSText objects are by default editable.

See also:	− setSelectable:, − isEditable

setFieldEditor:

− (void)setFieldEditor:(BOOL)flag

Controls whether the receiver interprets Tab, Shift-Tab, and Return (Enter) as cues to end editing, and possibly to change the first responder. If flag is YES, it does; if flag is NO, it doesn’t, instead accepting these characters as text input. See the NSWindow class specification for more information on field editors. By default, NSText objects don’t behave as field editors.

See also:	− isFieldEditor

setFont:

− (void)setFont:(NSFont *)aFont

Sets the font of all the receiver’s text to aFont.

See also:	− setFont:range:, − font

setFont:range:

− (void)setFont:(NSFont *)aFont range:(NSRange)aRange

Sets the font of characters within aRange to aFont. This method applies only to a rich text object.

See also:	− setFont:, − font

setHorizontallyResizable:

− (void)setHorizontallyResizable:(BOOL)flag

Controls whether the receiver changes its width to fit the width of its text. If flag is YES it does; if flag is NO it doesn’t.

See also:	− setVerticallyResizable:, − isHorizontallyResizable

setImportsGraphics:

− (void)setImportsGraphics:(BOOL)flag

Controls whether the receiver allows the user to import files by dragging. If flag is YES, it does; if flag is NO, it doesn’t. If the receiver is set to accept dragged files, it’s also made a rich text object. Subclasses may or may not accept dragged files by default.

See also:	− setRichText:, − importsGraphics

setMaxSize:

− (void)setMaxSize:(NSSize)aSize

Sets the receiver’s maximum size to aSize.

See also:	− setMinSize:, − maxSize

setMinSize:

− (void)setMinSize:(NSSize)aSize

Sets the receiver’s minimum size to aSize.

See also:	− setMaxSize:, − minSize

setRichText:

− (void)setRichText:(BOOL)flag

Controls whether the receiver allows the user to apply attributes to specific ranges of the text. If flag is YES it does; if flag is NO it doesn’t. If flag is NO, the receiver is also set not to accept dragged files. Subclasses may or may not let the user apply multiple attributes to the text and accept drag files by default.

See also:	− isRichText, − setImportsGraphics:

setSelectable:

− (void)setSelectable:(BOOL)flag

Controls whether the receiver allows the user to select its text. If flag is YES, the receiver allows the user to select text; if flag is NO, it doesn’t. You can set selections programmatically regardless of this setting. If the receiver is made not selectable, it’s also made not editable. NSText objects are by default editable and selectable.

See also:	− setEditable:, − isSelectable

setSelectedRange:

− (void)setSelectedRange:(NSRange)aRange

Selects the receiver’s characters within aRange.

See also:	− selectedRange

setString:

− (void)setString:(NSString *)aString

Replaces the receiver’s entire text with aString, applying the formatting attributes of the old first character to its new contents.

setTextColor:

− (void)setTextColor:(NSColor *)color

Sets the text color of all characters in the receiver to aColor. Removes the text color attribute if aColor is nil.

See also:	− setTextColor:range − textColor:

setTextColor:range:

− (void)setTextColor:(NSColor *)aColor range:(NSRange)aRange

Sets the text color of characters within aRange to aColor. Removes the text color attribute if aColor is nil. This method applies only to rich text objects.

See also:	− setTextColor: − textColor:

setUsesFontPanel:

− (void)setUsesFontPanel:(BOOL)flag

Controls whether the receiver uses the Font Panel and Font menu. If flag is YES, the receiver responds to messages from the Font Panel and from the Font menu, and updates the Font Panel with the selection font whenever it changes. If flag is NO the receiver doesn’t do any of this. By default, an NSText object uses the Font Panel and menu.

See also:	− usesFontPanel

setVerticallyResizable:

− (void)setVerticallyResizable:(BOOL)flag

Controls whether the receiver changes its height to fit the height of its text. If flag is YES it does; if flag is NO it doesn’t.

See also:	− setHorizontallyResizable:, − isVerticallyResizable

showGuessPanel:

− (void)showGuessPanel:(id)sender

This action method opens the Spelling panel, allowing the user to make a correction during spell checking.

See also:	− checkSpelling:

sizeToFit

− (void)sizeToFit

Resizes the receiver to fit its text.

See also:	− isHorizontallyResizable, − isVerticallyResizable

string

− (NSString *)string

Returns the characters of the receiver’s text.

See also:	− setString:

subscript:

− (void)subscript:(id)sender

This action method applies a subscript attribute to selected text (or all text if the receiver is a plain text object), lowering its baseline offset by a predefined amount.

See also:	− subscript:, − unscript:, − lowerBaseline: (NSTextView)

superscript:

− (void)superscript:(id)sender

This action method applies a superscript attribute to selected text (or all text if the receiver is a plain text object), raising its baseline offset by a predefined amount.

See also:	− subscript:, − unscript:, − raiseBaseline: (NSTextView)

textColor

− (NSColor *)textColor

Returns the color of the receiver’s first character, or for the insertion point if there’s no text.

See also:	− setTextColor:, − setTextColor:range:

toggleRuler:

− (void)toggleRuler:(id)sender

This action method shows or hides the ruler, if the receiver is enclosed in a scroll view.

underline:

− (void)underline:(id)sender

This action method underlines selected text for a rich text object, or all text for a plain text object.

unscript:

− (void)unscript:(id)sender

This action method removes any superscripting or subscripting from selected text (or all text if the receiver is a plain text object).

See also:	− subscript:, − superscript:, − raiseBaseline: (NSTextView), − lowerBaseline: (NSTextView)

usesFontPanel

− (BOOL)usesFontPanel

Returns YES if the receiver uses the Font Panel, NO otherwise.

See also:	− setUsesFontPanel:

writeRTFDToFile:atomically:

− (BOOL)writeRTFDToFile:(NSString *)path atomically:(BOOL)flag

Writes the receiver’s text as RTF with attachments to a file or directory at path. Returns YES on success and NO on failure. If atomicFlag is YES, attempts to write the file safely so that an existing file at path is not overwritten, nor does a new file at path actually get created, unless the write is successful.

See also:	− RTFFromRange:, − RTFDFromRange:, − readRTFDFromFile:

Methods Implemented By the Delegate

textDidBeginEditing:

− (void)textDidBeginEditing:(NSNotification *)aNotification

Informs the delegate that the text object has begun editing (that it has become first responder). The name of aNotification is NSTextViewDidBeingEditingNotification.

textDidChange:

− (void)textDidChange:(NSNotification *)aNotification

Informs the delegate that the text object has changed its characters or formatting attributes. The name of aNotification is NSTextViewDidChangeNotification.

textDidEndEditing:

− (void)textDidEndEditing:(NSNotification *)aNotification

Informs the delegate that the text object has finished editing (that it has resigned first responder status). The name of aNotification is NSTextViewDidEndEditingNotification.

textShouldBeginEditing:

− (BOOL)textShouldBeginEditing:(NSText *)aTextObject

Invoked from a text object’s implementation of becomeFirstResponder, this method requests permission for aTextObject to begin editing. If the delegate returns YES, the text object proceeds to make changes. If the delegate returns NO, the text object abandons the editing operation. This method is invoked whenever aTextObject attempts to become first responder.

See also:	− makeFirstResponder: (NSWindow), − becomeFirstResponder (NSResponder)

textShouldEndEditing:

− (BOOL)textShouldEndEditing:(NSText *)aTextObject

Invoked from a text object’s implementation of resignFirstResponder, this method requests permission for aTextObject to end editing. If the delegate returns YES, the text object proceeds to finish editing and resign first responder status. If the delegate returns NO, the text object selects all of its text and remains the first responder.

See also:	− resignFirstResponder (NSResponder)

Notifications

NSTextDidBeginEditingNotification

Posted when an NSText object begins any operation that changes characters or formatting attributes.

The notification contains:

Notification Object	The notifying NSText object.

Userinfo	None

NSTextDidChangeNotification

Posted after an NSText object performs any operation that changes characters or formatting attributes.

The notification contains:

Notification Object	The notifying NSText object.

Userinfo	None

NSTextDidEndEditingNotification

Posted when an NSText object resigns first responder status.

The notification contains:

Notification Object	The notifying NSText object.

Userinfo	None

Key	Value

NSTextMovement	The keyboard operation that ended editing, an NSNumber (int).

The value for NSTextMovement is one of:

NSIllegalTextMovement

NSReturnTextMovement

NSTabTextMovement

NSBacktabTextMovement

NSLeftTextMovement

NSRightTextMovement

NSUpTextMovement

NSDownTextMovement

The value for NSTextMovement is typically one of the first four. NSIllegalTextMovement indicates that the text object ended editing because of something other than keyboard input, typically a mouse click in another view. NSReturnTextMovement, NSTabTextMovement, and NSBacktabTextMovement indicate that a field editor ended editing because the user pressed the key named in the value. The remaining four values indicate the same for arrow keys.


NSTextAttachment
p NSTextAttachment

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSTextAttachment.h

Class Description

NSTextAttachment objects are used by the NSAttributedString class cluster as the values for attachment attributes (stored in the attributed string under the key named NSAttachmentAttributeName). The objects you create with this class are referred to as text attachment objects, or when no confusion will result, as text attachments or merely attachments. See the NSAttributedString and NSTextView class specifications for general information on text attachments.

A text attachment object contains an NSFileWrapper, which in turn holds the contents of the attached file. It also uses a cell object conforming to the NSTextAttachmentCell protocol to draw and handle mouse events. Most of the behavior of a text attachment is relegated to the file wrapper and the attachment cell. See the corresponding class and protocol specifications for more information.

Method Types

Creating an NSTextAttachment	− initWithFileWrapper:

Setting the file wrapper	− setFileWrapper:

− fileWrapper

Setting the attachment cell	− setAttachmentCell:

− attachmentCell

Instance Methods

p	attachmentCell

− (id <NSTextAttachmentCell>)attachmentCell

Returns the object used to draw the icon for the attachment and to handle mouse events. An NSTextAttachment by default uses an NSTextAttachmentCell that displays the attached file’s icon, or its contents if the file contains an image.

See also:	− fileWrapper, − image (NSCell), − icon (NSFileWrapper), − setAttachmentCell:

p	fileWrapper

− (NSFileWrapper *)fileWrapper

Returns the receiver’s file wrapper, which holds the contents of the attached file.

See also:	− setFileWrapper:

p	initWithFileWrapper:

− (id)initWithFileWrapper:(NSFileWrapper *)aWrapper

Initializes a newly allocated NSTextAttachment to contain aWrapper and to use an NSTextAttachmentCell as its attachment cell. If aWrapper contains an image file that the receiver can interpret as an NSImage object, it sets the attachment cell’s image to the NSImage rather than to aWrapper’s icon.

This method is the designated initializer for the NSTextAttachment class. Returns self.

See also:	− setFileWrapper:, − setAttachmentCell:

p	setAttachmentCell:

− (void)setAttachmentCell:(id <NSTextAttachmentCell>)aCell

Sets the object used to draw the icon for the attachment and to handle mouse events to aCell.

See also:	− setFileWrapper:, − setImage: (NSCell), − icon (NSFileWrapper), − attachmentCell

p	setFileWrapper:

− (void)setFileWrapper:(NSFileWrapper *)aWrapper

Sets the receiver’s file wrapper, which holds the contents of the attached file, to aWrapper.

See also:	− fileWrapper


NSTextAttachmentCell
p NSTextAttachmentCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSCell : NSObject

Conforms To:	NSTextAttachmentCell

NSObject (NSObject)

Declared In:	NSTextAttachment.h

Class Description

NSTextAttachmentCell is the class that the OPENSTEP text system uses to implement the functionality of the NSTextAttachmentCell protocol. See the NSAttributedString and NSTextView class specifications for general information on text attachments.

Adopted Protocols

NSTextAttachmentCell	− attachment

− cellBaselineOffset

− cellSize

− drawWithFrame:inView:

− highlight:withFrame:inView:

− trackMouse:inRect:ofView:untilMouseUp:

− setAttachment:

− wantsToTrackMouse

Instance Methods

p	trackMouse:inRect:ofView:untilMouseUp:

@protocol NSTextAttachmentCell

− (BOOL)trackMouse:(NSEvent *)theEvent

inRect:(NSRect)cellFrame

ofView:(NSView *)aTextView

untilMouseUp:(BOOL)flag

Handles a mouse-down event on the receiver’s image. NSTextAttachmentCell’s implementation of this method calls upon aTextView’s delegate to handle the event. If theEvent concludes as a double click, the text attachment cell sends the delegate a textView:doubleClickedOnCell:inRect: message and returns YES. Otherwise, depending on whether the user clicks or drags the cell, it sends the delegate a textView:clickedOnCell:inRect: or a textView:draggingCell:inRect:event: message and returns YES. NSTextAttachmentCell’s implementation returns NO only if flag is NO and the mouse is dragged outside of cellFrame. The delegate methods are invoked only if the delegate responds.

See also:	− wantsToTrackMouse, − trackMouse:inRect:ofView:untilMouseUp: (NSCell), − lockFocus (NSView)

p	wantsToTrackMouse

@protocol NSTextAttachmentCell

− (BOOL)wantsToTrackMouse

Returns YES. NSTextAttachmentCell objects support dragging. An NSTextView invokes this method before sending trackMouse:inRect:ofView:untilMouseUp: to the text attachment cell.

A more static subclass might override this method to return NO, which results in the attachment image behaving as any other glyph in the text, and not allow itself to be dragged or to perform a method on being clicked.


NSTextAttachmentCell_protocol
p NSTextAttachmentCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Adopted By:	NSTextAttachmentCell

Declared In:	AppKit/NSTextAttachment.h

Protocol Description

The NSTextAttachmentCell protocol declares the interface for objects that draw text attachment icons and handle mouse events on their icons. With the exceptions of cellBaselineOffset:, setAttachment: and attachment, all of these methods are implemented by the NSCell class and described in that class specification.

See the NSAttributedString and NSTextView class specifications for general information on text attachments.

Method Types

Drawing	− drawWithFrame:inView:

− highlight:withFrame:inView:

Cell size and position	− cellSize

− cellBaselineOffset

Event handling	− wantsToTrackMouse

− trackMouse:inRect:ofView:untilMouseUp:

Setting the attachment	− setAttachment:

− attachment

Instance Methods

p	attachment

− (NSTextAttachment *)attachment

Returns the text attachment object that owns the receiver.

See also:	− setAttachment:

p	cellBaselineOffset

− (NSPoint)cellBaselineOffset

Returns the position where the attachment cell’s image should be drawn in text, relative to the current point established in the glyph layout. The image should be drawn so that its lower left corner lies on this point.

See also:	− icon (NSFileWrapper)

p	cellSize

− (NSSize)cellSize

Returns the size of the attachment’s icon.

See also:	− icon (NSFileWrapper), − fileWrapper (NSTextAttachment)

p	drawWithFrame:inView:

− (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)aView

Draws the receiver’s image within cellFrame in aView, which should be the focus view.

See also:	− drawWithFrame:inView: (NSCell), − lockFocus (NSView)

p	highlight:withFrame:inView:

− (void)highlight:(BOOL)flag

withFrame:(NSRect)cellFrame

inView:(NSView *)aView

Draws the receiver’s image—with highlighting if flag is YES—within cellFrame in aView, which should be the focus view.

See also:	− highlight:withFrame:inView: (NSCell), − lockFocus (NSView)

p	setAttachment:

− (void)setAttachment:(NSTextAttachment *)anAttachment

Sets the text attachment object that owns the receiver to anAttachment, without retaining it (the text attachment, as the owner, retains the cell).

See also:	− attachment, − setAttachmentCell: (NSTextAttachment)

p	trackMouse:inRect:ofView:untilMouseUp:

− (BOOL)trackMouse:(NSEvent *)theEvent

inRect:(NSRect)cellFrame

ofView:(NSView *)aTextView

untilMouseUp:(BOOL)flag

Handles a mouse-down event on the receiver’s image. theEvent is the mouse-down event. cellFrame is the region of aTextView in which further mouse events should be tracked. aTextView is the view which received the event. It’s assumed to be an NSTextView, and should be the focus view. If flag is YES, the receiver tracks the mouse until a mouse-up event occurs; if flag is NO, it stops tracking when a mouse-dragged event occurs outside of cellFrame. Returns YES if the receiver successfully finished tracking the mouse (typically through a mouse-up event), NO otherwise (such as when the mouse is dragged outside cellFrame).

NSTextAttachmentCell’s implementation of this method calls upon aTextView’s delegate to handle the event. If theEvent is a mouse-up event for a double click, the text attachment cell sends the delegate a textView:doubleClickedOnCell:inRect: message and returns YES. Otherwise, depending on whether the user clicks or drags the cell, it sends the delegate a textView:clickedOnCell:inRect: or a textView:draggingCell:inRect:event: message and returns YES. NSTextAttachmentCell’s implementation returns NO only if flag is NO and the mouse is dragged outside of cellFrame. The delegate methods are invoked only if the delegate responds.

See also:	− wantsToTrackMouse, − trackMouse:inRect:ofView:untilMouseUp: (NSCell), − lockFocus (NSView)

p	wantsToTrackMouse

− (BOOL)wantsToTrackMouse

Returns YES if the receiver will handle a mouse event occurring over its image (to support dragging, for example), NO otherwise. NSTextAttachmentCell’s implementation of this method returns YES. The NSView containing the cell should invoke this method before sending a trackMouse:inRect:ofView:untilMouseUp: message.

For an attachment in an attributed string, if the attachment cell returns NO its attachment character should be selected rather than the cell being asked to track the mouse. this results in the attachment icon behaving as any regular glyph in text.


NSTextContainer
p NSTextContainer

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSTextContainer.h

Class Description

An NSTextContainer defines a region where text is laid out. An NSLayoutManager uses NSTextContainers to determine where to break lines, lay out portions of text, and so on. NSTextContainer defines rectangular regions, but you can create subclasses that define regions of other shapes, such as circular regions, regions with holes in them, or regions that flow alongside graphics.

You normally use an NSTextView to display the text laid out within an NSTextContainer. An NSTextView can have only one NSTextContainer; however, since the two are separate objects, you can replace an NSTextView’s container to change the layout of the text it displays. You can also display an NSTextContainer’s text in any NSView by locking the graphics focus on it and using NSLayoutManager’s drawBackgroundForGlyphRange:atPoint: and drawGlyphsForGlyphRange:atPoint: methods. If you have no need of actually displaying the text—if you’re only calculating line breaks or number of lines or pages, for example—you can use an NSTextContainer without an NSTextView.

Region, Bounding Rectangle, and Inset

An NSTextContainer’s region is defined within a bounding rectangle whose coordinate system starts at (0, 0) in the top left corner. The size of this rectangle is returned by the containerSize method and set using setContainerSize:. You can define a container’s region so that it’s always the same shape, such as a circle whose diameter is the narrower of the bounding rectangle’s dimensions, or you can define the region relative to the bounding rectangle, such as an oval region that fits inside the bounding rectangle (and that’s a circle when the bounding rectangle is square). Regardless of a text container’s shape, its NSTextView always clips drawing to its bounding rectangle.

A subclass of NSTextContainer defines its region by overriding three methods. The first, isSimpleRectangularTextContainer, indicates whether the region is currently a nonrotated rectangle, thus allowing the NSLayoutManager to optimize layout of text (since custom NSTextContainers typically define more complex regions, your implementation of this method will probably return NO). The second method, containsPoint:, is used for testing mouse events and determines whether or not a given point lies in the region. The third method is used for the actual layout of text, defining the region in terms of rectangles available to lay text in; this process is described in “Calculating Text Layout.”

An NSTextContainer usually covers its NSTextView exactly, but can be inset within the view frame with NSTextView’s setTextContainerInset: method. The NSTextContainer’s bounding rectangle from the inset position then establishes the limits of the NSTextContainer’s region. The inset also helps to determine the size of the bounding rectangle when the NSTextContainer tracks the height or width of its NSTextView, as described in “Tracking the Size of the NSTextView.”

Calculating Text Layout

An NSLayoutManager lays text within an NSTextContainer in lines of glyphs, running either horizontally or vertically. The layout of these lines within an NSTextContainer is determined by its shape. For example, if the NSTextContainer is narrower in some parts than in others, the lines in those parts must be shortened; if there are holes in the region, some lines must be fragmented; if there’s a gap across the entire region, the lines that would overlap it have to be shifted to compensate. This is illustrated in the figure below.

The NSLayoutManager proposes a rectangle for a given line, and then asks the NSTextContainer to adjust the rectangle to fit. The proposed rectangle usually spans the NSTextContainer’s bounding rectangle, but it can be narrower or wider, and it can also lie partially or completely outside the bounding rectangle. The method that an NSLayoutManager sends the container to adjust the proposed rectangle is lineFragmentRectForProposedRect:sweepDirection:movementDirection:remainingRect:, which returns the largest rectangle available for the proposed rectangle, based on the direction text is laid out. It also returns a rectangle containing any remaining space, such as that left on the other side of a hole or gap in the NSTextContainer.

Text is laid out along lines that run either horizontally or vertically, and in either direction. This type of movement is called the sweep direction and is expressed by the NSLineSweepDirection type. The direction in which the lines progress is then called the line movement direction and is expressed by the NSLineMovementDirection type. Each affects the adjustment of a line fragment rectangle in a different way: The rectangle can be shortened along the sweep direction and shifted in the line movement direction.

NSLineSweepDirection values	NSLineMovementDirection values

NSLineSweepLeft	NSLineMovesLeft

NSLineSweepRight	NSLineMovesRight

NSLineSweepDown	NSLineMovesDown

NSLineSweepUp	NSLineMovesUp

NSLineDoesntMove

For the three examples above, the sweep direction is NSLineSweepRight and the line movement direction is NSLineMovesDown. In the first example, the proposed rectangle spans the region’s bounding rectangle and is shortened by the text container to fit inside the hourglass shape with no remainder.

In the second example, the proposed rectangle crosses a hole, so the text container must return a shorter rectangle (the white rectangle on the left) along with a remainder (the white rectangle on the right). The next rectangle proposed by the NSLayoutManager will then be this remainder rectangle, and will be returned unchanged by the text container.

In the third example, a gap crosses the entire NSTextContainer. Here the text container shifts the proposed rectangle down until it lies completely within the container’s region. If the line movement direction here were NSLineDoesntMove, the NSTextContainer would have to return NSZeroRect indicating that the line simply doesn’t fit. In such a case it’s up to the NSLayoutManager to propose a different rectangle or to move on to a different container. When a text container shifts a line fragment rectangle, the layout manager takes this into account for subsequent lines.

The NSLayoutManager makes one final adjustment when it actually fits text into the rectangle. This adjustment is a small amount fixed by the NSTextContainer, called the line fragment padding, which defines the portion on each end of the line fragment rectangle left blank. Text is inset within the line fragment rectangle by this amount (the rectangle itself is unaffected). Padding allows for small-scale adjustment of the NSTextContainer’s region at the edges and around any holes, and keeps text from abutting any other graphics displayed near the region. You can change the padding from its default value with the setLineFragmentPadding: method, or override the default in your subclass. Note that line fragment padding isn’t a suitable means for expressing margins; you should set the NSTextView’s position and size for document margins or the paragraph margin attributes for text margins.

Tracking the Size of the NSTextView

Normally, if you resize an NSTextView its NSTextContainer doesn’t change in size. You can, however, set an NSTextContainer to track the size of its NSTextView and adjust its own size to match whenever the NSTextView’s size changes. The setHeightTracksTextView: and setWidthTracksTextView: methods allow you to control this tracking for either dimension.

When an NSTextContainer adjusts its size to match that of its NSTextView, it takes into account the inset specified by the NSTextView so that the bounding rectangle is inset from every edge possible. In other words, an NSTextContainer that tracks the size of its NSTextView is always smaller than the NSTextView (in the appropriate dimension) by twice the inset. Suppose an NSTextContainer is set to track width and its NSTextView gives it an inset of (10, 10). Now, if the NSTextView’s width is changed to 138, the NSTextContainer’s top left corner is set to lie at (10, 10) and its width is set to 118, so that its right edge is 10 points from the NSTextView’s right edge. Its height remains the same.

Whether it tracks the size of its NSTextView or not, an NSTextContainer doesn’t grow or shrink as text is added or deleted; instead, the NSLayoutManager resizes the NSTextView based on the portion of the NSTextContainer actually filled with text. To allow an NSTextView to be resized in this manner, use NSTextView’s setVerticallyResizable: or setHorizontallyResizable: methods as needed, set the text container not to track the size of its text view, and set the text container’s size in the appropriate dimension large enough to accommodate a great amount of text—about 1e7 (this incurs no cost whatever in processing or storage). For more information on automatic size adjustment, see “The OPENSTEP Text Handling System.”

Note that an NSTextView can be resized based on its NSTextContainer, and an NSTextContainer can resize itself based on its NSTextView. If you set both objects up to resize automatically in the same dimension, your application can get trapped in an infinite loop. When text is added to the NSTextContainer, the NSTextView is resized to fit the area actually used for text; this causes the NSTextContainer to resize itself and relay its text, which causes the NSTextView to resize itself again, and so on ad infinitum. Each type of size tracking has its proper uses; be sure to use only one for either dimension.

Method Types

Creating an instance	− initWithContainerSize:

Managing text components	− setLayoutManager:

− layoutManager

− replaceLayoutManager:

− setTextView:

− textView

Controlling size	− setContainerSize:

− containerSize

− setWidthTracksTextView:

− widthTracksTextView

− setHeightTracksTextView:

− heightTracksTextView

Setting line fragment padding	− setLineFragmentPadding:

− lineFragmentPadding

Calculating text layout	− lineFragmentRectForProposedRect:sweepDirection:

movementDirection:remainingRect:

− isSimpleRectangularTextContainer

Mouse hit testing	− containsPoint:

Instance Methods

p	containerSize

− (NSSize)containerSize

Returns the size of the receiver’s bounding rectangle, regardless of the size of its region.

See also:	− textContainerInset (NSTextView), − setContainerSize:

p	containsPoint:

− (BOOL)containsPoint:(NSPoint)aPoint

Overridden by subclasses to returns YES if aPoint lies within the receiver’s region or on the region’s edge—not simply within its bounding rectangle—NO otherwise. For example, if the receiver defines a donut shape and aPoint lies in the hole, this method returns NO. This method can be used for hit testing of mouse events.

NSTextContainer’s implementation merely checks that aPoint lies within its bounding rectangle.

p	heightTracksTextView

− (BOOL)heightTracksTextView

Returns YES if the receiver adjusts the height of its bounding rectangle when its NSTextView is resized, NO otherwise. The height is adjusted to the height of the NSTextView minus twice the inset height (as given by NSTextView’s textContainerInset method).

See the class description for more information on size tracking.

See also:	− widthTracksTextView, − setHeightTracksTextView:

p	initWithContainerSize:

− (id)initWithContainerSize:(NSSize)aSize

Initializes the receiver, a newly allocated NSTextContainer, with aSize as the size of its bounding rectangle. The new NSTextContainer must be added to an NSLayoutManager before it can be used; it must also have an NSTextView set for text to be displayed. This method is the designated initializer for the NSTextContainer class. Returns self.

See also:	− addTextContainer: (NSLayoutManager), − setTextView:

p	isSimpleRectangularTextContainer

− (BOOL)isSimpleRectangularTextContainer

Overridden by subclasses to return YES if the receiver’s region is a rectangle with no holes or gaps and whose edges are parallel to the NSTextView’s coordinate system axes; returns NO otherwise. An NSTextContainer whose shape changes can return YES if its region is currently a simple rectangle, but when its shape does change it must send textContainerChangedGeometry: to its NSLayoutManager so the layout can be recalculated.

NSTextContainer’s implementation of this method returns YES.

p	layoutManager

− (NSLayoutManager *)layoutManager

Returns the receiver’s NSLayoutManager.

See also:	− setLayoutManager:, − replaceLayoutManager:

p	lineFragmentPadding

− (float)lineFragmentPadding

Returns the amount (in points) by which text is inset within line fragment rectangles.

See also:	− lineFragmentRectForProposedRect:sweepDirection:movementDirection:

remainingRect:, − setLineFragmentPadding:

p	lineFragmentRectForProposedRect:sweepDirection:movementDirection:

remainingRect:

− (NSRect)lineFragmentRectForProposedRect:(NSRect)proposedRect

sweepDirection:(NSLineSweepDirection)sweepDirection

movementDirection:(NSLineMovementDirection)movementDirection

remainingRect:(NSRect *)remainingRect

Overridden by subclasses to calculate and return the longest rectangle available for proposedRect for displaying text, or NSZeroRect if there is none according to the receiver’s region definition.The receiver should examine proposedRect to see that it intersects its bounding rectangle, and should return a modified rectangle based on sweepDirection and movementDirection, whose possible values are listed in the class description. If sweepDirection is NSLineSweepRight, for example, the receiver uses this information to trim the right end of proposedRect as needed rather than the left end.

If proposedRect doesn’t completely overlap the region along the axis of movementDirection and movementDirection isn’t NSLineDoesntMove, this method can either shift the rectangle in that direction as much as needed so that it does completely overlap, or return NSZeroRect to indicate that the proposed rectangle simply doesn’t fit.

Upon returning, remainingRect contains the unused, possibly shifted, portion of proposedRect that’s available for further text, or NSZeroRect if there is no remainder.

See the class description for more information on overriding this method.

p	replaceLayoutManager:

− (void)replaceLayoutManager:(NSLayoutManager *)aLayoutManager

Replaces the NSLayoutManager for the group of text-system objects containing the receiver with aLayoutManager. All NSTextContainers and NSTextViews sharing the original NSLayoutManager then share the new one. This method makes all the adjustments necessary to keep these relationships intact, unlike setLayoutManager:.

See also:	− layoutManager

p	setContainerSize:

− (void)setContainerSize:(NSSize)aSize

Sets the size of the receiver’s bounding rectangle to aSize and sends textContainerChangedGeometry: to the NSLayoutManager.

See also:	− setTextContainerInset: (NSTextView), − containerSize

p	setHeightTracksTextView:

− (void)setHeightTracksTextView:(BOOL)flag

Controls whether the receiver adjusts the height of its bounding rectangle when its NSTextView is resized. If flag is YES, the receiver follows changes to the height of its text view; if flag is NO, it doesn’t.

See the class description for more information on size tracking.

See also:	− setContainerSize:, − setWidthTracksTextView:, − heightTracksTextView

p	setLayoutManager:

− (void)setLayoutManager:(NSLayoutManager *)aLayoutManager

Sets the receiver’s NSLayoutManager to aLayoutManager. This method is invoked automatically when you add an NSTextContainer to an NSLayoutManager; you should never need to invoke it directly, but might want to override it. If you want to replace the NSLayoutManager for an established group of text-system objects, use replaceLayoutManager:.

See also:	− addTextContainer: (NSLayoutManager), − layoutManager

p	setLineFragmentPadding:

− (void)setLineFragmentPadding:(float)aFloat

Sets the amount (in points) by which text is inset within line fragment rectangles to aFloat. Also sends textContainerChangedGeometry: to the receiver’s NSLayoutManager to inform it of the change.

See also:	− lineFragmentRectForProposedRect:sweepDirection:movementDirection:

remainingRect:, − lineFragmentPadding

p	setTextView:

− (void)setTextView:(NSTextView *)aTextView

Sets the receiver’s NSTextView to aTextView and sends setTextContainer: to aTextView to complete the association of the text container and text view. Since you usually specify an NSTextContainer when you create an NSTextView, you should rarely need to invoke this method. An NSTextContainer doesn’t need an NSTextView to calculate line fragment rectangles, but must have one to display text.

You can use this method to disconnect an NSTextView from a group of text-system objects by sending this message to its text container and passing nil as aTextView.

See also:	− initFrame:textContainer: (NSTextView), − replaceTextContainer: (NSTextView)

p	setWidthTracksTextView:

− (void)setWidthTracksTextView:(BOOL)flag

Controls whether the receiver adjusts the width of its bounding rectangle when its NSTextView is resized. If flag is YES, the receiver follows changes to the width of its text view; if flag is NO, it doesn’t.

See the class description for more information on size tracking.

See also:	− setContainerSize:, − setHeightTracksTextView:, − widthTracksTextView

p	textView

− (NSTextView *)textView

Returns the receiver’s NSTextView, or nil if it has none.

See also:	− setTextView:

p	widthTracksTextView

− (BOOL)widthTracksTextView

Returns YES if the receiver adjusts the width of its bounding rectangle when its NSTextView is resized, NO otherwise. The width is adjusted to the width of the NSTextView minus twice the inset width (as given by NSTextView’s textContainerInset method).

See the class description for more information on size tracking.

See also:	− heightTracksTextView, − setWidthTracksTextView:


NSTextField

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSControl : NSView : NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSTextField.h

Class Description

An NSTextField is a kind of NSControl that displays text that the user can select or edit, and which sends its action message to its target when the user presses the Return key while editing. Like other controls, it also performs validation on its value when edited; if the value isn’t valid it sends a special error action message to its target. An NSTextField can be assigned a delegate, who is then informed of delegate messages sent by the window’s field editor, such as textShouldEndEditing:. See the NSWindow and NSTextView class specifications for more information on a window’s field editor.

Typical of several kinds of control, NSTextField allows you to set its text and background color, whether it draws the background, and whether it draws a bezel or border around its text. You can also link text fields together in their window’s key view loop, as described in the NSWindow class specification.

Method Types

Controlling editability and selectability

− setEditable:

− isEditable

− setSelectable:

− isSelectable

Setting the error action	− setErrorAction:

− errorAction

Controlling rich text behavior	− setAllowsEditingTextAttriutes:

− allowsEditingTextAttributes

− setImportsGraphics:

− importsGraphics

Setting the text color	− setTextColor:

− textColor

Controlling the background	− setBackgroundColor:

− backgroundColor

− setDrawsBackground:

− drawsBackground

Setting a border	− setBezeled:

− isBezeled

− setBordered:

− isBordered

Linking text fields together	− setNextText:

− nextText

− setPreviousText:

− previousText

Selecting the text	− selectText:

Working with the responder chain	− acceptsFirstResponder

Using keyboard interface control	− setTitleWithMnemonic:

− performMnemonic:

Setting the delegate	− setDelegate:

− delegate

Text delegate methods	− textShouldBeginEditing:

− textDidBeginEditing:

− textDidChange:

− textShouldEndEditing:

− textDidEndEditing:

Instance Methods

acceptsFirstResponder

− (BOOL)acceptsFirstResponder

Returns YES if the receiver is editable or selectable, NO otherwise.

p	allowsEditingTextAttributes

− (BOOL)allowsEditingTextAttributes

Returns YES if the receiver allows the user to change font attributes of the receiver’s text, NO if the user isn’t permitted to do so. You can change text attributes programmatically regardless of this setting.

See also:	− importsGraphics, − setAllowsEditingTextAttributes:

backgroundColor

− (NSColor *)backgroundColor

Returns the color of the background that the receiver draws behind the text.

See also:	− drawsBackground, − backgroundColor (NSCell), − setBackgroundColor:

delegate

− (id)delegate

Returns the receiver’s delegate.

See also:	− textShouldBeginEditing:, − textShouldEndEditing:, − textDidBeginEditing:, − textDidEndEditing:, − textDidChange:, − setDelegate:

drawsBackground

− (BOOL)drawsBackground

Returns YES if the receiver’s cell draws its background color behind its text, NO if it draws no background.

See also:	− backgroundColor, − drawsBackground (NSTextFieldCell), − setDrawsBackground:

errorAction

− (SEL)errorAction

Returns the selector for the message sent to the receiver’s target whenever a validation error occurs.

See also:	− textShouldEndEditing:, − setErrorAction:

p	importsGraphics

− (BOOL)importsGraphics

Returns YES if the receiver allows the user to drag image files into it, NO if it doesn’t accept dragged images. You can add images programmatically regardless of this setting.

See also:	− allowsEditingTextAttributes, − importsGraphics (NSTextView), − setImportsGraphics:

isBezeled

− (BOOL)isBezeled

Returns YES if the receiver draws a bezeled frame around its contents, NO if it doesn’t.

See also:	− isBordered, − setBezeled:

isBordered

− (BOOL)isBordered

Returns YES if the receiver draws a solid black border around its contents, NO if it doesn’t.

See also:	− isBezeled, − setBordered:

isEditable

− (BOOL)isEditable

Returns YES if the user is allowed to select and edit the receiver’s text, NO if the user isn’t allowed to edit it (though the user may be able to select it).

See also:	− isSelectable, − setEditable:

isSelectable

− (BOOL)isSelectable

Returns YES if the user is allowed to select the receiver’s text, NO if the user isn’t allowed to select it. Selectable text isn’t necessarily editable; use isEditable to check for editability.

See also:	− setSelectable:

nextText

− (id)nextText

Returns the receiver’s next key view, the object that’s made first responder when the user presses the Tab key while editing the receiver. See the description of the nextKeyView method in NSView for more information.

See also:	− previousText, − setNextText:

p	performMnemonic:

− (BOOL)performMnemonic:(NSString *)aString

Does nothing and returns NO if the receiver is editable. Otherwise makes the receiver’s next key view the first responder and returns YES. This allows a text field to be used as a label for another interface object, so that it moves control to that object when its mnemonic is invoked.

See also:	− setNextKeyView: (NSView), − isEditable, − setTitleWithMnemonic:, − makeFirstResponder: (NSWindow)

previousText

− (id)previousText

Returns the receiver’s previous key view, the object that’s made first responder when the user presses Shift-Tab while editing the receiver. See the description of the previousKeyView method in NSView for more information.

See also:	− nextText, − setPreviousText:

selectText:

− (void)selectText:(id)sender

Selects the entire contents of the receiver if it’s selectable. However, if the receiver isn’t in some window’s view hierarchy, this method has no effect.

See also:	− isSelectable

p	setAllowsEditingTextAttributes:

− (void)setAllowsEditingTextAttributes:(BOOL)flag

Controls whether the receiver allows the user to change font attributes of the receiver’s text. If flag is YES, the user is permitted to make such changes; if flag is NO, the user isn’t so permitted. You can change text attributes programmatically regardless of this setting.

See also:	− setImportsGraphics:, − allowsEditingTextAttributes

setBackgroundColor:

− (void)setBackgroundColor:(NSColor *)aColor

Sets the color of the background that the receiver draws behind the text to aColor.

See also:	− setDrawsBackground:, − setBackgroundColor: (NSCell) − backgroundColor

setBezeled:

− (void)setBezeled:(BOOL)flag

Controls whether the receiver draws a bezeled border around its contents. If flag is YES, then it draws a bezeled border; if flag is NO, it draws no border.

See also:	− isBezeled, − setBordered:

setBordered:

− (void)setBordered:(BOOL)flag

Controls whether the receiver draws a solid black border around its contents. If flag is YES, then it draws a border; if flag is NO, it draws no border.

See also:	− isBordered, − setBezeled:

setDelegate:

− (void)setDelegate:(id)anObject

Sets the receiver’s delegate to anObject.

See also:	− textShouldBeginEditing:, − textShouldEndEditing:, − textDidBeginEditing:, − textDidEndEditing:, − textDidChange:, − delegate

setDrawsBackground:

− (void)setDrawsBackground:(BOOL)flag

Controls whether the receiver draws its background color behind its text. If flag is YES, then it does; if flag is NO, then it draws nothing behind its text.

See also:	− setBackgroundColor:, − setDrawsBackground: (NSTextFieldCell), − drawsBackground

setEditable:

− (void)setEditable:(BOOL)flag

Controls whether the user can edits the receiver’s text. If flag is YES, then the user is allowed to both select and edit text. If flag is NO, then the user isn’t permitted to edit text, and the receiver’s selectability is restored to its previous value. For example, if an NSTextField is selectable but not editable, then made editable for a time, then made not editable, it remains selectable. To guarantee that text is neither editable nor selectable, simply use setSelectable: to turn off selectability.

See also:	− isEditable

setErrorAction:

− (void)setErrorAction:(SEL)aSelector

Sets the selector for the message sent to the receiver’s target whenever a validation error occurs to aSelector.

See also:	− textShouldEndEditing:, − errorAction

p	setImportsGraphics:

− (void)setImportsGraphics:(BOOL)flag

Controls whether the receiver allows the user to drag image files into it. If flag is YES, the receiver accepts dragged images; if flag is NO, it doesn’t. You can add images programmatically regardless of this setting.

See also:	− setAllowsEditingTextAttributes:, − setImportsGraphics (NSTextView), − importsGraphics

setNextText:

− (void)setNextText:(id)anObject

Sets the receiver’s next key view to anObject, which should be a kind of NSView. See the description of the setNextKeyView: method in the NSView class specification for more information.

See also:	− setPreviousText:, − nextText

setPreviousText:

− (void)setPreviousText:(id)anObject

Sets the receiver’s previous key view to anObject, which should be a kind of NSView. See the description of the setPreviousKeyView: method in the NSView class specification for more information.

See also:	− setNextText:, − previousText

setSelectable:

− (void)setSelectable:(BOOL)flag

Returns YES if the user is allowed to select the receiver’s text, NO if the user isn’t allowed to select it. Selectable text isn’t necessarily editable; use isEditable to check for editability.

See also:	− setSelectable:

setTextColor:

− (void)setTextColor:(NSColor *)aColor

Sets the color used to draw the receiver’s text to aColor.

See also:	− setBackgroundColor:, − setTextColor: (NSTextFieldCell), − textColor

p	setTitleWithMnemonic:

− (void)setTitleWithMnemonic:(NSString *)aString

Sets the receiver’s string value to aString, using the first character preceded by an ampersand (‘&’) as the mnemonic and stripping out that first ampersand character. Use this method only with a non-editable text field being used as a label for another interface component, which you should establish using setNextKeyView:. When set up in this fashion, the text field’s mnemonic serves to select the other interface component.

See also:	− performMnemonic:

textColor

− (NSColor *)textColor

Returns the color used to draw the receiver’s text.

See also:	− backgroundColor, − textColor (NSTextFieldCell), − setTextColor:

textDidBeginEditing:

− (void)textDidBeginEditing:(NSNotification *)aNotification

Posts an NSControlTextDidBeginEditingNotification to the default notification center. This causes the receiver’s delegate to receive a control:textDidBeginEditing: message. See the NSControl class specification for more information on the text delegate method.

See also:	− textDidBeginEditing:, − textDidChange:, − textShouldEndEditing:, − textDidEndEditing:

textDidChange:

− (void)textDidChange:(NSNotification *)aNotification

Forwards this message to the receiver’s cell if it responds, and posts an NSControlTextDidChangeNotification to the default notification center. This causes the receiver’s delegate to receive a control:textDidChange: message. See the NSControl class specification for more information on the text delegate method.

See also:	− textShouldBeginEditing:, − textDidBeginEditing:, − textShouldEndEditing:, − textDidEndEditing:

textDidEndEditing:

− (void)textDidEndEditing:(NSNotification *)aNotification

Handles an end to editing. After validating the new value, posts an NSControlTextDidEndEditingNotification to the default notification center. This causes the receiver’s delegate to receive a control:textDidEndEditing: message. After this, sends endEditing: to the receiver’ cell, and handles the key that caused editing to end:

•	If the user ended editing by pressing Return, this method tries to send the receiver’s action to its target; if unsuccessful, it sends performKeyEquivalent: to its NSWindow (for example, to handle the default button on a panel); if that also fails, then the receiver simply selects its text.

•	If the user ended editing by pressing Tab or Shift-Tab, the receiver tries to have its NSWindow select its next or previous key view, using the NSWindow method selectKeyViewFollowingView: or selectKeyViewPreceedingView:. If unsuccessful in doing this, the receiver simply selects its text.

See the NSControl class specification for more information on the text delegate method.

See also:	− textShouldBeginEditing:, − textDidBeginEditing:, − textDidChange:, − textShouldEndEditing:

textShouldBeginEditing:

− (BOOL)textShouldBeginEditing:(NSText *)textObject

If the receiver isn’t editable, returns NO immediately. If it is editable and its delegate responds to control:textShouldBeginEditing:, invokes that method and returns the result. Otherwise simply returns YES to allow editing to occur. See the NSControl class specification for more information on the text delegate method.

See also:	− textDidBeginEditing:, − textDidChange:, − textShouldEndEditing:, − textDidEndEditing:

textShouldEndEditing:

− (BOOL)textShouldEndEditing:(NSText *)textObject

Performs validation on the receiver’s new value using NSCell’s isEntryAcceptable:, sending the receiver’s error action to its target if validation fails. If the new value is valid and the delegate responds to control:textShouldEndEditing:, invokes that method and returns the result, in addition beeping if the delegate returns NO. See the NSControl class specification for more information on the text delegate method.

See also:	− textShouldBeginEditing:, − textDidBeginEditing:, − textDidChange:, − textDidEndEditing:, − errorAction


NSTextFieldCell

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSActionCell : NSCell : NSObject

Conforms To:	NSCoding (NSCell)

NSCopying (NSCell)

NSObject (NSObject)

Declared In:	AppKit/NSTextFieldCell.h

Class Description

NSTextFieldCell adds to NSCell’s text-display capabilities by allowing you to set the color of both the text and its background. You can also specify whether the cell draws its background at all. All of the methods declared by this class are also declared by NSTextField, which uses NSTextFieldCells to draw and edit text.

Method Types

Setting the text color	− setTextColor:

− textColor

Controlling the background	− setBackgroundColor:

− backgroundColor

− setDrawsBackground:

− drawsBackground

Instance Methods

backgroundColor

− (NSColor *)backgroundColor

Returns the color of the background that the receiver draws behind the text.

See also:	− drawsBackground, − backgroundColor (NSTextField), − setBackgroundColor:

drawsBackground

− (BOOL)drawsBackground

Returns YES if the receiver’s cell draws its background color behind its text, NO if it draws no background.

See also:	− backgroundColor, − drawsBackground (NSTextField), − setDrawsBackground:

setBackgroundColor:

− (void)setBackgroundColor:(NSColor *)color

Sets the color of the background that the receiver draws behind the text to aColor.

See also:	− setDrawsBackground:, − setBackgroundColor: (NSTextField) − backgroundColor

setDrawsBackground:

− (void)setDrawsBackground:(BOOL)flag

Controls whether the receiver draws its background color behind its text. If flag is YES, then it does; if flag is NO, then it draws nothing behind its text.

See also:	− setBackgroundColor:, − setDrawsBackground: (NSTextField), − drawsBackground

setTextColor:

− (void)setTextColor:(NSColor *)color

Sets the color used to draw the receiver’s text to aColor.

See also:	− setBackgroundColor:, − setTextColor: (NSTextField), − textColor

textColor

− (NSColor *)textColor

Returns the color used to draw the receiver’s text.

See also:	− backgroundColor, − textColor (NSTextField), − setTextColor:


NSTextStorage
p NSTextStorage

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSMutableAttributedString : NSAttributedString : NSObject

Conforms To:	NSCopying

NSMutableCopying

NSObject (NSObject)

Declared In:	AppKit/NSTextStorage.h

Class Description

NSTextStorage is a semi-concrete subclass of NSMutableAttributedString that manages a set of client NSLayoutManagers, notifying of them of any changes to its characters or attributes so that they can re-lay and redisplay the text as needed. NSTextStorage defines the fundamental storage mechanism of NeXT’s extended text-handling system.

Like an abstract class of a class cluster, allocating and initializing an NSTextStorage actually produces an instance of a private subclass. You can use any of NSAttributedString and NSMutableAttributedString’s initialization methods to create an NSTextStorage object. Following this, you add NSLayoutManagers to it using addLayoutManager:.

The behavior of an NSTextStorage object is best illustrated by following the methods it invokes while being changed. There are three stages to editing a text storage object programmatically. The first stage is to send it a beginEditing message to announce a group of changes. In the second stage, you send it some editing messages, such as deleteCharactersInRange: and addAttributes:range:, to effect the changes in characters or attributes. Each time you send such a method, the text storage object invokes edited:range:changeInLength: to record the range of its characters affected since it received the beginEditing message. For the third stage, when you’re done changing the text storage object, you send it an endEditing message. This causes it to invoke its own processEditing method, fixing attributes within the recorded range of changed characters. After fixing its attributes, the text storage object sends a message to each NSLayoutManager indicating the range in the text storage object that has changed, along with the nature of those changes. The NSLayoutManagers in turn use this information to re-lay their glyphs and redisplay if necessary. NSTextStorage also keeps a delegate and sends it messages before and after processing edits.

Creating a Subclass of NSTextStorage

As indicated above, NSTextStorage isn’t a fully concrete class. It defines the storage for its NSLayoutManagers and implements all of the methods described in this specification, but doesn’t provide the primitive attributed string methods to subclasses. A subclass must define the storage for its attributed string, typically as an instance variable of type NSMutableAttributedString, override init and define its own initialization methods, and implement the primitive methods of both NSAttributedString and NSMutableAttributedString. For the record, these methods are:

− string

− attributesAtIndex:effectiveRange:

− replaceCharactersInRange:withString:

− setAttributes:range:

Beyond these requirements, if a subclass overrides or adds any methods that change its characters or attributes directly (not using the primitive methods or making extra changes after invoking the primitives), those methods must invoke edited:range:changeInLength: after performing the change in order to keep the change-tracking information up to date. See the description of this method for more information.

Method Types

Managing NSLayoutManagers	− addLayoutManager:

− removeLayoutManager:

− layoutManagers

Handling text edited messages	− edited:range:changeInLength:

− endEditing

− processEditing

Determining the nature of changes	− editedMask

Determining the extent of changes	− editedRange

− changeInLength

Setting the delegate	− setDelegate:

− delegate

Instance Methods

p	addLayoutManager:

− (void)addLayoutManager:(NSLayoutManager *)aLayoutManager

Adds aLayoutManager to the receiver’s set of NSLayoutManagers.

See also:	− removeLayoutManager:, − layoutManagers

p	changeInLength

− (int)changeInLength

Returns the difference between the current length of the edited range and its length before editing began (that is, before the receiver was sent the first beginEditing message or a single edited:range:changeInLength: message). This difference is accumulated with each invocation of edited:range:changeInLength:, until a final endEditing message processes the changes.

The receiver’s delegate and layout managers can use this information to determine the nature of edits in their respective notification methods.

See also:	− editedRange, − editedMask

p	delegate

− (id)delegate

Returns the receiver’s delegate.

See also:	− setDelegate:

p	edited:range:changeInLength:

− (void)edited:(unsigned)mask

range:(NSRange)oldRange

changeInLength:(int)lengthChange

Tracks changes made to the receiver, allowing the NSTextStorage to record the full extent of changes made between a pair of beginEditing and endEditing messages. If invoked outside of such a pair, this method immediately invokes processEditing. NSTextStorage invokes this method automatically each time it makes a change to its attributed string. Subclasses that override or add methods that alter their attributed strings directly should invoke this method after making those changes. The information accumulated with this method is then used in an invocation of processEditing to report the affected portion of the receiver.

mask specifies the nature of the changes. Its value is made by combining these options with the C bitwise OR operator:

Option	Meaning

NSTextStorageEditedAttributes	Attributes were added, removed, or changed.

NSTextStorageEditedCharacters	Characters were added, removed, or replaced.

oldRange indicates the extent of characters affected before the change took place. If the NSTextStorageEditedCharacters bit of mask is set, lengthChange gives the number of characters added to or removed from oldRange (otherwise its value is irrelevant). For example, when replacing “The” with “Several” in the string “The files couldn’t be saved”, oldRange is {0, 3} and lengthChange is 4.

Note:	The methods for querying changes, editedRange and changeInLength, indicate the extent of characters affected after the change. This method expects the characters before the change because that information is readily available as the argument to whatever method performs the change (such as replaceCharactersInRange:withString:).

p	editedMask

− (unsigned int)editedMask

Returns the kinds of edits pending for the receiver, as a mask containing either or both of NSTextStorageEditedAttributes and NSTextStorageEditedCharacters. Use the C bitwise AND operator to test the mask; testing for equality will fail if additional mask flags are added later. The receiver’s delegate and layout managers can use this information to determine the nature of edits in their respective notification methods.

See also:	− editedRange, − changeInLength

p	editedRange

− (NSRange)editedRange

Returns the range of the receiver to which pending changes have been made, whether of characters or of attributes. The receiver’s delegate and layout managers can use this information to determine the nature of edits in their respective notification methods.

See also:	− changeInLength, − editedMask

p	endEditing

− (void)endEditing

Clears the last recorded invocation of beginEditing, and if there are no more, invokes processEditing to clean up after changes and notify the delegate and layout managers of the edits.

p	layoutManagers

− (NSArray *)layoutManagers

Returns the receiver’s NSLayoutManagers.

See also:	− addLayoutManager:, − removeLayoutManager:

p	processEditing

− (void)processEditing

Cleans up changes made to the receiver and notifies its delegate and layout managers of changes. This method is automatically invoked in response to an endEditing or edited:range:changeInLength: message. You should never need to invoke it directly.

This method begins by posting an NSTextStorageWillProcessEditingNotification to the default notification center (which results in the delegate receiving a textStorageWillProcessEditing: message). It then invokes the inherited fixAttributesAfterEditingRange: method to fix up attributes after a batch of editing changes. After this, it posts an NSTextStorageDidProcessEditingNotification to the default notification center (which results in the delegate receiving a textStorageDidProcessEditing: message). Finally, it sends a textStorage:edited:range:changeInLength:invalidatedRange: message to each of the receiver’s NSLayoutManagers using the argument values provided.

p	removeLayoutManager:

− (void)removeLayoutManager:(NSLayoutManager *)aLayoutManager

Removes aLayoutManager from the receiver’s set of NSLayoutManagers.

See also:	− addLayoutManager:, − layoutManagers

p	setDelegate:

− (void)setDelegate:(id)anObject

Sets the receiver’s delegate to anObject.

See also:	− delegate

Methods Implemented By the Delegate

p	textStorageDidProcessEditing:

− (void)textStorageDidProcessEditing:(NSNotification *)aNotification

Informs the delegate that an NSTextStorage object has finished processing edits. The text storage object is available by sending object to aNotification, which is always an NSTextStorageDidProcessEditingNotification. The delegate can use this notification to verify the final state of the text storage object; it can’t change the text storage object’s characters without leaving it in an inconsistent state, but if necessary it can change attributes. Note that even in this case it’s possible to put a text storage object into an inconsistent state—for example by changing the font of a range to one that doesn’t support the characters in that range (such as using a Latin font for Kanji text).

p	textStorageWillProcessEditing:

− (void)textStorageWillProcessEditing:(NSNotification *)aNotification

Informs the delegate that an NSTextStorage object is about to process edits. The text storage object is available by sending object to aNotification, which is always an NSTextStorageWillProcessEditingNotification. The delegate can use this notification to verify the changed state of the text storage object, and to make changes to the text storage object’s characters or attributes to enforce whatever constraints it establishes (which doesn’t result in this message being sent again, however). For example, a code editor application might add a delegate that checks after edits to make sure that all programming language keywords are set in boldface.

Notifications

NSTextStorageDidProcessEditingNotification

Posted after the NSTextStorage finishes processing edits in processEditing. Observers other than the delegate shouldn’t make further changes to the NSTextStorage. The notification contains:

Notification Object	The NSTextStorage that processed edits.

Userinfo	None

NSTextStorageWillProcessEditingNotification

Posted before the NSTextStorage finishes processing edits in processEditing. Observers other than the delegate shouldn’t make further changes to the NSTextStorage. The notification contains:

Notification Object	The NSTextStorage about to process edits.

Userinfo	None


NSTextTab
p NSTextTab

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSCopying

NSObject (NSObject)

Declared In:	AppKit/NSParagraphStyle.h

Class Description

An NSTextTab represents a tab in an NSParagraphStyle object, storing an alignment type and location. NSTextTabs are most frequently used with NeXT’s extended text system and with NSRulerView and NSRulerMarker objects. See the appropriate class specifications for more information on these uses.

The text system supports four alignment types: left, center, right, and decimal (based on the decimal separator character of the locale in effect). These alignment types are absolute, not based on the line sweep direction of text. For example, tabbed text is always positioned to the left of a right-aligned tab, whether the line sweep direction is left-to-right or right-to-left. A tab’s location, on the other hand, is relative to the back margin. A tab set at 1.5", for example, is at 1.5" from the right in right-to-left text.

Adopted Protocols

NSCopying	− copyWithZone:

Method Types

Creating an NSTextTab	− initWithType:location:

Getting tab stop information	− location

− tabStopType

Instance Methods

p	initWithType:location:

− (id)initWithType:(NSTextTabType)type location:(float)location

Initializes a newly allocated NSTextTab with an alignment of type at location on the paragraph. The location is relative to the back margin, based on the line sweep direction of the paragraph. type can be any one of:

NSLeftTabStopType	NSRightTabStopType

NSCenterTabStopType	NSDecimalTabStopType

p	location

− (float)location

Returns the ruler location of the receiver relative to the back margin.

p	tabStopType

− (NSTextTabType)tabStopType

Returns the tab stop type of the receiver. The possible values are listed in the initWithType:location: method description.


NSTextView
p NSTextView

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSText : NSView : NSResponder : NSObject

Conforms To:	NSTextInput

NSChangeSpelling (NSText)

NSIgnoreMisspelledWords (NSText)

NSCoding (NSResponder) — Note: NSTextView doesn’t implement this protocol

NSObject (NSObject)

Declared In:	AppKit/NSTextView.h

Purpose

NSTextView is the front-end component of NeXT’s extended text system. It displays and manipulates text laid out in an area defined by an NSTextContainer, and adds many features to those defined by its superclass, NSText.

Principal Attributes

•	Supports rich text and graphics	•	Supports input management and key bindings

•	Works with the Font Panel and menu	•	Works with rulers

•	Provides delegation and notification	•	Works with the Services facility

•	Works with the pasteboard	•	Works with spell-checking services

Creation

Interface Builder

− initWithFrame:	Creates an NSTextView along with all its supporting objects.

− initWithFrame:textContainer:	Designated initializer.

Commonly Used Methods

The methods most commonly used with NSTextView objects are declared in NSText, the superclass. These methods provide access to the other major components of the text system:

− textStorage	Returns the associated NSTextStorage object.

− textContainer	Returns the associated NSTextContainer object.

− layoutManager	Returns the associated NSLayoutManager object.

Class Description

NSTextView is the front-end class to NeXT’s extended text-handling system. It draws the text managed by the back-end components and handles user events to select and modify its text. NSTextView is the principal means to obtain a text object that caters to almost all needs for displaying and managing text at the user interface level. While NSTextView is a subclass of NSText—which declares the most general OpenStep interface to the text system—NSTextView adds several major features over and above the capabilities of NSText.

One of the design goals of NSTextView is to provide a comprehensive set of text-handling features so that you should rarely need to create a subclass. In its standard incarnation, NSTextView creates the requisite group of objects that support the text handling system—NSTextContainer, NSLayoutManager, and NSTextStorage objects. Refer to “The OPENSTEP Text System” for a comprehensive overview of the components of the text system. Here are the major features that NSTextView adds to those of NSText:

Rulers. NSTextView works with the NSRulerView class to let users control paragraph formatting, in addition to using commands in the Format Text menu provided by Interface Builder.

Input management and key binding. Certain key combinations are bound to specific NSTextView methods so that the user can move the insertion point, for example, without using the mouse.

Marked text attributes. NSTextView defines a set of text attributes that support special display characteristics during input management. Marked text attributes only affect visual aspects of text—color, underline, and so on—they don’t include any attributes that would change the layout of text.

File and graphic attachments. The extended text system provides programmatic access to text attachments as instances of NSTextAttachment, through the NSTextView and NSTextStorage classes.

Delegate messages and notifications. NSTextView adds several delegate messages and notifications to those used by NSText. The delegate and observers of an NSTextView can receive any of the messages or notifications declared by both classes.

Creating NSTextView Objects

The easiest way to add an NSTextView to your application is through Interface Builder. Interface Builder’s Data Views palette supplies a specially configured NSScrollView object that contains an NSTextView object as its document view. This NSTextView is configured to work with the NSScrollView and other user-interface controls such as a ruler, the Font menu, the Edit menu, and so on.

Interface Builder also offers other objects—of the NSTextField and NSForm classes—that make use of NSTextView objects for their text-editing facilities. In fact, all NSTextFields and NSForms within the same window share the same NSTextView object (known as the field editor), thus reducing the memory demands of an application. If your application requires stand-alone or grouped text fields that support editing (and all the other facilities provided by the NSTextView class), these are the classes to use.

You can also create NSTextView objects programmatically, using either of the methods initWithFrame:textContainer: (the designated initializer), or initWithFrame:. The initWithFrame: method is the simplest way to obtain an NSTextView object—it creates all the other components of the text-handling system for you and releases them when you’re done. If you use initWithFrame:textContainer:, you must construct (and release) the other components yourself. See the “The OPENSTEP Text System” for more information.

Configuring Editing Behavior

Like NSText, NSTextView allows you to grant or deny the user the ability to select or edit its text, using the setSelectable: and setEditable: methods. These methods only affect what the user can do; you can still make changes to the NSTextView programmatically. An editable text view can behave as a normal text editor, accepting Tab and Return characters, or as a field editor, interpreting tabs and returns as cues to end editing. The setFieldEditor: method controls this behavior. NSTextView also implements the distinction between plain and rich text defined by NSText with its setRichText: and setImportsGraphics: methods. See the NSText class specification for more information on these various distinctions.

Attachments

While NSText leaves open the nature of imported graphics and other attachments, NSTextView explicitly uses NSTextAttachment objects, which contain NSFileWrappers that represent the attached files. NSTextView declares several delegate methods that let you handle user actions on an attachment’s image or icon. textView:clickedOnCell:inRect: and textView:doubleClickedOnCell:inRect: let the delegate take action on mouse clicks, and textView:draggedCell:inRect:event: lets the delegate initiate a dragging session for the attachment. See the NSTextAttachment, NSTextAttachmentCell, and NSFileWrapper class and protocol specifications for more information on working with attachments.

Input Management

NSTextView uses an input manager to turn basic character information into text and commands. It passes uninterpreted keyboard input to the input manager, which examines the characters generated and sends messages to the NSTextView based on those characters. If the typed characters are interpreted as text to input, the input manager sends the text view an insertText: message. If they’re interpreted as commands to perform, such as moving the insertion point or deleting text, the input manager sends the text view a doCommandBySelector: message. Many of the standard commands are described in the NSResponder class specification. NSTextView also gives its delegate a chance to handle a command by sending it a textView:doCommandBySelector: message. If the delegate implements this method and returns YES, the text view does nothing further; otherwise it tries to perform the command itself.

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

Using the Font Panel and Ruler

NSTextView is designed to work with the Application Kit’s font conversion system, defined by the NSFontPanel and NSFontManager classes. By default, an NSTextView keeps the Font Panel updated with the first font in its selection, or of its typing attributes (defined below). It also changes the font in response to messages from the Font Panel and Font menu. Such changes apply to the selected text or typing attributes for a rich text view, or to all the text in a plain text view. You can turn this behavior off using the setUsesFontPanel: method. Doing so is recommended for a text view that serves as a field editor, for example. Making an NSTextView not use the font conversion system renders some of its other methods unusable, as these methods require access to font information to work. See the description of setUsesFontPanel: for these side effects.

NSTextView also defines a comprehensive interface for manipulating paragraph attributes, using the NSRulerView class. If an NSTextView is enclosed in an NSScrollView, it can display a ruler view, which displays margin and tab markers that the user can manipulate to adjust their settings, as well as other controls for setting alignment, paragraph spacing, and so on. setRulerVisible: and the inherited toggleRuler: control whether the ruler view is displayed. The NSTextView serves as the ruler view’s client, as described in the NSRulerView class specification. Similar to the Font Panel, NSTextView can be set not to use a ruler with the setUsesRuler: method. This has side effects similar to those of setUsesFontPanel:.

Examining and Setting the Selection

Most of the time the selection is determined by the user through mouse or keyboard operations. You can get the range of characters currently selected using the selectedRange method. This is the single most commonly used method for examining the selection. You can also set the selection programmatically using setSelectedRange:. NSTextView indicates its selection by applying a special set of attributes to it. selectedTextAttributes returns these attributes, and setSelectedTextAttributes: sets them.

While changing the selection in response to user input, an NSTextView invokes its setSelectedRange:affinity:stillSelecting: method. The first argument is of course the range to select. The second, called the selection affinity, determines which glyph the insertion point displays near when the two glyphs aren’t adjacent. It’s typically used where lines wrap to place the insertion point at the end of one line or the beginning of the following line. You can get the selection affinity in effect using the selectionAffinity method. The last argument indicates whether the selection is still in the process of changing; the delegate and any observers aren’t notified of the change in the selection until the method is invoked with NO for this argument. An additional factor affecting selection behavior is the selection granularity: whether characters, words, or whole paragraphs are being selected. This is usually determined by number of initial clicks; for example, a double-click initiates word-level selection. NSTextView decides how much to change the selection during input tracking using its selectionRangeForProposedRange:granularity: method, as described below under “Subclass Responsibilities.”

An additional aspect of selection, actually related to input management, is the range of marked text. As the input manager interprets keyboard input, it can mark incomplete input in a special way. markedRange returns the range of any marked text, and markedTextAttributes returns the attributes used to highlight the marked text. You can change these attributes using setMarkedTextAttributes:

Setting Text Attributes

NSTextView allows you to change the attributes of its text programmatically through various methods, most inherited from the superclass, NSText. NSTextView adds its own methods for setting the attributes of text that the user types, for setting the baseline offset of text as an absolute value, and for adjusting kerning and use of ligatures. Most of the methods for changing attributes are defined as action methods, and apply to the selected text or typing attributes for a rich text view, or to all of the text in a plain text view.

An NSTextView maintains a set of typing attributes (font, size, color, and so on) that it applies to newly entered text, whether typed by the user or pasted as plain text. It automatically sets the typing attributes to the attributes of the first character immediately preceding the insertion point, of the first character of a paragraph if the insertion point is at the beginning of a paragraph, or of the first character of a selection. The user can change the typing attributes by choosing menu commands and using utilities such as the Font Panel. You can also set the typing attributes programmatically using setTypingAttributes:, though you should rarely find need to do so unless creating a subclass.

NSText defines the action methods superscript:, subscript:, and unscript:, which raise and lower the baseline of text by predefined increments. NSTextView gives you much finer control over the baseline offset of text by defining the raiseBaseline: and lowerBaseline: action methods, which raise or lower text by one point each time they’re invoked.

Kerning

NSTextView provides convenient action methods for adjusting the spacing between characters. By default, an NSTextView object uses standard kerning (as provided by the data in a font’s AFM file). A turnOffKerning: message causes this kerning information to be ignored and the selected text to be displayed using nominal widths. The loosenKerning: and tightenKerning: methods adjust kerning values over the selected text and useStandardKerning: reestablishes the default kerning values.

Kerning information is a character attribute that’s stored in the text view’s NSTextStorage object. If your application needs finer control over kerning than the methods of this class provide, you should operate on the NSTextStorage object directly through methods defined by its superclass, NSMutableAttributedString. See the NSAttributedString Class Cluster Additions specification for information on setting attributes.

Ligatures

NSTextView’s support for ligatures provides the minimum required ligatures for a given font and script. The required ligatures for a specific font and script are determined by the mechanisms that generate glyphs for a specific language. Some scripts may well have no ligatures at all—English text, as an example, doesn’t require ligatures, although certain ligatures such as “fi” and “fl” are desirable and are used if they’re available. Other scripts, such as Arabic, demand that certain ligatures must be available even if a turnOffLigatures: message is sent to the NSTextView. Other scripts and fonts have standard ligatures that are used if they’re available. The useAllLigatures: method extends ligature support to include all possible ligatures available in each font for a given script.

Ligature information is a character attribute that’s stored in the text view’s NSTextStorage object. If your application needs finer control over ligature use than the methods of this class provide, you should operate on the NSTextStorage object directly through methods defined by its superclass, NSMutableAttributedString. See the NSAttributedString Class Cluster Additions specification for information on setting attributes.

Using Multiple NSTextViews

A single NSLayoutManager can be assigned any number of NSTextContainers, in whose NSTextViews it lays out text sequentially. In such a configuration, many of the attributes accessed through the NSTextView interface are actually shared by all of these text views. Among these attributes are:

•	The selection

•	The delegate (see “Other Delegate Messages and Notifications” below for details)

•	Selectability

•	Editability

•	Whether they act as a field editor

•	Whether they display plain or rich text

•	Whether they import graphics

•	Whether the ruler is visible

•	Whether they use the Font Panel

•	Whether they use the ruler

Setting any of these attributes causes all associated NSTextView’s to share the new value.

With multiple NSTextViews, only one is the first responder at any time. NSLayoutManager defines these methods for determining and appropriately setting the first responder:

− layoutManagerOwnsFirstResponderInWindow:

− firstTextView

− textViewForBeginningOfSelection

See their descriptions in the NSLayoutManager class specification for more information.

Other Delegate Messages and Notifications

An NSTextView object can have a delegate that it informs of certain actions or pending changes to the state of the text. Several of the delegate methods have already been mentioned; here are all of the messages that a delegate can receive:

textView:willChangeSelectionFromCharacterRange:toCharacterRange:

textViewDidChangeSelection:

textShouldBeginEditing:

textDidBeginEditing:

textView:shouldChangeTextInRange:replacementString:

textDidChange:

textShouldEndEditing:

textDidEndEditing:

textView:doCommandBySelector:

textView:clickedCell:inRect:

textView:doubleClickedCell:inRect:

textView:draggedCell:inRect:event:

Those whose names begin with “text” rather than “textView” are declared by NSText and described in the NSText class specification. See “Methods Implemented By the Delegate” at the end of this class description for more details. The delegate can be any object you choose, and one delegate can control multiple NSTextView objects (or multiple series of connected NSTextView objects).

All NSTextView objects attached to the same NSLayoutManager share the same delegate: Setting the delegate of one such NSTextView sets the delegate for all the others. Delegate messages pass the id of the sender as an argument. For multiple NSTextViews attached to the same NSLayoutManager, the id is that of the notifying text view, the first NSTextView for the shared NSLayoutManager. As the name implies, this NSTextView is also responsible for posting notifications at the appropriate times.

The notifications posted by NSTextView are:

NSTextViewDidChangeSelectionNotification

NSTextDidBeginEditingNotification

NSTextDidEndEditingNotification

NSTextDidChangeNotification

NSTextViewWillChangeNotifyingTextViewNotification

Of these, the last is crucially import for observers to register for. If a new NSTextView is added at the beginning of a series of connected NSTextViews, it becomes the new notifying text view. It doesn’t have access to which objects are observing its group of text objects, so it posts an NSTextViewWillChangeNotifyingTextViewNotification, which allows all those observers to unregister themselves from the old notifying text view and reregister themselves with the new one. See the description for this notification at the end of this specification for more information.

Subclass Responsibilities

NSTextView expects subclasses to abide by certain rules of behavior, and provides many methods to help subclasses do so. Some of these methods are meant to be overridden to add information and behavior into the basic infrastructure. Some are meant to be invoked as part of that infrastructure when the subclass defines its own behavior. The following sections describe the major areas where a subclass has obligations or where it can expect help in implementing its new features.

Updating State

NSTextView automatically updates the Font Panel and ruler as its selection changes. If you add any new font or paragraph attributes to your subclass of NSTextView, you’ll need to override the methods that perform this updating to account for the added information. updateFontPanel makes the Font Panel display the font of the first character in the selection; you might override it to update the display of an accessory view in the Font Panel. Similarly, updateRuler causes the ruler to display the paragraph attributes for the first paragraph in the selection. You can also override this to customize display of items in the ruler. Be sure to invoke super’s implementation to have the basic updating performed as well.

Custom Import Types

NSTextView supports the dragging of files and colors into its text. If you customize the ability of your subclass to handle dragging operations for new types of data, you should override the acceptableDragTypes method to reflect those types. Your implementation should invoke super’s implementation, add to the array returned any types your subclass also supports, and return that array. If your subclass’s ability to accept your custom dragging types varies over time, you can override updateDragTypeRegistration to register or unregister the custom types according to the text view’s current status. By default this method enables dragging of all acceptable types if the receiver is editable and a rich text view.

Altering Selection Behavior

Your subclass of NSTextView can customize the way selections are made for the various granularities described in “Examining and Setting the Selection.” While tracking user changes to the selection, whether by the mouse or keyboard, an NSTextView repeatedly invokes selectionRangeForProposedRange:granularity: to determine what range to actually select. When finished tracking changes, it sends the delegate a textView:willChangeSelectionFromCharacterRange:toCharacterRange:. message By overriding the NSTextView method or implementing the delegate method, you can alter the way the selection is extended or reduced. For example, in a code editor you can provide a delegate that extends a double click on a brace or parenthesis character to its matching delimiter.

Note:	These mechanisms aren’t meant for changing language word definitions (such as what’s selected on a double click). This detail of selection is handled at a lower (and currently private) level of the text system.

Preparing to Change Text

If you create a subclass of NSTextView to add new capabilities that will modify the text in response to user actions, you may need to modify the range selected by the user before actually applying the change. For example, if the user is making a change to the ruler, the change must apply to whole paragraphs, so the selection may have to be extended to paragraph boundaries. Three methods calculate the range to which certain kinds of change should apply. rangeForUserTextChange returns the range to which any change to characters themselves—insertions and deletions—should apply. rangeForUserCharacterAttributeChange returns the range to which a character attribute change, such as a new font or color, should apply. Finally, rangeForUserParagraphAttributeChange returns the range for a paragraph-level change, such as a new or moved tab stop, or indent. These methods all return a range whose location is NSNotFound if a change isn’t possible; you should check the returned range and abandon the change in this case.

Notifying About Changes to the Text

In actually making changes to the text, you must ensure that the changes are properly performed and recorded by different parts of the text system. You do this by bracketing each batch of potential changes with shouldChangeTextInRange:replacementString: and didChangeText messages. These methods ensure that the appropriate delegate messages are sent and notifications posted. The first method asks the delegate for permission to begin editing with a textShouldBeginEditing: message. If the delegate returns NO, shouldChangeTextInRange:replacementString: in turn returns NO, in which case your subclass should disallow the change. If the delegate returns YES, the text view posts an NSTextDidBeginEditingNotification, and shouldChangeTextInRange:replacementString: in turn returns YES. In this case you can make your changes to the text, and follow up by invoking didChangeText. This method concludes the changes by posting an NSTextDidChangeNotification, which results in the delegate receiving a textDidChange: message.

The textShouldBeginEditing: and textDidBeginEditing: messages are sent only once during an editing session. More precisely, they’re sent upon the first user input since the NSTextView became the first responder. Thereafter, these messages—and the NSTextDidBeginEditingNotification—are skipped in the sequence. textView:shouldChangeTextInRange:replacementString:, however, must be invoked for each individual change.

Smart Insert and Delete

NSTextView defines several methods to aid in “smart” insertion and deletion of text, so that spacing and punctuation is preserved after a change. Smart insertion and deletion typically applies when the user has selected whole words or other significant units of text. A smart deletion of a word before a comma, for example, also deletes the space that would otherwise be left before the comma (though not placing it on the pasteboard in a Cut operation). A smart insertion of a word between another word and a comma adds a space between the two words to protect that boundary. NSTextView automatically uses smart insertion and deletion by default; you can turn this behavior off using setSmartInsertDeleteEnabled:. Doing so causes only the selected text to be deleted, and inserted text to be added with no addition of white space.

If your subclass of NSTextView defines any methods that insert or delete text, you can make them smart by taking advantage of two NSTextView methods. smartDeleteRangeForProposedRange: expands a proposed deletion range to include any whitespace that should also be deleted. If you need to save the text deleted, though, it’s typically best to save only the text from the original range. For smart insertion, smartInsertForString:replacingRange:beforeString:afterString: returns by reference two strings that you can insert before and after a given string to preserve spacing and punctuation. See the method descriptions for more information.

Adopted Protocols

NSTextInput	− conversationIdentifier

− doCommandBySelector:

− getMarkedText:selectedRange:

− hasMarkedText

− insertText:

− setMarkedText:selectedRange:

− unmarkText

Method Types

Creating an instance	− initWithFrame:textContainer:

− initWithFrame:

Registering Services information	+ registerForServices

Accessing related text-system objects

− setTextContainer:

− replaceTextContainer:

− textContainer

− setTextContainerInset:

− textContainerInset

− textContainerOrigin

− invalidateTextContainerOrigin

− layoutManager

− textStorage

Setting graphic attributes	− setBackgroundColor:

− backgroundColor

− setDrawsBackground:

− drawsBackground

Controlling display	− setNeedsDisplayInRect:avoidAdditionalLayout:

− shouldDrawInsertionPoint

− drawInsertionPointInRect:color:turnedOn:

− setConstrainedFrameSize:

Setting behavioral attributes	− setEditable:

− isEditable

− setSelectable:

− isSelectable

− setFieldEditor:

− isFieldEditor

− setRichText:

− isRichText

− setImportsGraphics:

− importsGraphics

Using the Font Panel and menu	− setUsesFontPanel:

− usesFontPanel

Using the ruler	− setUsesRuler:

− usesRuler

− setRulerVisible:

− isRulerVisible

Managing the selection	− setSelectedRange:

− selectedRange

− setSelectedRange:affinity:stillSelecting:

− selectionAffinity

− setSelectionGranularity:

− selectionGranularity

− setInsertionPointColor:

− insertionPointColor

− updateInsertionPointStateAndRestartTimer:

− setSelectedTextAttributes:

− selectedTextAttributes

− markedRange

− setMarkedTextAttributes:

− markedTextAttributes

Setting text attributes	− setAlignment:range:

− setTypingAttributes:

− typingAttributes

− useStandardKerning:

− lowerBaseline:

− raiseBaseline:

− turnOffKerning:

− loosenKerning:

− tightenKerning:

− useStandardLigatures:

− turnOffLigatures:

− useAllLigatures:

Other action methods	− pasteAsPlainText:

− pasteAsRichText:

Methods that subclasses should use or override

− updateFontPanel

− updateRuler

− acceptableDragTypes

− updateDragTypeRegistration

− selectionRangeForProposedRange:granularity:

− rangeForUserCharacterAttributeChange

− rangeForUserParagraphAttributeChange

− rangeForUserTextChange

− shouldChangeTextInRange:replacementString:

− didChangeText

− setSmartInsertDeleteEnabled:

− smartInsertDeleteEnabled

− smartDeleteRangeForProposedRange:

− smartInsertForString:replacingRange:beforeString:afterString:

Changing first responder status	− resignFirstResponder

− becomeFirstResponder

Working with the spelling checker	− spellCheckerDocumentTag

NSRulerView client methods	− rulerView:didMoveMarker:

− rulerView:didRemoveMarker:

− rulerView:didAddMarker:

− rulerView:shouldMoveMarker:

− rulerView:shouldAddMarker:

− rulerView:willMoveMarker:toLocation:

− rulerView:shouldRemoveMarker:

− rulerView:willAddMarker:atLocation:

− rulerView:handleMouseDown:

Assigning a delegate	− setDelegate:

− delegate

Class Methods

p	registerForServices

+ (void)registerForServices

Registers send and return types for the Services facility. This method is invoked automatically; you should never need to invoke it directly.

Instance Methods

p	acceptableDragTypes

− (NSArray *)acceptableDragTypes

Returns the data types that the receiver accepts as the destination view of a dragging operation. These types are automatically registered as necessary by the NSTextView. Subclasses should override this method as necessary to add their own types to those returned by NSTextView’s implementation. They must then also override the appropriate methods of the NSDraggingDestination protocol to support import of those types. See that protocol’s specification for more information.

See also:	− updateTextViewDragTypeRegistration

p	backgroundColor

− (NSColor *)backgroundColor

Returns the receiver’s background color.

See also:	− drawsBackground, − setBackgroundColor:

p	becomeFirstResponder

− (BOOL)becomeFirstResponder

Informs the receiver that it’s becoming the first responder. If the previous first responder was not an NSTextView on the same NSLayoutManager as the receiving NSTextView, this method draws the selection and updates the insertion point if necessary. Returns YES.

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

See also:	− resignFirstResponder

p	delegate

− (id)delegate

Returns the delegate used by the receiver (and by all other NSTextViews sharing the receiver’s NSLayoutManager), or nil if there is none.

See also:	− setDelegate:

p	didChangeText

− (void)didChangeText

Invoked automatically at the end of a series of changes, this method posts an NSTextDidChangeNotification to the default notification center, which also results in the delegate receiving an NSText-delegate textDidChange: message. Subclasses implementing methods that change their text should invoke this method at the end of those methods. See the class description for more information.

See also:	− shouldChangeTextInRange:replacementString:

p	drawInsertionPointInRect:color:turnedOn:

− (void)drawInsertionPointInRect:(NSRect)aRect

color:(NSColor *)aColor

turnedOn:(BOOL)flag

If flag is YES, draws the insertion point in aRect using aColor. If flag is NO, this method erases the insertion point. The PostScript focus must be locked on the receiver when this method is invoked.

See also:	− insertionPointColor, − shouldDrawInsertionPoint, − backgroundColor, − lockFocus (NSView)

p	drawsBackground

− (BOOL)drawsBackground

Returns YES if the receiver draws its background, NO if it doesn’t.

See also:	− backgroundColor, − setDrawsBackground:

p	encodeWithCoder:

@protocol NSCoding

− (void)encodeWithCoder:(NSCoder *)encoder

Raises an NSInternalInconsistencyException. NSTextView doesn’t support coding.

p	importsGraphics

− (BOOL)importsGraphics

Returns YES if the text views sharing the receiver’s NSLayoutManager allow the user to import files by dragging, NO if they don’t.

A text view that accepts dragged files is also a rich text view.

See also:	− isRichText, − textStorage, + attributedStringWithAttachment: (NSAttributedString), − insertAttributedString:atIndex: (NSMutableAttributedString), − setImportsGraphics:

p	initWithCoder:

@protocol NSCoding

− (id)initWithCoder:(NSCoder *)decoder

Raises an NSInternalInconsistencyException. NSTextView doesn’t support coding.

p	initWithFrame:

− (id)initWithFrame:(NSRect)frameRect

Initializes a newly allocated NSTextView object with frameRect as its frame rectangle. This method creates the entire collection of objects associated with an NSTextView—its NSTextContainer, NSLayoutManager, and NSTextStorage—and invokes initWithFrame:textContainer:. Returns self.

This method creates the text web in such a manner that the NSTextView object is the principal owner of the objects in the web. See “The OPENSTEP Text System” for a detailed description of ownership issues.

p	initWithFrame:textContainer:

− (id)initWithFrame:(NSRect)frameRect textContainer:(NSTextContainer *)aTextContainer

Initializes a newly allocated NSTextView object with frameRect as its frame rectangle and aTextContainer as its text container. This method is the designated initializer for NSTextView objects. Returns self.

Unlike initWithFrame:, which builds up an entire group of text-handling objects, you use this method after you’ve created the other components of the text handling system—an NSTextStorage object, an NSLayoutManager object, and an NSTextContainer object. Assembling the components in this fashion means that the NSTextStorage, not the NSTextView, is the principal owner of the component objects. See “The OPENSTEP Text System” for a detailed description of ownership issues.

See also:	− initWithFrame:

p	insertText:

− (void)insertText:(NSString *)aString

Inserts aString into the receiver’s text at the insertion point if there is one, otherwise replacing the selection. The inserted text is assigned the current typing attributes, as explained in the class description under “Setting Text Attributes.”

This method is the means by which typed text enters an NSTextView. See the NSInputManager class and NSTextInput protocol specifications for more information.

See also:	− typingAttributes

p	insertionPointColor

− (NSColor *)insertionPointColor

Returns the color used to draw the insertion point.

See also:	− drawInsertionPointInRect:color:turnedOn:, − shouldDrawInsertionPoint, − setInsertionPointColor:

p	invalidateTextContainerOrigin

− (NSColor *)invalidateTextContainerOrigin

Informs the receiver that it needs to recalculate the origin of its text container, usually because it’s been resized or the contents of the text container have changed. This method is invoked automatically; you should never need to invoke it directly.

See also:	− textContainer, − textContainerOrigin

p	isEditable

− (BOOL)isEditable

Returns YES if the text views sharing the receiver’s NSLayoutManager allow the user to edit text, NO if they don’t. If a text view is editable, it’s also selectable.

See also:	− isSelectable, − setEditable:

p	isFieldEditor

− (BOOL)isFieldEditor

Returns YES if the text views sharing the receiver’s NSLayoutManager interpret Tab, Shift-Tab, and Return (Enter) as cues to end editing, and possibly to change the first responder; no if they accept them as text input. See the NSWindow class specification for more information on field editors. By default, NSTextViews don’t behave as field editors.

See also:	− setFieldEditor:

p	isRichText

− (BOOL)isRichText

Returns YES if the text views sharing the receiver’s NSLayoutManager allow the user to apply attributes to specific ranges of the text, NO if they don’t.

See also:	− importsGraphics, − textStorage, − setRichText:

p	isRulerVisible

− (BOOL)isRulerVisible

Returns YES if the scroll view enclosing the text views sharing the receiver’s NSLayoutManager shows its ruler, NO otherwise.

See also:	− usesRuler, − setRulerVisible:, − toggleRuler: (NSText)

p	isSelectable

− (BOOL)isSelectable

Returns YES if the text views sharing the receiver’s NSLayoutManager allow the user to select text, NO if they don’t.

See also:	− isEditable, − setSelectable:

p	layoutManager

− (NSLayoutManager *)layoutManager

Returns the NSLayoutManager that lays out text for the receiver’s text container, or nil if there’s no such object (which is the case when a text view isn’t linked into a group of text objects).

See also:	− textContainer, − setLayoutManager: (NSTextContainer), − replaceLayoutManager: (NSTextContainer)

p	loosenKerning:

− (void)loosenKerning:(id)sender

This action method increases the space between glyphs in the receiver’s selection, or in all text if the receiver is a plain text view. Kerning values are determined by the point size of the fonts in the selection.

See also:	− tightenKerning, − turnOffKerning:, − useStandardKerning:

p	lowerBaseline:

− (void)lowerBaseline:(id)sender

This action method lowers the baseline offset of selected text by one point, or of all text if the receiver is a plain text view. As such, this method defines a more primitive operation than subscripting.

See also:	− raiseBaseline:, − subscript: (NSText), − unscript: (NSText)

p	markedRange

− (NSRange)markedRange

Returns the range of marked text. If there’s no marked text, returns a range whose location is NSNotFound.

See also:	− setMarkedTextAttributes:

p	markedTextAttributes

− (NSDictionary *)markedTextAttributes

Returns the attributes used to draw marked text.

See also:	− setMarkedTextAttributes:

p	pasteAsPlainText:

− (void)pasteAsPlainText:(id)sender

This action method inserts the contents of the pasteboard into the receiver’s text as plain text, in the manner of insertText:.

See also:	− pasteAsRichText:, − insertText:

p	pasteAsRichText:

− (void)pasteAsRichText:(id)sender

This action method inserts the contents of the pasteboard into the receiver’s text as rich text, maintaining its attributes. The text is inserted at the insertion point if there is one, otherwise replacing the selection.

See also:	− pasteAsRichText:, − insertText:

p	raiseBaseline:

− (void)raiseBaseline:(id)sender

This action method raises the baseline offset of selected text by one point, or of all text if the receiver is a plain text view. As such, this method defines a more primitive operation than superscripting.

See also:	− lowerBaseline:, − superscript: (NSText), − unscript: (NSText)

p	rangeForUserCharacterAttributeChange

− (NSRange)rangeForUserCharacterAttributeChange

Returns the range of characters affected by an action method that changes character (not paragraph) attributes, such as the NSText action method changeFont:. For rich text this is typically the range of the selection. For plain text this is the entire contents of the receiver.

If the receiver isn’t editable or doesn’t use the Font Panel, the range returned has a location of NSNotFound.

See also:	− rangeForUserParagraphAttributeChange, − rangeForUserTextChange,

− isEditable, − usesFontPanel

p	rangeForUserParagraphAttributeChange

− (NSRange)rangeForUserParagraphAttributeChange

Returns the range of characters affected by a method that changes paragraph (not character) attributes, such as the NSText action method alignLeft:. For rich text this is typically calculated by extending the range of the selection to paragraph boundaries. For plain text this is the entire contents of the receiver.

If the receiver isn’t editable the range returned has a location of NSNotFound.

See also:	− rangeForUserParagraphAttributeChange, − rangeForUserTextChange,

− isEditable, − usesRuler

p	rangeForUserTextChange

− (NSRange)rangeForUserTextChange

Returns the range of characters affected by a method that changes characters (as opposed to attributes), such as insertText:. This is typically the range of the selection.

If the receiver isn’t editable or doesn’t use a ruler, the range returned has a location of NSNotFound.

See also:	− rangeForUserParagraphAttributeChange, − rangeForUserTextChange, − isEditable, − usesRuler

p	replaceTextContainer:

− (void)replaceTextContainer:(NSTextContainer *)aTextContainer

Replaces the NSTextContainer for the group of text-system objects containing the receiver with aTextContainer, keeping the association between the receiver and its layout manager intact, unlike setTextContainer:. Raises NSInvalidArgumentException if aTextContainer is nil.

See also:	− initWithFrame:textContainer:, − setTextContainer:

p	resignFirstResponder

− (BOOL)resignFirstResponder

Notifies the receiver that it’s been asked to relinquish its status as first responder in its NSWindow. If the object that will become the new first responder is an NSTextView attached to the same NSLayoutManager as the receiver, this method returns YES with no further action. Otherwise, this method sends a textShouldEndEditing: message to its delegate (if any). If the delegate returns NO, this method returns NO. If the delegate returns YES this method hides the selection highlighting and posts an NSTextDidEndEditingNotification to the default notification center.

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

See also:	− becomeFirstResponder

continue with this topic


NSTextView2
p	rulerView:didAddMarker:

− (void)rulerView:(NSRulerView *)aRulerView didAddMarker:(NSRulerMarker *)aMarker

This NSRulerView client method modifies the paragraph style of the paragraphs containing the selection to accommodate a new NSTextTab represented by aMarker. It then records the change by invoking didChangeText.

NSTextView checks for permission to make the change in its rulerView:shouldAddMarker: method, which invokes shouldChangeTextInRange:replacementString: to send out the proper request and notifications, and only invokes this method if permission is granted.

See also:	− representedObject (NSRulerMarker), − rulerView:didMoveMarker:, − rulerView:didRemoveMarker:

p	rulerView:didMoveMarker:

− (void)rulerView:(NSRulerView *)aRulerView didMoveMarker:(NSRulerMarker *)aMarker

This NSRulerView client method modifies the paragraph style of the paragraphs containing the selection to record the new location of the NSTextTab represented by aMarker. It then records the change by invoking didChangeText.

NSTextView checks for permission to make the change in its rulerView:shouldMoveMarker: method, which invokes shouldChangeTextInRange:replacementString: to send out the proper request and notifications, and only invokes this method if permission is granted.

See also:	− representedObject (NSRulerMarker), − rulerView:didAddMarker:, − rulerView:didRemoveMarker:

p	rulerView:didRemoveMarker:

− (void)rulerView:(NSRulerView *)aRulerView didRemoveMarker:(NSRulerMarker *)aMarker

This NSRulerView client method modifies the paragraph style of the paragraphs containing the selection—if possible—by removing the NSTextTab represented by aMarker. It then records the change by invoking didChangeText.

NSTextView checks for permission to move or remove a tab stop in its rulerView:shouldMoveMarker: method, which invokes shouldChangeTextInRange:replacementString: to send out the proper request and notifications, and only invokes this method if permission is granted.

See also:	− representedObject (NSRulerMarker), − shouldChangeTextInRange:replacementString:, − rulerView:didAddMarker:, − rulerView:didMoveMarker:

p	rulerView:handleMouseDown:

− (void)rulerView:(NSRulerView *)aRulerView handleMouseDown:(NSEvent *)theEvent

This NSRulerView client method adds a left tab marker to the ruler, but a subclass can override this method to provide other behavior, such as creating guidelines. This method is invoked once with theEvent when the user first clicks in the aRulerView’s ruler area, as described in the NSRulerView class specification.

p	rulerView:shouldAddMarker:

− (BOOL)rulerView:(NSRulerView *)aRulerView shouldAddMarker:(NSRulerMarker *)aMarker

This NSRulerView client method controls whether a new tab stop can be added. The receiver checks for permission to make the change by invoking shouldChangeTextInRange:replacementString: and returning the return value of that message. If the change is allowed, the receiver is then sent a rulerView:didAddMarker: message.

See also:	− rulerView:shouldMoveMarker:, − rulerView:shouldRemoveMarker:

p	rulerView:shouldMoveMarker:

− (BOOL)rulerView:(NSRulerView *)aRulerView shouldMoveMarker:(NSRulerMarker *)aMarker

This NSRulerView client method controls whether an existing tab stop can be moved. The receiver checks for permission to make the change by invoking shouldChangeTextInRange:replacementString: and returning the return value of that message. If the change is allowed, the receiver is then sent a rulerView:didMoveMarker: message.

See also:	− rulerView:shouldAddMarker:, − rulerView:shouldRemoveMarker:

p	rulerView:shouldRemoveMarker:

− (BOOL)rulerView:(NSRulerView *)aRulerView shouldRemoveMarker:(NSRulerMarker *)aMarker

This NSRulerView client method controls whether an existing tab stop can be removed. Returns YES if aMarker represents an NSTextTab, NO otherwise. Because this method can be invoked repeatedly as the user drags a ruler marker, it returns that value immediately. If the change is allows and the user actually removes the marker, the receiver is also sent a rulerView:didRemoveMarker: message.

See also:	− rulerView:shouldAddMarker:, − rulerView:shouldMoveMarker:

p	rulerView:willAddMarker:atLocation:

− (float)rulerView:(NSRulerView *)aRulerView

willAddMarker:(NSRulerMarker *)aMarker

atLocation:(float)location

This NSRulerView client method ensures that the proposed location of aMarker lies within the appropriate bounds for the receiver’s text container, returning the modified location.

See also:	− rulerView:didAddMarker:

p	rulerView:willMoveMarker:toLocation:

− (float)rulerView:(NSRulerView *)aRulerView

willMoveMarker:(NSRulerMarker *)aMarker

toLocation:(float)location

This NSRulerView client method ensures that the proposed location of aMarker lies within the appropriate bounds for the receiver’s text container, returning the modified location.

See also:	− rulerView:didMoveMarker:

p	selectedRange

− (NSRange)selectedRange

Returns the range of characters selected in the receiver’s layout manager.

See also:	− selectedTextAttributes, − setSelectedRange:affinity:stillSelecting:, − selectionRangeForProposedRange:granularity:, − setSelectedRange:

p	selectedTextAttributes

− (NSDictionary *)selectedTextAttributes

Returns the attributes used to indicate the selection. This is typically just the text background color.

See also:	− selectedRange, − setSelectedTextAttributes:

p	selectionAffinity

− (NSSelectionAffinity)selectionAffinity

Returns the preferred direction of selection, either NSSelectionAffinityUpstream or NSSelectionAffinityDownstream. Selection affinity determines whether, for example, the insertion point appears after the last character on a line or before the first character on the following line in cases where text wraps across line boundaries.

See also:	− setSelectedRange:affinity:stillSelecting:

p	selectionGranularity

− (NSSelectionGranularity)selectionGranularity

Returns the current selection granularity, used during mouse tracking to modify the range of the selection. This is one of:

NSSelectByCharacter

NSSelectByWord

NSSelectByParagraph

See also:	− selectionRangeForProposedRange:granularity:, − setSelectionGranularity:

p	selectionRangeForProposedRange:granularity:

− (NSRange)selectionRangeForProposedRange:(NSRange)proposedSelRange granularity:(NSSelectionGranularity)granularity

Adjusts the proposedSelRange if necessary, based on granularity, which is one of:

NSSelectByCharacter

NSSelectByWord

NSSelectByParagraph

Returns the adjusted range. This method is invoked repeatedly during mouse tracking to modify the range of the selection. Override this method to specialize selection behavior.

See also:	− setSelectionGranularity:

p	setAlignment:range:

− (void)setAlignment:(NSTextAlignment)alignment range:(NSRange)aRange

Sets the alignment of the paragraphs containing characters in aRange to alignment, which is one of:

NSLeftTextAlignment

NSRightTextAlignment

NSCenterTextAlignment

NSJustifiedTextAlignment

NSNaturalTextAlignment

See also:	− rangeForUserParagraphAttributeChange

p	setBackgroundColor:

− (void)setBackgroundColor:(NSColor *)aColor

Sets the receiver’s background color to aColor.

See also:	− setDrawsBackground:, − backgroundColor

p	setConstrainedFrameSize:

− (void)setConstrainedFrameSize:(NSSize)desiredSize

Attempts to set the frame size for the NSTextView to desiredSize, constrained by the receiver’s existing minimum and maximum sizes and by whether resizing is permitted.

See also:	− minSize (NSText), − maxSize (NSText), − isHorizontallyResizable (NSText), − isVerticallyResizable (NSText)

p	setDelegate:

− (void)setDelegate:(id)anObject

Sets the delegate for all NSTextViews sharing the receiver’s NSLayoutManager to anObject, without retaining it.

See also:	− delegate

p	setDrawsBackground:

− (void)setDrawsBackground:(BOOL)flag

Controls whether the receiver draws its background. If flag is YES, the receiver fills its background with the background color; if flag is NO, it doesn’t.

See also:	− setBackgroundColor:, − drawsBackground

p	setEditable:

− (void)setEditable:(BOOL)flag

Controls whether the text views sharing the receiver’s NSLayoutManager allow the user to edit text. If flag is YES, they allow the user to edit text and attributes; if flag is NO, they don’t. If n NSTextView is made editable, it’s also made selectable. NSTextViews are by default editable.

See also:	− setSelectable:, − isEditable

p	setFieldEditor:

− (void)setFieldEditor:(BOOL)flag

Controls whether the text views sharing the receiver’s NSLayoutManager interpret Tab, Shift-Tab, and Return (Enter) as cues to end editing, and possibly to change the first responder. If flag is YES, they do; if flag is NO, they don’t, instead accepting these characters as text input. See the NSWindow class specification for more information on field editors. By default, NSTextViews don’t behave as field editors.

See also:	− isFieldEditor

p	setImportsGraphics:

− (void)setImportsGraphics:(BOOL)flag

Controls whether the text views sharing the receiver’s NSLayoutManager allow the user to import files by dragging. If flag is YES, they do; if flag is NO, they don’t. If an NSTextView is set to accept dragged files, it’s also set for rich text. By default, NSTextViews don’t accept dragged files.

See also:	− textStorage, − setRichText:, − importsGraphics

p	setInsertionPointColor:

− (void)setInsertionPointColor:(NSColor *)aColor

Sets the color of the insertion point to aColor.

See also:	− drawInsertionPointInRect:color:turnedOn:, − shouldDrawInsertionPoint, − insertionPointColor

p	setMarkedTextAttributes:

− (void)setMarkedTextAttributes:(NSDictionary *)attributes

Sets the attributes used to draw marked text to attributes. Text color, background color, and underline are the only supported attributes for marked text.

See also:	− markedTextAttributes, − markedRange

p	setNeedsDisplayInRect:avoidAdditionalLayout:

− (void)setNeedsDisplayInRect:(NSRect)aRect avoidAdditionalLayout:(BOOL)flag

Marks the receiver as requiring display within aRect. If flag is YES, the receiver won’t perform any layout that might be required to complete the display, even if this means that portions of the NSTextView remain empty. If flag is NO, the receiver performs at least as much layout as needed to display aRect.

NSTextView overrides the NSView setNeedsDisplayInRect: method such that it invokes this method with NO as flag.

p	setRichText:

− (void)setRichText:(BOOL)flag

Controls whether the text views sharing the receiver’s NSLayoutManager allow the user to apply attributes to specific ranges of the text. If flag is YES they do; if flag is NO they don’t. If flag is NO, they’re also set not to accept dragged files. By default, NSTextViews let the user apply multiple attributes to text, but don’t accept dragged files.

See also:	− textStorage, − isRichText, − setImportsGraphics:

p	setRulerVisible:

− (void)setRulerVisible:(BOOL)flag

Controls whether the scroll view enclosing text views sharing the receiver’s NSLayoutManager displays the ruler. If flag is YES it shows the ruler; if flag is NO it hides the ruler. By default, the ruler is not visible.

See also:	− setUsesRuler:, − isRulerVisible, − toggleRuler: (NSText)

p	setSelectable:

− (void)setSelectable:(BOOL)flag

Controls whether the text views sharing the receiver’s NSLayoutManager allow the user to select text. If flag is YES, they do; if flag is NO, they don’t. If an NSTextView is made not selectable, it’s also made not editable. NSTextViews are by default both editable and selectable.

See also:	− setEditable:, − isSelectable

p	setSelectedRange:

− (void)setSelectedRange:(NSRange)charRange

Sets the selection to the characters in charRange, resets the selection granularity to NSSelectByCharacter, posts an NSTextViewDidChangeSelectionNotification to the default notification center. Also removes the marking from marked text if the new selection is greater than the marked region.

charRange must begin and end on glyph boundaries and not split base glyphs and their non-spacing marks.

See also:	− setSelectedRange:affinity:stillSelecting:, − selectionAffinity, − selectionGranularity, − selectedRange

p	setSelectedRange:affinity:stillSelecting:

− (void)setSelectedRange:(NSRange)charRange

affinity:(NSSelectionAffinity)affinity

stillSelecting:(BOOL)flag

Sets the selection to the characters in charRange, using affinity if needed to determine how to display the selection or insertion point (see the description for selectionAffinity for more information). flag indicates whether this method is being invoked during mouse-dragging or after the user releases the mouse. If flag is YES the receiver doesn’t send notifications or remove the marking from its marked text; if flag is NO it does as appropriate. This method also resets the selection granularity to NSSelectByCharacter.

charRange must begin and end on glyph boundaries and not split base glyphs and their non-spacing marks.

See also:	− setSelectedRange:, − selectionAffinity, − selectionGranularity, − setSelectedRange:

p	setSelectedTextAttributes:

− (void)setSelectedTextAttributes:(NSDictionary *)attributes

Sets the attributes used to indicate the selection to attributes. Text color, background color, and underline are the only supported attributes for selected text.

See also:	− selectedRange, − selectedTextAttributes

p	setSelectionGranularity:

− (void)setSelectionGranularity:(NSSelectionGranularity)granularity

Sets the selection granularity for subsequent extension of a selection to granularity, which may be one of:

NSSelectByCharacter

NSSelectByWord

NSSelectByParagraph

Selection granularity is used to determine how the selection is modified when the user Shift-clicks or drags the mouse after a double- or triple-click. For example, if the user selects a word by double-clicking, the selection granularity is set to NSSelectByWord. Subsequent shift-clicks then extend the selection by words.

Selection granularity is reset to NSSelectByCharacter whenever the selection is set. You should always set the selection granularity after setting the selection.

See also:	− selectionGranularity, − setSelectedRange:

p	setSmartInsertDeleteEnabled:

− (void)setSmartInsertDeleteEnabled:(BOOL)flag

Controls whether the receiver inserts or deletes space around selected words so as to preserve proper spacing and punctuation. If flag is YES it does; if flag is NO it inserts and deletes exactly what’s selected.

See also:	− smartInsertForString:replacingRange:beforeString:afterString:, − smartDeleteRangeForProposedRange:, − smartInsertDeleteEnabled

p	setTextContainer:

− (void)setTextContainer:(NSTextContainer *)aTextContainer

Sets the receiver’s text container to aTextContainer. The receiver then uses the layout manager and text storage of aTextContainer. This method is invoked automatically when you create an NSTextView; you should never invoke it directly, but might want to override it. To change the text view for an established group of text-system objects, send setTextView: to the text container. To replace the text container for a text view and maintain the view’s association with the existing layout manager and text storage, use replaceTextContainer:.

See also:	− textContainer

p	setTextContainerInset:

− (void)setTextContainerInset:(NSSize)inset

Sets the empty space the NSTextView leaves around its associated text container to inset.

See also:	− textContainerOrigin, − invalidateTextContainerOrigin, − textContainerInset

p	setTypingAttributes:

− (void)setTypingAttributes:(NSDictionary *)attributes

Sets the receiver’s typing attributes to attributes. Typing attributes are reset automatically whenever the selection changes. If you add any user actions that change text attributes, you should use this method to apply those attributes to a zero-length selection.

See also:	− typingAttributes

p	setUsesFontPanel:

− (void)setUsesFontPanel:(BOOL)flag

Controls whether the text views sharing the receiver’s NSLayoutManager use the Font Panel and Font menu. If flag is YES, they respond to messages from the Font Panel and from the Font menu, and update the Font Panel with the selection font whenever it changes. If flag is NO they disallow character attribute changes. By default, NSTextView objects use the Font Panel and menu.

See also:	− rangeForUserCharacterAttributeChange, − usesFontPanel

p	setUsesRuler:

− (void)setUsesRuler:(BOOL)flag

Controls whether the text views sharing the receiver’s NSLayoutManager use an NSRulerView and respond to Format menu commands. If flag is YES, they respond to NSRulerView client messages and to paragraph-related menu actions, and update the ruler (when visible) as the selection changes with its paragraph and tab attributes. If flag is NO, the ruler is hidden and the text views disallow paragraph attribute changes. By default, NSTextView objects use the ruler.

See also:	− setRulerVisible:, − rangeForUserParagraphAttributeChange, − usesRuler

p	shouldChangeTextInRange:replacementString:

− (BOOL)shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString

Initiates a series of delegate messages (and general notifications) to determine whether modifications can be made to the receiver’s text. If characters in the text string are being changed, replacementString contains the characters that will replace the characters in affectedCharRange. If only text attributes are being changed, replacementString is nil. This method checks with the delegate as needed using textShouldBeginEditing: and textView:shouldChangeTextInRange:replacementString:, returning YES to allow the change, and NO to prohibit it.

This method must be invoked at the start of any sequence of user-initiated editing changes. If your subclass of NSTextView implements new methods that modify the text, make sure to invoke this method to determine whether the change should be made. If the change is allowed, complete the change by invoking the didChangeText method. See “Notifying About Changes to the Text” in the class description for more information. If you can’t determine the affected range or replacement string before beginning changes, pass (NSNotFound, 0) and nil for these values.

See also:	− isEditable

p	shouldDrawInsertionPoint

− (BOOL)shouldDrawInsertionPoint

Returns YES if the receiver should draw its insertion point, NO if the insertion point can’t or shouldn’t be drawn (for example, if the receiver’s window isn’t key).

See also:	− drawInsertionPointInRect:color:turnedOn:

p	smartDeleteRangeForProposedRange:

− (NSRange)smartDeleteRangeForProposedRange:(NSRange)proposedCharRange

Given proposedCharRange, returns an extended range that includes adjacent whitespace that should be deleted along with the proposed range in order to preserve proper spacing and punctuation of the text surrounding the deletion.

NSTextView uses this method as necessary; you can also use it in implementing your own methods that delete text, typically when the selection granularity is NSSelectByWord. To do so, invoke this method with the proposed range to delete, then actually delete the range returned. If placing text on the pasteboard, however, you should put only the characters from the proposed range onto the pasteboard.

See also:	− smartInsertForString:replacingRange:beforeString:afterString:,

− selectionGranularity, − smartInsertDeleteEnabled

p	smartInsertDeleteEnabled

− (BOOL)smartInsertDeleteEnabled

Returns YES if the receiver inserts or deletes space around selected words so as to preserve proper spacing and punctuation, NO if it inserts and deletes exactly what’s selected.

See also:	− smartInsertForString:replacingRange:beforeString:afterString:,

− smartDeleteRangeForProposedRange:, − setSmartInsertDeleteEnabled:

p	smartInsertForString:replacingRange:beforeString:afterString:

− (void)smartInsertForString:(NSString *)aString

replacingRange:(NSRange)charRange

beforeString:(NSString **)beforeString

afterString:(NSString **)afterString

Determines whether whitespace needs to be added around aString to preserve proper spacing and punctuation when it’s inserted into the receiver’s text over charRange. Returns by reference in beforeString and afterString any whitespace that should be added, unless either or both is NULL. Both are returned as nil if aString is nil or if smart insertion and deletion is disabled.

NSTextView uses this method as necessary; you can also use it in implementing your own methods that insert text. To do so, invoke this method with the proper arguments, then insert beforeString, aString, and afterString in order over charRange.

See also:	− smartDeleteRangeForProposedRange:, − smartInsertDeleteEnabled

p	spellCheckerDocumentTag

− (int)spellCheckerDocumentTag

Returns a tag identifying the NSTextView text as a document for the spell checker server. The document tag is obtained by sending a uniqueSpellDocumentTag message to the spell server the first time this method is invoked for a particular group of NSTextViews. See the NSSpellChecking and NSSpellServer class specifications for more information on how this tag is used.

p	textContainer

− (NSTextContainer *)textContainer

Returns the receiver’s text container.

See also:	− setTextContainer:

p	textContainerInset

− (NSSize)textContainerInset

Returns the empty space the NSTextView leaves around its text container.

See also:	− textContainerOrigin, − invalidateTextContainerOrigin, − setTextContainerInset:

p	textContainerOrigin

− (NSPoint)textContainerOrigin

Returns the origin of the receiver’s text container, which is calculated from the receiver’s bounds rectangle, container inset, and the container’s used rect.

See also:	− invalidateTextContainerOrigin, − textContainerInset, − usedRectForTextContainer: (NSLayoutManager)

p	textStorage

− (NSTextStorage *)textStorage

Returns the receiver’s text storage object.

p	tightenKerning:

− (void)tightenKerning:(id)sender

This action method decreases the space between glyphs in the receiver’s selection, or for all glyphs if the receiver is a plain text view. Kerning values are determined by the point size of the fonts in the selection.

See also:	− loosenKerning:, − useStandardKerning:, − turnOffKerning:

p	turnOffKerning:

− (void)turnOffKerning:(id)sender

This action method causes the receiver to use nominal glyph spacing for the glyphs in its selection, or for all glyphs if the receiver is a plain text view.

See also:	− useStandardKerning:, − loosenKerning:, − tightenKerning:, − isRichText

p	turnOffLigatures:

− (void)turnOffLigatures:(id)sender

This action method causes the receiver to use only required ligatures when setting text, for the glyphs in the selection if the receiver is a rich text view, or for all glyphs if it’s a plain text view.

See also:	− useAllLigatures:, − isRichText, − useStandardLigatures:

p	typingAttributes

− (NSDictionary *)typingAttributes

Returns the current typing attributes.

See also:	− setTypingAttributes:

p	updateDragTypeRegistration

− (void)updateDragTypeRegistration

If the receiver is editable and is a rich text view, causes all NSTextViews associated with the receiver’s NSLayoutManager to register their acceptable drag types. If the NSTextView isn’t editable or isn’t rich text, causes those NSTextViews to unregister their dragged types.

Subclasses can override this method to change the conditions for registering and unregistering drag types, whether as a group or individually based on the current state of the NSTextView. They can then invoke this method when that state changes to perform that reregistration.

See also:	− acceptableDragTypes, − registerForDraggedTypes: (NSView), − unregisterDraggedTypes (NSView), − isEditable, − importsGraphics, − isRichText

p	updateFontPanel

− (void)updateFontPanel

Updates the Font Panel to contain the font attributes of the selection. Does nothing if the receiver doesn’t use the Font Panel. You should never need to invoke this method directly, but you can override it if needed to handle additional font attributes.

See also:	− usesFontPanel

p	updateInsertionPointStateAndRestartTimer:

− (void)updateInsertionPointStateAndRestartTimer:(BOOL)flag

Updates the insertion point’s location and, if flag is YES, restarts the blinking cursor timer. This method is invoked automatically whenever the insertion point needs to be moved; you should never need to invoke it directly, but you can override it to add different insertion point behavior.

See also:	− shouldDrawInsertionPoint, − drawInsertionPointInRect:color:turnedOn:

p	updateRuler

− (void)updateRuler

Updates the NSRulerView in the receiver’s enclosing scroll view to reflect the selection’s paragraph and marker attributes. Does nothing if the ruler isn’t visible or if the receiver doesn’t use the ruler. You should never need to invoke this method directly, but you can override this method if needed to handle additional ruler attributes.

See also:	− usesRuler

p	useAllLigatures:

− (void)useAllLigatures:(id)sender

This action method causes the receiver to use all ligatures available for the fonts and languages used when setting text, for the glyphs in the selection if the receiver is a rich text view, or for all glyphs if it’s a plain text view.

See also:	− turnOffLigatures:, − useStandardLigatures:

p	usesFontPanel

− (BOOL)usesFontPanel

Returns YES if the text views sharing the receiver’s NSLayoutManager use the Font Panel, NO otherwise. See setUsesFontPanel: and rangeForUserCharacterAttributeChange for the effect this has on an NSTextView’s behavior.

p	usesRuler

− (BOOL)usesRuler

Returns YES if the text views sharing the receiver’s NSLayoutManager use a ruler view, NO otherwise. See setUsesRuler: and rangeForUserParagraphAttributeChange for the effect this has on an NSTextView’s behavior

See also:	− setUsesRuler:

p	useStandardKerning:

− (void)useStandardKerning:(id)sender

This action method causes the receiver to use pair kerning data for the glyphs in its selection, or for all glyphs if the receiver is a plain text view. This data is taken from a font’s AFM file

See also:	− isRichText, − loosenKerning:, − tightenKerning:, − turnOffKerning:

p	useStandardLigatures:

− (void)useStandardLigatures:(id)sender

This action method causes the receiver to use the standard ligatures available for the fonts and languages used when setting text, for the glyphs in the selection if the receiver is a rich text view, or for all glyphs if it’s a plain text view.

See also:	− turnOffLigatures:, − useAllLigatures:

Methods Implemented By the Delegate

NSTextView communicates with its delegate through methods declared both by NSTextView and by its superclass, NSText. See the NSText class specification for those other delegate methods.

p	textView:clickedOnCell:inRect:

− (void)textView:(NSTextView *)aTextView

clickedOnCell:(id <NSTextAttachmentCell>)attachmentCell

inRect:(NSRect)cellFrame

Invoked after the user clicks on attachmentCell within cellFrame in an NSTextView and the cell wants to track the mouse. The delegate can use this message as its cue to perform an action or select the attachment cell’s character. aTextView is the first NSTextView in a series shared by an NSLayoutManager, not necessarily the one that draws attachmentCell.

The delegate may subsequently receive a textView:doubleClickedOnCell: message if the user continues to perform a double click.

See also:	− wantsToTrackMouse (NSTextAttachmentCell)

p	textView:doCommandBySelector:

− (BOOL)textView:(NSTextView *)aTextView

doCommandBySelector:(SEL)aSelector

Sent from NSTextView’s doCommandBySelector:, this method allows the delegate to perform the command for the text view. If the delegate returns YES, the text view doesn’t perform aSelector; if the delegate returns NO, the text view attempts to perform it. aTextView is the first NSTextView in a series shared by an NSLayoutManager.

p	textView:doubleClickedOnCell:inRect:

− (void)textView:(NSTextView *)aTextView

doubleClickedOnCell:(id <NSTextAttachmentCell>)attachmentCell

inRect:(NSRect)cellFrame

Invoked when the user double-clicks on attachmentCell within cellFrame in an NSTextView and the cell want to track the mouse. The delegate can use this message as its cue to perform an action, such as opening the file represented by the attachment. aTextView is the first NSTextView in a series shared by an NSLayoutManager, not necessarily the one that draws attachmentCell.

See also:	− wantsToTrackMouse (NSTextAttachmentCell)

p	textView:draggedCell:inRect:event:

− (void)textView:(NSTextView *)aTextView

draggedCell:(id <NSTextAttachmentCell>)attachmentCell

inRect:(NSRect)aRect

event:(NSEvent *)theEvent

Invoked when the user attempts to drag attachmentCell from aRect within an NSTextView and the cell wants to track the mouse. theEvent is the mouse-down event that preceded the mouse-dragged event. The delegate can use this message as its cue to initiate a dragging operation.

See also:	− wantsToTrackMouse (NSTextAttachmentCell), − dragImage:at:offset:event:pasteboard:source:slideBack: (NSView), − dragFile:fromRect:slideBack:event: (NSView)

p	textView:shouldChangeTextInRange:replacementString:

− (BOOL)textView:(NSTextView *)aTextView

shouldChangeTextInRange:(NSRange)affectedCharRange

replacementString:(NSString *)replacementString

Invoked when an NSTextView needs to determine if text in the range affectedCharRange should be changed. If characters in the text string are being changed, replacementString contains the characters that will replace the characters in affectedCharRange. If only text attributes are being changed, replacementString is nil. The delegate can return YES to allow the replacement, or NO to reject the change.

aTextView is the first NSTextView in a series shared by an NSLayoutManager.

p	textView:willChangeSelectionFromCharacterRange:toCharacterRange:

− (NSRange)textView:(NSTextView *)aTextView

willChangeSelectionFromCharacterRange:(NSRange)oldSelectedCharRange toCharacterRange:(NSRange)newSelectedCharRange

Invoked before an NSTextView finishes changing the selection—that is, when the last argument to a setSelectedRange:affinity:stillSelecting: message is NO. oldSelectedCharRange is the original range of the selection. newSelectedCharRange is the proposed character range for the new selection. The delegate can return and adjusted range or return newSelectedCharRange unmodified.

aTextView is the first NSTextView in a series shared by an NSLayoutManager.

p	textViewDidChangeSelection:

− (void)textViewDidChangeSelection:(NSNotification *)aNotification

Invoked when the selection changes in the NSTextView. The name of aNotification is NSTextViewDidChangeSelectionNotification.

See also:	NSTextViewDidChangeSelectionNotification

Notifications

NSTextView posts the following notifications as well as those declared by its superclasses, particularly NSText. See the NSText class specification for those other notifications.

p	NSTextViewDidChangeSelectionNotification

Posted when the selected range of characters changes. NSTextView posts this notification whenever setSelectedRange:affinity:stillSelecting: is invoked either directly, or through the many methods (mouseDown:, selectAll:, and so on) that invoke it indirectly. When the user is selecting text, this notification is posted only once, at the end of the selection operation. The NSTextView’s delegate receives a textViewDidChangeSelection: message when this notification is posted.

The notification contains:

Notification Object	The notifying NSTextView.

Userinfo

Key	Value

NSOldSelectedCharacterRange	An NSValue object containing an NSRange

p	NSTextViewWillChangeNotifyingTextViewNotification

Posted when a new NSTextView is established as the NSTextView that sends notifications. This allows observers to reregister themselves for the new NSTextView. Methods such as removeTextContainerAtIndex:, textContainerChangedTextView:, and insertTextContainer:atIndex: cause this notification to be posted.

The notification contains:

Notification Object	The old notifying NSTextView, or nil.

Userinfo

Key	Value

NSOldNotifyingTextView	The old NSTextView, if one exists

NSNewNotifyingTextView	The new NSTextView, if one exists

There’s no delegate method associated with this notification. The text-handling system ensures that when a new NSTextView replaces an old one as the notifying NSTextView, the existing delegate becomes the delegate of the new NSTextView and the delegate is registered to receive NSTextView notifications from the new notifying NSTextView. All other observers are responsible for registering themselves on receiving this notification.

See also:	− removeObserver: (NSNotificationCenter), − addObserver:selector:name:object: (NSNotificationCenter)


NSView

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSView.h

Purpose

NSView is an abstract class that defines the basic drawing, event-handling, and printing architecture of an OPENSTEP application. You typically don’t interact with NSView API directly; rather, your custom view classes inherit from NSView and override many of its methods, which are invoked automatically by the Application Kit. If you’re not creating a custom view class, there are few methods you need to use.

Principal Attributes

•	Event handling	•	Integrated display to screen and printer

•	Flexible coordinate systems	•	Icon dragging

Creation

Interface Builder

− initWithFrame:	Designated initializer.

Commonly Used Methods

− frame	Returns the NSView’s location and size.

− bounds	Returns the NSView’s internal origin and size.

− setNeedsDisplay:	Marks the NSView as needing to be redrawn.

− window	Returns the NSWindow that contains the NSView.

− drawRect:	Draws the NSView. (All subclasses must implement this method, but it’s rarely invoked explicitly.)

Class Description

NSView is an abstract class that provides concrete subclasses with a structure for drawing, printing, and handling events. NSViews are arranged within an NSWindow, in a nested hierarchy of subviews. A view object claims a rectangular region of its enclosing superview, is responsible for all drawing within that region, and is eligible to receive mouse events occurring in it as well. In addition to these major responsibilities, NSView handles dragging of icons and works with the NSScrollView class to support efficient scrolling. The following sections explore these areas and more.

Most of NSView’s functionality is either automatically invoked by the Application Kit, or is available in Interface Builder. Unless you’re implementing a concrete subclass of NSView or working intimately with the content of the view hierarchy at run time, you don’t need to know much about this class’s interface. See “Commonly Used Methods” above for methods you might use regardless.

The View Hierarchy

To be displayed, an NSView must be placed in an NSWindow. All view objects within an NSWindow are arranged in a hierarchy that begins at the NSWindow’s content view, with each NSView having a single superview and zero or more subviews (see the NSWindow class specification for more on the content view). An NSView’s superview and all the NSViews above the superview are sometimes referred to as the NSView’s ancestors. An NSView’s subviews and all of their subviews on down are known as the NSView’s descendants. Each NSView in the view hierarchy has its own area to draw in and its own coordinate system, expressed as a transformation of its superview’s coordinate system. An NSView can scale, translate, or rotate its coordinates dynamically, and a subclass can declare its y axis flipped to allow drawing from top to bottom—useful for drawing text, for example.

Graphically, an NSView can be regarded as a framed canvas. The frame locates the NSView in its superview, defines its size, and clips drawing to its edges, while the canvas defines the NSView’s own internal coordinate system and hosts the actual drawing. The frame can be moved around, resized, and rotated in the superview, so that the NSView’s image moves with it. Similarly, the canvas can be shifted, stretched, and rotated, so that the drawn image moves within the frame. The frame maps onto a region of the canvas that defines the bounds of what can possibly be seen. An NSView therefore keeps track of its space using two rectangles, one for each perspective: The frame rectangle gives the exterior perspective and the bounds rectangle give the interior. The frame and bounds methods, respectively, return these rectangles. This figure shows the relation between the frame rectangle, on the left, and the bounds rectangle over the canvas, on the right:

Although the bounds rectangle indicates which portion of the NSView that’s potentially visible through the frame, if the frame runs outside of the superview the image will be clipped even within the bounds rectangle. An NSView’s visible rectangle reflects the portion of an NSView that actually displays, in terms of its own coordinate system (the darker gray rectangle in the figure below). It isn’t often important to know what the visible rectangle is, since the display mechanism automatically limits drawing to visible portions of a view. If a subclass must perform expensive precalculation to build its image, though, it can use the visibleRect method to limit its work to what’s actually needed.

The initWithFrame: method establishes an NSView’s frame rectangle, but doesn’t insert it into an NSWindow’s view hierarchy. This is the job of the addSubview: method, which you send to the NSView that you want to contain the newly initialized one. The frame rectangle is then interpreted in terms of the superview, properly locating the new NSView both by its place in the view hierarchy and its location in the superview’s NSWindow.

After initialization, you can move an NSView programmatically using any of the frame-setting methods: setFrame:, setFrameOrigin:, setFrameSize:, and setFrameRotation:. When you move an NSView all of its subviews move along with it. When you change the frame rectangle’s size, the bounds rectangle is automatically resized to match (see figure below), and the subviews are automatically resized as described later under “Moving and Resizing NSViews.” setFrameRotation: rotates the NSView around the origin of the frame rectangle (which is typically the lower left corner).

A number of methods access the view hierarchy itself. superview returns the receiver’s containing NSView, while subviews returns an NSArray containing its immediate descendant NSViews. The window method returns the NSWindow whose view hierarchy the receiver belongs to. You can add NSViews to and remove them from the view hierarchy using the methods addSubview:, removeFromSuperview, and replaceSubview:with:. An additional method, addSubview:positioned:relativeTo:, allows you to specify the ordering of NSViews that may overlap (though laying out NSViews so that they overlap isn’t recommended). When an NSView is added as a subview of another, it automatically invokes the viewWillMoveToSuperview: and if necessary the viewWillMoveToWindow: methods. Concrete subclasses can override these methods, allowing an instance to query its new superview or NSWindow about relevant state and update itself accordingly. A few other methods allow you to inspect relationships among NSViews: isDescendantOf: confirms the containment of the receiver, ancestorSharedWithView: find the common container of two NSViews, and opaqueAncestor returns the closest containing NSView that’s guaranteed to draw every pixel in the receiver’s frame (possible the receiver itself).

Coordinate Conversion in the View Hierarchy

At various times, particularly when handling events, you need to convert a rectangle or point from the coordinate system of one NSView to another (typically a superview or subview). NSView defines six methods that convert rectangles, points, and sizes in either direction:

− convertPoint:fromView:	− convertPoint:toView:

− convertSize:fromView:	− convertSize:toView:

− convertRect:fromView:	− convertRect:toView:

These methods convert geometric structures between the receiver’s coordinate system and another NSView’s within the same NSWindow, returning an alternate expression for the same on-screen location or area. Note that the structure in question needn’t actually be located within the NSView’s bounds rectangle; it’s merely assumed to be expressed in that NSView’s coordinate system. If the second argument to a conversion method is nil, the conversion is made between the receiver’s coordinate system and the base coordinate system of its NSWindow.

For converting to and from the screen coordinate system, NSWindow defines the convertBaseToScreen: and convertScreenToBase: methods. Using the NSView conversion methods along with these allows you to convert a geometric structure between an NSView’s coordinate system and the screen’s with only two messages.

Conversion is straightforward when neither NSView is rotated, or when dealing only with points. When converting rectangles or sizes between NSViews with different rotations, the geometric structure must be altered in a reasonable way. In converting a rectangle NSView makes the assumption that you want to guarantee coverage of the original screen area. To this end, the converted rectangle is enlarged so that when located in the appropriate NSView it completely covers the original rectangle (the left side of the figure below, with 15 degrees of rotation). In converting a size NSView simply treats it as a vector from (0.0, 0.0) and maps it onto the destination coordinate system. Though the length remains the same, the balance along the two axes shifts according to the rotation (the right side of the figure below, rotated 45 degrees).

Drawing in an NSView

Drawing in an NSView is as simple as implementing the drawRect: method to generate the appropriate PostScript code for the image you want displayed—the display mechanism handles the rest of the work. On the other hand, it can be as complex as dealing with the PostScript language itself, the coordinate transformations from superview to subview, and the operation of the display mechanism. This section and the following, “The Display Mechanism,” progress from the basic to the esoteric, keeping the picture correct, if incomplete, at each stage.

In order for a concrete subclass of NSView to display any kind of image, it must implement the drawRect: method. This method is invoked during the display process to generate PostScript code that’s rendered by the Window Server into a raster image. drawRect: takes a single argument, an NSRect describing the area that needs to be drawn in the receiver’s own coordinate system. Here’s an example:

- (void)drawRect:(NSRect)aRect

{

    PSsetgray(NSWhite);

    NSRectFill(aRect);

    PSsetgray(NSBlack);

    PSarc(0.0, 0.0, 117.0, 0.0, 360.0);

    PSfill();

    return;

}

This method first fills the view’s background with white, then draws a black circle at the origin (0.0, 0.0). An NSView automatically clips drawing to its frame rectangle, so the results look like this:

NSView-Sample.tiff ¬

Except for the background, this implementation of drawRect: ignores the rectangle provided, drawing everything each time it’s invoked. This isn’t a problem for a simple image, but for complex drawing it can be an extremely inefficient practice. Sending drawing instructions and data to the Window Server has a cost, and it’s best to minimize that cost where possible. You can do this by testing whether a particular graphic shape intersects the rectangle being drawn, using NSIntersectsRect() and similar functions.

How to Draw

As indicated in the example above, drawing can be performed by invoking PostScript client library functions (also known as single-operator functions), which map directly to PostScript operators. The Application Kit provides a few higher-level mechanisms for handing PostScript instructions to the Window Server. The first is the pswrap program, which converts custom PostScript procedures into C functions that you can call in the same manner as client library functions. Wrapping complex drawing procedures minimizes the overhead of communication with the Window Server by passing a group of instructions in one interprocess message, as opposed to a number of such messages for repeated single-operator calls. The Application Kit itself defines some pswrap functions, such as NSRectFill(), and you can define your own.

Describing the PostScript language, client libraries, and pswrap is outside this scope of this class description. For more information, see:

PostScript Language Reference Manual, Second Edition. Adobe Systems Incorporated. Addison Wesley, 1990. ISBN 0−201−18127−4.

Descriptions of OPENSTEP PostScript operators and client functions, accessible from the Project Builder application in the Application Kit framework documentation.

For information on pswrap, contact Adobe Systems.

The second higher-level mechanism is provided by Application Kit classes that perform drawing within an NSView, such as NSImage and the various NSCell subclasses. These classes send PostScript instructions to the Window Server but don’t have the overhead of maintaining a drawing context that NSView has. Objects that draw themselves are useful for encapsulating graphic elements that need to be drawn over and over, at different locations, or in slightly different ways. See the appropriate class specifications for more information on drawing with them.

Another way of drawing within an NSView is to add subviews that each do their own drawing. This is somewhat more heavyweight than using NSCells or NSImages, but the elements of such a constructed group have the full power of the NSView machinery at their disposal, including the autosizing of components and event handling, features described later in this class description.

Checking the Output Device

Most of an NSView’s displayed image is a stable representation of its state, and is defined in the device-independent PostScript language. View objects also interact dynamically with the user, however, and this interaction often involves drawing that isn’t integral to the image itself—selections and other highlighting, for example. Such drawing should be performed only to the computer screen, and never to a printer or fax device, or to the pasteboard (as when drawing an EPS image). You can predicate drawing on this difference of output device by sending the current DPS context an isDrawingToScreen message:

NSDPSContext *context = [NSDPSContext currentContext];

if (context && [context isDrawingToScreen]) {

    /* Draw things that should only appear on a computer screen. */

}

Coordinate System Transformations

By default, an NSView’s coordinate system is based at (0.0, 0.0) in the lower-left corner of its bounds rectangle, its units are the same size as those of its superview, and its axes are parallel to those of its frame rectangle. To change this coordinate system you can alter the NSView’s bounds rectangle, thereby placing the canvas inside the frame rectangle, or transform it directly using PostScript operators in the drawRect: method. Changing the bounds rectangle sets up the basic coordinate system, with which all drawing performed by the NSView begins; concrete subclasses of NSView typically alter the bounds rectangle immediately as needed in their initWithFrame: methods (or other designated initializers). Direct transformations are useful for temporary effects, such as scaling one axis to draw an oval instead of a circle, then scaling it back before stroking the path to preserve line widths; rotating the axes to draw text at an angle; or repeatedly translating the origin to draw the same figure in several locations.

The basic method for changing the bounds rectangle is setBounds:, which both positions and stretches the canvas. The origin of the rectangle provided to setBounds: becomes the lower-left corner of the bounds rectangle, and the size of the rectangle is made to fit in the frame rectangle, effectively scaling the NSView’s drawn image. In the figure below, the bounds rectangle from the previous example is moved and doubled in size; the result appears on the right:

You can also set the parts of the bounds rectangle independently, using setBoundsOrigin: and setBoundsSize:. An additional method, setBoundsRotation:, rotates the coordinate system around its origin within the bounds rectangle (not the origin of the bounds rectangle itself). It also enlarges the visible rectangle to account for the rotation, so that it’s expressed in the rotated coordinates yet completely covers the visible portion of the frame rectangle. This adds regions that must be drawn, yet will never be displayed (the triangular areas in the figure below). For this reason, rotating the bounds rectangle is strongly discouraged. It’s better to rotate the coordinate system by using PostScript operators in the drawRect: method rather than by rotating the bounds rectangle.

setBoundsOrigin:, setBoundsSize:, and setBoundsRotation: all express their transformations in absolute terms. Another set of methods transform the coordinate system in relative terms; if you invoke them repeatedly, their effects accumulate. These methods are translateOriginToPoint:, scaleUnitSquareToSize:, and rotateByAngle:. See the individual method descriptions for more information.

One final type of coordinate transformation is statically established by overriding the isFlipped method. NSView’s implementation returns NO, which means that the origin of the coordinate system lies at the lower-left corner of the default bounds rectangle and the y axis runs from bottom to top. When a subclass overrides this method to return YES, the NSView machinery automatically adjusts itself to assume that the upper-left corner of the NSView holds the origin. In other words, when isFlipped returns YES the y axis runs from top to bottom. A flipped coordinate system affects all drawing in the NSView itself and reckons the frame rectangles of all immediate subviews from their upper-left corners, but it doesn’t affect the coordinate systems of those subviews or the drawing performed by them.

A flipped coordinate system doesn’t affect an NSView’s subviews, but the other coordinate transformations do. Translation of the bounds rectangle from the coordinate system origin shifts all subviews along with the rest of the NSView’s image. Scaling and rotation actually affect the drawing of the subviews, as their coordinate systems inherit and build on these alterations. You can determine whether an NSView’s coordinate system is (or was ever) altered from the base coordinate system of its window using two methods. isRotatedFromBase returns YES if the receiver or any of its ancestors in the view hierarchy has ever been rotated, whether of the frame or of the bounds rectangle. isRotatedOrScaledFromBase similarly returns YES if the receiver or any of its ancestors has ever been rotated or been scaled from the base coordinate system’s unit size. You can determine whether the NSView has never been rotated by checking that isRotatedOrScaledFromBase returns YES while isRotatedFromBase returns NO. Note that these methods only offer hints about the coordinate system. Their purpose is to help optimize certain operations, not to reflect the present state: Once an NSView is marked as having been rotated or scaled, it remains so marked for its lifetime.

To get the actual amount of rotation, use the frameRotation and boundsRotation methods. These return the rotation relative to the superview only, not to the base coordinate system, so if you want the latter amount you have to progress up through each superview to the NSWindow’s content view, accumulating the rotation as you go. To get the scaling relative to the superview you can use convertSize:toView: and examine the ratio of the original size to that of the superview. To get the scaling relative to the base coordinate system, use nil as the second argument, which converts to the NSWindow’s base coordinate system.

The Display Mechanism

Displaying an NSView centers around the drawRect: method, which transmits drawing instructions to the Window Server. Before this can happen, however, a number of other things must be established. First, of course, is the rectangle in the view that needs to be drawn. Once this is known, the view must be checked for opacity; if the view is partially transparent, its nearest opaque ancestor must be found and drawing must commence from there. Once all of this is determined and a particular view is to be drawn, the Window Server must know which window device the view is in, how to clip drawing to the appropriate region, and what coordinate system to use. This is all handled outside drawRect:, by NSView’s various display methods. The following sections examine each of these points in turn.

Marking a View as Needing Display

The most common way of causing an NSView to redisplay is to tell it that its image is invalid. On each pass through the event loop, all views that need to redisplay do so. NSView defines two methods for marking a view’s image as invalid; setNeedsDisplay:, which invalidates the view’s entire bounds rectangle, and setNeedsDisplayInRect:, which invalidates a portion of the view. The automatic display of views is controlled by their window; you can turn this behavior off using NSWindow’s setAutodisplay: method. You should rarely need to do this however; the autodisplay mechanism is well-suited to most kinds of update and redisplay.

The autodisplay mechanism invokes various methods that actually do the work of displaying. You can also use these methods to force a view to redisplay itself immediately when necessary. display and displayRect: are the counterparts to the methods mentioned above; both cause the receiver to redisplay itself regardless of whether it needs to or not. Two additional methods, displayIfNeeded and displayIfNeededInRect:, redisplay invalidated rectangles in the receiver if it’s been marked invalid with the methods above. The rectangles that actually get drawn are guaranteed to be at least those marked as invalid, but the view may coalesce them into larger rectangles to save multiple invocations of drawRect:.

Opacity

NSViews don’t necessarily cover every bit of their frames with drawing. Because of this, the display methods must be sure to find an opaque background behind the view that’s ostensibly being drawn, and begin displaying from there forward. The display methods above all pull back up the view hierarchy to the first view that responds YES to an isOpaque message, bringing the invalidated rectangles along. NSView by default responds NO to isOpaque, so it’s important to remember to override this method to return YES if appropriate when defining a subclass. Most Application Kit subclasses of NSView actually do this.

If you want to exclude background views from drawing when forcing display to occur unconditionally, you can use NSView methods that explicitly omit backing up to an opaque ancestor. These methods, parallel to those mentioned above, are displayRectIgnoringOpacity:, displayIfNeededIgnoringOpacity:, and displayIfNeededInRectIgnoringOpacity:.

Locking Focus

Before a display... method invokes drawRect:, it sets the Window Server up with information about the view, including the window device it draws in, the coordinate system and clipping path it uses, and other PostScript graphics state (discussed in detail below, under “PostScript Graphics State Objects”). The method used to do this is lockFocus, and it has a companion method that undoes its effects, called unlockFocus.

All drawing code invoked by an NSView must be bracketed by invocations of these methods to produce proper results. If you define some methods that need to draw in a view without going through the display methods above, for example, you must send lockFocus to the view that you’re drawing in before sending commands to the Window Server, and unlockFocus as soon as your done.

It’s perfectly reasonable to lock the PostScript focus on one view when another already has it. In fact, this is exactly what happens when subviews are drawn in their superview. The focusing machinery keeps a stack of which views have been focused, so that when one view is sent an unlockFocus message, the PostScript focus is restored to the view that was focused immediately before.

PostScript Graphics State Objects

When an NSView receives a lockFocus message, its basic drawing environment state is constructed and sent to the Window Server as a PostScript graphics state object, or gstate (this is a PostScript user object, not an Objective-C object). The basic state includes default values for parameters that don’t change often, but leaves many other parameters undefined:

Parameter	Default Value

coordinate transformation	The NSView’s coordinate system as established by the bounds rectangle

position	No default value, must be set before drawing

path	No default value

clipping path	As established by lockFocus

font	No default value, must be set before drawing text

line width	0.0

line cap	0 (a square butt end)

line join	0 (mitered joins)

halftone screen	A device-dependent, type 3 halftone dictionary

halftone phase	0,0

flatness	1.0

miter limit	10

dash pattern	A normal solid line

device	The current window

stroke adjust	true

color	No guaranteed default value

color space	No guaranteed default value, varies with color

color rendering	Calibrated RGB rendering

overprint	false

black generation	No default value

transfer	No default value

undercolor removal	No default value

alpha (opacity)	1.0 (opaque)

instance drawing mode	false

When drawing in an NSView, you must be sure to explicitly set relevant parameters that have no default value, or a PostScript error will result. Further, although drawing methods are free to set any gstate parameter, they should always restore the parameters to their original values when finished. This protects multiple drawing methods, and objects that draw within an NSView, such as NSImages and NSCells, from altering each other’s graphics states. You can protect the gstate by bracketing the changes with PSgsave() and PSgrestore(), or by explicitly placing the parameter in question on the stack and resetting it later—for example, saving the line width only using PScurrentlinewidth(), performing your drawing, then calling PSsetlinewidth() to restore the prior value.

Normally the graphics state object is reconstructed from scratch each time the NSView is focused. You can instruct an NSView to keep a graphics state object indefinitely by sending it an allocateGState message (typically in the initialization method for a concrete subclass). This eliminates the overhead of continual reconstruction of the graphics state, and also allows you to omit commands for setting parameters from your drawing code. However, because a graphics state object does consume a fair amount of memory, you should be sure to test your application’s performance with and without it. Persistent gstate objects are most suitable for NSViews that must be redrawn frequently with the same parameters.

When you set an NSView to use a persistent gstate object, it doesn’t actually allocate one until it needs it. When it does create the graphics state object, the NSView invokes its setUpGState method to set the parameters. Your subclass can override this method to establish the parameters that you want kept in the graphics state using such methods and client library functions as NSColor’s and NSFont’s set, PSsetlinewidth(), PSsetdash(), and so on.

You can cause an NSView to discard its gstate object by sending it a releaseGState message, or simply to invalidate it using renewGState. The latter method causes the NSView to reestablish its gstate parameters by invoking setUpGState the next time it’s needed. Finally, if for some reason you need to access the persistent gstate object directly, the gstate method returns its PostScript user object identifier.

Moving and Resizing NSViews

Repositioning an NSView is a potentially complex operation. Moving or resizing can expose portions of the NSView’s superview that weren’t previously visible, requiring the superview to redisplay. Resizing can also affect the layout of an NSView’s subviews. Changes to an NSView’s layout in any case may be of interest to other objects, which might need to be notified of the change. The following sections explore each of these areas.

Displaying After Moving or Resizing

None of the methods that alter an NSView’s frame rectangle redisplays the NSView or marks it as needing display. When using the setFrame... methods, then, you must mark both the view being repositioned and its superview as needing display. This can be as simple as marking the superview in its entirety as needing display, or better, marking the superview in the old frame of the repositioned view and the view itself in its entirety. This code fragment sets theView’s frame rectangle, and updates its superview appropriately:

NSView *theView;      /* Assume this exists. */

NSRect newFrame;      /* Assume this exists. */

[[theView superview] setNeedsDisplayInRect:[theView frame]];

[theView setFrame:newFrame];

[theView setNeedsDisplay:YES];

This sample marks the superview as needing display in the frame of the view about to be moved. Then, after theView is repositioned, it’s marked as needing display in its entirety, which is nearly always the case.

Note:	The setBounds... methods also don’t redisplay the NSView, but because their changes don’t affect superviews you can simply mark the repositioned NSView as needing display.

Autoresizing of Subviews

When an NSView’s frame size changes, they layout of its subviews must often be adjusted to fit in the new size. NSView defines a mechanism that automates this process, allowing you to specify how any NSView should reposition itself when its superview is resized. Interface Builder allows you to set these attributes graphically with its Size Inspector, and in test mode you can examine the effects of autoresizing. You can also set autoresizing attributes programmatically using setAutoresizingMask: with a mask containing any of the constants illustrated below, combined using the C bitwise OR operator:

When one of these mask flags is omitted, the NSView’s layout is fixed in that aspect; when it’s included the NSView’s layout is flexible in that aspect. For example, to keep an NSView in the lower left corner of its superview, you specify NSViewMaxXMargin | NSViewMaxYMargin. When more than one aspect along an axis is made flexible, the resize amount is distributed evenly among them.

Autoresizing is on by default, but you can turn it off using the setAutoresizesSubviews: method. Note that when you turn off an NSView’s autoresizing, all of its descendants are likewise shielded from changes in the superview. Changes to subviews, however, can still percolate downward. Similarly, if a subview has no autoresize mask, it won’t change in size, and therefore none of its subview will autoresize.

Autoresizing is accomplished using two methods. resizeSubviewsWithOldSize: is invoked automatically by an NSView whenever its frame size changes. This method then simply sends a resizeWithOldSuperviewSize: message to each subview. Each subview compares the old frame size to the new size and adjusts its position and size according to its autoresize mask. Subclasses of NSView can override either method to alter their autoresizing behavior.

Two cautions apply to autoresizing. First, it doesn’t work at all in NSView that have been rotated. Subviews that have been rotated can autoresize within a nonaltered superview, but then their descendants aren’t autoresized. Also, for autoresizing to work correctly, the subview being autoresized must lie completely within its superview’s frame. Apart from these limitations, autoresizing covers most layout changes quite well.

Notifications

Beyond resizing its subviews, an NSView broadcasts notifications to interested observers any time its bounds and frame rectangles change. The notification names are NSViewFrameDidChangeNotification and NSBoundsDidChangeNotification, respectively. An NSView that bases its own display on the layout of its subviews, for example, can register itself as an observer for those subviews and update itself any time they’re moved or resized. NSScrollView and NSClipView cooperate in this manner to adjust the NSScrollView’s NSScroller’s. You can turn notifications on and off using setPostsFrameChangedNotification: and setPostsBoundsChangedNofitications:.

Event Handling

NSViews are the most typical receivers of event and action messages, as described in the NSResponder and NSEvent class specifications. An NSView subclass can handle any event or action message simply by implementing it (being sure to invoke super’s implementation as needed). Then, if an instance of that class is the first in the responder chain to respond to that message, it receives such messages as they’re generated.

Except for an NSWindow’s content view, an NSView’s next responder is always its superview—most of the responder chain, in fact, comprises the NSViews from an NSWindow’s first responder up to its content view. NSView addSubview: method automatically sets the receiver as the new subview’s superview; you should never send setNextResponder: to an NSView object. You can safely add responders to the top end of an NSWindow’s responder chain—the NSWindow itself if it has no delegate, or the delegate if it does.

As the class that handles display, NSView is the typical recipient of mouse and keyboard events. Mouse clicks, drags, and movements usually occur in some NSView or other, and most keystrokes represent text to be added for display at some point in a window. A mouse event starts at the lowest NSView containing it in the view hierarchy (or, the topmost NSView displayed under the cursor), and proceeds up the responder chain through superviews until some object handles it. “Mouse Events,” below, covers the details of handling mouse events. Most keyboard events start at the first responder, whatever it might be, and are similarly offered up the responder chain. Some actually change the first responder, thus allowing the user to perform many actions without using the mouse. See the NSResponder class specification for information on keyboard events. Tracking-rectangle events are monitored by the NSWindow and dispatched directly to the object that owns the tracking rectangle. “Tracking Rectangles and Cursor Rectangles” describes how to set up and handle these. An additional section covers the use of context-sensitive pop-up menus by your views.

Mouse Events

An NSView can receive mouse events of three general types: clicks, drags, and movements. A custom subclass of NSView can interpret a mouse event as a cue to perform a certain action, such as sending a target-action message, selecting a graphic element, and so on. NSViews automatically receive mouse-clicked and mouse-dragged events, but because mouse-moved events occur so often and can bog down the event queue, an NSView must explicitly request its NSWindow to watch for them using NSWindow’s setAcceptsMouseMovedEvents: method. Tracking rectangles, described below, are a less expensive way of following the mouse’s location.

The NSView selected to receive a mouse event is determined by the NSWindow using NSView’s hitTest: method, which returns the lowest descendant that contains the cursor location of the event (this is also the topmost NSView displayed). Once the recipient is determined, the NSWindow sends it a mouseDown: message, which includes an NSEvent object containing information about the click. NSEvent’s locationInWindow locates the cursor’s hot spot in the coordinate system of the receiver’s NSWindow. To convert it to the NSView’s coordinate system, use convertPoint:fromView: with a nil NSView argument. From here, you can use mouse:inRect: to determine whether the click occurred in an interesting area.

One of the earliest things to consider in handling mouse-down events is whether the receiving NSView should become the first responder, which means that it will be the first candidate for subsequent key events and action messages. NSViews that handle graphic elements that the user can select—drawing shapes or text, for example—should typically accept first responder status on a mouse-down event, by overriding the acceptsFirstResponder method to return YES. This results in the window making the receiving NSView first responder with NSWindow’s makeFirstResponder: method. Some NSViews, however, may not wish to change the selection upon the first mouse click in a non-key window, which should normally only order the window to the front. NSView’s acceptsFirstMouse: method controls whether an initial mouse click is sent to the NSView or not. By default it returns NO, which in most cases is appropriate behavior. Certain subclasses, such as controls that don’t affect the selection, override this method to return YES.

Once an NSView has accepted a mouse event and determined its location, it can also check which mouse button was clicked and how many times. NSEvent’s type method distinguishes between left and right mouse events, and the NSView can base its behavior on this information. Right mouse events are defined by the Application Kit to open pop-up menus, but you can override this behavior if necessary. NSEvent’s clickCount method returns a number identifying the mouse event as a single-, double-, or triple-click (and so on).

NSViews that handle mouse clicks as a single event, from mouse down, through dragging, to mouse up, must usually short-circuit the application’s normal event loop, entering a modal event loop to catch and process only events of interest. For example, an NSButton highlights upon a mouse-down event, then follows the mouse location during dragging, highlighting when the mouse is inside and unhighlighting when the mouse is outside. If the mouse is inside on the mouse-up event, the NSButton sends its action message. This method template shows one possible kind of modal event loop:

- (void)mouseDown:(NSEvent *)theEvent

{

    BOOL keepOn = YES;

    BOOL isInside = YES;

    NSPoint mouseLoc;

    do {

        mouseLoc = [self convertPoint:[theEvent mouseLocationInWindow

            fromView:nil]];

        isInside = [self mouse:mouseLoc inRect:[self bounds]];

        switch ([theEvent type]) {

            case NSLeftMouseDragged:

                [self highlight:isInside];

                break;

            case NSLeftMouseUp:

                if (isInside) [self doSomethingSignificant];

                [self highlight:NO];

                keepOn = NO;

                break;

            default:

                /* Ignore any other kind of event. */

                break;

        }

        theEvent = [[self window] nextEventMatchingMask: NSLeftMouseUpMask |

            NSLeftMouseDraggedMask];

    } while (keepOn);

    return;

}

This loop converts the mouse location and checks whether it’s inside the receiver. It highlights itself using the fictional highlight: method according to this, and on a mouse up inside, invokes doSomethingSignificant to perform an important action. Instead of merely highlighting, a custom NSView might move a selected object, draw a graphic image according to the mouse’s location, and so on.

This kind of modal event loop is driven only as long as the user actually moves the mouse. It won’t work, for example, to cause continual scrolling if the user presses the mouse button but never moves the mouse itself. For this, your modal loop should start a periodic event stream using NSEvent’s class method startPeriodicEventsAfterDelay:withPeriod:, and add NSPeriodicMask to the mask passed to nextEventMatchingMask:. In the switch() statement the NSView can then check for a case of NSPeriodic and take whatever action it needs to; scrolling a document view or moving a step in an animation, for example. If you need to check the mouse location during a periodic event, you can use NSWindow’s mouseLocationOutsideOfEventStream method.

Tracking Rectangles and Cursor Rectangles

One special type of event is that for tracking mouse movement into and out of a region in the NSView. Such a region is known as a tracking rectangle; it triggers mouse-entered events when the cursor enters it and mouse-exited events when the cursor leaves it. This can be useful for displaying context-sensitive messages or highlighting graphic elements under the cursor, for example. An NSView can have any number of tracking rectangles, which can overlap or be nested one within the other; the NSEvent objects generated for tracking events include a tag that identified the rectangle that triggered the event.

To create a tracking rectangle, use the addTrackingRect:owner:userData:assumeInside: method. This method registers an owner for the tracking rectangle provided, so that the owner receives the event messages. This is typically the NSView itself, but need not be. The method returns the tracking rectangle’s tag so that you can store it for later reference in the event handling methods, mouseEntered: and mouseExited:. To remove a tracking rectangle, use the removeTrackingRect: method, which takes as an argument the tag of the tracking rectangle to remove.

Tracking rectangles, though created and used by NSViews, are actually maintained by NSWindows. Because of this, a tracking rectangle is a static entity; it doesn’t move or change its size when the NSView does. If you use tracking rectangles, you should be sure to remove and reestablish them any time you change the frame rectangle of the NSView that contains them. If you’re using a custom subclass of NSView, you can override the frame- and bounds-setting methods to do this. You can also register an observer for the NSViewFrameDidChangeNotification (described below), and have it reestablish the tracking rectangles on receiving the notification.

One common use of tracking rectangles is to change the cursor image over different types of graphic elements. Text, for example, typically requires an I-beam cursor. Changing the cursor is such a common operation that NSView defines several convenience methods to ease the process. A tracking rectangle generated by these methods is called a cursor rectangle. The Application Kit itself assumes ownership of cursor rectangles, so that when the user moves the mouse over the rectangle the cursor automatically changes to the appropriate image. Unlike general tracking rectangles, cursor rectangles may not partially overlap. They may, however, be completely nested, one within the other.

Because cursor rectangles need to be reset often as the NSView’s size and graphic elements change, NSView defines a single method, resetCursorRects, that’s invoked any time its cursor rectangles need to be reestablished. A concrete subclass overrides this method, invoking addCursorRect:cursor: for each cursor rectangle it wishes to set. Thereafter, the NSView’s cursor rectangles can be rebuilt by invoking NSWindow’s invalidateCursorRectsForView: method. If you find you need to temporarily remove a single cursor rectangle, you can do this with removeCursorRect:cursor:. Be aware that resetCursorRects will reestablish that rectangle, unless you implement it to do otherwise.

An NSView’s cursor rectangles are automatically reset whenever:

•	Its frame or bounds rectangle changes, whether by a setFrame... or setBounds... message or by autoresizing.

•	Its NSWindow is resized. In this case all of the NSWindow’s view objects get their cursor rectangles reset.

•	It’s moved in the view hierarchy.

•	It’s scrolled in an NSScrollView or NSClipView.

You can temporarily disable all the cursor rectangles in a window using NSWindow’s disableCursorRects and enableCursorRects methods. NSWindow’s areCursorRectsEnabled tells you whether they’re currently enabled.

Context-Sensitive Menus

On Microsoft Windows, any view can be assigned a pop-up menu that’s displayed when the user clicks the right mouse button over the view. setMenu: assigns an NSMenu to a view, and menu returns it. Your subclass can define a menu that’s used for all instances by implementing the defaultMenu class method. It can also change the menu displayed based on the mouse event by overriding the menuForEvent: instance method. This allows the view clicked to display different menus based on the location of the mouse and of the view’s state, or to change or enable individual menu items based on the commands available for the view or for that region of the view. See the NSMenu and NSMenuItem class and protocol specifications for more information on using menus.

Printing and Faxing

Printing or faxing an NSView uses the same PostScript description as for displaying on the screen, by simply changing the device. An NSView can check whether it’s drawing to the screen in order to conditionally include or omit elements such as highlighting, but normally doesn’t need to be involved with the PostScript generation process in a special way for printing. It may, however, need to take part in peripheral issues, including how it’s divided into pages and placed on them, and generation of document structuring comments used by some PostScript document programs. The sections below cover these areas.

To print or fax an NSView, send it a print: or fax: message. You can also generate an EPS representation using either dataWithEPSInsideRect: or writeEPSInsideRect:toPasteboard:. For any of these jobs, the NSView creates an NSPrintOperation object that manages the process of generating proper PostScript code for a printer or fax device. NSPageLayout, NSPrintInfo, and NSPrintPanel objects are also involved in the process. See those classes’ specifications for more information on the printing process itself.

Pagination

When an NSView is printed onto pages smaller than itself, it tiles itself out onto separate logical pages so that its entire visible region is printed. A subclass of NSView can alter the way pagination is performed by overriding two small sets of methods. The first set affects automatic pagination; the second replaces automatic pagination completely. One extra method allows the NSView to adjust the location of the printed image on the page. Finally, after pagination has actually been performed, the NSView is given the chance to draw additional marks on the page.

NSView’s automatic pagination tries to fit as much of the view being printed onto a logical page, slicing the view into the largest possible chunks. This is sufficient for many views, but if a view’s image must be divided only at certain places—between lines of text or cells in a table, for example, the view can adjust the automatic mechanism to accommodate this by reducing the height or width of each page. It does so by overriding up to four methods. adjustPageHeightNew:top:bottom:limit: provides an out parameter for the new bottom coordinate of the page, followed by the proposed top and bottom. An additional parameter limits the height of the page; the bottom can’t be moved above it. adjustPageWidthNew:left:right:limit: works in the same way to allow the view to adjust the width of a page. The limits are calculated as a percentage of the proposed page’s height or width. Your view subclass can also customize this percentage by overriding the methods heightAdjustLimit and widthAdjustLimit to return the reducible fraction of the page.

More complex views, such as those that display separate pages over a background, need to direct their own pagination. An NSView subclass that needs to do so overrides the knowsPagesFirst:last: method to return YES, which signals that it will be calculating each page’s dimensions, and returns by reference its first and last page numbers. The pagination machinery then uses these numbers, sending rectForPage: to the NSView, which uses the page number and the current printing information to calculate an appropriate rectangle in its coordinate system. The adjustPage... methods aren’t used in this case.

The last stage of pagination involves placing the image to be printed on the logical page. NSView’s locationOfPrintRect: places it according to the NSPrintInfo’s status. By default it places the image in the upper left corner of the page, but if NSPrintInfo’s isHorizontallyCentered or isVerticallyCentered methods return YES, it centers a single-page image along the appropriate axis. A multiple-page document, however, is always placed so that the divided pieces can be assembled at their edges.

After the NSView has sliced out a rectangle and positioned it on a page, it’s given two chances to add extra marks to the page, such as crop marks or fold lines. drawPageBorderWithSize: is used for logical pages, and is invoked for each paginated portion of the view. drawSheetBorderWithSize: is used for actual physical pages, or sheets, on which one or more logical pages may be laid out. In a 2-up printing, for example, the former method is invoked twice for each sheet, while the latter is invoked once for each sheet.

PostScript Document Structure

As an adjunct to the PostScript language itself, Adobe has defined a set of document structuring conventions that describe the internal structure of a given PostScript language document. NSView properly generates the basic information needed to structure its output, and defines a number of methods that subclasses can override to provide additional information. This section only describes the methods that relate to the structure of a conforming PostScript language document; see the individual method descriptions and Adobe’s PostScript Language Reference Manual, Appendix G for more information.

An NSView subclass can override any of the methods that write out document structuring comments and definitions. When overriding begin... or add... methods, be sure to invoke super’s implementation before writing additional information; when overriding end... methods, invoke super’s implementation last. This sample method, for example, adds a comment to the header of a document:

- (void)endHeaderComments

{

    NSDPSContext *context = [NSDPSContext currentContext];

    [context printFormat:@"%%%%SomeComment: %d\n", someNumber];

    [super endHeaderComments];

    return;

}

The initial portion of a conforming PostScript language document is called the prologue, and contains two parts itself: the header and a set of procedure definitions. NSView’s beginPrologueBBox:... writes out the very beginning of the document. endHeaderComments closes the first part of the prologue. Subclasses can add their own procedure definitions to the end of the prologue by overriding endPrologue.

After the prologue comes the script, which contains a section that applies to the entire document, followed by sections for each page, and finally the document trailer. beginSetup and endSetup write the document setup section. Each page is written with five methods, in addition to drawRect:. beginPage:label:bBox:fonts: writes out the beginning of each page’s document structuring comments. It’s followed by beginPageSetupRect:placement:, which starts the page setup section. An additional method, addToPageSetup, does nothing by default, but allows subclasses to append extra procedure definitions and comments to the page setup. The page setup concludes with an endPageSetup message. After all this, endPage wraps up the page description; subclasses can override this method to add document structuring comments and PostScript code to the page trailer. The document trailer is written by the beginTrailer and endTrailer methods.

Communicating with the Window Server During Printing

While an NSView is printing, its connection to the Window Server is replaced by a connection to the print job output. Sometimes the NSView needs to communicate briefly with the Window Server while printing; for example, it may need to read some data stored only on the Window Server, or open an attention panel to alert the user of a problem. In these cases, it can temporarily swap in the NSApplication object’s DPS context to restore access to the application’s Window Server state and to the screen. When finished, the view object restores the print operation’s context to continue generating its image:

[NSDPSContext setCurrentContext:[NSApp context]];

/* Communicate with the Window Server. */

[NSDPSContext setCurrentContext:[[NSPrintOperation currentOperation] context]];

/* Resume generating PostScript code. */

continue in this topic


NSView2

Other Features

Besides the fundamentals of drawing and event handling, NSView includes several auxiliary features. These are tagging NSViews for quick location, support for dragging of images and file icons, and cooperation with the scrolling machinery to facilitate viewing larger NSViews through smaller ones. The following sections introduce each of these features and name the methods and cooperating classes or protocols involved in each.

Tags

NSView defines methods that allow you to tag individual view objects with integer tags and to search the view hierarchy based on those tags. NSView’s tag method always returns −1. You can override this in subclasses to return a special value, or even add a setTag: method to allow the tag to be changed at run time (several Application Kit classes, especially NSControl and NSCell, do just this). The viewWithTag: method proceeds through all of the receiver’s descendants (including itself), searching for a subview with the given tag and returning it if it’s found.

Dragging

A view object can act as either the source or destination for dragged images and file icons. The basic dragging methods, dragImage:... and dragFile:... methods, handle the mechanics of moving the image on the screen and notifying the destination of the dragging operations. To act as a source for dragging operations, a concrete subclass of NSView can adopt the NSDraggingSource protocol, by which the source indicates what kinds of dragging operations are allowed and is notified of dragging operations as they begin. Both NSView and NSWindow subclasses can act as destinations for dragging operations, by adopting the NSDraggingDestination protocol and making use of the NSDraggingInfo protocol. For more information see the dragging protocol specifications and the descriptions of dragImage:... and dragFile:... in this specification.

Scrolling

NSView defines a number of methods to support scrolling, whereby the NSView being scrolled—the document view—is displayed partially through another—the content or clip view (not to be confused with a window’s content view). Scrolling is effected by moving the clip view’s bounds rectangle, which reveals the different regions of the document view. Most of the scrolling methods assume that the NSView is enclosed within an NSClipView and an NSScrollView, which handle the mechanics of scrolling for you. You can, however, reproduce the effects of scrolling yourself if you wish. See the NSScrollView, NSClipView, and NSScroller class specifications for information on how scrolling is implemented by the Application Kit.

NSView’s most direct scrolling methods are scrollPoint: and scrollRectToVisible:, both of which assume that the receiver is embedded in an NSClipView. These methods move the clip view so that the requested point or rectangle in the receiver become visible. Another method, autoscroll:, automatically scrolls the receiver in an NSClipView based on the location of the mouse. It’s useful for moving the document view when the user drags an icon outside of the visible area. The enclosingScrollView method returns the NSScrollView that contains the NSView, allowing you to tune the way scrolling occurs.

Two other methods aid in scrolling. A subclass of NSView can override adjustScroll: to change the way automatic (user-driven) scrolling occurs. It can quantize scrolling into regular units, to the edges of a spreadsheet’s cells, for example, or simply limit scrolling to a specific region of the NSView. The last scrolling method, scrollRect:by:, copies an already-drawn portion of the NSView to a new location. It’s useful for producing temporary effects, but note that any subsequent drawing will obliterate the copied portion.

Method Types

Creating instances	− initWithFrame:

Managing the view hierarchy	− superview

− subviews

− window

− addSubview:

− addSubview:positioned:relativeTo:

− removeFromSuperview

− replaceSubview:with:

− isDescendantOf:

− opaqueAncestor

− ancestorSharedWithView:

− sortSubviewsUsingFunction:context:

− viewWillMoveToSuperview:

− viewWillMoveToWindow:

Searching by tag	− viewWithTag:

− tag

Modifying the frame rectangle	− setFrame:

− frame

− setFrameOrigin:

− setFrameSize:

− setFrameRotation:

− frameRotation

Modifying the bounds rectangle	− setBounds:

− bounds

− setBoundsOrigin:

− setBoundsSize:

− setBoundsRotation:

− boundsRotation

Modifying the coordinate system	− translateOriginToPoint:

− scaleUnitSquareToSize:

− rotateByAngle:

Examining coordinate system modifications

− isFlipped

− isRotatedFromBase

− isRotatedOrScaledFromBase

Converting coordinates	− convertPoint:fromView:

− convertPoint:toView:

− convertSize:fromView:

− convertSize:toView:

− convertRect:fromView:

− convertRect:toView:

− centerScanRect:

Controlling notifications	− setPostsFrameChangedNotifications:

− postsFrameChangedNotifications

− setPostsBoundsChangedNotifications:

− postsBoundsChangedNotifications

Resizing subviews	− resizeSubviewsWithOldSize:

− resizeWithOldSuperviewSize:

− setAutoresizesSubviews:

− autoresizesSubviews

− setAutoresizingMask:

− autoresizingMask

Focusing	− lockFocus

− unlockFocus

+ focusView

Displaying	− setNeedsDisplay:

− setNeedsDisplayInRect:

− needsDisplay

− display

− displayRect:

− displayRectIgnoringOpacity:

− displayIfNeeded

− displayIfNeededInRect:

− displayIfNeededIgnoringOpacity

− displayIfNeededInRectIgnoringOpacity:

− isOpaque

Drawing	− drawRect:

− visibleRect

− canDraw

− shouldDrawColor

Managing a graphics state	− allocateGState

− gState

− setUpGState

− renewGState

− releaseGState

Event handling	− acceptsFirstMouse:

− hitTest:

− mouse:inRect:

− performKeyEquivalent:

− performMnemonic:

Dragging operations	− dragImage:at:offset:event:pasteboard:source:slideBack:

− dragFile:fromRect:slideBack:event:

− registerForDraggedTypes:

− unregisterDraggedTypes

− shouldDelayWindowOrderingForEvent:

Managing cursor rectangles	− addCursorRect:cursor:

− removeCursorRect:cursor:

− discardCursorRects

− resetCursorRects

Managing tracking rectangles	− addTrackingRect:owner:userData:assumeInside:

− removeTrackingRect:

Scrolling	− scrollPoint:

− scrollRectToVisible:

− autoscroll:

− adjustScroll:

− scrollRect:by:

− enclosingScrollView

Context-sensitive menus	− menuForEvent:

+ defaultMenu

Managing the key view loop	− setNextKeyView:

− nextKeyView

− nextValidKeyView

− previousKeyView

− previousValidKeyView

Printing and faxing	− print:

− fax:

− dataWithEPSInsideRect:

− writeEPSInsideRect:toPasteboard:

Pagination	− heightAdjustLimit

− widthAdjustLimit

− adjustPageWidthNew:left:right:limit:

− adjustPageHeightNew:top:bottom:limit:

− knowsPagesFirst:last:

− rectForPage:

− locationOfPrintRect:

Adorning pages in printout	− drawPageBorderWithSize:

− drawSheetBorderWithSize:

Writing conforming PostScript	− beginPrologueBBox:creationDate:createdBy:fonts:

forWhom:pages:title:

− endHeaderComments

− endPrologue

− beginSetup

− endSetup

− beginPage:label:bBox:fonts:

− beginPageSetupRect:placement:

− addToPageSetup

− endPageSetup

− endPage

− beginTrailer

− endTrailer

Class Methods

p	defaultMenu

+ (NSMenu *)defaultMenu

Overridden by subclasses to return the default pop-up menu for instances of the receiving class. NSView’s implementation returns nil. This menu is used only on Microsoft Windows.

See also:	− menuForEvent:, − menu(NSResponder)

focusView

+ (NSView *)focusView

Returns the currently focused NSView object, or nil if there is none.

See also:	− lockFocus, − unlockFocus

Instance Methods

acceptsFirstMouse:

− (BOOL)acceptsFirstMouse:(NSEvent *)theEvent

Overridden by subclasses to return YES if the receiver should be sent a mouseDown: message for theEvent, an initial mouse-down event over the receiver in its window, NO if not. The receiver can either return a value unconditionally, or use theEvent’s location to determine whether or not it wants the event. NSView’s implementation ignores theEvent and returns NO.

Override this method in a subclass to allow instances to respond to initial mouse-down events. For example, most view objects refuse an initial mouse-down event, so that the event simply activates the window. Many control objects, however, such as NSButton and NSSlider, do accept them, so that the user can immediately manipulate the control without having to release the mouse button.

See also:	− hitTest:

addCursorRect:cursor:

− (void)addCursorRect:(NSRect)aRect cursor:(NSCursor *)aCursor

Establishes aCursor as the cursor to be used when the mouse pointer lies within aRect.

Note:	Cursor rectangles aren’t subject to clipping by superviews, nor are they intended for use with rotated NSViews. You should explicitly confine a cursor rectangle to the NSView’s visible rectangle to prevent improper behavior.

This method is intended to be invoked only by the resetCursorRects method. If invoked in any other way, the resulting cursor rectangle will be discarded the next time the NSView’s cursor rectangles are rebuilt.

See also:	− removeCursorRect:cursor:, − discardCursorRects, − resetCursorRects, − visibleRectangle

addSubview:

− (void)addSubview:(NSView *)aView

Adds aView to the receiver’s subviews so that it’s displayed above its siblings. Also sets the receiver as aView’s next responder.

See also:	− addSubview:positioned:relativeTo:, − subviews, − removeFromSuperview, − setNextResponder: (NSResponder)

addSubview:positioned:relativeTo:

− (void)addSubview:(NSView *)aView

positioned:(NSWindowOrderingMode)place

relativeTo:(NSView *)otherView

Inserts aView among the receiver’s subviews so that it’s displayed immediately above or below otherView according to whether place is NSWindowAbove or NSWindowBelow. If otherView is nil (or isn’t a subview of the receiver), aView is added above or below all of its new siblings. Also sets the receiver as aView’s next responder.

See also:	− addSubview:, − subviews, removeFromSuperView, − setNextResponder: (NSResponder)

addToPageSetup

− (void)addToPageSetup

Implemented by subclasses that perform their own pagination to add a scaling operator to the PostScript code generated when printing. This method is invoked by print: and fax:. NSView’s implementation of this method does nothing.

See the NSPrintInfo class specification for information on retrieving document scaling during printing.

See also:	− beginPageSetupRect:placement:

addTrackingRect:owner:userData:assumeInside:

− (NSTrackingRectTag)addTrackingRect:(NSRect)aRect

owner:(id)anObject

userData:(void *)userData

assumeInside:(BOOL)flag

Establishes aRect as an area for tracking mouse-entered and mouse-exited events within the receiver, and returns an tag that identifies the tracking rectangle in NSEvent objects and that can be used to remove the tracking rectangle. anObject is the object that gets sent the event messages. It can be the receiver itself or some other object (such as an NSCursor or a custom drawing tool object), as long as it responds to both mouseEntered: and mouseExited:. userData is supplied in the NSEvent object for each tracking event. flag determines which event is sent first by indicating where the mouse is assumed to be at the time this method is invoked. If flag is YES, the first event will be generated when the mouse leaves aRect; if flag is NO the first event will be generated when the mouse enters it.

Tracking rectangles provide a general mechanism that can be used to trigger actions based on the mouse location (for example, a status bar or hint field that provides information on the item the cursor lies over). To simply change the cursor over a particular area, use addCursorRect:cursor:. If you must use tracking rectangles to change the cursor, the NSCursor class specification describes the additional methods that must be invoked to change cursors by using tracking rectangles.

See also:	− removeTrackingRect:, − userData (NSEvent)

adjustPageHeightNew:top:bottom:limit:

− (void)adjustPageHeightNew:(float *)newBottom

top:(float)top

bottom:(float)proposedBottom

limit:(float)bottomLimit

Overridden by subclasses to adjust page height during automatic pagination. This method is invoked by print: and fax: with top and proposedBottom set to the top and bottom edges of the pending page rectangle in the receiver’s coordinate system. The receiver can raise the bottom edge and return the new value in newBottom, allowing it to prevent items such as lines of text from being divided across pages. bottomLimit is the topmost value that newBottom can be set to, as calculated using the return value of heightAdjustLimit. If this limit is exceeded, the pagination mechanism simply uses bottomLimit for the bottom edge.

NSView’s implementation of this method propagates the message to its subviews, allowing nested views to adjust page height for their drawing as well. An NSButton or other small view, for example, will nudge the bottom edge up if necessary to prevent itself from being cut in two (thereby pushing it onto an adjacent page). Subclasses should invoke super’s implementation, if desired, after first making their own adjustments.

See also:	− adjustPageWidthNew:left:right:limit:

adjustPageWidthNew:left:right:limit:

− (void)adjustPageWidthNew:(float *)newRight

left:(float)left

right:(float)proposedRight

limit:(float)rightLimit

Overridden by subclasses to adjust page width during automatic pagination. This method is invoked by print: and fax: with left and proposedRight set to the side edges of the pending page rectangle in the receiver’s coordinate system. The receiver can pull in the right edge and return the new value in newRight, allowing it to prevent items such as small images or text columns from being divided across pages. rightLimit is the leftmost value that newRight can be set to, as calculated using the return value of widthAdjustLimit. If this limit is exceeded, the pagination mechanism simply uses rightLimit for the right edge.

NSView’s implementation of this method propagates the message to its subviews, allowing nested views to adjust page width for their drawing as well. An NSButton or other small view, for example, will nudge the bottom edge up if necessary to prevent itself from being cut in two (thereby pushing it onto an adjacent page). Subclasses should invoke super’s implementation, if desired, after first making their own adjustments.

See also:	− adjustPageHeightNew:top:bottom:limit:

continue in this topic


NSView3

adjustScroll:

− (NSRect)adjustScroll:(NSRect)proposedVisibleRect

Overridden by subclasses to modify proposedVisibleRect, returning the altered rectangle. NSClipView invokes this method to allow its document view to adjust its position during scrolling. For example, a custom view object that displays a table of data can adjust the origin of proposedVisibleRect so that rows or columns aren’t cut off by the edge of the enclosing NSClipView. NSView’s implementation simply returns proposedVisibleRect.

Note:	NSClipView only invokes this method during automatic or user-controlled scrolling. Its scrollToPoint: method doesn’t invoke this method, so you can still force a scroll to an arbitrary point.

allocateGState

− (void)allocateGState

Causes the receiver to maintain a private PostScript graphics state object, which encapsulates all parameters of the graphics environment. The receiver builds the graphics state parameters using setUpGState, then automatically establishes this graphics state each time the PostScript focus is locked on it. A graphics state may improve performance for view objects that are focused often and need to set many parameters, but use of standard PostScript operators is normally efficient enough.

Because graphics states occupy a fair amount of memory, they can actually degrade performance. Be sure to test application performance with and without the private graphics state before committing to its use.

See also:	− setUpGState, − gstate, − renewGState, − releaseGState

ancestorSharedWithView:

− (NSView *)ancestorSharedWithView:(NSView *)aView

Returns the closest ancestor shared by the receiver and aView, or nil if there’s no such object. Returns self if aView is identical to the receiver.

See also:	− isDescendantOf:

autoresizesSubviews

− (BOOL)autoresizesSubviews

Returns YES if the receiver automatically resizes its subviews using resizeSubviewsWithOldSize: whenever its frame size changes, NO otherwise.

See also:	− setAutoresizesSubviews:

autoresizingMask

− (unsigned int)autoresizingMask

Returns the receiver’s autoresizing mask, which determines how it’s resized by the resizeWithOldSuperviewSize: method. The autoresizing mask values are listed under the setAutoresizingMask: method description. If the autoresizing mask is equal to NSViewNotSizable (that is, if none of the options are set), then the receiver doesn’t resize at all in resizeWithOldSuperviewSize:.

autoscroll:

− (BOOL)autoscroll:(NSEvent *)theEvent

Scrolls the receiver’s closest ancestor NSClipView proportionally to theEvent’s distance outside of it. theEvent’s location should be expressed in the window’s base coordinate system (which it normally is), not the receiving view object’s. Returns YES if any scrolling is performed; otherwise returns NO.

View objects that track mouse-dragged events can use this method to scroll automatically when the mouse is dragged outside of the NSClipView. Repeated invocations of this method (with an appropriate delay) result in continual scrolling, even when the mouse doesn’t move.

See also:	− autoscroll: (NSClipView), − scrollPoint:, − isDescendantOf:

beginPage:label:bBox:fonts:

− (void)beginPage:(int)ordinalNum

label:(NSString *)aString

bBox:(NSRect)pageRect

fonts:(NSString *)fontNames

Writes a conforming PostScript page separator. This method is invoked by print: and fax:.

ordinalNum is the page’s position in the document’s page sequence (from 1 through n for an n-page document).

aString is a string that contains no white space characters. It identifies the page according to the document’s internal numbering scheme. If aString is empty (@“”), the text equivalent of ordinalNum is used.

pageRect is the rectangle enclosing all the drawing on the page about to be printed, in the default PostScript coordinate system of the page (not of the receiving NSView). If pageRect is an empty rectangle (width and height of zero), “(atend)” is output instead of a description of the bounding box, and the bounding box is output at the end of the page.

fontNames is a string containing the names of the fonts used in the page, each pair separated by a space. If the fonts used are unknown before the page is printed, fontNames can be empty. In this case “(atend)” is output instead of the font names, which are listed automatically at the end of the page description.

See also:	− endPage, NSIsEmptyRect() (Foundation Kit)

beginPageSetupRect:placement:

− (void)beginPageSetupRect:(NSRect)aRect placement:(NSPoint)location

Writes the page setup section for a page, generating the initial coordinate transformation for printing the region defined by aRect in the receiver’s coordinate system. location is the offset in page coordinates of the rectangle on the physical page.

This method is invoked by print: and fax: after the starting comments for the page have been written. It generates a PostScript save operation and invokes lockFocus, which are balanced in the endPage method with an unlockFocus and a PostScript restore operation.

See also:	− addToPageSetup

beginPrologueBBox:creationDate:createdBy:fonts:forWhom:pages:title:

− (void)beginPrologueBBox:(NSRect)boundingBox

creationDate:(NSString *)dateCreated

createdBy:(NSString *)anApplication

fonts:(NSString *)fontNames

forWhom:(NSString *)user

pages:(int)numPages

title:(NSString *)aTitle

Invoked by print: and fax: to write the start of a conforming PostScript header.

boundingBox is the bounding box of the document, expressed in the default PostScript coordinate system on the page. The document bounding box is the union of the bounding boxes of every page in the document. If it’s unknown, boundingBox should be empty (width and height of zero). In this case “(atend)” is output instead of the bounding box, which is accumulated as pages are printed and written in the trailer.

dateCreated is a text string containing a human readable date. If dateCreated is empty (@“”) the current date is used.

anApplication is a string containing the name of the document creator. If anApplication is empty then the string returned by NSProcessInfo’s processName instance method is used.

fontNames is a string holding the names of the fonts used in the document, each pair separated by a space. If the fonts used are unknown before the document is printed, fontNames should be empty. In this case “(atend)” is output instead of the font names, and the name of each NSFont used by the view is written in the trailer.

user is a string containing the name of the person the document is being printed for. If user is empty the login name of the current user is substituted.

numPages specifies the number of pages in the document. If unknown at the beginning of printing, numPages should have a value of −1. In this case “(atend)” is output instead of a page count, the pages are counted as they are generated, and the resulting count is written in the trailer.

aTitle is a string specifying the title of the document. If aTitle is empty, then the title of the receiver’s window is used. If the window has no title, “Untitled” is output.

See also:	− beginTrailer, − endTrailier, − set (NSFont), + useFont: (NSFont)

beginSetup

− (void)beginSetup

Writes the beginning of the document setup section, which begins with a %%BeginSetup comment and includes a %%PaperSize comment declaring the type of paper being used. This method is invoked by print: and fax: at the start of the setup section of the document, which occurs after the prologue of the document has been written, but before any pages are written. This section of the output is intended for device setup or general initialization code.

beginTrailer

− (void)beginTrailer

Writes the start of a conforming PostScript trailer, which begins with a %%Trailer comment. This method is invoked by print: and fax: immediately after all pages have been written.

bounds

− (NSRect)bounds

Returns the receiver’s bounds rectangle, which expresses its location and size in its own coordinate system. The bounds rectangle may be rotated; use the boundsRotation method to check this.

See also:	− frame, − setBounds:

boundsRotation

− (float)boundsRotation

Returns the angle of the receiver’s bounds rectangle relative to its frame rectangle. See the setBoundsRotation: method description for more information on bounds rotation.

See also:	− rotateByAngle:, − setBoundsRotation:

canDraw

− (BOOL)canDraw

Returns YES if drawing commands will produce any result, NO otherwise. Use this method when invoking a draw method directly along with lockFocus and unlockFocus, bypassing the display... methods (which test drawing ability and perform locking for you). If this method returns NO, you shouldn’t invoke lockFocus or perform any drawing.

An NSView can draw if it’s attached to a view hierarchy in an NSWindow and the NSWindow has a corresponding PostScript window device, or during printing if the NSView is a descendant of the view being printed.

centerScanRect:

− (NSRect)centerScanRect:(NSRect)aRect

Converts the corners of a rectangle to lie on the center of device pixels, which is useful in compensating for PostScript overscanning when the coordinate system has been scaled. This method converts the given rectangle to device coordinates, adjusts the rectangle to lie in the center of the pixels, and converts the resulting rectangle back to the receiver’s coordinate system. Returns the adjusted rectangle.

See also:	− isRotatedOrScaledFromBase

convertPoint:fromView:

− (NSPoint)convertPoint:(NSPoint)aPoint fromView:(NSView *)aView

Converts aPoint from aView’s coordinate system to that of the receiver. If aView is nil, this method instead converts from window base coordinates. Both aView and the receiver must belong to the same NSWindow. Returns the converted point.

See also:	− convertRect:fromView:, − convertSize:fromView:, − sharedAncestorWithView:, − contentView (NSWindow)

convertPoint:toView:

− (NSPoint)convertPoint:(NSPoint)aPoint toView:(NSView *)aView

Converts aPoint from the receiver’s coordinate system to that of aView. If aView is nil, this method instead converts to window base coordinates. Both aView and the receiver must belong to the same NSWindow. Returns the converted point.

See also:	− convertRect:toView:, − convertSize:toView:, − sharedAncestorWithView:, − contentView (NSWindow)

convertRect:fromView:

− (NSRect)convertRect:(NSRect)aRect fromView:(NSView *)aView

Converts aRect from aView’s coordinate system to that of the receiver. If aView is nil, this method instead converts from window base coordinates. Both aView and the receiver must belong to the same NSWindow. Returns the converted rectangle.

See also:	− convertPoint:fromView:, − convertSize:fromView:, − sharedAncestorWithView:, − contentView (NSWindow)

convertRect:toView:

− (NSRect)convertRect:(NSRect)aRect toView:(NSView *)aView

Converts aRect from the receiver’s coordinate system to that of aView. If aView is nil, this method instead converts to window base coordinates. Both aView and the receiver must belong to the same NSWindow. Returns the converted rectangle.

See also:	− convertPoint:toView:, − convertSize:toView:, − sharedAncestorWithView:, − contentView (NSWindow)

convertSize:fromView:

− (NSSize)convertSize:(NSSize)aSize fromView:(NSView *)aView

Converts aSize from aView’s coordinate system to that of the receiver. If aView is nil, this method instead converts from window base coordinates. Both aView and the receiver must belong to the same NSWindow. Returns the converted size.

See also:	− convertPoint:fromView:, − convertRect:fromView:, − sharedAncestorWithView:, − contentView (NSWindow)

convertSize:toView:

− (NSSize)convertSize:(NSSize)aSize toView:(NSView *)aView

Converts aSize from the receiver’s coordinate system to that of aView. If aView is nil, this method instead converts to window base coordinates. Both aView and the receiver must belong to the same NSWindow. Returns the converted size.

See also:	− convertPoint:toView:, − convertRect:toView:, − sharedAncestorWithView:, − contentView (NSWindow)

dataWithEPSInsideRect:

− (NSData *)dataWithEPSInsideRect:(NSRect)aRect

Returns EPS data that draws the region of the receiver within aRect. This data can be placed on an NSPasteboard, written to a file, or used to create an NSImage object.

See also:	− writeEPSInsideRect:toPasteboard:

discardCursorRects

− (void)discardCursorRects

Invalidates all cursor rectangles set up using addCursorRect:cursor:. You need never invoke this method directly; it’s invoked automatically before the NSView’s cursor rectangles are reestablished using resetCursorRects.

See also:	− discardCursorRects (NSWindow)

display

− (void)display

Displays the receiver and all its subviews if possible, invoking each NSView’s lockFocus, drawRect:, and unlockFocus methods as necessary. If the receiver isn’t opaque, this method backs up the view hierarchy to the first opaque ancestor, calculates the portion of the opaque ancestor covered by the receiver, and begins displaying from there.

See also:	− canDraw, − opaqueAncestor, − visibleRect, − displayIfNeededIgnoringOpacity

displayIfNeeded

− (void)displayIfNeeded

Displays the receiver and all its subviews if any part of the receiver has been marked as needing display with a setNeedsDisplay: or setNeedsDisplayInRect: message. This method invokes each NSView’s lockFocus, drawRect:, and unlockFocus methods as necessary. If the receiver isn’t opaque, this method backs up the view hierarchy to the first opaque ancestor, calculates the portion of the opaque ancestor covered by the receiver, and begins displaying from there.

See also:	− display, − needsDisplay, − displayIfNeededIgnoringOpacity

displayIfNeededIgnoringOpacity

− (void)displayIfNeededIgnoringOpacity

Acts as displayIfNeeded, except that this method doesn’t back up to the first opaque ancestor—it simply causes the receiver and its descendants to execute their drawing code.

displayIfNeededInRect:

− (void)displayIfNeededInRect:(NSRect)aRect

Acts as displayIfNeeded, confining drawing to aRect.

displayIfNeededInRectIgnoringOpacity:

− (void)displayIfNeededInRectIgnoringOpacity:(NSRect)rect

Acts as displayIfNeeded, but confining drawing to aRect and not backing up to the first opaque ancestor—it simply causes the receiver and its descendants to execute their drawing code.

displayRect:

− (void)displayRect:(NSRect)aRect

Acts as display, confining drawing to aRect.

displayRectIgnoringOpacity:

− (void)displayRectIgnoringOpacity:(NSRect)aRect

Acts as display, but confining drawing to aRect and not backing up to the first opaque ancestor—it simply causes the receiver and its descendants to execute their drawing code.

dragFile:fromRect:slideBack:event:

− (BOOL)dragFile:(NSString *)fullPath

fromRect:(NSRect)aRect

slideBack:(BOOL)flag

event:(NSEvent *)theEvent

Initiates a dragging operation from the receiver, allowing the user to drag a file icon to any application that has window or view objects that accept files. This method must be invoked only within an implementation of the mouseDown: method. Returns YES if the receiver successfully initiates the dragging operation (which doesn’t necessarily mean the dragging operation concluded successfully). Otherwise returns NO.

The dragging operation uses these arguments:

•	fullPath is an absolute path for the file to be dragged.

•	aRect describes the position of the icon in the receiver’s coordinate system.

•	flag indicates whether the icon being dragged should slide back to its position in the receiver if the file isn’t accepted. The icon slides back to aRect, if flag is YES, the file is not accepted by the dragging destination, and the user has not disabled icon animation; otherwise it simply disappears.

•	theEvent is the mouse-down event object from which to initiate the drag operation. In particular, its mouse location is used for the offset of the icon being dragged.

See the NSDraggingSource, NSDraggingInfo, and NSDraggingDestination protocol specifications for more information on dragging operations.

See also:	− dragImage:at:offset:event:pasteboard:source:slideBack:, − shouldDelayWindowOrderingForEvent:

dragImage:at:offset:event:pasteboard:source:slideBack:

− (void)dragImage:(NSImage *)anImage

at:(NSPoint)imageLoc

offset:(NSSize)mouseOffset

event:(NSEvent *)theEvent

pasteboard:(NSPasteboard *)pboard

source:(id)sourceObject

slideBack:(BOOL)flag

Initiates a dragging operation from the receiver, allowing the user to drag arbitrary data with a specified icon into any application that has window or view objects that accept dragged data. This method must be invoked only within an implementation of the mouseDown: method. The dragging operation uses these arguments:

•	anImage is the NSImage to be dragged.

•	imageLoc is the location of the image’s lower left corner, in the receiver’s coordinate system. It determines the placement of the dragged image under the cursor.

•	mouseOffset is the mouse’s current location relative to the mouse-down location. It determines the initial location of the image when dragging commences. If you initiate a dragging operation immediately on a mouse-down event, this should be (0.0, 0.0). If you test for a mouse-dragged event first, this should be the difference between the mouse-dragged event’s location and that of the mouse-down event.

•	theEvent is the left-mouse-down event that triggered the dragging operation (see below).

•	pboard holds the data to be transferred to the destination (see below).

•	sourceObject serves as the controller of the dragging operation. It must conform to the NSDraggingSource protocol, and is typically the receiver itself or its NSWindow.

•	flag determines whether the NSImage should slide back if it’s rejected. The image slides back to aPoint if flag is YES, the image isn’t accepted by the dragging destination, and the user hasn’t disabled icon animation; otherwise it simply disappears.

Before invoking this method, you must place the data to be transferred on pboard. To do this, get the drag pasteboard object (NSDragPboard), declare the types of the data, and then put the data on the pasteboard. This code fragment initiates a dragging operation on an image itself (that is, the image is the data to be transferred):

- (void)mouseDown:(NSEvent *)theEvent

{

    NSSize dragOffset = NSMakeSize(0.0, 0.0);

    NSPasteboard *pboard;

    pboard = [NSPasteboard pasteboardWithName:NSDragPboard];

    [pboard declareTypes:[NSArray arrayWithObject:NSTIFFPboardType] owner:self];

    [pboard setData:[[self image] TIFFRepresentation] forType:NSTIFFPboardType];

    [self dragImage:[self image] at:[self imageLocation] offset:dragOffset

           event:theEvent pasteboard:pboard source:self slideBack:YES];

    return;

}

See the NSDraggingSource, NSDraggingInfo, and NSDraggingDestination protocol specifications for more information on dragging operations.

See also:	− dragFile:fromRect:slideBack:event:, − shouldDelayWindowOrderingForEvent:

drawPageBorderWithSize:

− (void)drawPageBorderWithSize:(NSSize)borderSize

Allows applications that use the Application Kit pagination facility to draw additional marks on each logical page, such as alignment marks or a virtual sheet border. This method is invoked by beginPageSetupRect:placement:. The default implementation doesn’t draw anything.

See also:	− drawSheetBorderWithSize:

drawRect:

− (void)drawRect:(NSRect)aRect

Overridden by subclasses to draw the receiver’s image within aRect. The receiver can assume that the PostScript focus has been locked, that drawing will be clipped to its frame rectangle, and that the coordinate transformations of its frame and bounds rectangles have been applied; all it need do is invoke PostScript client functions. aRect is provided for optimization; it’s perfectly correct, though inefficient, to draw images that lie outside the requested rectangle. See “How to Draw” in the class description for information and references on drawing.

This method is intended to be completely overridden by each subclass that performs drawing. Don’t invoke super’s implementation in your subclass.

See also:	− display..., − shouldDrawColor, − isFlipped

drawSheetBorderWithSize:

− (void)drawSheetBorderWithSize:(NSSize)borderSize

Allows applications that use the Application Kit pagination facility to draw additional marks on each printed sheet, such as crop marks or fold lines. This method is invoked by beginPageSetupRect:placement:. The default implementation doesn’t draw anything.

See also:	− drawPageBorderWithSize:

enclosingScrollView

− (NSScrollView *)enclosingScrollView

Returns the nearest ancestor NSScrollView containing the receiver (not including the receiver itself); otherwise returns nil.

endHeaderComments

− (void)endHeaderComments

Writes out the end of a conforming PostScript header, starting with the %%EndComments line and then the start of the prologue, including the Application Kit’s standard printing package. Override endPrologue to add your own global definitions. This method is invoked by print: and fax: after beginPrologueBBox:creationDate:createdBy:fonts:forWhom:pages:title: and before endPrologue.

endPage

− (void)endPage

Writes the end of a conforming PostScript page. This method is invoked after each page is printed. It balances the preceding invocation of beginPageSetupRect:placement: by invoking unlockFocus and generating a PostScript restore operator, and generates a PostScript showpage operator to finish the page. This method also generates comments for the bounding box and page fonts, if they were specified as being at the end of the page.

See also:	− beginPrologueBBox:creationDate:createdBy:fonts:forWhom:pages:title:

endPageSetup

− (void)endPageSetup

Writes the end of the page setup section, which begins with a %%EndPageSetup comment. This method is invoked by print: and fax: just after beginPageSetupRect:placement: is invoked.

endPrologue

− (void)endPrologue

Writes the end of the conforming PostScript prologue. This method is invoked by print: and fax: after the prologue of the document has been written. Subclasses can override this method to add their own definitions to the prologue. For example:

- endPrologue

{

    [[NSDPSContext currentContext] printFormat:@"/littleProc {pop} def");

    [super endPrologue];

    return;

}

endSetup

− (void)endSetup

Writes out the end of the setup section, which begins with a %%EndSetup comment. This method is invoked by print: and fax: just after beginSetup is invoked.

endTrailer

− (void)endTrailer

Writes the end of the conforming PostScript trailer. This method is invoked by print: and fax: just after beginTrailer is invoked.

See also:	− beginTrailer

p	fax:

− (void)fax:(id)sender

Opens the Fax panel, and if the user chooses an option other than canceling, prints the receiver and all its subviews to a fax modem.

See also:	− print:

frame

− (NSRect)frame

Returns the receiver’s frame rectangle, which defines its position in its superview. The frame rectangle may be rotated; use the frameRotation method to check this.

See also:	− bounds, − setFrame:

frameRotation

− (float)frameRotation

Returns the angle of the receiver’s frame relative to its superview’s coordinate system.

See also:	− setFrameRotation:, − boundsRotation

gState

− (int)gState

Returns the PostScript user object identifier for the receiver’s PostScript graphics state object, as created with allocateGState, or 0 if it doesn’t have one. A view object allocates its graphics state object only when needed, so if the receiver hasn’t been focused since receiving the allocateGState message, this method returns 0.

See also:	− allocateGState, − lockFocus

heightAdjustLimit

− (float)heightAdjustLimit

Returns the fraction (between 0.0 and 1.0) of the page that can be pushed onto the next page during automatic pagination to prevent items such as lines of text from being divided across pages. This fraction is used to calculate the bottom edge limit for a adjustPageHeightNew:top:bottom:limit: message.

See also:	− widthAdjustLimit

hitTest:

− (NSView *)hitTest:(NSPoint)aPoint

Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains aPoint, or nil if aPoint lies completely outside the receiver. aPoint is in the coordinate system of the receiver’s superview, not of the receiver itself.

This method is used primarily by an NSWindow to determine which NSView should receive a mouse-down event. You’d rarely need invoke this method, but you might want to override it to have a view object hide mouse-down events from its subviews.

See also:	− mouse:inRect:, − convertPoint:toView:

initWithFrame:

− (id)initWithFrame:(NSRect)frameRect

Initializes a newly allocated NSView with frameRect as its frame rectangle. The new view object must be inserted into the view hierarchy of an NSWindow before it can be used. This method is the designated initializer for the NSView class. Returns self.

See also:	− addSubview:, − addSubview:positioned:relativeTo:, − setFrame:

isDescendantOf:

− (BOOL)isDescendantOf:(NSView *)aView

Returns YES if the receiver is a subview, immediate or not, of aView, or if it’s identical to aView; otherwise returns NO.

See also:	− superview, − subviews, − ancestorSharedWithView:

isFlipped

− (BOOL)isFlipped

Returns YES if the receiver uses flipped drawing coordinates or NO if it uses native PostScript coordinates. NSView’s implementation returns NO; subclasses that use flipped coordinates should override this method to return YES.

isOpaque

− (BOOL)isOpaque

Overridden by subclasses to return YES if the receiver is opaque, NO otherwise. A view object is opaque if it completely covers its frame rectangle when drawing itself. NSView, being an abstract class, performs no drawing at all and so returns NO.

See also:	− opaqueAncestor, − displayRectIgnoringOpacity:, − displayIfNeededIgnoringOpacity, − displayIfNeededInRectIgnoringOpacity:

isRotatedFromBase

− (BOOL)isRotatedFromBase

Returns YES if the receiver or any of its ancestors has ever received a setFrameRotation: or setBoundsRotation: message; otherwise returns NO. This intent of this information is to optimize drawing and coordinate calculation, not necessarily to reflect the exact state of the receiver’s coordinate system, so it may not reflect the actual rotation. For example, if an NSView is rotated to 45 degrees and later back to zero, this method still returns YES.

See also:	− frameRotation, − boundsRotation

isRotatedOrScaledFromBase

− (BOOL)isRotatedOrScaledFromBase

Returns YES if the receiver or any of its ancestors have ever had a nonzero frame or bounds rotation, or has been scaled from the window’s base coordinate system; otherwise returns NO. This intent of this information is to optimize drawing and coordinate calculation, not necessarily to reflect the exact state of the receiver’s coordinate system, so it may not reflect the actual rotation or scaling. For example, if an NSView is rotated to 45 degrees and later back to zero, this method still returns YES.

See also:	− frameRotation, − boundsRotation, − centerScanRect:, − setBounds:, − setBoundsSize:, − scaleUnitSquareToSize:

knowsPagesFirst:last:

− (BOOL)knowsPagesFirst:(int *)firstPageNum last:(int *)lastPageNum

Overridden by subclasses to indicate whether the receiver wishes to perform its own pagination. This method is invoked by print: and fax:. If the receiver returns NO, it’s paginated by NSView’s automatic pagination mechanism. If the receiver returns YES, the printing mechanism later invokes rectForPage: to determine the rectangle of each page from the out parameters firstPageNum to lastPageNum. NSView’s implementation returns NO.

This method is normally invoked with the value of firstPageNum set to 1 and of lastPageNum set to the maximum integer size. If the receiver returns YES it must alter these values to reflect its own numbering scheme, and possibly to limit which pages are printed.

See also:	− getRect:forPage:

locationOfPrintRect:

− (NSPoint)locationOfPrintRect:(NSRect)aRect

Invoked by print: and fax: to determine the location of aRect, the rectangle being printed on the physical page. The return value of this method is used to set the origin for aRect, whose size the receiver can examine in order to properly place it. Both the rectangle and the returned location are expressed in the default PostScript coordinate system of the page.

NSView’s implementation places aRect according to the status of the NSPrintInfo object for the print job. By default it places the image in the upper left corner of the page, but if NSPrintInfo’s isHorizontallyCentered or isVerticallyCentered method returns YES, it centers a single-page image along the appropriate axis. A multiple-page document, however, is always placed so that the divided pieces can be assembled at their edges.

lockFocus

− (void)lockFocus

Locks the PostScript focus on the receiver, so that subsequent PostScript commands take effect in the receiver’s window and coordinate system. If you don’t use a display... method to draw an NSView, you must invoke lockFocus before invoking methods that send PostScript commands to the Window Server, and must balance it with an unlockFocus message when finished.

See also:	+ focusView, − display..., − drawRect:

p	menuForEvent:

− (NSMenu *)menuForEvent:(NSEvent *)theEvent

Overridden by subclasses to return a context-sensitive pop-up menu for the mouse-up event theEvent. The receiver can use information in the mouse event, such as its location over a particular element of the receiver, to determine what kind of menu to return. For example, a text object might display a text-editing menu when the mouse lies over text and a menu for changing graphic attributes when the mouse lies over an embedded image.

NSView’s implementation returns the receiver’s normal menu. This menu is used only on Microsoft Windows.

See also:	+ defaultMenu, − menu (NSResponder)

mouse:inRect:

− (BOOL)mouse:(NSPoint)aPoint inRect:(NSRect)aRect

Returns YES if aRect contains aPoint (which represents the hot spot of the mouse cursor), accounting for whether the receiver is flipped or not. aPoint and aRect must be expressed in the receiver’s coordinate system.

Never use the Foundation Kit’s NSPointInRect() function as a substitute for this method. It doesn’t account for flipped coordinate systems.

See also:	− hitTest:, − isFlipped, NSMouseInRect() (Foundation Kit), − convertPoint:fromView:

needsDisplay

− (BOOL)needsDisplay

Returns YES if the receiver needs to be displayed, as indicated using the setNeedsDisplay: and setNeedsDisplayInRect: methods; returns NO otherwise. The displayIfNeeded... methods check this status to avoid unnecessary drawing, and all display methods clear this status to indicate that the view object is up to date.

needsPanelToBecomeKey

− (BOOL)needsPanelToBecomeKey

Overridden by subclasses to return YES if the receiver requires its panel, which might otherwise avoid becoming key, to become the key window so that it can handle keyboard input. Such a subclass should also override acceptsFirstResponder to return YES. NSView’s implementation returns NO.

See also:	− becomesKeyOnlyIfNeeded (NSPanel)

p	nextKeyView

− (NSView *)nextKeyView

Returns the view object following the receiver in the key view loop, or nil if there is none. This view should, if possible, be made first responder when the user navigates forward from the receiver using keyboard interface control.

See also:	 − nextValidKeyView, − setNextKeyView:, − previousKeyView,

 − previousValidKeyView

p	nextValidKeyView

− (NSView *)nextValidKeyView

Returns the closest view object in the key view loop that follows the receiver and actually accepts first responder status, or nil if there is none.

See also:	− nextKeyView, − setNextKeyView:, − previousKeyView, − previousValidKeyView

continue in this topic


NSView4

opaqueAncestor

− (NSView *)opaqueAncestor

Returns the receiver’s closest opaque ancestor (including the receiver itself).

See also:	− isOpaque, − displayRectIgnoringOpacity:, − displayIfNeededIgnoringOpacity, − displayIfNeededInRectIgnoringOpacity:

performKeyEquivalent:

− (BOOL)performKeyEquivalent:(NSEvent *)theEvent

Implemented by subclasses to respond to key equivalents (also known as shortcuts). If the receiver’s key equivalent is the same as the characters of the key-down event theEvent, as returned by charactersIgnoringModifiers, it should take the appropriate action and return YES. Otherwise, it should return the result invoking super’s implementation. NSView’s implementation of this method simply passes the message down the view hierarchy (from superviews to subviews) and returns NO if none of the receiver’s subviews responds YES.

See also:	− performMnemonic:, − keyDown: (NSWindow)

p	performMnemonic:

− (BOOL)performMnemonic:(NSString *)aString

Implemented by subclasses to respond to mnemonics. If the receiver’s mnemonic is the same as the characters of the key-down event theEvent, as returned by charactersIgnoringModifiers, it should take the appropriate action and return YES. Otherwise, it should return the result invoking super’s implementation. NSView’s implementation of this method simply passes the message down the view hierarchy (from superviews to subviews) and returns NO if none of the receiver’s subviews responds YES.

See also:	− performKeyEquivalent:, − keyDown: (NSWindow)

postsBoundsChangedNotifications

− (BOOL)postsBoundsChangedNotifications

Returns YES if the receiver posts notifications to the default notification center whenever its bounds rectangle changes; returns NO otherwise. See setPostsBoundsChangedNotifications: for a list of methods that result in notifications.

postsFrameChangedNotifications

− (BOOL)postsFrameChangedNotifications

Returns YES if the receiver posts notifications to the default notification center whenever its frame rectangle changes; returns NO otherwise. See setFrameRotation: for a list of methods that result in notifications.

p	previousKeyView

− (NSView *)previousKeyView

See also:	Returns the view object preceding the receiver in the key view loop, or nil if there is none. This view should, if possible, be made first responder when the user navigates backward from the receiver using keyboard interface control.− previousValidKeyView, − nextKeyView, − nextValidKeyView, − setNextKeyView:

p	previousValidKeyView

− (NSView *)previousValidKeyView

Returns the closest view object in the key view loop that precedes the receiver and actually accepts first responder status, or nil if there is none.

See also:	− previousKeyView, − nextValidKeyView, − nextKeyView, − setNextKeyView:

print:

− (void)print:(id)sender

Opens the Print panel, and if the user chooses an option other than canceling, prints the receiver and all its subviews to the device specified in the Print panel.

See also:	− fax:, − dataUsingEPSInsideRect:, − writeEPSInsideRect:toPasteboard:

rectForPage:

− (NSRect)rectForPage:(int)pageNumber

Implemented by subclasses to determine the portion of the receiver to be printed for page number page. If the receiver responded YES to an earlier knowsPagesFirst:last: message, this method is invoked for each page it specified in the out parameters of that message. The receiver is later made to display this rectangle in order to generate the image for this page. This method should return NSZeroRect if pageNumber is outside the receiver’s bounds.

If an NSView responds NO to knowsPagesFirst:last:, this method isn’t invoked by the printing mechanism.

See also:	− adjustPageHeight:top:bottom:limit:, − adjustPageWidth:left:right:limit:

registerForDraggedTypes:

− (void)registerForDraggedTypes:(NSArray *)pboardTypes

Registers pboardTypes as the pasteboard types that the receiver will accept as the destination of an image-dragging session.

Note:	Registering an NSView for dragged types automatically makes it a candidate destination object for a dragging session. As such, it must properly implement some or all of the NSDraggingDestination protocol methods. As a convenience, NSView provides default implementations of these methods. See the NSDraggingDestination protocol specification for details.

See also:	− unregisterDraggedTypes

releaseGState

− (void)releaseGState

Frees the receiver’s PostScript graphics state object, if it has one.

See also:	− allocateGState

removeCursorRect:cursor:

− (void)removeCursorRect:(NSRect)aRect cursor:(NSCursor *)aCursor

Completely removes a cursor rectangle from the receiver. aRect and aCursor must match values previously specified using addCursorRect:cursor:. You should rarely need to use this method. resetCursorRects, which is invoked any time cursor rectangles need to be rebuilt, should establish only the cursor rectangles needed. If you implement resetCursorRects in this way, you can then simply modify the state that resetCursorRects uses to build its cursor rectangles and then invoke NSWindow’s invalidateCursorRectsForView:.

See also:	− discardCursorRects

removeFromSuperview

− (void)removeFromSuperview

Unlinks the receiver from its superview and its NSWindow, removes it from the responder chain, and invalidates its cursor rectangles. The receiver is also released; if you plan to reuse it, be sure to retain it before sending this message and to release it as appropriate when adding it as a subview of another NSView.

Never invoke this method during display.

See also:	− addSubview:, − addSubview:positioned:relativeTo:

removeTrackingRect:

− (void)removeTrackingRect:(NSTrackingRectTag)aTag

Removes the tracking rectangle identified by aTag, which is the value returned by a previous addTrackingRect:owner:userData:assumeInside: message.

renewGState

− (void)renewGState

Invalidates the receiver’s PostScript graphics state object, if it has one, so that it will be regenerated using setUpGState the next time the receiver is focused for drawing.

See also:	− lockFocus

replaceSubview:with:

− (void)replaceSubview:(NSView *)oldView with:(NSView *)newView

Replaces oldView with newView in the receiver’s subviews. Does nothing and returns nil if oldView is not a subview of the receiver.

This method causes oldView to be released; if you plan to reuse it, be sure to retain it before sending this message and to release it as appropriate when adding it as a subview of another NSView.

See also:	− addSubview:, − addSubview:positioned:relativeTo:

resetCursorRects

− (void)resetCursorRects

Overridden by subclasses to define their default cursor rectangles. A subclass’s implementation must invoke addCursorRect:cursor: for each cursor rectangle it wants to establish. NSView’s implementation does nothing.

Application code should never invoke this method directly; it’s invoked automatically as described in the class description under “Tracking Rectangles and Cursor Rectangles.” Use NSWindow’s invalidateCursorRectsForView: instead to explicitly rebuild cursor rectangles.

See also:	− visibleRectangle

resizeSubviewsWithOldSize:

− (void)resizeSubviewsWithOldSize:(NSSize)oldFrameSize

Informs the receivers’s subviews that the receiver’s bounds rectangle size has changed from oldFrameSize. If the receiver is configured to autoresize its subviews, this method is automatically invoked by any method that changes the receiver’s frame size.

NSView’s implementation sends resizeWithOldSuperviewSize: to the receiver’s subviews with oldFrameSize as the argument. You shouldn’t invoke this method directly, but you can override it to define a specific retiling behavior.

See also:	− setAutoresizesSubviews:

resizeWithOldSuperviewSize:

− (void)resizeWithOldSuperviewSize:(NSSize)oldFrameSize

Informs the receiver that the frame size of its superview has changed from oldFrameSize. This method is normally invoked automatically from resizeSubviewsWithOldSize:.

NSView’s implementation resizes the receiver according to the autoresizing options listed under the setAutoresizingMask: method description. You shouldn’t invoke this method directly, but you can override it to define a specific resizing behavior.

rotateByAngle:

− (void)rotateByAngle:(float)angle

Rotates the receiver’s bounds rectangle by angle degrees around the origin of the coordinate system, (0.0, 0.0) See the setBoundsRotation: method description for more information.This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.

This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

See also:	− setFrameRotation:, − setPostsBoundsChangedNotifications:

scaleUnitSquareToSize:

− (void)scaleUnitSquareToSize:(NSSize)newUnitSize

Scales the receiver’s coordinate system so that the unit square changes to newUnitSize. For example, a newUnitSize of (0.5, 1.0) causes the receiver’s horizontal coordinates to be halved, in turn doubling the width of its bounds rectangle. Note that scaling is performed from the origin of the coordinate system, (0.0, 0.0), not the origin of the bounds rectangle; as a result, both the origin and size of the bounds rectangle are changed. The frame rectangle remains unchanged.

This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.

This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

See also:	− setBoundsSize:, − setPostsBoundsChangedNotifications:

scrollPoint:

− (void)scrollPoint:(NSPoint)aPoint

Scrolls the receiver’s closest ancestor NSClipView so that aPoint in the receiver lies at the origin of the NSClipView’s bounds rectangle.

See also:	− autoscroll:, − scrollToPoint: (NSClipView), − isDescendantOf:

scrollRect:by:

− (void)scrollRect:(NSRect)aRect by:(NSSize)offset

Copies the visible portion of the receiver’s rendered image within aRect and lays that portion down again at offset from aRect’s origin. This method is useful during scrolling or translation of the coordinate system to efficiently move as much of the receiver’s rendered image as possible without requiring it to be redrawn, following these steps:

1.	Invoke scrollRect:by: to copy the rendered image.

2.	Move the view object’s origin or scroll it within its superview.

3.	Calculate the newly exposed rectangles and invoke either displayRect: or setNeedsDisplayInRect: to draw them.

You should rarely need to use this method, however. The scrollPoint:, scrollRectToVisible:, and autoscroll: methods automatically perform optimized scrolling.

See also:	− setBoundsOrigin:, − translateOriginToPoint:

scrollRectToVisible:

− (BOOL)scrollRectToVisible:(NSRect)aRect

Scrolls the receiver’s closest ancestor NSClipView the minimum distance needed so that aRect in the receiver becomes visible in the NSClipView. Returns YES if any scrolling is performed; otherwise returns NO.

See also:	− autoscroll:, − scrollToPoint: (NSClipView), − isDescendantOf:

setAutoresizesSubviews:

− (void)setAutoresizesSubviews:(BOOL)flag

Determines whether the receiver automatically resizes its subviews when its frame size changes. If flag is YES, the receiver invokes resizeSubviewsWithOldSize: whenever its frame size changes; if flag is NO, it doesn’t. View objects by default do autoresize their subviews.

See also:	− autoresizesSubviews:

setAutoresizingMask:

− (void)setAutoresizingMask:(unsigned int)mask

Determines how the receiver’s resizeWithOldSuperviewSize: method changes its frame rectangle. mask can be specified by combining any of the following options using the C bitwise OR operator:

Option	Meaning

NSViewMinXMargin	The left margin between the receiver and its superview is flexible.

NSViewWidthSizable	The receiver’s width is flexible.

NSViewMaxXMargin	The right margin between the receiver and its superview is flexible.

NSViewMinYMargin	The top margin between the receiver and its superview is flexible.

NSViewHeightSizable	The receiver’s height is flexible.

NSViewMaxYMargin	The bottom margin between the receiver and its superview is flexible.

Where more than one option along an axis is set, resizeWithOldSuperviewSize: by default distributes the size difference as evenly as possible among the flexible portions. For example, if NSViewWidthSizable and NSViewMaxXMargin are set and the superview’s width has increased by 10.0 units, the receiver’s frame and right margin are each widened by 5.0 units.

See also:	− autoresizingMask, − resizeSubviewsWithOldSize:, − setAutoresizesSubviews:

setBounds:

− (void)setBounds:(NSRect)boundsRect

Sets the receiver’s bounds rectangle to boundsRect. The bounds rectangle determines the origin and scale of the receiver’s coordinate system within its frame rectangle. This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.

This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

See also:	− bounds, − setBoundsRotation:, − setBoundsOrigin:, − setBoundsSize:, − setFrame:, − setPostsBoundsChangedNotifications:

setBoundsOrigin:

− (void)setBoundsOrigin:(NSPoint)newOrigin

Sets the origin of the receiver’s bounds rectangle to newOrigin, effectively shifting its coordinate system so that newOrigin lies at the origin of the receiver’s frame rectangle. This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.

This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

See also:	− translateOriginToPoint:, − bounds, − setBoundsRotation:, − setBounds:, − setBoundsSize:, − setPostsBoundsChangedNotifications:

setBoundsRotation:

− (void)setBoundsRotation:(float)angle

Sets the rotation of the receiver’s bounds rectangle to angle. Positive values indicate counterclockwise rotation, negative clockwise. Rotation is performed around the coordinate system origin, (0.0, 0.0), which need not coincide with that of the frame rectangle or the bounds rectangle. This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.

This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

Bounds rotation affects the orientation of the drawing within the view object’s frame rectangle, but not the orientation of the frame rectangle itself. Also, for a rotated bounds rectangle to enclose all the visible areas of its view object—that is, to guarantee coverage over the frame rectangle—it must also contain some areas that aren’t visible. This can cause unnecessary drawing to be requested, which may affect performance. It may be better in many cases to rotate the PostScript coordinate system in the drawRect: method rather than use this method.

See also:	− rotateByAngle:, − boundsRotation, − setFrameRotation:, − setPostsBoundsChangedNotifications:

setBoundsSize:

− (void)setBoundsSize:(NSSize)newSize

Sets the size of the receiver’s bounds rectangle to newSize, inversely scaling its coordinate system relative to its frame rectangle. For example, a view object with a frame size of (100.0, 100.0) and a bounds size of (200.0, 100.0) draws half as wide along the x axis. This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.

This method posts an NSViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.

See also:	− bounds, − setBoundsRotation:, − setBounds:, − setBoundsOrigin:, − setPostsBoundsChangedNotifications:

setFrame:

− (void)setFrame:(NSRect)frameRect

Sets the receiver’s frame rectangle to frameRect, thereby repositioning and resizing it within the coordinate system of its superview. This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.

This method posts an NSViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.

See also:	− frame, − setFrameRotation:, − setFrameOrigin:, − setFrameSize:, − setBounds:, − setPostsFrameChangedNotifications:

setFrameOrigin:

− (void)setFrameOrigin:(NSPoint)newOrigin

Sets the origin of the receiver’s frame rectangle to newOrigin, effectively repositioning it within its superview. This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.

This method posts an NSViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.

See also:	− frame, − setFrameSize:, − setFrame:, − setFrameRotation:, − setPostsFrameChangedNotifications:

setFrameRotation:

− (void)setFrameRotation:(float)angle

Sets the rotation of the receiver’s frame rectangle to angle, rotating it within its superview without affecting its coordinate system. Positive values indicate counterclockwise rotation, negative clockwise. Rotation is performed around the origin of the frame rectangle.

This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.

This method posts an NSViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.

See also:	− frameRotation:, − setBoundsRotation:

setFrameSize:

− (void)setFrameSize:(NSSize)newSize

Sets the size of the receiver’s frame rectangle to newSize, resizing it within its superview without affecting its coordinate system. This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.

This method posts an NSViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.

See also:	− frame, − setFrameOrigin:, − setFrame:, − setFrameRotation:, − setPostsFrameChangedNotifications:

setNeedsDisplay:

− (void)setNeedsDisplay:(BOOL)flag

If flag is YES, marks the receiver’s entire bounds as needing display; if flag is NO, marks it as not needing display. Whenever the data or state used for drawing a view object changes, the view should be sent a setNeedsDisplay: message. NSViews marked as needing display are automatically redisplayed on each pass through the application’s event loop. (View objects that need to redisplay before the event loop comes around can of course immediately be sent the appropriate display... method.)

See also:	− setNeedsDisplayInRect:, − needsDisplay

setNeedsDisplayInRect:

− (void)setNeedsDisplayInRect:(NSRect)invalidRect

Marks the region of the receiver within invalidRect as needing display, increasing the receiver’s existing invalid region to include it. A later displayIfNeeded... method will then perform drawing only within the invalid region. NSViews marked as needing display are automatically redisplayed on each pass through the application’s event loop. (View objects that need to redisplay before the event loop comes around can of course immediately be sent the appropriate display... method.)

See also:	− setNeedsDisplay:, − needsDisplay

p	setNextKeyView:

− (void)setNextKeyView:(NSView *)aView

Inserts aView after the receiver in the key view loop of the receiver’s NSWindow.

See also:	− nextKeyView, − nextValidKeyView:, − previousKeyView, − previousValidKeyView

setPostsBoundsChangedNotifications:

− (void)setPostsBoundsChangedNotifications:(BOOL)flag

Controls whether the receiver informs observers when its bounds rectangle changes. If flag is YES, the receiver will post notifications to the default notification center whenever its bounds rectangle changes; if flag is NO it won’t. The following methods can result in notification posting:

setBounds:

setBoundsOrigin:

setBoundsSize:

setBoundsRotation:

translateOriginToPoint:

scaleUnitSquareToSize:

rotateByAngle:

See also:	− postsBoundsChangedNotifications

setPostsFrameChangedNotifications:

− (void)setPostsFrameChangedNotifications:(BOOL)flag

Controls whether the receiver informs observers when its frame rectangle changes. If flag is YES, the receiver will post notifications to the default notification center whenever its frame rectangle changes; if flag is NO it won’t. The following methods can result in notification posting:

setFrame:

setFrameOrigin:

setFrameSize:

setFrameRotation:

See also:	− postsFrameChangedNotifications

setUpGState

− (void)setUpGState

Overridden by subclasses to (re)initialize the receiver’s graphics state object. This method is automatically invoked when the graphics state object created using allocateGState needs to be initialized. NSView’s implementation does nothing. Your subclass can override it to set the current font, line width, or any other PostScript graphics state parameter except coordinate transformations and the clipping path—these are established by the frame and bounds rectangles, and by methods such as scaleUnitSquareToSize: and translateOriginToPoint:. Note that drawSelf: can further transform the coordinate system and clipping path for whatever temporary effects is needs.

See also:	− allocateGState, − renewGState

shouldDelayWindowOrderingForEvent:

− (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)theEvent

Overridden by subclasses to allow the user to drag images from the receiver without its window moving forward and possibly obscuring the destination, and without activating the application. If this method returns YES, the normal window ordering and activation mechanism is delayed (not necessarily prevented) until the next mouse-up event. If it returns NO then normal ordering and activation occurs. Never invoke this method directly; it’s invoked automatically for each mouse-down event directed at the NSView.

An NSView subclass that allows dragging should implement this method to return YES if theEvent, an initial mouse-down event, is potentially the beginning of a dragging session or of some other context where window ordering isn’t appropriate. This method is invoked before a mouseDown: message for theEvent is sent. NSView’s implementation returns NO.

If, after delaying window ordering, the receiver actually initiates a dragging session or similar operation, it should also send a preventWindowOrdering message to NSApp, which completely prevents the window from ordering forward and the activation from becoming active. preventWindowOrdering is sent automatically by NSView’s dragImage:... and dragFile:... methods.

shouldDrawColor

− (BOOL)shouldDrawColor

Returns NO if the receiver is being drawn in an NSWindow (as opposed, for example, to being printed) and the NSWindow can’t store color; otherwise returns YES. An NSView can base its drawing behavior on the return value of this method to improve its appearance in grayscale windows.

See also:	− drawRect:, − canStoreColor (NSWindow)

sortSubviewsUsingFunction:context:

− (void)sortSubviewsUsingFunction:(int (*)(id, id, void *))compare context:(void *)context

Orders the receivers immediate subviews using the comparator function compare, which takes as arguments two subviews to be ordered and the context supplied, which may be arbitrary data used to help in the decision. compare should return NSOrderedAscending if the first subview should be ordered lower, NSOrderedDescending if the second subview should be ordered lower, and NSOrderedSame if their ordering isn’t important.

See also:	− sortedArrayUsingFunction:context: (NSArray class cluster of the Foundation Kit)

subviews

− (NSArray *)subviews

Return the receiver’s immediate subviews.

See also:	− superview, − addSubview:, − addSubview:positioned:relativeTo:, − removeFromSuperview

superview

− (NSView *)superview

Returns the receiver’s superview, or nil if it has none. When applying this method iteratively or recursively, be sure to compare the returned NSView to the content view of the NSWindow to avoid proceeding out of the view hierarchy.

See also:	− window, − subviews, − removeFromSuperview

tag

− (int)tag

Returns the receiver’s tag, an integer that you can use to identify view objects in your application. NSView’s implementation returns −1. Subclasses can override this method to provide individual tags, possibly adding storage and a setTag: method (which NSView doesn’t define).

See also:	− viewWithTag:

translateOriginToPoint:

− (void)translateOriginToPoint:(NSPoint)newOrigin

Translates the receiver’s coordinate system so that its origin moves to newOrigin. In the process, the origin of the receiver’s bounds rectangle is shifted by (−newOrigin.x, −newOrigin.y). This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.

Note the difference between this method and setting the bounds origin. Translation effectively moves the image inside the bounds rectangle, while setting the bounds origin effectively moves the rectangle over the image. The two are in a sense inverse, although translation is cumulative and setting the bounds origin is absolute.

This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

See also:	− setBoundsOrigin:, − setBounds:, − setPostsBoundsChangedNotifications:

unlockFocus

− (void)unlockFocus

Balances an earlier lockFocus message, restoring the focus to the previously focused view is necessary.

See also:	− allocateGState

unregisterDraggedTypes

− (void)unregisterDraggedTypes

Unregisters the receiver as a possible destination in a dragging session.

See also:	− registerForDraggedTypes:

viewWillMoveToSuperview:

− (void)viewWillMoveToSuperview:(NSView *)newSuperview

Informs the receiver that it’s being added as a subview of newSuperview. Subclasses can override this method to perform whatever actions are necessary.

See also:	− viewWillMoveToWindow:

viewWillMoveToWindow:

− (void)viewWillMoveToWindow:(NSWindow *)newWindow

Informs the receiver that it’s being added to the view hierarchy of newWindow. Subclasses can override this method to perform whatever actions are necessary.

See also:	− viewWillMoveToSuperview:

viewWithTag:

− (id)viewWithTag:(int)aTag

Returns the receiver’s nearest descendant (including itself) whose tag is aTag, or nil if no subview has that tag.

See also:	− tag

visibleRect

− (NSRect)visibleRect

Returns the portion of the receiver not clipped by its superviews. Visibility is therefore defined quite simply, and doesn’t account for whether other NSViews (or windows) overlap the receiver or whether the receiver has a window at all.

Note:	During a printing operation the visible rectangle is further clipped to the page being imaged.

See also:	− isVisible (NSWindow), − documentVisibleRect (NSScrollView), − documentVisibleRect (NSClipView)

widthAdjustLimit

− (float)widthAdjustLimit

Returns the fraction (between 0.0 and 1.0) of the page that can be pushed onto the next page during automatic pagination to prevent items such as small images or text columns from being divided across pages. This fraction is used to calculate the right edge limit for a adjustPageWidthNew:left:right:limit: message.

See also:	− heightAdjustLimit

window

− (NSWindow *)window

Returns the receiver’s window object, or nil if it has none.

See also:	− superview

writeEPSInsideRect:toPasteboard:

− (void)writeEPSInsideRect:(NSRect)aRect toPasteboard:(NSPasteboard *)pboard

Writes EPS data that draws the region of the receiver within aRect onto pboard.

See also:	− dataUsingEPSInsideRect:

Notifications

NSViewBoundsDidChangeNotification

Posted whenever the NSView’s bounds rectangle changes independently of the frame rectangle, if the NSView is configured using setPostsBoundsChangedNotifications: to post such notifications. The notification contains:

Notification Object	The NSView whose bounds rectangle has changed

Userinfo	None

 The following methods can result in notification posting:

setBounds:

setBoundsOrigin:

setBoundsSize:

setBoundsRotation:

translateOriginToPoint:

scaleUnitSquareToSize:

rotateByAngle:

Note that the bounds rectangle resizes automatically to track the frame rectangle. Because the primary change is that of the frame rectangle, however, setFrame: and setFrameSize: don’t result in a bounds-changed notification.

NSViewFocusDidChangeNotification

Posted whenever the NSView loses the PostScript focus other than by an unlockFocus message (for example, when its frame or bounds rectangle is changed). The notification contains:

Notification Object	The NSView that has lost focus.

Userinfo	None

See also:	+ focusView

NSViewFrameDidChangeNotification

Posted whenever the NSView’s frame rectangle changes, if the NSView is configured using setPostsFrameChangedNotifications: to post such notifications. The notification contains:

Notification Object	The NSView whose frame rectangle has changed

Userinfo	None

 The following methods can result in notification posting:

setFrame:

setFrameOrigin:

setFrameSize:

setFrameRotation:


NSWindow

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSResponder : NSObject

Conforms To:	NSCoding (NSResponder)

NSObject (NSObject)

Declared In:	AppKit/NSWindow.h

Purpose

An NSWindow manages an on-screen window, coordinating the display and event handling for its NSViews. Interface Builder allows you to create and set up NSWindows, but there are many things you may wish to do programmatically as well.

Principal Attributes

•	Manages a view hierarchy	•	Uses a delegate

•	Distributes events to view objects	•	Provides a field editor to view objects

Creation

Interface Builder

− initWithContentRect:styleMask:backing:defer:	Designated initializer.

Commonly Used Methods

− makeKeyAndOrderFront:	Move the NSWindow to the front and makes it the key window.

− makeFirstResponder:	Sets the first responder in the NSWindow.

− fieldEditor:forObject:	Returns the shared text object for the NSWindow.

− setContentView:	Sets the root-level NSView in the NSWindow.

− representedFilename	Returns the filename whose contents the NSWindow presents.

− setDocumentEdited:	Sets whether the NSWindow’s represented file needs to be saved.

− setTitle:	Sets the title of the NSWindow.

− setTitleWithRepresentedFilename:	Sets the title of the NSWindow in a readable format for filenames.

Class Description

The NSWindow class defines objects that manage and coordinate the windows that an application displays on the screen. A single NSWindow object corresponds to at most one on-screen window. The two principal functions of NSWindow are to provide an area in which NSViews can be placed, and to accept and distribute, to the appropriate NSViews, events that the user instigates through actions on the mouse and keyboard. Note that the term window sometimes refers to the Application Kit object and sometimes to the Window Server’s PostScript window device; which meaning is intended is made clear in context. The Application Kit also defines an abstract subclass of NSWindow—NSPanel—that adds behavior more appropriate for auxiliary windows.

You typically set windows up using Interface Builder, which allows you to position them, set up many of their visual and behavioral attributes, and lay out views on them. The programmatic work you do with windows more often involves bringing them on and off the screen; changing dynamic attributes such as the window’s title; running modal windows to restrict user input; and assigning a delegate that can monitor certain of its actions, such as closing and resizing.

Window Anatomy

An NSWindow is defined by a frame rectangle that encloses the entire window, including its title bar, border, and other peripheral elements (such as the resize bar on OPENSTEP for Mach), and by a content rectangle that encloses just its content area. Both rectangles are specified in the screen coordinate system and restricted to integer values. The frame rectangle establishes the NSWindow’s base coordinate system. This coordinate system is always aligned with and measured in the same increments as the screen coordinate system (in other words, the base coordinate system can’t be rotated or scaled). The origin of the base coordinate system is the bottom left corner of the NSWindow’s frame rectangle.

You create an NSWindow programmatically through one of the initWithContentRect:... methods by specifying, among other attributes, the size and location of its content rectangle. The frame rectangle is derived from the dimensions of the content rectangle. Various sections below describe other attributes you can specify at initialization and afterward.

When it’s created, an NSWindow automatically creates two NSViews: An opaque frame view that fills the frame rectangle and draws the border, title bar, other peripheral elements, and background, and a transparent content view that fills the content rectangle. The frame view and its peripheral elements are private objects that your application can’t access directly. The content view is the “highest” accessible NSView in the NSWindow; you can replace the default content view with an NSView of your own creation using the setContentView: method. The NSWindow determines the placement of the content view; you can’t position it using NSView’s setFrame... methods, but must use NSWindow’s placement methods, described below under “Windows on the Screen.”

You add other NSViews to the NSWindow as subviews of the content view, or as subviews of any of the content view’s subviews, and so on, through NSView’s addSubview: method. This tree of NSViews is called the NSWindow’s view hierarchy. When an NSWindow is told to display itself, it does so by sending display... messages to the top-level NSView in its view hierarchy. Because displaying is carried out in a determined order, the content view (which is drawn first) may be wholly or partially obscured by its subviews, and these subviews may be obscured by their subviews (and so on).

Window Styles

The peripheral elements that an NSWindow displays define its style. Though you can’t access and manipulate them directly, you can determine at initialization whether an NSWindow has them by providing a style mask to the initWithContentRect:styleMask:backing:defer: method. There are four possible style elements, specifiable by combining their mask values using the C bitwise OR operator:

Element	Mask Value

A title bar	NSTitledWindowMask

A close button	NSClosableWindowMask

A miniaturize button	NSMiniaturizableWindowMask

A resize bar, border, or box	NSResizableWindowMask

You can also specify NSBorderlessWindowMask, in which case none of these accoutrements is used.

Windows on the Screen

NSWindows can be placed on the screen in three dimensions. Besides horizontal and vertical placement, NSWindows are ordered back-to-front in several distinct levels, which group windows of similar type and purpose so that the more “important” ones appear above those less so. Placing an NSWindow on the screen is accomplished with the setFrame:display: method and its variants, setFrameOrigin: and setFrameTopLeftPoint:. Ordering takes place in two ways. setLevel: puts an NSWindow into a group, such as that for standard windows, floating windows (for example, palettes and some inspector panels), menus, and so on. orderWindow:relativeTo: orders an NSWindow within its level above or below another. Convenience methods for ordering include makeKeyAndOrderFront:, orderFront: and orderBack:, as well as orderOut:, which removes an NSWindow from the screen. The isVisible method tells whether an NSWindow is on-screen or off. You can also set a window to order out automatically when its application isn’t active using setHidesOnDeactivate:.

NSWindow offers several means of constraining and adjusting window placement. setMinSize: and setMaxSize: limit the user’s ability to resize the NSWindow (you can still set it to any size programmatically). Similarly, setAspectRatio: keeps a window’s width and height at the same proportions as the user resizes it, and setResizeIncrements: makes the window resize in discrete amounts larger than a single pixel. constrainFrameRectToScreen: adjusts a proposed frame rectangle so that it lies on the screen in such a way that the user can move and resize a window. Note that any NSWindow with a title bar automatically constrains itself to the screen. cascadeTopLeftFromPoint: shifts the top left point by an amount that allows one NSWindow to be placed relative to another so that both their title bars are visible. Finally, the center method places an NSWindow in the most prominent location on the screen, one suitable for important messages and attention panels.

Closely related to window ordering is the idea of opening or closing an NSWindow. Normally, opening is accomplished simply by ordering the NSWindow above or below another that’s on-screen. Closing a window involves explicit use of the either the close method, which simply removes the NSWindow from the screen, or performClose:, which highlights the close button as though the user clicked it. Closing an NSWindow involves at least ordering it out, but adds the possibility of disposing of it altogether. The setReleasedWhenClosed: method sets whether an NSWindow releases itself when sent a close message. An NSWindow’s delegate is also notified when it’s about to close, as described under “Notifications and the NSWindow’s Delegate.”

Miniaturizable windows can be removed from the screen and replaced by a smaller counterpart, whether a freestanding miniwindow or, on Microsoft Windows, a button in the task bar. The miniaturize: and deminiaturize: methods reduce and reconstitute an NSWindow, and performMiniaturize: simulates the user clicking on the NSWindow’s miniaturize button. You can also set the image and title displayed in a freestanding miniwindow by sending setMiniwindowImage: and setMiniwindowTitle: messages to the NSWindow object.

An NSWindow can store its placement in the user defaults system, so that it appears in the same location the next time the user starts the application. The saveFrameUsingName: method stores the frame rectangle, and setFrameUsingName: sets it from the value in user defaults. You can also use the setFrameAutosaveName: method to have an NSWindow save the frame rectangle any time it changes. To expunge a frame rectangle from the defaults system, use the class method removeFrameUsingName:.

Titles and Represented Files

A titled NSWindow can display an arbitrary title or one derived from a filename. setTitle: puts an arbitrary string on the title bar. setTitleWithRepresentedFilename: formats a filename in the title bar in a readable format (which varies with the platform), and associates the NSWindow with that file. You can set the associated file without changing the title using setRepresentedFilename:. You can use the association between the NSWindow and the file in any way you see fit. One convenience offered by NSWindow is marking the file as being edited, so that you can prompt the user to save it on closing the window. The method for marking this is setDocumentEdited:. When the window closes, its delegate can check it with isDocumentEdited to see whether the document needs to be saved.

Most OPENSTEP applications include a submenu that displays the titles of windows, called the Window menu. This submenu automatically lists windows that have a title bar and are resizable, and that can become the main window (as described under “Event Handling”). When you change an NSWindow’s title, this change is also automatically reflected in the Window menu. You can exclude a window that would otherwise be listed by sending it a setExcludedFromWindowsMenu: message.

Window Device Attributes

Nearly every NSWindow has a corresponding PostScript window device in the Window Server. The window device holds the NSWindow’s drawn image, and has two attributes determined by the Window Server and five attributes that the NSWindow controls. The Window Server assigns the window device a unique identifier (within an application). This is the window number, and it’s returned by the windowNumber method. Each window also has a PostScript graphics state that most NSViews share for drawing (NSViews can create their own as well). The gstate method returns its identifier. The five attributes under direct NSWindow control are:

•	Where the drawn image is stored, called the window’s backing

•	When the window device is created

•	Whether the window device persists when the window is off-screen

•	How much memory is used for each pixel (also called the depth limit)

•	Whether the depth limit changes with the screen capacity

A window device’s backing is set when the NSWindow is initialized, and can be one of three types. A buffered window device renders all drawing into a display buffer and then flushes it to the screen. This produces very smooth display, but can require significant amounts of memory. Buffered windows are best for displaying material that must be redrawn often, such as text. A retained window device also uses a buffer, but draws directly to the screen where possible and to the buffer for any portions that are obscured. A nonretained window device has no buffer at all, and must redraw portions as they’re exposed. Further, this redrawing is suspended when the NSWindow’s display mechanism is preempted. For example, if the user drags a window across a nonretained window, the nonretained window is “erased” and isn’t redrawn until the user releases the mouse. Both retained and nonretained windows are also subject to a flashing effect as individual drawing operations are performed, but their results do get to the screen more quickly than those of buffered windows. You can change the backing type between buffered and retained after initialization using the setBacking: method.

The last argument to initWithContentRect:styleMask:backing:defer: specifies whether the NSWindow creates its window device immediately, or only when it’s ordered on-screen. Deferring creation of the window device can offer some performance gain for windows that aren’t displayed immediately, as it reduces the amount of work that needs to be performed up front. This is particularly useful when creation of the NSWindow itself can’t be deferred or when an NSWindow is needed for purposes other than displaying content. Submenus with key equivalents, for example, must exist for the key equivalents to work, but may never actually be displayed.

Memory can also be saved by destroying the window device when the NSWindow is ordered off-screen. The setOneShot: method controls this behavior. One-shot window devices exist only when their NSWindows are ordered on-screen.

Like the display hardware, a window device’s buffer has a depth, or a limit to the memory allotted each pixel. Buffered and retained windows start out with a default window depth of 2 bits per pixel, and this depth grows to the window device’s limit as the NSWindow draws richer images (more shades of gray, more colors). A window device’s depth is set using the setDepthLimit: method, which takes as an argument a window depth limit creating using the NSBestDepth() function.

If an NSWindow draws color into its buffer and there’s a color screen available, the Window Server automatically promotes the window’s depth (up to its limit). This happens whether or not the window is actually on a color screen; similarly, if the user drags a window that displays color from a color to a monochrome screen, it remains at its richer depth. In both cases, the window’s depth is greater than the screen can properly display. Keeping a window’s depth at its richest preserves the displayed image, but may produce undesired results such as dithering on a more limited screen, and does causes slight performance reduction when the window buffer is deeper than the screen requires. You can set an NSWindow to keep its depth at the limit of the screen it’s on with the setDynamicDepthLimit: method. When it’s moved to a new screen, a window with a dynamic depth limit is redrawn into the newly adjust buffer. Making a window’s depth limit dynamic overrides the limit set using setDepthLimit:, and removing the dynamic limit reverts the static limit to the default.

Window Display and Updating

Display of an NSWindow begins with the drawing performed by its view objects, which accumulates in the window’s display buffer or appears immediately on the screen. NSWindows, like NSViews, can be displayed unconditionally or merely marked as needing display, using the display and setViewsNeedDisplay: methods, respectively. A displayIfNeeded message causes the NSWindow’s views to display only if they’ve been marked as needing display. Normally, any time an NSView is marked as needing display the NSWindow makes note of this fact and automatically displays itself shortly after. This automatic display is typically performed on each pass through the event loop, but can be turned off using the setAutodisplay: method. If you turn off autodisplay for an NSWindow, you’re then responsible for displaying it whenever necessary.

A relating mechanism is that of updating. On each pass through the event loop, the application object invokes its updateWindows method, which sends an update message to each NSWindow. Subclasses of NSWindow can override this method to examine the state of the application and change their own state or appearance accordingly—enabling or disabling menus, buttons, and other controls based on the object that’s selected, for example.

In addition to display on the screen, an NSWindow can print itself in its entirety, just as an NSView does. The print: method runs the application’s print panel and causes the NSWindow’s frame view to print itself. The fax: and dataWithEPSInsideRect: methods behave similarly. See the NSView class specification for more information on printing.

Event Handling

As described in the NSResponder class specification, most events coming into an application make their way to a NSWindow in a sendEvent: message. A key event is directed at the key window, while a mouse event is directed at whatever window lies under the cursor. If an event affects the NSWindow directly—resizing or moving it, for example—it performs the appropriate operation itself and sends messages to its delegate informing it of its intentions, thus allowing your application to intercede. The window sends other events up its responder chain from the appropriate starting point: the first responder for a key event, the view under the cursor for a mouse event. These events are then typically handled by some view object in the window. See the NSView and NSEvent class specifications for more information on how to intercept and handle events.

The following sections describe aspects of events not directly related to handling individual events. These include changing the key and main windows, which is often handled by views that receive mouse events, but which you must sometimes perform explicitly, such as when opening a new window; changing the first responder by keyboard rather than mouse actions; sharing a single text object for lightweight editing tasks; and running a modal event loop around an entire window rather than a single view object.

Changing the Key and Main Windows

Windows already on screen automatically change their status as the key or main window according to the user’s actions with the mouse and to how the view clicked handles the mouse event. You can also change the key and main windows programmatically by sending the relevant window object a makeKeyWindow or makeMainWindow message. This is particularly useful to do when creating a new window. Since this operation is often combined with ordering the window to the front of the screen, NSWindow defines a convenience method, makeKeyAndOrderFront:, that performs both operations.

Not all windows are suitable for acting as the key or main window. For example, a window that merely displays information, and contains no objects that need to respond to events or action messages, can completely forgo ever becoming the key window. Similarly, a window that acts as a floating palette of items that are only dragged out by mouse actions never needs to be the key window. Such a window can be defined as a subclass of NSWindow that overrides the methods canBecomeKeyWindow and canBecomeMainWindow to return NO instead of the default of YES. This prevents it from ever becoming the key or main window. Though NSWindow defines these methods, typically only subclasses of NSPanel refuse to accept key or main window status.

Keyboard Interface Control

A window’s first responder is often a view object selected by the user clicking on it. For text fields and other view objects (mainly subclasses of NSControl), an NSWindow also allows the user to select the first responder with the keyboard using the Tab and Shift keys. NSView defines the methods for setting up and examining the loop of objects that the user can select in this manner. A view that’s the first responder is called the key view, and the views that can become the key view in a window are linked together in the window’s key view loop. You normally set up the key view loop using Interface Builder, establishing connections between the nextKeyView outlets of views in the window, and setting the window’s initialFirstResponder outlet to the view that you want selected when the window is first placed on-screen.

In addition to the key view loop, a window can have a default button cell, which uses the Return (or Enter) key as its key equivalent. setDefaultButtonCell: establishes this button cell; you can also set it in Interface Builder by setting a button cell’s key equivalent to ‘\r’. The default button cell draws itself as a focal element for keyboard interface control, unless another button cell is focused on. In this case it temporarily draws itself as normal and disables its key equivalent. Another default key established by NSWindow is the Escape key, which immediately aborts a modal loop (described below under “Modal Windows”).

See the NSResponder class specification for more information on keyboard interface control.

The Field Editor

Each NSWindow keeps a text object that’s shared for light editing tasks. This object, the window’s field editor, is inserted into the view hierarchy when an object needs to edit some text, and removed when the object is finished.The field editor is used by NSTextFields and other controls, for example, to edit the text that they display. The fieldEditor:forObject: method returns an NSWindow’s field editor, after asking the delegate for a substitute using windowWillReturnFieldEditor:toObject:. You can override the NSWindow method in subclasses or provide a delegate to substitute a different class of text object than the default of NSTextView, thereby customizing text-editing in your application.

Modal Windows

You can write a modal event loop for a view object to focus events on that object, such as for tracking the mouse. This normally requires you to write your own event loop for the operation in question. You can also make a whole window or panel run in modal fashion, using the application’s normal event loop machinery but restricting input to the modal window or panel. This is particularly useful for windows and panels that require the user’s attention before an action can proceed: Error messages and warnings are usually presented in modal panels, and operations that require input, such a printing or saving a document, also use modal windows or panels.

OPENSTEP defines two mechanisms for operating a modal window or panel. The first, and simpler, is to invoke NSApplication’s runModalForWindow: method, which monopolizes events for the NSWindow specified until one of the methods stopModal, abortModal, or stopModalWithCode: is invoked, typically by a button’s action method. stopModal ends the modal status of the window or panel from within the event loop. It doesn’t work if invoked from a method invoked by a timer or by a distributed object, since those mechanisms operate outside of the event loop. To terminate the modal loop in these situations, you can use abortModal. stopModal is typically invoked when the user clicks the OK button (or equivalent), abortModal when the user clicks the Cancel button (or presses the Escape key). These two methods are equivalent to stopModalWithCode: with the appropriate argument. See the method descriptions in the NSApplication class specification for more information.

The second mechanism for operating a modal window or panel, called a modal session, allows the application to perform a long operation while still bringing events to the window or panel. This is particularly useful for panels that allow the user to cancel or modify an operation. To begin a modal session, invoke NSApplication’s beginModalSessionForWindow: method, which sets the window up for the session and returns an identifier used for other session-controlling methods. At this point, the application can run in a loop that performs the operation, on each pass sending runModalSession: to the application object so that pending events can be dispatched to the modal window. This method returns a code indicating whether the operation should continue, stop, or abort, which is typically established by the methods described above for runModalForWindow:. After the loop concludes, you can order the window off-screen and invoke NSApplication’s endModalSession: method to restore the normal event loop. The method descriptions in the NSApplication class specification include example code illustrating modal sessions.

The normal behavior of a modal window or session is to exclude all other windows and panels from receiving events. This behavior is appropriate for most non-modal windows and panels, but for those that serve as general auxiliary controls, such as menus and the Font Panel, it’s overly restrictive. The user must be able to use menu key equivalents (such as for Cut and Paste) and change the font of text in the modal window, and this requires non-modal panels to receiver events. The means for doing this is for the NSWindow subclass to override the worksWhenModal method to return YES. Windows that do so can receive mouse and keyboard events even when a modal window is present. If a subclass needs to work when a modal window is present, it should usually be a subclass of NSPanel, not of NSWindow.

Modal windows and sessions provide different levels of control to the application and the user. Modal windows restrict all action to the window itself and any methods invoked from the window. Modal sessions allow the application to continue an operation while accepting input only through the modal session window. Beyond this, you can use distributed objects to perform background operations in a separate thread, while allowing the user to perform other actions with any part of the application. The background thread can communicate with the main thread, allowing the application to display the status of the operation in a non-modal panel, perhaps include controls to stop or affect the operations as it occurs. Note that because the Application Kit isn’t thread-safe, the background thread should communicate with a designated object in the main thread that in turn interacts with the Application Kit.

Notifications and the NSWindow’s Delegate

NSWindow offers observers a rich set of notifications, which it broadcasts on such occurrences as gaining or losing key or main window status, miniaturizing, moving or resizing, becoming exposed, and closing. Each notification is matched to a delegate method, so an NSWindow’s delegate is automatically registered for all notifications that it has methods for. NSWindow also offers its delegate a few other methods, such as windowShouldClose:, which requests approval to close, windowWillResize:toSize:, which allows the delegate to constrain the NSWindow’s size, and windowWillReturnFieldEditor:toObject:, which gives the delegate a chance to modify the field editor or substitute a different editor. See the individual notification and delegate method descriptions at the end of this specification for more information.

Other Features

NSWindow defines a number of methods to assist its view objects in certain operations that may extend in scope beyond a single view or even outside the window containing them. First of these operations is image dragging. Although most dragging operations are initiated by and occur between view objects, NSWindow also defines an image-dragging method, dragImage:at:offset:event:pasteboard:source:slideBack:. An NSWindow can also serve as the destination for dragging operations, registering the types it accepts with registerForDraggedTypes: and unregisterForDraggedTypes. See the descriptions of these same methods in the NSView class specification for more information.

NSViews also handle definition of cursor rectangles—areas where the cursor image changes when the mouse enters them. NSWindow can disable and reenable all of its cursor rectangles with the disableCursorRects and enableCursorRects methods. You can determine whether they’re enabled using areCursorRectsEnabled. To reset the cursor rectangles for a particular NSView, invoke the invalidateCursorRectsForView: method, and to reset them all, use resetCursorRects.

Finally, to support transitory drawing by NSViews, NSWindow declares methods that temporarily cache a portion of its raster image so that it can be restored later. This feature is useful for situations where highly dynamic drawing must be done over the otherwise static image of the window. For example, in a drawing program where the user drags lines and other shapes directly onto a canvas, it’s more efficient to restore the window’s cached image and draw anew over that than to have all of the view objects send PostScript instructions to the Window Server. For more information, see “Transitory Drawing” in the NSView class specification, and the individual method descriptions of cacheImageInRect:, restoreCachedImage, and discardCachedImage in this class specification.

Method Types

Creating instances	− initWithContentRect:styleMask:backing:defer:

− initWithContentRect:styleMask:backing:defer:screen:

Calculating layout	+ contentRectForFrameRect:styleMask:

+ frameRectForContentRect:styleMask:

+ minFrameWidthWithTitle:styleMask:

Converting coordinates	− convertBaseToScreen:

− convertScreenToBase:

Moving and resizing	− setFrame:display:

− frame

− setFrameOrigin:

− setFrameTopLeftPoint:

− setContentSize:

− cascadeTopLeftFromPoint:

− center

− resizeFlags

Constraining window size	− maxSize

− minSize

− setMaxSize:

− setMinSize:

− setAspectRatio:

− aspectRatio

− setResizeIncrements:

− resizeIncrements

− constrainFrameRect:toScreen:

Saving the frame to user defaults	+ removeFrameUsingName:

− saveFrameUsingName:

− setFrameUsingName:

− setFrameAutosaveName:

− frameAutosaveName

− setFrameFromString:

− stringWithSavedFrame

Ordering windows	− orderBack:

− orderFront:

− orderFrontRegardless

− orderOut:

− orderWindow:relativeTo:

− setLevel:

− level

− isVisible

Making key and main windows	− becomeKeyWindow

− canBecomeKeyWindow

− isKeyWindow

− makeKeyAndOrderFront:

− makeKeyWindow

− resignKeyWindow

− becomeMainWindow

− canBecomeMainWindow

− isMainWindow

− makeMainWindow

− resignMainWindow

Display and drawing	− display

− displayIfNeeded

− setViewsNeedDisplay:

− viewsNeedDisplay

− useOptimizedDrawing:

− setAutodisplay:

− isAutodisplay

− update

Flushing graphics	− flushWindow

− flushWindowIfNeeded

− enableFlushWindow

− disableFlushWindow

− isFlushWindowDisabled

Bracketing temporary drawing	− cacheImageInRect:

− restoreCachedImage

− discardCachedImage

Window Server information	− windowNumber

− gState

− deviceDescription

− setBackingType:

− backingType

− setOneShot:

− isOneShot

+ defaultDepthLimit

− setDepthLimit:

− depthLimit

− setDynamicDepthLimit:

− hasDynamicDepthLimit

− canStoreColor

Screen information	− deepestScreen

− screen

Working with the responder chain	− makeFirstResponder:

− firstResponder

Event handling	− currentEvent

− nextEventMatchingMask:

− nextEventMatchingMask:untilDate:inMode:dequeue:

− discardEventsMatchingMask:beforeEvent:

− postEvent:atStart:

− sendEvent:

− tryToPerform:with:

− keyDown:

− mouseLocationOutsideOfEventStream

− setAcceptsMouseMovedEvents:

− acceptsMouseMovedEvents

Working with the field editor	− fieldEditor:forObject:

− endEditingFor:

Keyboard interface control	− setInitialFirstResponder:

− initialFirstResponder

− selectKeyViewFollowingView:

− selectKeyViewPrecedingView:

− selectNextKeyView:

− selectPreviousKeyView:

− keyViewSelectionDirection

Setting the title and filename	− setTitle:

− setTitleWithRepresentedFilename:

− title

− setRepresentedFilename:

− representedFilename

Marking a window edited	− setDocumentEdited:

− isDocumentEdited

Closing the window	− close

− performClose:

− setReleasedWhenClosed:

− isReleasedWhenClosed

Miniaturizing and miniwindows	− miniaturize:

− performMiniaturize:

− deminiaturize:

− isMiniaturized

− setMiniwindowImage:

− miniwindowImage

− setMiniwindowTitle:

− miniwindowTitle

Working with menus	+ menuChanged:

Working with the Windows menu	− setExcludedFromWindowsMenu:

− isExcludedFromWindowsMenu

Working with cursor rectangles	− areCursorRectsEnabled

− enableCursorRects

− disableCursorRects

− discardCursorRects

− invalidateCursorRectsForView:

− resetCursorRects

Dragging	− dragImage:at:offset:event:pasteboard:source:slideBack:

− registerForDraggedTypes:

− unregisterDraggedTypes

Controlling behavior	− setHidesOnDeactivate:

− hidesOnDeactivate

− worksWhenModal

Setting the content view	− setContentView:

− contentView

Setting background color	− setBackgroundColor:

− backgroundColor

Getting the style mask	− styleMask

Working with Services	− validRequestorForSendType:returnType:

Printing and faxing	− print:

− dataWithEPSInsideRect:

− fax:

Getting the Microsoft Windows handle

− windowHandle

Setting the delegate	− setDelegate:

− delegate

Class Methods

contentRectForFrameRect:styleMask:

+ (NSRect)contentRectForFrameRect:(NSRect)frameRect styleMask:(unsigned int)aStyle

Returns the content rectangle used by an NSWindow with a frame rectangle of frameRect and a style mask of aStyle. Both frameRect and the returned content rectangle are expressed in screen coordinates. See the initWithContentRect:styleMask:backing:defer: method description for a list of style mask values.

See also:	+ frameRectForContentRect:styleMask:

defaultDepthLimit

+ (NSWindowDepth)defaultDepthLimit

Returns the default depth limit for instances of NSWindow. This is the smaller of:

•	The depth of the deepest display device available to the Window Server

•	The depth set for the application by the NSWindowDepthLimit parameter

The value returned can be examined with the Application Kit functions NSPlanarFromDepth(), NSColorSpaceFromDepth(), NSBitsPerSampleFromDepth(), NSBitsPerPixelFromDepth().

See also:	− setDepthLimit:, − setDynamicDepthLimit:, − canStoreColor

frameRectForContentRect:styleMask:

+ (NSRect)frameRectForContentRect:(NSRect)contentRect styleMask:(unsigned int)aStyle

Returns the frame rectangle used by an NSWindow with a content rectangle of contentRect and a style mask of aStyle. Both contentRect and the returned frame rectangle are expressed in screen coordinates. See the initWithContentRect:styleMask:backing:defer: method description for a list of style mask values.

See also:	+ contentRectForContentRect:styleMask:

p	menuChanged:

+ (void)menuChanged:(NSMenu *)aMenu

On Microsoft Windows, locates all objects inheriting from NSWindow that use aMenu and causes them to update their state and redisplay the menu. On Mach, this method does nothing.

See also:	− menu (NSResponder)

minFrameWidthWithTitle:styleMask:

+ (float)minFrameWidthWithTitle:(NSString *)aTitle styleMask:(unsigned int)aStyle

Returns the minimum width that an NSWindow’s frame rectangle must have for it to display all of aTitle, given aStyle as its style mask. See the initWithContentRect:styleMask:backing:defer: method description for a list of acceptable style mask values.

removeFrameUsingName:

+ (void)removeFrameUsingName:(NSString *)name

Removes the frame data stored under name from the application’s user defaults.

See also:	− setFrameUsingName:, − setFrameAutosaveName:

Instance Methods

acceptsMouseMovedEvents

− (BOOL)acceptsMouseMovedEvents

Returns YES if the receiver accepts and distributes mouse-moved events, NO if it doesn’t. NSWindows by default don’t accept mouse-moved events.

See also:	− setAcceptsMouseMovedEvents:

areCursorRectsEnabled

− (BOOL)areCursorRectsEnabled

Returns YES if the receiver’s cursor rectangles are enabled, NO if they’re not.

See also:	− setCursorRectsEnabled:, − addCursorRect:cursor: (NSView)

aspectRatio

− (NSSize)aspectRatio

Returns the receiver’s size aspect ratio. The size of the receiver’s frame rectangle is constrained to integral multiples of this ratio when the user resizes it. You can set an NSWindow’s size to any ratio programmatically.

See also:	− resizeIncrements, − setAspectRatio:, − setFrame:display:

backgroundColor

− (NSColor *)backgroundColor

Returns the color of the receiver’s background.

See also:	− setBackgroundColor:

backingType

− (NSBackingStoreType)backingType

Returns the receiver’s backing store type as one of the following constants:

NSBackingStoreBuffered

NSBackingStoreRetained

NSBackingStoreNonretained

See also:	− setBackingType:

becomeKeyWindow

− (void)becomeKeyWindow

Invoked automatically to inform the receiver that it has become the key window; never invoke this method directly. This method reestablishes the receiver’s first responder, sends becomeKeyWindow to that object if it responds, and posts an NSWindowDidBecomeKeyNotification to the default notification center.

See also:	− makeKeyWindow, − makeKeyAndOrderFront:, − becomeMainWindow

becomeMainWindow

− (void)becomeMainWindow

Invoked automatically to inform the receiver that it has become the main window; never invoke this method directly. This method posts an NSWindowDidBecomeMainNotification to the default notification center.

See also:	− makeMainWindow, − becomeKeyWindow

cacheImageInRect:

− (void)cacheImageInRect:(NSRect)aRect

Stores the receiver’s raster image from aRect, which is expressed in the receiver’s base coordinate system. This allows the receiver to perform temporary drawing, such as a band around the selection as the user drags the mouse, and to quickly restore the previous image by invoking restoreCachedImage and flushWindowIfNeeded. The next time the window displays, it discards its cached image rectangles. You can also explicitly use discardCachedImage to free the memory occupied by cached image rectangles.

See also:	− display

canBecomeKeyWindow

− (BOOL)canBecomeKeyWindow

Returns YES if the receiver is able to be the key window, and NO if it can’t. Attempts to make the receiver the key window are abandoned if this method returns NO. NSWindow’s implementation returns YES if the receiver has a title bar or a resize bar/border, NO otherwise.

See also:	− isKeyWindow, − makeKeyWindow

continue in this topic


NSWindow2
canBecomeMainWindow

− (BOOL)canBecomeMainWindow

Returns YES if the receiver is able to be the main window, and NO if it can’t. Attempts to make the receiver the main window are abandoned if this method returns NO. NSWindow’s implementation returns YES if the receiver is visible, is not an NSPanel, and has a title bar or a resize bar/border. Otherwise it returns NO.

See also:	− isMainWindow, − makeMainWindow

canStoreColor

− (BOOL)canStoreColor

Returns YES if the receiver has a depth limit that allows it to store color values, and NO if it doesn’t.

See also:	− depthLimit, − shouldDrawColor (NSView)

cascadeTopLeftFromPoint:

− (NSPoint)cascadeTopLeftFromPoint:(NSPoint)topLeftPoint

Returns a point shifted from topLeftPoint that can be used to place the receiver in a cascade relative to another NSWindow positioned at topLeftPoint, so that the title bars of both NSWindows are fully visible. Both points are expressed in screen coordinates.

See also:	− setFrameTopLeftPoint:

center

− (void)center

Sets the receiver’s location to the center of the screen: The receiver is placed dead-center horizontally and somewhat above center vertically. Such a placement is considered to carry a certain visual immediacy and importance. This method doesn’t put the receiver on-screen, however, use makeKeyAndOrderFront: to do that.

You typically use this method to place a NSWindow—most likely an attention panel—where the user can’t miss it. This method is invoked automatically when an NSPanel is placed on the screen by NSApplication’s runModalForWindow: method.

close

− (void)close

Removes the receiver from the screen. If the receiver is set to be released when it’s closed (the default), a release message is sent to the object after the current event is completed.

This method doesn’t result in any notification that the receiver is closing, as performClose: and closing due to user action do. Use performClose: if you want to be sure that observers and the delegate will be notified of the receiver’s closing.

See also:	− setReleasedWhenClosed:

constrainFrameRect:toScreen:

− (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)aScreen

Modifies and returns frameRect so that its top edge lies on aScreen. If the receiver is resizable, the rectangle’s height is adjusted to bring the bottom edge onto the screen as well. The rectangle’s width and horizontal location are unaffected. You shouldn’t need to invoke this method yourself; it’s invoked automatically (and the modified frame is used to locate and set the size of the receiver) whenever a titled NSWindow is placed on-screen and whenever its size is changed.

Subclasses can override this method to prevent their instances from being constrained, or to constrain them differently.

contentView

− (id)contentView

Returns the receivers’s content view, the highest accessible NSView object in the receiver’s view hierarchy.

See also:	− setContentView:

convertBaseToScreen:

− (NSPoint)convertBaseToScreen:(NSPoint)aPoint

Converts aPoint from the receiver’s base coordinate system to the screen coordinate system. Returns the converted point.

See also:	− convertScreenToBase:, − convertPoint:toView: (NSView)

convertScreenToBase:

− (NSPoint)convertScreenToBase:(NSPoint)aPoint

Converts aPoint from the screen coordinate system to the receiver’s base coordinate system. Returns the converted point.

See also:	− convertBaseToScreen:, − convertPoint:fromView: (NSView)

currentEvent

− (NSEvent *)currentEvent

Returns the event currently being processed by the application, by invoking NSApp’s currentEvent method.

dataWithEPSInsideRect:

− (NSData *)dataWithEPSInsideRect:(NSRect)aRect

Returns EPS data that draws the region of the receiver within aRect (which is expressed in the receiver’s base coordinate system). This data can be placed on an NSPasteboard, written to a file, or used to create an NSImage object.

See also:	− dataWithEPSInsideRect: (NSView), − writeEPSInsideRect:toPasteboard: (NSView)

deepestScreen

− (NSScreen *)deepestScreen

Returns the deepest screen that the receiver is on (it may be split over several screens), or nil if the receiver is off-screen.

See also:	− screen

defaultButtonCell:

− (NSButtonCell *)defaultButtonCell

Returns the button cell that performs as if clicked when the NSWindow receives a Return (or Enter) key event. This cell draws itself as if it were the focal element for keyboard interface control, unless another button cell is focused on, in which case the default button cell temporarily draws itself as normal and disables its key equivalent.

The window receives a Return key event if no responder in its responder chain claims it, or if the user presses the Control key along with the Return key.

See also:	− setDefaultButtonCell:, − disableKeyEquivalentForDefaultButtonCell, − enableKeyEquivalentForDefaultButtonCell

delegate

− (id)delegate

Returns the receiver’s delegate, or nil if it doesn’t have one.

See also:	− setDelegate:

deminiaturize:

− (void)deminiaturize:(id)sender

Deminiaturizes the receiver. You rarely need to invoke this method; it’s invoked automatically when an NSWindow is deminiaturized by the user.

See also:	− miniaturize:, − styleMask

depthLimit

− (NSWindowDepth)depthLimit

Returns the depth limit of the receiver. The value returned can be examined with the Application Kit functions NSPlanarFromDepth(), NSColorSpaceFromDepth(), NSBitsPerSampleFromDepth(), NSBitsPerPixelFromDepth().

See also:	+ defaultDepthLimit, − setDepthLimit:, − setDynamicDepthLimit:

deviceDescription

− (NSDictionary *)deviceDescription

Returns a dictionary containing information about the receiver’s resolution, color depth, and so on. This information is useful for tuning images and colors to the window’s display capabilities. The contents of the dictionary are:

Dictionary Key	Value

NSDeviceResolution	An NSValue containing an NSSize that describe the receiver’s raster

resolution in dots per inch (dpi).

NSDeviceColorSpaceName	An NSString giving the name of the receiver’s color space.

See the Application Kit Types and Constants for a list of possible

values.

NSDeviceBitsPerSample	An NSNumber containing an integer that gives the bit depth of

the receiver’s raster image (2-bit, 8-bit, etc.).

NSDeviceIsScreen	“YES”, indicating that the receiver displays on the screen.

NSDeviceSize	An NSValue containing an NSSize that gives the size of the receiver’s

frame rectangle.

See also:	− deviceDescription (NSScreen), − bestRepresentationForDevice: (NSImage), − colorUsingColorSpaceName: (NSColor)

disableCursorRects

− (void)disableCursorRects

Disables all cursor rectangle management within the receiver. Use this method when you need to do some special cursor manipulation and you don’t want the Application Kit interfering.

See also:	− enableCursorRects

disableFlushWindow

− (void)disableFlushWindow

Disables the flushWindow method for the receiver. If the receiver is buffered, this prevents drawing from being automatically flushed by NSView’s display... methods from the receiver’s backing store to the screen. This permits several NSViews to be displayed before the results are shown to the user.

Flushing should be disabled only temporarily, while the NSWindow’s display is being updated. Each disableFlushWindow message must be paired with a subsequent enableFlushWindow message. Invocations of these methods can be nested; flushing isn’t reenabled until the last (unnested) reenableFlushWindow message is sent.

disableKeyEquivalentForDefaultButtonCell

− (void)disableKeyEquivalentForDefaultButtonCell

Disables the default button cell’s key equivalent, so that it doesn’t perform a click when the user presses Return (or Enter). See the method description for defaultButtonCell for more information.

See also:	− enableKeyEquivalentForDefaultButtonCell

discardCachedImage

− (void)discardCachedImage

Discards all of the receiver’s cached image rectangles. An NSWindow automatically discards its cached image rectangles when it displays.

See also:	− cacheImageInRect:, − restoreCachedImage, − display

discardCursorRects

− (void)discardCursorRects

Invalidates all cursor rectangles in the receiver. This method is invoked by resetCursorRects to clear out existing cursor rectangles before resetting them. You shouldn’t invoke it in the code you write, but might want to override it to change its behavior.

See also:	− resetCursorRects

discardEventsMatchingMask:beforeEvent:

− (void)discardEventsMatchingMask:(unsigned int)mask beforeEvent:(NSEvent *)lastEvent

Forwards the message to the NSApplication object.

display

− (void)display

Passes a display message down the receiver’s view hierarchy, thus redrawing all NSViews within the receiver, including the frame view which draws the border, title bar, and other peripheral elements.

You rarely need to invoke this method. NSWindows normally record which of their NSViews need display and display them automatically on each pass through the event loop.

See also:	− display (NSView), − displayIfNeeded, − isAutodisplay

displayIfNeeded

− (void)displayIfNeeded

Passes a displayIfNeeded message down the receiver’s view hierarchy, thus redrawing all NSViews that need to be displayed, including the frame view which draws the border, title bar, and other peripheral elements. This method is useful when you want to modify some number of NSViews, and then display only the ones that were modified.

You rarely need to invoke this method. NSWindows normally record which of their NSViews need display and display them automatically on each pass through the event loop.

See also:	− display, − displayIfNeeded (NSView), − setNeedsDisplay: (NSView), − isAutodisplay

dragImage:at:offset:event:pasteboard:source:slideBack:

− (void)dragImage:(NSImage *)anImage

at:(NSPoint)aPoint

offset:(NSSize)initialOffset

event:(NSEvent *)theEvent

pasteboard:(NSPasteboard *)pboard

source:(id)sourceObject

slideBack:(BOOL)flag

Begins a dragging session. This method is essentially the same as NSView’s method of the same name, except that aPoint is given in the NSWindow’s base coordinate system. This method should be invoked only from within an NSView’s implementation of the mouseDown: method. See the description of this method in the NSView class specification for more information.

enableCursorRects

− (void)enableCursorRects

Reenables cursor rectangle management within the receiver after a disableCursorRects message.

enableFlushWindow

− (void)enableFlushWindow

Reenables the flushWindow method for the receiver after it was disabled through a previous disableFlushWindow message.

enableKeyEquivalentForDefaultButtonCell

− (void)enableKeyEquivalentForDefaultButtonCell

Reenables the default button cell’s key equivalent, so that it performs a click when the user presses Return (or Enter). See the method description for defaultButtonCell for more information.

See also:	− disableKeyEquivalentForDefaultButtonCell

endEditingFor:

− (void)endEditingFor:(id)anObject

Forces the field editor, which anObject is assumed to be using, to give up its first responder status, and prepares it for its next assignment. If the field editor is the first responder, it’s made to resign that status even if its resignFirstResponder method returns NO. This forces the field editor to send a textDidEndEditing: message to its delegate. The field editor is then removed from the view hierarchy, its delegate is set to nil, and it’s emptied of any text it may contain.

This method is typically invoked by the object using the field editor when it’s finished. Other objects normally change the first responder by simply using makeFirstResponder:, which allows a field editor or other object to retain its first responder status if, for example, the user has entered an invalid value. endEditingFor: should be used only as a last resort if the field editor refuses to resign first responder status. Even in this case, you should always allow the field editor a chance to validate its text and take whatever other action it needs first. You can do this by first trying to make the NSWindow the first responder:

if ([myWindow makeFirstResponder:myWindow]) {

    /* All fields are now valid; it’s safe to use fieldEditor:forObject:

     * to claim the field editor. */

}

else {

    /* Force first responder to resign. */

    [myWindow endEditingFor:nil];

}

See also:	− fieldEditor:forObject:, − windowWillReturnFieldEditor:toObject:

fax:

− (void)fax:(id)sender

Runs the Fax panel, and if the user chooses an option other than canceling, prints the receiver (its frame view and all subviews) to a fax modem.

See also:	− print:

fieldEditor:forObject:

− (NSText *)fieldEditor:(BOOL)createFlag forObject:(id)anObject

Returns the receiver’s field editor, creating it if needed and if createFlag is YES. Returns nil if createFlag is NO and the field editor doesn’t exist. anObject is used to allow the receiver’s delegate to substitute another object in place of the field editor, as described below. The field editor may be in use by some view object, so be sure to properly dissociate it from that object before actually using it yourself (the appropriate way to do this is illustrated in the description of endEditingFor:). Once you retrieve the field editor, you can insert it into the view hierarchy and set a delegate to interpret text events, have it perform whatever editing is needed. Then, when it sends a textDidEndEditing: message to the delegate, you can get its text to display or store, and remove the field editor using endEditingFor:.

The field editor is provided as a convenience and can be used however your application sees fit. Typically, the field editor is used by simple text-bearing objects—for example, an NSTextField object uses its window’s field editor to display and manipulate text. The field editor can be shared by any number of objects and so its state may be constantly changing. Therefore, it shouldn’t be used to display text that demands sophisticated layout (for this you should create a dedicated NSText object).

A freshly created NSWindow doesn’t have a field editor. After a field editor has been created for an NSWindow, the createFlag argument is ignored. By passing NO for createFlag and testing the return value, however, you can predicate an action on the existence of the field editor.

The receiver’s delegate can substitute a custom editor in place of the NSWindow’s field editor by implementing windowWillReturnFieldEditor:toObject:. The receiver sends this message to its delegate with itself and anObject as the arguments, and if the return value is non-nil the NSWindow returns that object instead of its field editor. However, note the following:

•	If the NSWindow’s delegate is identical to anObject, windowWillReturnFieldEditor:toObject: isn’t sent.

•	The object returned by the delegate method, though it may become first responder, does not become the NSWindow’s field editor. Other objects continue to use the NSWindow’s established field editor.

firstResponder

− (NSResponder *)firstResponder

Returns the receiver’s first responder.

See also:	− makeFirstResponder:, − acceptsFirstResponder (NSResponder)

flushWindow

− (void)flushWindow

Flushes the receiver’s off-screen buffer to the screen, if the receiver is buffered and flushing is enabled. Does nothing for other display devices, such as a printer. This method is automatically invoked by NSWindow’s and NSView’s display... methods.

See also:	− flushWindowIfNeeded, − display... (NSView), − disableFlushWindow, − enableFlushWindow

flushWindowIfNeeded

− (void)flushWindowIfNeeded

Flushes the receiver’s off-screen buffer to the screen, if flushing is enabled and if the last flushWindow message had no effect because flushing was disabled. To avoid unnecessary flushing, use this method rather than flushWindow to flush an NSWindow after flushing has been reenabled.

See also:	− flushWindow, − disableFlushWindow, − enableFlushWindow

frame

− (NSRect)frame

Returns the receiver’s frame rectangle. The frame rectangle is always reckoned in the screen coordinate system.

See also:	− screen, − deepestScreen

frameAutosaveName

− (NSString *)frameAutosaveName

Returns the name used to automatically save the receiver’s frame rectangle data in the defaults system, as set through setFrameAutosaveName:. If the receiver has an autosave name, its frame data is written whenever the frame rectangle changes.

See also:	− setFrameUsingName:

gState

− (int)gState

Returns the PostScript graphics state object associated with the receiver. This graphics state is used by default for all NSViews in the receiver’s view hierarchy, but individual NSViews can be made to use their own with the NSView method allocateGState.

hasDynamicDepthLimit

− (BOOL)hasDynamicDepthLimit

Returns YES if the receiver’s depth limit can change to match the depth of the screen it’s on, NO if it can’t.

See also:	− setDynamicDepthLimit:

hidesOnDeactivate

− (BOOL)hidesOnDeactivate

Returns YES if the receiver is removed from the screen when its application is deactivated, and NO if it remains on-screen.

See also:	− setHidesOnDeactivate:

p	initialFirstResponder

− (NSView *)initialFirstResponder

Returns the NSView that’s made first responder the first time the receiver is placed on-screen.

See also:	− setInitialFirstResponder:, − setNextKeyView:

initWithContentRect:styleMask:backing:defer:

− (id)initWithContentRect:(NSRect)contentRect

styleMask:(unsigned int)styleMask

backing:(NSBackingStoreType)backingType

defer:(BOOL)flag

Initializes the receiver, a newly allocated NSWindow object, and returns self. This method is the designated initializer for the NSWindow class.

contentRect specifies the location and size of the NSWindow’s content area in screen coordinates. Note that the Window Server limits window position coordinates to ±16,000 and sizes to 10,000.

styleMask specifies the receiver’s style. It can either be NSBorderlessWindowMask, or it can contain any of the following options, combined using the C bitwise OR operator:

Option	Meaning

NSTitledWindowMask	The NSWindow displays a title bar.

NSClosableWindowMask	The NSWindow displays a close button.

NSMiniaturizableWindowMask	The NSWindow displays a miniaturize button.

NSResizableWindowMask	The NSWindow displays a resize bar or border.

Borderless windows display none of the usual peripheral elements, and are generally useful only for display or caching purposes; you should normally not need to create them. Also, note that an NSWindow’s style mask should include NSTitledWindowMask if it includes any of the others.

backingType specifies how the drawing done in the receiver is buffered by the object’s window device:

NSBackingStoreBuffered

NSBackingStoreRetained

NSBackingStoreNonretained

flag determines whether the Window Server creates a window device for the new object immediately. If flag is YES, it defers creating the window until the receiver is ordered on-screen. All display messages sent to the NSWindow or its NSViews are postponed until the window is created, just before it’s moved on-screen. Deferring the creation of the window improves launch time and minimizes the virtual memory load on the Server.

The new NSWindow creates an instance of NSView to be its default content view. You can replace it with your own object by using the setContentView: method.

See also:	− orderFront:, − setTitle:, − setOneShot:, − initWithContentRect:styleMask:backing:defer:screen:

initWithContentRect:styleMask:backing:defer:screen:

− (id)initWithContentRect:(NSRect)contentRect

styleMask:(unsigned int)styleMask

backing:(NSBackingStoreType)bufferingType

defer:(BOOL)flag

screen:(NSScreen *)aScreen

Initializes a newly allocated NSWindow object and returns self. This method is equivalent to initWithContentRect:styleMask:backing:defer:screen:, except that the content rectangle is specified relative to the lower left corner of aScreen.

If aScreen is nil, the content rectangle is interpreted relative to the lower left corner of the main screen. The main screen is the one that contains the current key window, or, if there is no key window, the one that contains the main menu. If there’s neither a key window nor a main menu (if there’s no active application), the main screen is the one where the origin of the screen coordinate system is located.

See also:	− orderFront:, − setTitle:, − setOneShot:, − initWithContentRect:styleMask:backing:defer:

invalidateCursorRectsForView:

− (void)invalidateCursorRectsForView:(NSView *)aView

Marks as invalid the cursor rectangles of aView, an NSView in the receiver’s view hierarchy, so that they’ll be set up again when the receiver becomes key (or immediately if the receiver is key).

See also:	− resetCursorRects, − resetCursorRects (NSView)

isAutodisplay

− (BOOL)isAutodisplay

Returns YES if the receiver automatically displays its views that are marked as needing it, NO if it doesn’t. Automatic display typically occurs on each pass through the event loop.

See also:	− setAutodisplay:, − displayIfNeeded, − setNeedsDisplay: (NSView)

isDocumentEdited

− (BOOL)isDocumentEdited

Returns YES or NO according to the argument supplied with the last setDocumentEdited: message.

isExcludedFromWindowsMenu

− (BOOL)isExcludedFromWindowsMenu

Returns YES if the receiver’s title is omitted from the application’s Windows menu, and NO if it is listed.

See also:	− setExcludedFromWindowsMenu:

isFlushWindowDisabled

− (BOOL)isFlushWindowDisabled

Returns YES if the receiver’s flushing ability has been disabled; otherwise returns NO.

See also:	− disableFlushWindow, − enableFlushWindow

isKeyWindow

− (BOOL)isKeyWindow

Returns YES if the receiver is the key window for the application, and NO if it isn’t.

See also:	− isMainWindow, − makeKeyWindow

isMainWindow

− (BOOL)isMainWindow

Returns YES if the receiver is the main window for the application, and NO if it isn’t.

See also:	− isKeyWindow, − makeMainWindow

isMiniaturized

− (BOOL)isMiniaturized

Returns YES if the receiver has been miniaturized, NO if it hasn’t. A miniaturized window is removed from the screen and replaced by a miniwindow, icon, or button that represents it, called the counterpart (the particular form depends on the platform).

See also:	− miniaturize:

isOneShot

− (BOOL)isOneShot

Returns YES if the PostScript window device that the receiver manages is freed when it’s removed from the screen list, and NO if not. The default is NO.

See also:	− setOneShot:

isReleasedWhenClosed

− (BOOL)isReleasedWhenClosed

Returns YES if the receiver is automatically released after being closed, NO if it’s simply removed from the screen. The default for NSWindow is YES; the default for NSPanel is NO.

See also:	− setReleasedWhenClosed:

isVisible

− (BOOL)isVisible

Returns YES if the receiver is on-screen (even if it’s obscured by other windows).

See also:	− visibleRect (NSView)

keyDown:

− (void)keyDown:(NSEvent *)theEvent

Handles a keyboard event that may need to be interpreted as changing the key view or triggering a mnemonic.

See also:	− selectNextKeyView:, − nextKeyView (NSView), − performMnemonic: (NSView)

p	keyViewSelectionDirection

− (NSSelectionDirection)keyViewSelectionDirection

Returns the direction that the receiver is currently using to change the key view, one of:

Value	Meaning

NSDirectSelection	The receiver isn’t traversing the key view loop.

NSSelectingNext	The receiver is proceeding to the next valid key view.

NSSelectingPrevious	The receiver is proceeding to the previous valid key view.

See also:	− selectNextKeyView:, − selectPreviousKeyView:

level

− (int)level

Returns the level of the receiver as set using setLevel:. See that method description for a list of possible values.

makeFirstResponder:

− (BOOL)makeFirstResponder:(NSResponder *)aResponder

Attempts to make aResponder the first responder for the receiver. If aResponder isn’t already the first responder, this method first sends a resignFirstResponder message to the object that is. If that object refuses to resign, it remains the first responder and this method immediately returns NO. If it returns YES, this methods sends a becomeFirstResponder message to aResponder. If aResponder accepts first responder status, this method returns YES. If it refuses, this method returns NO, and the NSWindow becomes first responder.

The Application Kit uses this method to alter the first responder in response to mouse-down events; you can also use it to explicitly set the first responder from within your program. aResponder is typically an NSView in the receiver’s view hierarchy.

See also:	− becomeFirstResponder (NSResponder), − resignFirstResponder (NSResponder)

makeKeyAndOrderFront:

− (void)makeKeyAndOrderFront:(id)sender

Moves the receiver to the front of the screen list, within its level, and makes it the key window.

See also:	− orderFront:, − orderBack:, − orderOut:, − orderWindow:relativeTo:, − setlevel:

makeKeyWindow

− (void)makeKeyWindow

Makes the receiver the key window.

See also:	− makeMainWindow, − becomeKeyWindow, − isKeyWindow

makeMainWindow

− (void)makeMainWindow

Makes the receiver the main window.

See also:	− makeKeyWindow, − becomeMainWindow, − isMainWindow

maxSize

− (NSSize)maxSize

Returns the maximum size to which the receiver’s frame can be sized either by the user or by the setFrame... methods other than setFrame:display:.

See also:	− setMaxSize:, − minSize, − aspectRatio, − resizeIncrements

miniaturize:

− (void)miniaturize:(id)sender

Removes the receiver from the screen list and displays its counterpart in the appropriate location.

See also:	− deminiaturize:

miniwindowImage

− (NSImage *)miniwindowImage

Returns the image that’s displayed in the receiver’s miniwindow.

See also:	− setMiniwindowImage:, − miniwindowTitle

miniwindowTitle

− (NSString *)miniwindowTitle

Returns the title that’s displayed in the receiver’s miniwindow.

See also:	− setMiniwindowTitle:, − miniwindowImage

minSize

− (NSSize)minSize

Returns the minimum size to which the receiver’s frame can be sized either by the user or by the setFrame... methods other than setFrame:display:.

See also:	− setMinSize:, − maxSize, − aspectRatio, − resizeIncrements

mouseLocationOutsideOfEventStream

− (NSPoint)mouseLocationOutsideOfEventStream

Returns the current location of the mouse reckoned in the receiver’s base coordinate system, regardless of the current event being handled or of any events pending.

See also:	− currentEvent (NSApplication)

nextEventMatchingMask:

− (NSEvent *)nextEventMatchingMask:(unsigned int)mask

Invokes NSApplication’s nextEventMatchingMask:untilDate:inMode:dequeue: method, using mask as the first argument, with an unlimited expiration, a mode of NSEventTrackingRunLoopMode, and a dequeue flag of YES. See the method description in the NSApplication class specification for more information.

nextEventMatchingMask:untilDate:inMode:dequeue:

− (NSEvent *)nextEventMatchingMask:(unsigned int)mask

untilDate:(NSDate *)expirationDate

inMode:(NSString *)mode

dequeue:(BOOL)flag

Forwards the message to the global NSApplication object, NSApp. See the method description in the NSApplication class specification for more information.

orderBack:

− (void)orderBack:(id)sender

Moves the receiver to the back of its level in the screen list, without changing either the key window or the main window.

See also:	− orderFront:, − orderOut:, − orderWindow:relativeTo:, − makeKeyAndOrderFront:, − level

orderFront:

− (void)orderFront:(id)sender

Moves the receiver to the front of its level in the screen list, without changing either the key window or the main window.

See also:	− orderBack:, − orderOut:, − orderWindow:relativeTo:, − makeKeyAndOrderFront:, − level

orderFrontRegardless

− (void)orderFrontRegardless

Moves the receiver to the front of its level, even if its application isn’t active, but without changing either the key window or the main window. Normally an NSWindow can’t be moved in front of the key window unless the NSWindow and the key window are in the same application. You should rarely need to invoke this method; it’s designed to be used when applications are cooperating in such a way that an active application (with the key window) is using another application to display data.

See also:	− orderFront:, − level

orderOut:

− (void)orderOut:(id)sender

Takes the receiver out of the screen list. If the receiver is the key or main window, the NSWindow immediately below it is made key or main in its place.

See also:	− orderFront:, − orderBack:, − orderWindow:relativeTo:

orderWindow:relativeTo:

− (void)orderWindow:(NSWindowOrderingMode)place relativeTo:(int)otherWindowNumber

Repositions the receiver’s window device in the Window Server’s screen list. If place is NSWindowOut, the receiver is removed from the screen list and otherWindowNumber is ignored. If it’s NSWindowAbove the receiver is ordered immediately above the window whose window number is otherWindowNumber. Similarly, if place is NSWindowBelow is placed immediately below the window represented by otherWindowNumber. If otherWindowNumber is 0, the receiver is placed above or below all other windows in its level.

See also:	− orderFront:, − orderBack:, − orderOut:, − makeKeyAndOrderFront:, − level, − windowNumber

performClose:

− (void)performClose:(id)sender

Simulates the user clicking the close button by momentarily highlighting the button and then closing the receiver. If the receiver’s delegate or the receiver itself implements windowShouldClose:, then that message is sent with the NSWindow as the argument (only one such message is sent; if both the delegate and the NSWindow implement the method, only the delegate will receive the message). If the method returns NO, the NSWindow isn’t closed.

If the receiver doesn’t have a close button or can’t be closed (for example, if the delegate replies NO to a windowShouldClose: message), then this method calls NSBeep().

See also:	− close, − styleMask, − performClick: (NSButton), − performMiniaturize:

performMiniaturize:

− (void)performMiniaturize:(id)sender

Simulates the user clicking the miniaturize button by momentarily highlighting the button then miniaturizing the receiver. If the receiver doesn’t have a miniaturize button or can’t be miniaturized for some reason, then this method calls NSBeep().

See also:	− close, − styleMask, − performClick: (NSButton), − performClose:

postEvent:atStart:

− (void)postEvent:(NSEvent *)anEvent atStart:(BOOL)flag

Forwards the message to the global NSApplication object, NSApp.

print:

− (void)print:(id)sender

Runs the Print panel, and if the user chooses an option other than canceling, prints the receiver (its frame view and all subviews).

See also:	− fax:

registerForDraggedTypes:

− (void)registerForDraggedTypes:(NSArray *)pboardTypes

Registers pboardTypes as the pasteboard types that the receiver will accept as the destination of an image-dragging session.

Note:	Registering an NSWindow for dragged types automatically makes it a candidate destination object for a dragging session. As such, it must properly implement some or all of the NSDraggingDestination protocol methods. As a convenience, NSWindow provides default implementations of these methods. See the NSDraggingDestination protocol specification for details.

See also:	− unregisterDraggedTypes

representedFilename

− (NSString *)representedFilename

Returns the name of the file that the receiver represents.

See also:	− setRepresentedFilename:

resetCursorRects

− (void)resetCursorRects

Invokes discardCursorRects to clear the receiver’s cursor rectangles, then sends resetCursorRects to every NSView in the receiver’s view hierarchy.

This method is typically invoked by the NSApplication object when it detects that the key window’s cursor rectangles are invalid. In program code, it’s more efficient to invoke invalidateCursorRectsForView:.

resignKeyWindow

− (void)resignKeyWindow

Never invoke this method; it’s invoked automatically when the NSWindow resigns key window status. This method sends resignKeyWindow to the receiver’s first responder, sends windowDidResignKey: to the receiver’s delegate, and posts an NSWindowDidResignKeyNotification to the default notification center.

See also:	− becomeKeyWindow, − resignMainWindow

resignMainWindow

− (void)resignMainWindow

Never invoke this method; it’s invoked automatically when the NSWindow resigns main window status. This method sends windowDidResignMain: to the receiver’s delegate and posts an NSWindowDidResignMainNotification to the default notification center.

See also:	− becomeMainWindow, − resignKeyWindow

resizeFlags

− (int)resizeFlags

Valid only while the receiver is being resized, this method returns the flags field of the event record for the mouse-down event that initiated the resizing session. The integer encodes, as a mask, which of the modifier keys was held down when the event occurred. The flags are listed in the NSEvent class’s modifierFlags method description. You can use this method to constrain the direction or amount of resizing. Because of its limited validity, this method should only be invoked from within an implementation of the delegate method windowWillResize:toSize:.

resizeIncrements

− (NSSize)resizeIncrements

Returns the receiver’s resizing increments, which restrict the user’s ability to resize it so that its width and height alter by integral multiples of increments.width and increments.height when the user resizes it. These amounts are whole number values, 1.0 or greater. You can set an NSWindow’s size to any value programmatically.

See also:	− setResizeIncrements:, − setAspectRatio:, − setFrame:display:

restoreCachedImage

− (void)restoreCachedImage

Splices the receiver’s cached image rectangles, if any, back into its raster image (and buffer if it has one), undoing the effect of any drawing performed within those areas since they were established using cacheImageInRect:. You must invoke flushWindowIfNeeded after this method to guarantee proper redisplay. An NSWindow automatically discards its cached image rectangles when it displays.

See also:	− discardCachedImage, − display

saveFrameUsingName:

− (void)saveFrameUsingName:(NSString *)name

Saves the receiver’s frame rectangle in the user-defaults system. With the companion method setFrameUsingName:, you can save and reset an NSWindow’s frame over various launchings of an application. The default is owned by the application and stored under the name “NSWindow Frame name”. See the NSUserDefaults class specification for more information.

See also:	− setFrameUsingName:, − stringWithSavedFrame

screen

− (NSScreen *)screen

Returns the screen that the receiver is on. If the receiver is partly on one screen and partly on another, the screen where most of it lies is the one returned.

See also:	− bestScreen

p	selectKeyViewFollowingView:

− (void)selectKeyViewFollowingView:(NSView *)aView

Sends nextValidKeyView: to aView, and if that message returns an NSView, invokes makeFirstResponder: with the returned NSView.

See also:	− selectKeyViewPrecedingView:

p	selectKeyViewPrecedingView:

− (void)selectKeyViewPrecedingView:(NSView *)aView

Sends previousValidKeyView: to aView, and if that message returns an NSView, invokes makeFirstResponder: with the returned NSView.

See also:	− selectKeyViewFollowingView:

p	selectNextKeyView:

− (void)selectNextKeyView:(id)sender

Searches for a candidate key view and, if it finds one, invokes makeFirstResponder: to establish it as the first responder. The candidate is one of (in order):

•	The current first responder’s next valid key view, as returned by NSView’s nextValidKeyView: method.

•	The object designated as the receiver’s initial first responder (using setInitialFirstResponder:), if it returns YES to an acceptsFirstResponder message.

•	Otherwise, the initial first responder’s next valid key view, which may end up being nil.

See also:	− selectPreviousKeyView:, − selectKeyViewFollowingView:

p	selectPreviousKeyView:

− (void)selectPreviousKeyView:(id)sender

Searches for a candidate key view and, if it finds one, invokes makeFirstResponder: to establish it as the first responder. The candidate is one of (in order):

•	The current first responder’s previous valid key view, as returned by NSView’s previousValidKeyView: method.

•	The object designated as the receiver’s initial first responder (using setInitialFirstResponder:), if it returns YES to an acceptsFirstResponder message.

•	Otherwise, the initial first responder’s previous valid key view, which may end up being nil.

See also:	− selectNextKeyView:, − selectKeyViewPrecedingView:

sendEvent:

− (void)sendEvent:(NSEvent *)theEvent

Dispatches mouse and keyboard events sent to the receiver by the NSApplication object. Never invoke this method directly.

setAcceptsMouseMovedEvents:

− (void)setAcceptsMouseMovedEvents:(BOOL)flag

Controls whether the receiver accepts mouse-moved events and distributes them to its responders. If flag is YES it does accept them, if flag is NO it doesn’t. NSWindows by default don’t accept mouse-moved events.

See also:	− acceptsMouseMovedEvents

setAspectRatio:

− (void)setAspectRatio:(NSSize)ratio

Sets the receiver’s size aspect ratio to ratio, constraining the size of its frame rectangle to integral multiples of this size when the user resizes it. You can set an NSWindow’s size to any ratio programmatically.

See also:	− setResizeIncrements:, − aspectRatio, − setFrame:display:

setAutodisplay:

− (void)setAutodisplay:(BOOL)flag

Controls whether the receiver automatically displays its views that are marked as needing it. If flag is YES, views are automatically displayed as needed, typically on each pass through the event loop. If flag is NO, the receiver or its views must be explicitly displayed.

See also:	− isAutodisplay, − displayIfNeeded, − displayIfNeeded (NSView)

continue in this topic


NSWindow3
setBackgroundColor:

− (void)setBackgroundColor:(NSColor *)aColor

Sets the color of the receiver’s background to aColor.

See also:	− backgroundColor

setBackingType:

− (void)setBackingType:(NSBackingStoreType)backingType

Sets the receiver’s backing store type to backingType, which may be one of the following constants:

NSBackingStoreBuffered

NSBackingStoreRetained

This method can only be used to switch a buffered NSWindow to retained or vice versa; you can’t change the backing type to or from nonretained after initializing an NSWindow (a PostScript error is generated if you attempt to do so).

See also:	− backingType, − initWithContentRect:...

setContentSize:

− (void)setContentSize:(NSSize)aSize

Sets the size of the receiver’s content view to aSize, which is expressed in the receiver’s base coordinate system. This in turn alters the size of the NSWindow itself. Note that the Window Server limits window sizes to 10,000; if necessary, be sure to limit aSize as needed relative to the frame rectangle.

See also:	− setFrame:display:, + contentRectForFrameRect:styleMask:, + frameRectForContentRect:styleMask

setContentView:

− (void)setContentView:(NSView *)aView

Makes aView the receiver’s content view; the previous content view is removed from the receiver’s view hierarchy and released. aView is resized to fit precisely within the content area of the NSWindow. You can modify the content view’s coordinate system through its bounds rectangle, but can’t alter its frame rectangle (that is, its size or location) directly.

This method causes the old content view to be released; if you plan to reuse it, be sure to retain it before sending this message and to release it as appropriate when adding it to another NSWindow or NSView.

See also:	− contentView, − setContentSize:

setDefaultButtonCell:

− (void)setDefaultButtonCell:(NSButtonCell *)aButtonCell

Makes aButtonCell’s key equivalent that for the Return (or Enter) key, so that when the user presses return that button performs as if clicked. See the method description for defaultButtonCell for more information.

See also:	− disableKeyEquivalentForDefaultButtonCell, − enableKeyEquivalentForDefaultButtonCell

setDelegate:

− (void)setDelegate:(id)anObject

Makes anObject the receiver’s delegate, without retaining it. An NSWindow’s delegate is inserted into the responder chain after the NSWindow itself, and is informed of various actions by the NSWindow through delegation messages.

See also:	− delegate, − tryToPerform:with:, − sendAction:to:from: (NSApplication)

setDepthLimit:

− (void)setDepthLimit:(NSWindowDepth)limit

Sets the depth limit of the receiver to limit, which can be creating using the NSBestDepth() function. A value of 0 indicates the receiver’s default depth limit; this can be useful for reverting an NSWindow to its initial depth.

See also:	− depthLimit, + defaultDepthLimit, − setDynamicDepthLimit:

setDocumentEdited:

− (void)setDocumentEdited:(BOOL)flag

Records whether the receiver’s document has been edited but not saved. NSWindows are by default in “not edited” status.

You should invoke this method with an argument of YES every time the NSWindow’s document changes in such a way that it needs to be saved and with an argument of NO every time it gets saved. Then, before closing the NSWindow you can use isDocumentEdited to determine whether to allow the user a chance to save the document.

setDynamicDepthLimit:

− (void)setDynamicDepthLimit:(BOOL)flag

Sets whether the receiver changes its depth to match the depth of the screen that it’s on, or the deepest when it spans multiple screens. If flag is YES, the depth limit depends on which screen the receiver is on. If flag is NO, the receiver uses either its preset depth limit or the default depth limit. A different, and nondynamic, depth limit can be set with the setDepthLimit: method.

See also:	− hasDynamicDepthLimit, + defaultDepthLimit

setExcludedFromWindowsMenu:

− (void)setExcludedFromWindowsMenu:(BOOL)flag

Controls whether the receiver’s title is omitted from the application’s Windows menu. If flag is YES it’s omitted; if flag is NO, it’s listed when it or its miniwindow is on-screen. The default is NO.

See also:	− isExcludedFromWindowsMenu

setFrame:display:

− (void)setFrame:(NSRect)frameRect display:(BOOL)flag

Sets the origin and size of the receiver’s frame rectangle according to frameRect, thereby setting its position and size on-screen, and invokes display if flag is YES. Note that the Window Server limits window position coordinates to ±16,000 and sizes to 10,000.

See also:	− frame, − setFrameFromString:, − setFrameOrigin:, − setFrameTopLeftPoint:, − setFrameUsingName:

setFrameAutosaveName:

− (BOOL)setFrameAutosaveName:(NSString *)name

Sets the name used to automatically save the receiver’s frame rectangle in the defaults system to name. If name isn’t the empty string (@“”), the receiver’s frame is saved as a user default (as described in saveFrameUsingName:) each time the frame changes. Returns YES if the name is set successfully, NO if it’s being used as an autosave name by another NSWindow in the application (in which case the receiver’s old name remains in effect).

See also:	− setFrameUsingName:, + removeFrameUsingName:, − stringWithSavedFrame, − setFrameFromString:

setFrameFromString:

− (void)setFrameFromString:(NSString *)aString

Sets the receiver’s frame rectangle from the string representation aString, a representation previously creating using stringWithSavedFrame. The frame is constrained according to the receiver’s minimum and maximum size settings. This method causes a windowWillResize:toSize: message to be sent to the delegate.

See also:	− stringWithSavedFrame

setFrameOrigin:

− (void)setFrameOrigin:(NSPoint)aPoint

Positions the lower left corner of the receiver’s frame rectangle at aPoint in screen coordinates. Note that the Window Server limits window position coordinates to ±16,000.

See also:	− setFrame:display:, − setFrameTopLeftPoint:

setFrameTopLeftPoint:

− (void)setFrameTopLeftPoint:(NSPoint)aPoint

Positions the top left corner of the receiver’s frame rectangle at aPoint in screen coordinates. Note that the Window Server limits window position coordinates to ±16,000; if necessary, adjust aPoint relative to the window’s lower left corner to account for this.

See also:	− cascadeTopLeftFromPoint:, − setFrame:display:, − setFrameOrigin:

setFrameUsingName:

− (BOOL)setFrameUsingName:(NSString *)name

Sets the receiver’s frame rectangle by reading the rectangle data stored in name from the defaults system. The frame is constrained according to the receiver’s minimum and maximum size settings. This method causes a windowWillResize:toSize: message to be sent to the delegate. Returns YES if name is read and the frame is set successfully; otherwise returns NO.

See also:	− setFrameAutosaveName:, + removeFrameUsingName:, − stringWithSavedFrame, − setFrameFromString:

setHidesOnDeactivate:

− (void)setHidesOnDeactivate:(BOOL)flag

Determines whether the receiver is removed from the screen when the application is inactive. If flag is YES, the receiver is hidden (taken out of the screen list) when the application stops being the active application. If flag is NO, the receiver stays on-screen. The default for NSWindow is NO; the default for NSPanel is YES.

See also:	− hidesOnDeactivate:

p	setInitialFirstResponder:

− (void)setInitialFirstResponder:(NSView *)aView

Sets aView as the NSView that’s made first responder (also called the key view) the first time the receiver is placed on-screen.

See also:	− initialFirstResponder

setLevel:

− (void)setLevel:(int)newLevel

Sets the receiver’s window level to newLevel. Some useful predefined values are:

Level	Comment

NSNormalWindowLevel	The default level for NSWindow objects

NSFloatingWindowLevel	Useful for floating palettes.

NSDockWindowLevel	Reserved for the application dock (not used on Microsoft

Windows).

NSSubmenuWindowLevel	Reserved for submenus (not used on Microsoft Windows).

NSMainMenuWindowLevel	Reserved for the application’s main menu (not used on

Microsoft Windows).

Each level in the list groups windows within it above those in all preceding groups. Floating windows, for example, appear above all normal level windows. When a window enters a new level it’s ordered above all of its peers in that level.

See also:	− level, − orderWindow:relativeTo:, − orderFront:, − orderBack:

setMaxSize:

− (void)setMaxSize:(NSSize)aSize

Sets the maximum size to which the receiver’s frame can be sized to aSize. The maximum size constraint is enforced for resizing by the user as well as for the setFrame... methods other than setFrame:display:. Note that the Window Server limits window sizes to 10,000.

See also:	− maxSize, − setMinSize:, − setAspectRatio:, − setResizeIncrements:

setMiniwindowImage:

− (void)setMiniwindowImage:(NSImage *)anImage

Sets the image displayed by the receiver’s miniwindow to anImage.

See also:	− miniwindowImage, − isMiniaturized

setMiniwindowTitle:

− (void)setMiniwindowTitle:(NSString *)aString

Sets the title of the receiver’s miniaturized counterpart to aString and redisplays it. A miniwindow’s title normally reflects that of its full-size counterpart, abbreviated to fit if necessary. Although this method allows you to set the miniwindow’s title explicitly, changing the full-size NSWindow’s title (through setTitle: or setTitleWithRepresentedFilename:) automatically changes the miniwindow’s title as well.

See also:	− miniwindowTitle

setMinSize:

− (void)setMinSize:(NSSize)aSize

Returns the minimum size to which the receiver’s frame can be sized to aSize. The minimum size constraint is enforced for resizing by the user as well as for the setFrame... methods other than setFrame:display:.

See also:	− minSize, − setMaxSize:, − setAspectRatio:, − setResizeIncrements:

setOneShot:

− (void)setOneShot:(BOOL)flag

Sets whether the PostScript window device that the receiver manages should be freed when it’s removed from the screen list (and another one created if it’s returned to the screen). This can result in memory savings and performance improvement for NWindows that don’t take long to display. It’s particularly appropriate for NSWindows that the user might use once or twice but not display continually. The default is NO.

See also:	− isOneShot

setReleasedWhenClosed:

− (void)setReleasedWhenClosed:(BOOL)flag

Determines the receiver’s behavior when it receives a close message. If flag is NO, the receiver is merely hidden (taken out of the screen list). If flag is YES, the receiver is hidden and then released. The default for NSWindow is YES; the default for NSPanel is NO.

Another strategy for releasing an NSWindow is to have its delegate autorelease it on receiving a windowShouldClose: message.

See also:	− close, − isReleasedWhenClosed

setRepresentedFilename:

− (void)setRepresentedFilename:(NSString *)path

Sets the name of the file that the receiver represents to path.

See also:	− representedFilename:, − setTitleWithRepresentedFilename:

setResizeIncrements:

− (void)setResizeIncrements:(NSSize)increments

Restricts the user’s ability to resize the window so that its width and height alter by multiples of increments.width and increments.height as the user resizes it. These amounts should be whole numbers, 1.0 or greater. You can set an NSWindow’s size to any ratio programmatically.

See also:	− resizeIncrements, − setAspectRatio:, − setFrame:display:

setTitle:

− (void)setTitle:(NSString *)aString

Sets the string that appears in the receiver’s title bar (if it has one) to aString and displays the title. Also sets the title of the receiver’s miniwindow.

See also:	− title, − setTitleWithRepresentedFilename:, − setMiniwindowTitle:

setTitleWithRepresentedFilename:

− (void)setTitleWithRepresentedFilename:(NSString *)path

Sets path as the receiver’s title, formatting it as a file system path, and records path as the receiver’s associated filename using setRepresentedFilename:. The title format varies with the platform. On Mach-based systems, the file name is displayed first, followed by an em dash and the path for the directory containing the file. The em dash is offset by two spaces on either side. For example:

MyFile  —  /Net/server/group/home

This method also sets the title of the receiver’s miniwindow.

See also:	− title, − setTitle:, − setMiniwindowTitle:, − setRepresentedFilename:

setViewsNeedDisplay:

− (void)setViewsNeedDisplay:(BOOL)flag

Records the receiver’s display status. If flag is YES, the receiver records itself as needing display. If flag is NO the receiver records its NSViews as not needing display. You should rarely need to invoke this method; NSView’s setNeedsDisplay: and similar methods invoke it automatically.

See also:	− viewsNeedDisplay

stringWithSavedFrame

− (NSString *)stringWithSavedFrame

Returns a string that represents the receiver’s frame rectangle in a format that can be used with a later setFrameUsingName: message.

styleMask

− (unsigned int)styleMask

Returns the receiver’s style mask, indicating what kinds of control items it displays. See the description for the style mask in the initWithContentRect:styleMask:backing:defer: method description. An NSWindow’s style is set when the object is initialized. Once set, it can’t be changed.

title

− (NSString *)title

Returns the string that appears in the title bar of the receiver.

See also:	− setTitle:, − setTitleWithRepresentedFilename:

tryToPerform:with:

− (BOOL)tryToPerform:(SEL)anAction with:(id)anObject

Overrides NSResponder’s implementation to add the receiver’s delegate to the series of objects requested to perform anAction. Returns YES if a receiver for anAction is found; otherwise returns NO.

See also:	− tryToPerform:with: (NSResponder)

unregisterDraggedTypes

− (void)unregisterDraggedTypes

Unregisters the receiver as a possible destination for dragging operations.

See also:	− registerForDraggedTypes:

update

− (void)update

The default implementation of this method does nothing more than post an NSWindowDidUpdateNotification to the default notification center. A subclass can override this method to perform specialized operations, but should send an update message to super just before returning. For example, the NSMenu class implements this method to disable and enable menu commands.

An NSWindow is automatically sent an update message on every pass through the event loop and before it’s ordered on-screen. You can manually cause an update message to be sent to all visible NSWindows through NSApplication’s updateWindows method.

See also:	− setWindowsNeedUpdate: (NSApplication), − updateWindows (NSApplication)

useOptimizedDrawing:

− (void)useOptimizedDrawing:(BOOL)flag

Informs the receiver whether to optimize focusing and drawing when displaying its NSViews. The optimizations may prevent sibling subviews from being displayed in the correct order—which matters only if the subviews overlap. You should always set flag to YES if there are no overlapping subviews within the NSWindow. The default is NO.

validRequestorForSendType:returnType:

− (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType

Searches for an object that responds to a Services request by providing input of sendType and accepting output of returnType. Returns that object, or nil if none is found.

Messages to perform this method are initiated by the Services menu. It’s part of the mechanism that passes validRequestorForSendType:andReturnType: messages up the responder chain. See the Services documentation in Programming Topics for more information.

This method works by forwarding the message to the receiver’s delegate if it responds (and provided it isn’t an NSResponder with its own next responder). If the delegate doesn’t respond to the message or returns nil when sent it, this method forwards the message to the NSApplication object. If the NSApplication object returns nil, this method also returns nil. Otherwise this method returns the object returned by the delegate or NSApplication object.

See also:	− validRequestorForSendType:returnType: (NSResponder and NSApplication)

viewsNeedDisplay

− (BOOL)viewsNeedDisplay

Returns YES if any of the receiver’s NSView’s need to be displayed, NO otherwise.

See also:	− setViewsNeedDisplay:

windowHandle

− (void *)windowHandle

Returns a Microsoft Windows HWND handle as a pointer to void. This value can be cast directly to HWND. This method exists only on Microsoft Windows; don’t attempt to invoke it on Mach.

windowNumber

− (int)windowNumber

Returns the window number of the receiver’s PostScript window device. Each window device in an application is given a unique window number—note that this isn’t the same as the global window number assigned by the Window Server. This number can be used to identify the window device with the orderWindow:relativeTo: method and in the Application Kit functions NSWindowList() and NSConvertWindowNumberToGlobal().

If the receiver doesn’t have a window device, the value returned will be equal to or less than 0.

See also:	− initWithContentRect:styleMask:backing:defer:, − setOneShot:

worksWhenModal

− (BOOL)worksWhenModal

Returns YES if the receiver is able to receive keyboard and mouse events even when some other window is being run modally, NO otherwise. NSWindow’s implementation of this method returns NO. Only subclasses of NSPanel should override this default.

See also:	− setWorksWhenModal: (NSPanel)

Methods Implemented By the Delegate

windowDidBecomeKey:

− (void)windowDidBecomeKey:(NSNotification *)aNotification

Sent by the default notification center immediately after an NSWindow has become key. aNotification is always NSWindowDidBecomeKeyNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

windowDidBecomeMain:

− (void)windowDidBecomeMain:(NSNotification *)aNotification

Sent by the default notification center immediately after an NSWindow has become main. aNotification is always NSWindowDidBecomeMainNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

windowDidChangeScreen:

− (void)windowDidChangeScreen:(NSNotification *)aNotification

Sent by the default notification center immediately after an NSWindow has changed screen. aNotification is always NSWindowDidChangeScreenNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

windowDidDeminiaturize:

− (void)windowDidDeminiaturize:(NSNotification *)aNotification

Sent by the default notification center immediately after an NSWindow has been deminiaturized. aNotification is always NSWindowDidDeminiaturizeNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

windowDidExpose:

− (void)windowDidExpose:(NSNotification *)aNotification

Sent by the default notification center immediately after an NSWindow has been exposed. aNotification is always NSWindowDidExposeNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

windowDidMiniaturize:

− (void)windowDidMiniaturize:(NSNotification *)aNotification

Sent by the default notification center immediately after an NSWindow has been miniaturized. aNotification is always NSWindowDidMiniaturizeNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

windowDidMove:

− (void)windowDidMove:(NSNotification *)aNotification

Sent by the default notification center immediately after an NSWindow has been moved. aNotification is always NSWindowDidMoveNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

windowDidResignKey:

− (void)windowDidResignKey:(NSNotification *)aNotification

Sent by the default notification center immediately after an NSWindow has resigned its status as key window. aNotification is always NSWindowDidResignKeyNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

windowDidResignMain:

− (void)windowDidResignMain:(NSNotification *)aNotification

Sent by the default notification center immediately after an NSWindow has resigned its status as main window. aNotification is always NSWindowDidResignMainNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

windowDidResize:

− (void)windowDidResize:(NSNotification *)aNotification

Sent by the default notification center immediately after an NSWindow has been resized. aNotification is always NSWindowDidResizeNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

windowDidUpdate:

− (void)windowDidUpdate:(NSNotification *)aNotification

Sent by the default notification center immediately after an NSWindow receives an update message. aNotification is always NSWindowDidUpdateNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

windowShouldClose:

− (BOOL)windowShouldClose:(id)sender

Invoked just before the user (or the performClose: method) closes sender. The delegate can return NO to prevent sender from closing.

windowWillClose:

− (void)windowWillClose:(NSNotification *)aNotification

Sent by the default notification center immediately before an NSWindow closes. aNotification is always NSWindowWillCloseNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

p	windowWillMiniaturize:

− (void)windowWillMiniaturize:(NSNotification *)aNotification

Sent by the default notification center immediately before an NSWindow is miniaturized. aNotification is always NSWindowWillMiniaturizeNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

p	windowWillMove:

− (void)windowWillMove:(NSNotification *)aNotification

Sent by the default notification center immediately before an NSWindow is moved. aNotification is always NSWindowWillMoveNotification. You can retrieve the NSWindow object in question by sending object to aNotification.

p	windowWillResize:toSize:

− (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize

Invoked sender is being resized (whether by the user or through one of the setFrame... methods other than setFrame:display:). proposedFrameSize contains the size (in screen coordinates) that the sender will be resized to. To reset the size, simply return sender directly from this method. The NSWindow’s minimum and maximum size constraints have already been applied when this method is invoked.

While the user is resizing an NSWindow, the delegate is sent a series of windowWillResize:toSize: messages as the NSWindow’s outline is dragged. The NSWindow’s outline is displayed at the constrained size as set by this method.

windowWillReturnFieldEditor:toObject:

− (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)anObject

Invoked when sender’s field editor is requested by anObject. If the delegate’s implementation of this method returns an object other than nil, the NSWindow substitutes it for the field editor and returns it to anObject.

See also:	− fieldEditor:forObject

Notifications

NSWindowDidBecomeKeyNotification

Posted whenever the NSWindow becomes the key window. The notification contains:

Notification Object	The NSWindow that has become key

Userinfo	None

NSWindowDidBecomeMainNotification

Posted whenever the NSWindow becomes the main window. The notification contains:

Notification Object	The NSWindow that has become main

Userinfo	None

NSWindowDidChangeScreenNotification

Posted whenever a portion of the NSWindow’s frame moves onto or off of a screen. The notification contains:

Notification Object	The NSWindow that has changed screen

Userinfo	None

NSWindowDidDeminiaturizeNotification

Posted whenever the NSWindow is deminiaturized. The notification contains:

Notification Object	The NSWindow that has deminiaturized

Userinfo	None

NSWindowDidExposeNotification

Posted whenever a portion of a nonretained NSWindow is exposed, whether by being ordered above other windows or by other widows being removed from above it. The notification contains:

Notification Object	The NSWindow that has been exposed

Userinfo

Key	Value

NSExposedRect	The rectangle that has been exposed

NSWindowDidMiniaturizeNotification

Posted whenever the NSWindow is miniaturized. The notification contains:

Notification Object	The NSWindow that has miniaturized

Userinfo	None

NSWindowDidMoveNotification

Posted whenever the NSWindow is moved. The notification contains:

Notification Object	The NSWindow that has moved

Userinfo	None

NSWindowDidResignKeyNotification

Posted whenever the NSWindow resigns its status as key window. The notification contains:

Notification Object	The NSWindow that has resigned its key window status

Userinfo	None

NSWindowDidResignMainNotification

Posted whenever the NSWindow resigns its status as main window. The notification contains:

Notification Object	The NSWindow that has resigned its main window status

Userinfo	None

NSWindowDidResizeNotification

Posted whenever the NSWindow’s size changes. The notification contains:

Notification Object	The NSWindow whose size has changed

Userinfo	None

NSWindowDidUpdateNotification

Posted whenever the NSWindow receives an update message. The notification contains:

Notification Object	The NSWindow that received the update message

Userinfo	None

NSWindowWillCloseNotification

Posted whenever the NSWindow is about to close. The notification contains:

Notification Object	The NSWindow that’s closing

Userinfo	None

p	NSWindowWillMiniaturizeNotification

Posted whenever the NSWindow is about to miniaturize. The notification contains:

Notification Object	The NSWindow that’s miniaturizing

Userinfo	None

p	NSWindowWillMoveNotification

Posted whenever the NSWindow is about to move. The notification contains:

Notification Object	The NSWindow that’s moving

Userinfo	None


NSWorkspace

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

Inherits From:	NSObject

Conforms To:	NSObject (NSObject)

Declared In:	AppKit/NSWorkspace.h

Class Description

An NSWorkspace object responds to application requests to perform a variety of services:

•	opening, manipulating, and obtaining information about files and devices

•	tracking changes to the file system, devices, and the user database

•	launching applications

•	miscellaneous services such as animating an image and requesting additional time before power off

There is one shared NSWorkspace object per application. You use the class method sharedWorkspace to access it. For example, the following statement uses an NSWorkspace object to request that a file be opened in the Edit application:

[[NSWorkspace sharedWorkspace] openFile:@"/Myfiles/README"

withApplication:@"Edit"];

Note:	On the Microsoft Windows platform, some of the methods in this class have no effect. Refer to the method descriptions below.

Method Types

Accessing the shared NSWorkspace

+ sharedWorkspace

Accessing the NSWorkspace notification center

− notificationCenter

Opening files	− openFile:

− openFile:withApplication:

− openFile:fromImage:at:inView:

− openFile:withApplication:andDeactivate:

− openTempFile:

Manipulating applications	− launchApplication:

− launchApplication:showIcon:autolaunch:

− hideOtherApplications

Manipulating files	− performFileOperation:source:destination:files:tag:

− selectFile:inFileViewerRootedAtPath:

Requesting information about files

− iconForFile:

− iconForFileType:

− iconForFiles:

− getInfoForFile:application:type:

− fullPathForApplication:

− getFileSystemInfoForPath:isRemovable:isWritable:

isUnmountable:description:type:

Requesting additional time before logout

− extendPowerOffBy:

Tracking changes to the file system

− noteFileSystemChanged

− fileSystemChanged

Updating registered services and file types

− findApplications

Tracking changes to the defaults database

− noteUserDefaultsChanged

− userDefaultsChanged

Tracking status changes for applications and devices

− mountedRemovableMedia

− mountNewRemovableMedia

− checkForRemovableMedia

Animating an image	− slideImage:from:to:

Unmounting a device	− unmountAndEjectDeviceAtPath:

Class Methods

sharedWorkspace

+ (NSWorkspace *)sharedWorkspace

Returns the shared NSWorkspace instance.

Instance Methods

checkForRemovableMedia

− (void)checkForRemovableMedia

On the Mach platform, polls the system’s drives for any disks that have been inserted but not yet mounted. checkForRemovableMedia doesn’t wait until such disks are mounted; instead, it requests that the disk be mounted asynchronously and returns immediately.

 This method has no effect on the Microsoft Windows platform.

See also:	− mountNewRemovableMedia, − mountedRemovableMedia

extendPowerOffBy:

− (int)extendPowerOffBy:(int)requested

Requests requested milliseconds more time before the power goes off or the user logs out. Returns the number of additional milliseconds granted. On some platforms you might not be able to extend the time.

fileSystemChanged

− (BOOL)fileSystemChanged

On the Mach platform, returns YES if a change to the file system has been registered with a noteFileSystemChanged message since the last fileSystemChanged message; NO otherwise.

This method is not implemented on the Microsoft Windows platform. If you try to use it, it raises an NSInvalidArgumentException.

findApplications

− (void)findApplications

On the Mach platform, examines all applications in the normal places (/LocalApps, /NextApps, /NextDeveloper/Apps) and updates the records of registered services and file types.

 This method has no effect on the Microsoft Windows platform.

fullPathForApplication:

− (NSString *)fullPathForApplication:(NSString *)appName

Returns the full path for the application appName, or nil if appName isn’t in one of the normal places.

getFileSystemInfoForPath:isRemovable:isWritable:isUnmountable:

description:type:

− (BOOL)getFileSystemInfoForPath:(NSString *)fullPath

isRemovable:(BOOL *)removableFlag

isWritable:(BOOL *)writableFlag

isUnmountable:(BOOL *)unmountableFlag

description:(NSString **)description

type:(NSString **)fileSystemType

On the Mach platform, describes the file system at fullPath. This method has no effect on the Microsoft Windows platform.

Returns YES if fullPath is a file system mount point, NO otherwise. If the return value is YES, description describes the file system; this value can be used in strings, but it shouldn’t be depended upon by program logic. Example values for description are “hard”, “nfs”, and “foreign”. fileSystemType indicates the file system type; values could be “NeXT”, “DOS”, or other values. removableFlag is YES if the file system is on removable media, NO otherwise. writableFlag is YES if the file system’s media is writable, NO otherwise. unmountableFlag returns YES if the file system is unmountable, NO otherwise.

getInfoForFile:application:type:

− (BOOL)getInfoForFile:(NSString *)fullPath

application:(NSString **)appName

type:(NSString **)type

Retrieves information about the file specified by fullPath. If this method returns YES, the NSString pointed to by appName is set to the application the system would use to open fullPath. The NSString pointed to by type contains one of the following values or a file name extension such as “rtf” indicating the file’s type:

Value	Type of File

NSPlainFileType	Plain (untyped) file

NSDirectoryFileType	Directory

NSApplicationFileType	OpenStep application

NSFilesystemFileType	File system mount point

NSShellCommandFileType	Executable shell command

This method returns NO if it could not find fullPath.

See also:	− iconForFile:, − iconForFiles:

hideOtherApplications

− (void)hideOtherApplications

Hides all applications other than the sender. This method has no effect on the Microsoft Windows platform. On the Mach platform, the user can hide all applications except the current one by Command-double-clicking an application’s tile, so programmatic invocation of this method is usually unnecessary.

iconForFile:

− (NSImage *)iconForFile:(NSString *)fullPath

Returns an NSImage with the icon for the single file specified by fullPath.

See also:	− getInfoForFile:application:type:, − iconForFileType:, − iconForFiles:

iconForFileType:

− (NSImage *)iconForFileType:(NSString *)fileType

Returns an NSImage the icon for the file type specified by fileType.

See also:	− iconForFile:, − iconForFiles:

iconForFiles:

− (NSImage *)iconForFiles:(NSArray *)fullPaths

Returns an NSImage with the icon for the files specified in fullPaths, an array of NSStrings. If fullPaths specifies one file, its icon is returned. If fullPaths specifies more than one file, an icon representing the multiple selection is returned.

See also:	− iconForFile:, − iconForFileType:

launchApplication:

− (BOOL)launchApplication:(NSString *)appName

Launches the application appName. appName need not be specified with a full path and, in the case of an application wrapper, can be specified with or without the .app extension. Returns YES if the application is successfully launched or already running, NO if it can’t be launched.

Before this method begins, it posts an NSWorkspaceWillLaunchApplicationNotification to the NSWorkspace’s notification center. When the operation is complete, it posts an NSWorkspaceDidLaunchApplicationNotification.

See also:	− launchApplication:showIcon:autolaunch:

launchApplication:showIcon:autolaunch:

− (BOOL)launchApplication:(NSString *)appName

showIcon:(BOOL)showIcon

autolaunch:(BOOL)autolaunch

Launches the application appName. If showIcon is NO, the application’s icon won’t be placed on the screen. (The icon still exists, though.) If autolaunch is YES, the autolaunch default will be set as though the application were autolaunched at startup. This method is provided to enable daemon-like applications that lack a normal user interface and for use by alternative dock programs.  Its use is not generally encouraged.

Returns YES if the application is successfully launched or already running, and NO if it can’t be launched.

Before this method begins, it posts an NSWorkspaceWillLaunchApplicationNotification to the NSWorkspace’s notification center. When the operation is complete, it posts an NSWorkspaceDidLaunchApplicationNotification.

See also:	− launchApplication:

mountNewRemovableMedia

− (NSArray *)mountNewRemovableMedia

On the Mach platform, polls the system’s drives for any disks that have been inserted but not yet mounted, waits until the new disks have been mounted, and returns an NSArray of NSStrings containing full pathnames to all newly mounted disks. This method posts an NSWorkspaceDidMountNotification to the NSWorkspace’s notification center when it is finished.

This method is not implemented on the Microsoft Windows platform. If you try to use it, it raises an NSInvalidArgumentException.

See also:	− checkForRemovableMedia, − mountedRemovableMedia

mountedRemovableMedia

− (NSArray *)mountedRemovableMedia

Returns an NSArray of NSStrings containing the full pathnames of all currently mounted removable disks. This method is not implemented on the Microsoft Windows platform. If you try to use it, it raises an NSInvalidArgumentException.

On the Mach platform, if the computer provides an interrupt or other notification when the user inserts a disk into a drive, the Workspace Manager will mount the disk immediately. However, if no notification is given, the Workspace Manager won’t be aware that a disk needs to be mounted. On such systems, an application should invoke either mountNewRemovableMedia: or checkForRemovableMedia before invoking mountedRemovableMedia:. Either of these methods cause the Workspace Manager to poll the drives to see if a disk is present. If a disk has been inserted but not yet mounted, these methods will cause the Workspace Manager to mount it.

The Disk button in an Open or Save panel invokes mountedRemovableMedia: and mountNewRemovableMedia: as part of its operation, so most applications won’t need to invoke these methods directly.

See also:	− checkForRemovableMedia, − mountNewRemovableMedia

noteFileSystemChanged

− (void)noteFileSystemChanged

On the Mach platform, informs NSWorkspace that the file system has changed. NSWorkspace then gets the status of all the files and directories it is interested in and updates itself appropriately. This method is used by many objects that write or delete files.

This method has no effect on the Microsoft Windows platform.

See also:	− fileSystemChanged

noteUserDefaultsChanged

− (void)noteUserDefaultsChanged

On the Mach platform, informs NSWorkspace that the defaults database has changed. NSWorkspace then reads all the defaults it is interested in and reconfigures itself appropriately. For example, on Mach platforms, this method is used by the Preferences application to notify Workspace Manager whether the user prefers to see hidden files.

This method has no effect on the Microsoft Windows platform.

See also:	− userDefaultsChanged

notificationCenter

− (NSNotificationCenter *)notificationCenter

Returns the notification center for workspace notifications.

openFile:

− (BOOL)openFile:(NSString *)fullPath

Opens the file specified by fullPath using the default application for its type; returns YES if file was successfully opened, NO otherwise. The sending application is deactivated before the request is sent.

See also:	− openFile:fromImage:at:inView:, − openFile:withApplication:, − openFile:withApplication:andDeactivate:, − openTempFile:

openFile:fromImage:at:inView:

− (BOOL)openFile:(NSString *)fullPath

fromImage:(NSImage *)anImage

at:(NSPoint)point

inView:(NSView *)aView

Opens the file specified by fullPath using the default application for its type. On the Mach platform, Workspace Manager provides animation before opening the file to give the user feedback that the file is to be opened. To provide this animation, anImage should contain an icon for the file, and its image should be displayed at point, specified in aView’s coordinates. On the Microsoft Windows platform, this method is the same as the openFile: method.

The sending application is deactivated before the request is sent. Returns YES if the file is successfully opened, NO otherwise.

See also:	− openFile:, − openFile:withApplication:, − openFile:withApplication:andDeactivate:, − openTempFile:

openFile:withApplication:

− (BOOL)openFile:(NSString *)fullPath withApplication:(NSString *)appName

Opens the file specified by fullPath using the appName application. appName need not be specified with a full path and, in the case of an application wrapper, can be specified with or without the .app extension. The sending application is deactivated before the request is sent. Returns YES if the file is successfully opened, NO otherwise.

See also:	− openFile:, − openFile:withApplication:andDeactivate:

openFile:withApplication:andDeactivate:

− (BOOL)openFile:(NSString *)fullPath

withApplication:(NSString *)appName

andDeactivate:(BOOL)flag

Opens the file specified by fullPath using the appName application. appName need not be specified with a full path and, in the case of an application wrapper, can be specified with or without the .app extension. If appName is nil, the default application for the file’s type is used. If flag is YES, the sending application is deactivated before the request is sent, allowing the opening application to become the active application. Returns YES if the file is successfully opened, NO otherwise.

See also:	− openFile:, − openFile:withApplication:, − application:openFile: (NSApplication delegate method)

openTempFile:

− (BOOL)openTempFile:(NSString *)fullPath

Opens the temporary file specified by fullPath using the default application for its type. The sending application is deactivated before the request is sent. Using this method instead of one of the openFile:... methods lets the receiving application know that it should delete the file when it no longer needs it. Returns YES if the file is successfully opened, NO otherwise.

See also:	− openFile:, − openFile:fromImage:at:inView:, − openFile:withApplication:, − openFile:withApplication:andDeactivate:

performFileOperation:source:destination:files:tag:

− (BOOL)performFileOperation:(NSString *)operation

source:(NSString *)source

destination:(NSString *)destination

files:(NSArray *)files

tag:(int *)tag

Performs a file operation on a set of files in a particular directory. operation is some file operation, such as compressing or moving files. files contains NSString specifying the names of the files to be manipulated. The file names are given relative to the source directory. The list can contain both files and directories; all of them must be located directly within source (not in one of its subdirectories).

Some operations—such as moving, copying, and linking files—require a destination directory to be specified. If not, destination should be the empty string (@"").

The possible values for operation are:

Operation	Meaning

NSWorkspaceMoveOperation	Move file to destination

NSWorkspaceCopyOperation	Copy file to destination

NSWorkspaceLinkOperation	Create link to file in destination

NSWorkspaceCompressOperation	Compress file

NSWorkspaceDecompressOperation	Decompress file

NSWorkspaceEncryptOperation	Encrypt file

NSWorkspaceDecryptOperation	Decrypt file

NSWorkspaceDestroyOperation	Destroy file

NSWorkspaceRecycleOperation	Move file to recycler

NSWorkspaceDuplicateOperation	Duplicate file in source directory

Note:	NSWorkspaceCompressOperation, NSWorkspaceDecompressOperation, NSWorkspaceEncryptOperation, and NSWorkspaceDecryptOperation are not available on the Microsoft Windows platform.

This method returns YES if the operation succeeded, NO otherwise, In tag, the method returns a negative integer if the operation fails, 0 if the operation is performed synchronously and succeeds, and a positive integer if the operation is performed asynchronously. The positive integer is a tag that identifies the requested file operation. Before this method returns, it posts an NSWorkspaceDidPerformFileOperationNotification to NSWorkspace’s notification center.

selectFile:inFileViewerRootedAtPath:

− (BOOL)selectFile:(NSString *)fullPath inFileViewerRootedAtPath:(NSString *)rootFullPath

Selects the file specified by fullPath. If a path is specified by rootFullPath, a new file viewer is opened. If rootFullPath is an empty string (@""), the file is selected in the main viewer. Returns YES if the file is successfully selected, NO otherwise.

slideImage:from:to:

− (void)slideImage:(NSImage *)image

from:(NSPoint)fromPoint

to:(NSPoint)toPoint

On Mach platforms, animates a sliding image of image from fromPoint to toPoint, specified in screen coordinates. This method has no effect on the Microsoft Windows platform.

unmountAndEjectDeviceAtPath:

− (BOOL)unmountAndEjectDeviceAtPath:(NSString *)path

Unmounts and ejects the device at path. Returns YES if unmount succeeded and NO otherwise. When this method begins, it posts an NSWorkspaceWillUnmountNotification to NSWorkspace’s notification center. When it is finished, it posts an NSWorkspaceDidUnmountNotification.

userDefaultsChanged

− (BOOL)userDefaultsChanged

On the Mach platform, returns whether a change to the defaults database has been registered with a noteUserDefaultsChanged message since the last userDefaultsChanged message.

This method has no effect on the Microsoft Windows platform.

Notifications

All NSWorkspace notifications are posted to NSWorkspace’s own notification center, not the application’s default notification center. Access this center using the notificationCenter method.

NSNotificationCenter *workspaceCenter = [[NSWorkspace sharedWorkspace]

notificationCenter];

NSWorkspaceDidLaunchApplicationNotification

Posted when a new application has started up.

The notification object contains:

Notification Object	the shared NSWorkspace instance

Userinfo

Key	Value

NSApplicationName	The application being terminated

NSWorkspaceDidMountNotification

Posted when a new device has been mounted.

The notification object contains:

Notification Object	the shared NSWorkspace instance

Userinfo

Key	Value

NSDevicePath	The path where the device was mounted

NSWorkspaceDidPerformFileOperationNotification

Posted when a file operation has been performed.

Notification Object	the shared NSWorkspace instance

Userinfo

Key	Value

NSOperationNumber	A number indicating the type of file operation completed

NSWorkspaceDidTerminateApplicationNotification

Posted when an application finishes executing.

The notification object contains:

Notification Object	the shared NSWorkspace instance

Userinfo

Key	Value

NSApplicationName	The application that terminated

NSWorkspaceDidUnmountNotification

Posted when the workspace has unmounted a device.

Notification Object	the shared NSWorkspace instance

Userinfo

Key	Value

NSDevicePath	The path where the device was previously mounted

NSWorkspaceWillLaunchApplicationNotification

Posted when the workspace is about to launch an application.

Notification Object	the shared NSWorkspace instance

Userinfo

Key	Value

NSApplicationName	The application about to be launched

NSWorkspaceWillPowerOffNotification

Posted when the user has requested that the machine be powered off.

Notification Object	the shared NSWorkspace instance

Userinfo	None

NSWorkspaceWillUnmountNotification

Posted when the workspace is about to unmount a device.

Notification Object	the shared NSWorkspace instance

Userinfo

Key	Value

NSDevicePath	The path where the device is mounted


Protocols

NSChangeSpelling

NSColorPickingCustom

NSColorPickingDefault

NSDPSContextNotification

NSDraggingDestination

NSDraggingInfo

NSDraggingSource

NSIgnoreMisspelledWords

NSMenuActionResponder

NSMenuItem

NSNibAwakening

NSServicesRequests

NSTableDataSource

NSTextAttachmentCell


Single-Operator Functions

Copyright ©1996 by NeXT Software, Inc.  All Rights Reserved.

PSadjustcursor(float dx, float dy)

PSalphaimage(void)

PSbasetocurrent(float bx, float by, float *cx, float *cy)

PSbasetoscreen(float bx, float by, float *sx, float *sy)

PSbuttondown(boolean *isdown)

PScleartrackingrect(int trectnum, userobject gstate)

PScomposite(float src, float src, float width, float height, userobject srcgstate, float dest, float dest, int op)

The value passed as op should be one of the following:

NX_CLEAR 	NX_SIN	NX_SATOP

NX_COPY	NX_DIN	NX_DATOP

NX_SOVER	NX_SOUT 	NX_PLUSD

NX_DOVER	NX_DOUT	NX_PLUSL

NX_XOR

PScompositerect(float dest, float dest, float width, float height, int op)

The value passed as op should be one of the constants listed under PScomposite(), plus NX_HIGHLIGHT.

PScountframebuffers(int *count)

PScountscreenlist(int context, int *count)

PScountwindowlist(int context, int *count)

PScurrentactiveapp(int *context)

Warning:  Don’t use this function if you’re using the Application Kit.

PScurrentalpha(float *coverage)

PScurrentdefaultdepthlimit(int *depth)

Warning:  Don’t use this function if you’re using the Application Kit.

PScurrentdeviceinfo(userobject window, int *min, int *max, boolean *iscolor)

PScurrenteventmask(userobject window, int *mask)

Warning:  Don’t use this function if you’re using the Application Kit.

PScurrentframebuffertransfer(void)

PScurrentmouse(userobject window, float *x, float *y)

Warning:  Don’t use this function if you’re using the Application Kit.

PScurrentowner(userobject window, int *context)

PScurrentshowpageprocedure(void)

PScurrentrusage(float *ctime, float *utime, float *stime, int *msgsend, int *msgrcv, int *nsignals, int *nvcsw, int *nivcsw)

PScurrenttobase(float cx, float cy, float *bx, float *by)

PScurrenttoscreen(float cx, float cx, float *sx, float *sy)

PScurrentuser(int *uiId, int *gid)

PScurrentwaitcursorenabled(boolean *isenabled)

PScurrentwindow(userobject *window)

PScurrentwindowalpha(userobject window, int *alpha)

PScurrentwindowbounds(userobject window, float *x, float *y, float *width, float *height)

Warning:  Don’t use this function if you’re using the Application Kit.

PScurrentwindowdepth(userobject window, int *depth)

Warning:  Don’t use this function if you’re using the Application Kit.

PScurrentwindowdepthlimit(userobject window, int *depth)

Warning:  Don’t use this function if you’re using the Application Kit.

PScurrentwindowdict(userobject window)

Warning:  Don’t use this function if you’re using the Application Kit.

PScurrentwindowlevel(userobject window, int *level)

PScurrentwriteblock(bool *doesblock)

PSdissolve(float src, float src, float sourceWidth, float width, userobject srcgstate, float dest, float dest, float delta)

PSdumpwindow(int dumplevel, userobject window)

Warning:  Don’t use this function if you’re using the Application Kit.

PSdumpwindows(int dumplevel, userobject context)

Warning:  Don’t use this function if you’re using the Application Kit.

PSfindwindow(float x, float y, int place, userobject otherwindow, float *x', float *y', userobject *window, boolean *found)

The value passed as place should be one of the following:

NX_ABOVE

NX_BELOW

PSflushgraphics(void)

Warning:  Don’t use this function if you’re using the Application Kit.

PSframebuffer(int index, int stringlen, char string[], int *slot, int *unit, int *romid, int *x, int *y, int *width, int *height, int *maxdepth)

PSfrontwindow(int *window)

Warning:  Don’t use this function if you’re using the Application Kit.

PShidecursor(void)

PShideinstance(float x, float y, float width, float height)

PSmachportdevice(int width, int height, const int bbox[], int bboxSize, const float matrix[], const char *hostname, const char *portname, const char *pixelencoding)

PSmovewindow(float x, float y, userobject window)

Warning:  Don’t use this function if you’re using the Application Kit.

PSnewinstance(void)

PSnextrelease(int size, char string[])

PSobscurecursor(void)

PSorderwindow(int place, userobject otherwindow, int window)

Warning:  Don’t use this function if you’re using the Application Kit.

The value passed as place should be one of the following:

NX_ABOVE

NX_BELOW

NX_OUT

PSosname(int size, char string[])

PSostype(int *type)

PSplacewindow(float x, float y, float width, float height, userobject window)†

Warning:  Don’t use this function if you’re using the Application Kit.

PSplaysound(const char *soundname, int priority)

PSposteventbycontext(int type, float x, float y, int time, int flags, int window, int subtype, int misc0, int misc1, int context, boolean *success )

PSreadimage(void)

PSrevealcursor(void)

PSrightbuttondown(int *isdown)

PSrightstilldown(int eventnum, boolean *stilldown)

PSscreenlist(int context, int count, int array[])

PSscreentobase(float sx, float sy, float *bx, float *by)

PSscreentocurrent(float sx, float sy, float *cx, float *cy)

PSsetactiveapp(int context)

Warning:  Don’t use this function if you’re using the Application Kit.

PSsetalpha(float coverage)

PSsetautofill(boolean flag, userobject window)

PSsetcursor(float x, float y, float mx, float my)

PSsetdefaultdepthlimit(int depth)

Warning:  Don’t use this function if you’re using the Application Kit.

PSseteventmask(int mask, userobject window)

Warning:  Don’t use this function if you’re using the Application Kit.

See the constants listed under “Event Type Masks” in the section “Types and Constants” for a list of mask values.

PSsetexposurecolor(void)

PSsetflushexposures(boolean flag)

Warning:  Don’t use this function if you’re using the Application Kit.

PSsetframebuffertransfer(void)

PSsetinstance(boolean flag)

PSsetmouse(float x, float y)

PSsetowner(userobject context, userobject window)

PSsetsendexposed(boolean flag, userobject window)†

Warning:  Don’t use this function if you’re using the Application Kit.

PSsetshowpageprocedure(int window)

Warning:  Don’t use this function if you’re using the Application Kit.

PSsettrackingrect(float x, float y, float width, float height, boolean leftbool, boolean rightbool, boolean insidebool, int userdata, int trectnum, userobject gstate)

Note:  Only the Form 1 version of the settrackingrect operator is offered as a C function.

PSsetwaitcursorenabled(boolean flag)

PSsetwindowdepthlimit(int depth, userobject window)

Warning:  Don’t use this function if you’re using the Application Kit.

PSsetwindowdict(userobject window)

Warning:  Don’t use this function if you’re using the Application Kit.

PSsetwindowlevel(int level, userobject window)

PSsetwindowtype(int type, userobject window)

Warning:  Don’t use this function if you’re using the Application Kit.

PSsetwriteblock(int flag)

PSshow(const char *string)

PSshowcursor(void)

PSsizeimage(float x, float y, float width, float height, int *pixelswide, int *pixelshigh, int *bits/sample, float matrix[], boolean *multiproc, int *ncolors)

PSstilldown(int eventnum, boolean *stilldown)

PStermwindow(userobject window)

Warning:  Don’t use this function if you’re using the Application Kit.

PSwindow(float x, float y, float width, float height, int type, int *window)

Warning:  Don’t use this function if you’re using the Application Kit.

PSwindowdevice(userobject window)

PSwindowdeviceround(userobject window)

PSwindowlist(int context, int count, int subarray[])


Types and Constants

DPSTypes