Last active
October 22, 2020 19:23
-
-
Save chockenberry/11235824 to your computer and use it in GitHub Desktop.
Pipe standard output to a running Cocoa app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' |
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
What's the problem?