richard@brainstorm.co.uk
)Implementation of class for communicating with the pasteboard server.
Copyright: (C) 1997,1999,2003 Free Software Foundation, Inc.
The pasteboard system is the core of OpenStep
inter-application communications. This
chapter is concerned with the use of the system, for
detailed reference see the
NSPasteboard
class.
For non-standard services provided by
applications (ie those which do not fit the
general services mechanism described below),
you generally use the Distributed Objects system (see
NSConnection
) directly, and some hints about that are provided at the
end of this chapter.
The most obvious use of the pasteboard system is to support cut and paste of text and other data, permitting the user to take selected information from a document open in an application, and move it around in the same document, or to another document open in the same application, or to a document open in another application entirely.
While some objects (eg instances of
NSText
) will handle cut and paste for you automatically,
you may often need to do this yourself in your own
classes. The mechanism for this is quite
simple, and should be done in a method called
when the user selects the Cut or
Copy item on the Edit menu.
The methods to do this should be called
cut: and copy: respectively, and
will be called automatically when the menu items
are selected.
NSPasteboard *pb = [NSPasteboard generalPasteboard];
// Provide string data immediately. [pb declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner: nil]; [pb setString: myString forType: NSStringPboardType];
- (void) pasteboard: (NSPasteboard*)pb provideDataForType: (NSString*)type { // Place the data needed for pasting onto the pasteboard. [pb setData: data forType: type]; }
// Supply RTF data to the pasteboard system. - (id) copy: (id)sender { NSPasteboard *pb = [NSPasteboard generalPasteboard]; [pb declareTypes: [NSArray arrayWithObjects: NSRTFPboardType, NSStringPboardType, nil] owner: nil]; [pb setData: myData forType: NSRTFPboardType]; }The providing object can retrieve the data initially stored in the pasteboard, and set the type of data actually needed.
- (void) pasteboard: (NSPasteboard*)pb provideDataForType: (NSString*)type { if ([type isEqualToString: NSStringPboardType] == YES) { NSData *d = [pb dataForType: NSRTFPboardType]; NSString *s = [self convertToString: d]; [pb setString: s forType: NSStringPboardType]; } else { // Unsupported type ... should not happen [pb setData: nil forType: type]; } }
Similarly, when the user selects the Paste item on the Edit menu, the paste: method in your code will be called, and this method should retrieve data from the pasteboard and insert it into your custom object so that the user can see it.
- (id) paste: (id)sender { NSPasteboard *pb = [NSPasteboard generalPasteboard]; NSString *info = [pb stringForType: NSStringPboardType]; // Now make use of info return self; }
The drag and drop system for transferring data is in essence
a simple extension of copy and paste, where the data being
dragged is a copy of some initially selected data, and
the location to which it is pasted depends on where it is
dropped.
To support drag and drop, you use a few
standard methods to interact with pasteboards, but you
need to extend this with DnD specific methods to handle the
drag and drop process.
The services system provides a standardised mechanism for an application to provide services to other applications. Like cut and paste, or drag and drop, the use of an application service is normally initiated by the user selecting some data to work with. The user then goes to the services menu, and selects a service listed there. The selection of a menu item causes the data to be placed on a pasteboard and transferred to the service providing application, where the action of the service is performed on it, and resulting data transferred back to the original system via the pasteboard system again.
To make use of a service then, you typically need to make
no changes to your application, making the services
facility supremely easy to deal with!
If however,
you wish to make use of a service programmatically (rather
than from the services menu), you can use the
NSPerformService()
function to invoke the service directly...
// Create a pasteboard and store a string in it. NSPasteboard *pb = [NSPasteboard pasteboardWithUniqueName]; [pb declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner: nil]; [pb setString: myString forType: NSStringPboardType]; // Invoke a service which takes string input and produces data output. if (NSPerformService(@"TheServiceName", pb) == YES) { result = [pb dataForType: NSGeneralPboardType]; }
Providing a service is a bit trickier, it involves
implementing a method to perform the service
(usually in your
[NSApplication -delegate]
object) and specifying information about your service in
the Info.plist file for your application.
When your
application is installed in one of the standard
locations, and the make_services tool is run
to update the cache of services information, your service
automatically becomes available on the services
menu of every application you run.
At runtime, you
use
[NSApplication -setServicesProvider:]
to specify the object which implements the method to perform the service, or, if you are providing the service from a process other than a GUI application, you use the NSRegisterServicesProvider()
function.
Your Info.plist should contain an array named
NSServices
listing all the services your
application provides. Each service definition should
be a dictionary containing the following information -
NSStringPboardType
in your code. :userData:error:
// If NSMessage=encryptData - (void) encryptString: (NSPasteboard*)pboard userData: (NSString*)userData error: (NSString**)error;This method will be pass the pasteboard to use and an optional user data string, and must return results in the pasteboard, or an error message in the error argument.
default
and this entry will be used where
none of the specific languages listed are found in the
application user's preferences. The actual code to implement a service is very simple, even with error checking added -
- (void) encryptString: (NSPasteboard*)pboard userData: (NSString*)userData error: (NSString**)error { NSString *d; if ([pboard types] containsObject: NSStringPboardType] == NO) { *error = @"Bad types for encrypt service ... no string data"; return; } s = [pboard stringForType: NSStringPboardType]; if ([d length] == 0) { *error = @"No data supplied for encrypt service"; return; } s = [self encryptString: s]; // Do the real work [pboard declareTypes: [NSArray arrayWithObject: NSStringPboardType owner: nil]; [pboard setString: s forType: NSStringPboardType]; return; }
A filter service is a special case of an inter-application service. Its action is to take data of one type and convert it to another type. Unlike general services, this is not directly initiated by user action clicking on an item in the services menu (indeed, filter services do not appear on the services menu), but is instead performed transparently when the application asks the pasteboard system for data of a particular type, but the pasteboard only contains data of some other type.
A filter service definition in the Info.plist file differs from that of a standard service in that the NSMessage entry is replaced by an NSFilter entry, the NSMenuItem and NSKeyEquivalent entries are omitted, and a few other entries may be added -
Filter services are used implicitly whenever you get a pasteboard by using one of the methods +pasteboardByFilteringData:ofType: , +pasteboardByFilteringFile: or +pasteboardByFilteringTypesInPasteboard: as the pasteboard system will automatically invoke any available filter to convert the data in the pasteboard to any required type as long as a conversion can be done using a single filter.
While the general services mechanism described above covers most eventualities, there are some circumstances where you might want your application to offer more complex services which require the client application to have been written to make use of those services and where the interaction between the two is much trickier.
In most cases, such situations are handled by server processes rather than GUI applications, thus avoiding all the overheads of a GUI application... linking with the GUI library and using the windowing system etc. On occasion you may actually want the services to use facilities from the GUI library (such as the NSPasteboard or NSWorkspace class).
Traditionally, NeXTstep and GNUstep applications permit you to connect to an application using the standard NSConnection mechanisms, with the name of the port you connect to being (by convention) the name of the application. The root proxy of the NSConnection obtained this way would be the [NSApplication -delegate] object, and any messages sent to this object would be handled by the application delegate.
In the interests of security, GNUstep provides a
mechanism to ensure that only those
methods you explicitly want to be available to
remote processes are actually available.
Those methods are assumed to be any of the standard
application methods, and any methods
implementing the standard services
mechanism (ie. methods whose names begin
application:
or end with
:userData:error:
), plus any methods
listed in the array returned by the
GSPermittedMessages
user default.
If your application wishes to make
non-standard methods available, it should use
[NSUserDefaults -registerDefaults:]
to set a standard value for GSPermittedMessages. Users of the application can then use the defaults system to override that standard setting for the application in order to reduce or increase the list of messages available to remote processes.
To make use of a service, you need to check to ensure
that the application providing the service is running,
connect to it, and then send messages to it. You
should take care to catch exceptions and deal with a
loss of connection to the server application.
As an aid to using the services, GNUstep provides a
helper function (GSContactApplication()) which
encapsulates the process of establishing a
connection and launching the server application
if necessary.
id proxy = GSContactApplication(@"pathToApp", nil, nil); if (proxy != nil) { NS_EXCEPTION { id result = [proxy performTask: taskName withArgument: anArgument]; if (result == nil) { // handle error } else { // Use result } } NS_HANDLER // Handle exception NS_ENDHANDLER }
If we want to send repeated messages, we may store the proxy to server application, and might want to keep track of the state of the connection to be sure that the proxy is still valid.
ASSIGN(remote, proxy); // We want to keep hold of the proxy for use later, so we need to know // if the connection dies ... we ask for a notification to call our // connectionBecameInvalid: method when the connection dies ... in that // method we can release the proxy. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(connectionBecameInvalid:) name: NSConnectionDidDieNotification object: [remote connectionForProxy]];
- Declared in:
- AppKit/NSPasteboard.h
The pasteboard system is the primary mechanism for data exchange between OpenStep applications. It is used for cut and paste of data, as the exchange mechanism for services (as listed on the services menu), for communicating with a spelling server in order to perform spell checking, and for filter services which convert data of one type to another transparently.
Pasteboards are identified by names, some of which are standard and are intended to exist permanently and be shared between all applications, others are temporary or private and are used to handle specific services.
All data transferred to/from pasteboards is typed. Mostly using one of several standard types for common data or using standardised names which identify particular kinds of files and their contents (see the NSCreateFileContentsPboardType() an NSCreateFilenamePboardType() functions for details). It is also possible for cooperating applications to use their own private types... any string value will do.
Each pasteboard has an owner... an object
which declares the types of data it can provide.
Unless versions of the pasteboard data corresponding
to all the declared types are written to the pasteboard,
the owner is responsible for producing the data for the
pasteboard when it is called for (lazy provision
of data).
The pasteboard owner needs to implement
the methods of the NSPasteboardOwner informal protocol
in order to do this.
Creates and returns a pasteboard from which the
data in the named file can be read in
all the types to which it can be converted by filter
services.
The type of
data in the file is inferred from the
file extension.
No filtering is actually performed until some object asks the pasteboard for the data, so calling this method is quite inexpensive.
Creates and returns a pasteboard from which the
data in the named file can be read in all the types
to which it can be converted by filter services.
The type of data in the file is inferred
from the file extension.
Creates and returns a pasteboard where the data contained in pboard is available for reading in as many types as it can be converted to by available filter services. This normally expands on the range of types available in pboard.
NB. This only permits a single level of filtering... if pboard was previously returned by another filtering method, it is returned instead of a new pasteboard.
Returns the pasteboard for the specified name. Creates a new pasteboard if (and only if) one with the given name does not exist.
Standard pasteboard names are -
nil
.
Adds newTypes to the pasteboard and declares newOwner to be the owner of the pasteboard. Use only after -declareTypes:owner: has been called for the same owner, because the new owner may not support all the types declared by a previous owner.
Returns the new change count for the pasteboard, or zero if an error occurs.
nil
if no such
data is available.
Sets the owner of the pasteboard to be
newOwner and declares
newTypes as the types of data supported
by it.
This invalidates existing data in the
pasteboard (except where the GNUstep
-setHistory:
extension allows multi-version data to be
held).
The value of newOwner may be
nil
, but if it is, data should
immediately be written to the pasteboard for
all the value in newTypes as a
nil
owner cannot be used for lazy
supply of data.
This increments the change count for the pasteboard
and the new count is returned, or zero is returned if
an error occurs.
Where
-setChangeCount:
has been used, the highest count to date is
incremented and returned, rather than the
last value specified by the
-setChangeCount:
method.
The types you declare can be arbitrary strings, but
as at least two applications really need to be aware
of the same type for it to be of use, it is much more
normal to use a predefined (standard) type or a
type representing the name or content of a
particular kind of file (returned by the
NSCreateFilenamePboardType()
or
NSCreateFilenamePboardType()
function).
The standard type for raw
data is
NSGeneralPboardType
The predefined pasteboard types are -
Obtains data of the specified dataType from the
pasteboard, deserializes it to the specified
filename and returns the file name (or
nil
on failure).
This method should only be used to read data written by the -writeFileContents: or -writeFileWrapper: method.
Obtains data of the specified dataType from the
pasteboard, deserializes it and returns the
resulting file wrapper (or nil
).
This method should only be used to read data written by the -writeFileContents: or -writeFileWrapper: method.
Writes data of type dataType
to the pasteboard server so that other applications
can read it. The dataType must be one of
the types previously declared for the pasteboard.
All the other methods for writing
data to the pasteboard call this one.
Returns YES
on success,
NO
if the data could not
be written for some reason.
Serialises the data in the supplied property list and writes it to the pasteboard server using the -setData:forType: method.
Data written using this method can be read by -propertyListForType: or, if it was a simple string, by -stringForType:
If the data is retrieved using -dataForType: then it needs to be deserialized into a property list.
Writes string it to the pasteboard server using the -setPropertyList:forType: method.
The data may subsequently be read from the receiver using the -stringForType: or -propertyListForType: method.
If the data is retrieved using -dataForType: then it needs to be deserialized into a property list.
Obtains data of the specified dataType
from the pasteboard, deserializes it and returns the
resulting string (or nil
).
The string should have been written using the -setString:forType: or -setPropertyList:forType: method.
Writes the contents of the file
filename to the pasteboard server after
declaring the type NSFileContentsPboardType as
well as a type based on the file extension (given by
the
NSCreateFileContentsPboardType()
function) if those types have not already been declared.
If the filename has no extension, only NSFileContentsPboardType is used.
Data written to a pasteboard by this method should be read using the -readFileContentsType:toFile: or -readFileWrapper method.
If the data is retrieved using -dataForType: then it needs to be deserialized by the NSFileWrapper class.
Writes the contents of the file wrapper to the pasteboard server after declaring the type NSFileContentsPboardType as well as a type based on the file extension of the wrappers preferred filename if those types have not already been declared.
Raises an exception if there is no preferred filename.
Data written to a pasteboard by this method should be read using the -readFileContentsType:toFile: or -readFileWrapper method.
If the data is retrieved using -dataForType: then it needs to be deserialized by the NSFileWrapper class.
- Declared in:
- AppKit/NSPasteboard.h
- Declared in:
- AppKit/NSPasteboard.h
GNUstep adds a mechanism for mapping between OpenStep pasteboard types and MIME types. This is useful for inter-operation with other systems, as MIME types have come into common usage ( long after the OpenStep specification was created).
The other extension to the pasteboard system produced by GNUstep is the ability to keep a history of recent items placed in a pasteboard, and retrieve data from that history rather than just the current item.
Once the -setChangeCount: message has been sent to an NSPasteboard the object will gain an extra GNUstep behaviour - when getting data from the pasteboard, the data need no longer be from the latest version but may be a version from a previous representation with the specified change count.
The value of count must be one which has previously been returned by -declareTypes:owner: and should not be further in the past than specified by the -setHistory: method.
- Declared in:
- AppKit/NSPasteboard.h