Up

NSPasteboard

Authors

Richard Frith-Macdonald (richard@brainstorm.co.uk)
Implementation of class for communicating with the pasteboard server.

Copyright: (C) 1997,1999,2003 Free Software Foundation, Inc.


Contents -

  1. The pasteboard system
  2. Cut and Paste
  3. Drag and Drop
  4. Services
  5. Filter services
  6. Distributed Objects services
  7. Software documentation for the NSObject(NSPasteboardReading) informal protocol
  8. Software documentation for the NSObject(NSPasteboardWriting) informal protocol
  9. Software documentation for the NSPasteboardReading protocol
  10. Software documentation for the NSPasteboardWriting protocol

The pasteboard system

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.

Cut and Paste

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.

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.

Drag and Drop

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.

Services

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 -

NSSendTypes
This is an array containing the string values of the types of data that the service provider can handle (ie the types of data the application requesting the service may send).
The string values are the same as the standard constant names for these types, so the string "NSStringPboardType" would match the use of the NSStringPboardType in your code.
Similarly, the functions NSCreateFileContentsPboardType() and NSCreateFilenamePboardType() return types whose string values are found by appending the filename extension concerned to the strings "NSTypedFileContentsPboardType:" and "NSTypedFilenamesPboardType:" respectively.
NSReturnTypes
These are the types of data that the service provider may return and are specified in the same way as the NSSendTypes.
NB. A service must handle at least one send type or one return type, but it is OK to have a service which expects no input data or one which produces no output data.
NSMessage
This mandatory string value is the interesting part of the message which is sent to your service provider in order to perform the service.
The method in your application which does the work, must take three arguments and have a name formed of this value followed by :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.
NSPortName
This specifies the name of the Distributed Objects port (see NSConnection and NSPort ) on which the service provider will be listening for messages. While its value depends on how you register the service, it is normally the name of the application providing the service. This information is required in order for other applications to know how to contact the service provider.
NSUserData
This is an optional arbitrary string which (if present) is passed as the userData argument to the method implementing the service. This permits a service provider to implement a single method to handle a variety of similar services, whose exact characteristics are determined by this parameter.
NSMenuItem
This is a dictionary containing language names and the text to appear in the services menu for each language. It may contain an entry where the language name is default and this entry will be used where none of the specific languages listed are found in the application user's preferences.
These text items may contain a single slash ('/') character, and if this is present, the text after the slash will appear in a submenu of the services menu, with the text before the slash being the name of that submenu. This is very useful where a single application provides a variety of services and wishes to group them together.
NSKeyEquivalent
This is an optional dictionary specifying the key equivalents to select the menu items listed in the NSMenuItem specification.
NSTimeout
This is an optional timeout (in milliseconds) specifying how long the system should wait for the service provider to perform the service. If omitted, it defaults to 30000 (30 seconds).
NSExecutable
This is an optional path to the executable binary of the program which performs the service.. it's used to launch the program if it is not already running. Normally, for an application, this is not necessary, as the system knows how to launch any applications found installed in standard locations.
NSHost
Not yet implemented... this provides for the system to launch the executable for this service on a different host on the network.

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;
}
    

Filter services

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 -

NSFilter
This is the first part of the message name for the method which actually implements the filter service... just like the NSMessage entry in a normal service.
NSInputMechanism
This (optional) entry is a string value specifying an alternative mechanism for performing the filer service (instead of sending a message to an application to ask it to do it).
Possible values are -
NSIdentity
The data to be filtered is simply placed upon the pasteboard without any transformation.
NSMapFile
The data to be filtered is the name of a file, which is loaded into memory and placed on the pasteboard without any transformation.
If the data to be filtered contains multiple file names, only the first is used.
NSUnixStdio
The data to be filtered is the name of a file, which is passed as the argument to a unix command-line program, and the standard output of that program is captured and placed on the pasteboard. The program is run each time data is requested, so this is inefficient in comparison to a filter implemented using the standard method (of sending a message to a running application).
If the data to be filtered contains multiple file names, only the first is used.

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.

Distributed Objects services

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]];

Software documentation for the NSObject(NSPasteboardReading) informal protocol

NSObject(NSPasteboardReading)

Declared in:
AppKit/NSPasteboard.h
Availability: MacOS-X 10.6.0

Description forthcoming.
Method summary

readingOptionsForType: pasteboard: 

+ (NSPasteboardReadingOptions) readingOptionsForType: (NSString*)type pasteboard: (NSPasteboard*)pasteboard;
Availability: MacOS-X 10.6.0

Description forthcoming.

initWithPasteboardPropertyList: ofType: 

- (id) initWithPasteboardPropertyList: (id)propertyList ofType: (NSString*)type;
Availability: MacOS-X 10.6.0

Description forthcoming.

Software documentation for the NSObject(NSPasteboardWriting) informal protocol

NSObject(NSPasteboardWriting)

Declared in:
AppKit/NSPasteboard.h
Availability: MacOS-X 10.6.0

Description forthcoming.
Method summary

writingOptionsForType: pasteboard: 

- (NSPasteboardWritingOptions) writingOptionsForType: (NSString*)type pasteboard: (NSPasteboard*)pasteboard;
Availability: MacOS-X 10.6.0

Description forthcoming.

Software documentation for the NSPasteboardReading protocol

NSPasteboardReading

Declared in:
AppKit/NSPasteboard.h
Conforms to:
NSObject
Availability: MacOS-X 10.6.0

Description forthcoming.
Method summary

readableTypesForPasteboard: 

+ (NSArray*) readableTypesForPasteboard: (NSPasteboard*)pasteboard;
Availability: MacOS-X 10.6.0

Description forthcoming.

Software documentation for the NSPasteboardWriting protocol

NSPasteboardWriting

Declared in:
AppKit/NSPasteboard.h
Conforms to:
NSObject
Availability: MacOS-X 10.6.0

Description forthcoming.
Method summary

pasteboardPropertyListForType: 

- (id) pasteboardPropertyListForType: (NSString*)type;
Availability: MacOS-X 10.6.0

Description forthcoming.

writableTypesForPasteboard: 

- (NSArray*) writableTypesForPasteboard: (NSPasteboard*)pasteboard;
Availability: MacOS-X 10.6.0

Description forthcoming.


Up