Skip to content

Instantly share code, notes, and snippets.

@chockenberry
Last active October 22, 2020 19:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chockenberry/11235824 to your computer and use it in GitHub Desktop.
Save chockenberry/11235824 to your computer and use it in GitHub Desktop.
Pipe standard output to a running Cocoa app
1) Create a script named '~/bin/xscope':
#!/bin/sh
parameter=""
if [ -z "$1" ]; then
parameter=`cat /dev/stdin`
else
parameter="$1"
fi
if [ ! -z "$parameter" ]; then
open "xscope://text/$parameter"
fi
2) In the Cocoa app, register for the AppleEvent sent by 'open' when the application delegate starts up:
- (void)setUpEventHandlerForURL
{
[[NSAppleEventManager sharedAppleEventManager] setEventHandler:self
andSelector:@selector(getURLFromEvent:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
}
3) Handle the URL event:
- (void)getURLFromEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
NSString *URLString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
NSURL *URL = [NSURL URLWithString:URLString];
if ([[URL host] isEqualToString:@"text"]) {
NSString *path = [URL path];
if (path && [path length] > 0) {
NSString *encodedParameter = [path substringFromIndex:1];
NSString *textParameter = [encodedParameter stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
DebugLog(@"textParameter = %@", textParameter);
}
}
}
4) Finally, add this to your Info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>xScope URL scheme</string>
<key>CFBundleURLSchemes</key>
<array>
<string>xscope</string>
</array>
</dict>
</array>
5) Now pipe output to the app using:
$ cal | ~/bin/xscope
or by using a parameter:
$ ~/bin/xscope $'\xf0\x9f\x8d\x94'
@JensAyton
Copy link

Please don’t use scheme:// for non-RFC 1808 URI schemes.

@chockenberry
Copy link
Author

What's the problem?

@JensAyton
Copy link

The use of :// is conventionally reserved for URIs that take the form <scheme>://<net_loc>/<path>;<params>?<query>#<fragment>. The // serves no other purpose than to signify that the scheme conforms to that pattern. To keep generic tools – like NSURL – working as intended, use scheme:foo without // for URIs that don’t.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment