问题
[1] When I select and right-click any text in any app, I get a Services
menu where I can click to invoke any service like Search With Google
.
After clicking, a NSPasteboard
object is automatically sent to the service containing the selected text.
[2] 3rd party apps can use the BOOL NSPerformService ( NSString *itemName, NSPasteboard *pboard )
function to programatically invoke any service.
Here the app has to set the NSPasteboard
object, which is sent to the service.
Is there a way to programatically invoke any service, but without setting the NSPasteboard
object (the NSPasteboard
object should automatically contain the selected text like in [1]) ?
How is the NSPasteboard
object containing selected text sent to the service by OS X in [1]? Is there some private API?
回答1:
This is documented in the Services Implementation Guide, in particular the Using Services chapter.
First, when the user opens the Services menu, Cocoa calls -validRequestorForSendType:returnType:
on the objects in the responder chain to determine which combinations of send type and return type can be handled by which object, if any, based on its current state (e.g. the current selection). That controls which Services menu items are enabled.
When the user selects a service menu item, Cocoa creates a pasteboard and calls -writeSelectionToPasteboard:types:
on the requestor object returned by -validRequestorForSendType:returnType:
. That object should put the selection data on the provided pasteboard in whichever of the types it supports.
Cocoa then passes the pasteboard off to the system. The system communicates with Cocoa in the service provider process. Cocoa invokes -<messageName>:userData:error:
on the service provider object in that process, where <messageName>
comes from the description of the service in that app's Info.plist file. The service provider object is whatever the app registered with Cocoa using NSRegisterServicesProvider()
.
The service provider processes the input data, if any, from the pasteboard and stores the return data, if any, to it.
After the provider is done, Cocoa in the original app calls -readSelectionFromPasteboard:
on the requestor object. Again, the pasteboard is provided to that method.
来源:https://stackoverflow.com/questions/28786776/how-does-right-clicking-text-and-selecting-a-service-work