BlueGit

timfa posprint

Files

posprint / packaging / macos / launcher.m

launcher.m

launcher.m 2.4 KiB Download Raw
1#import <Cocoa/Cocoa.h>
2#include <spawn.h>
3#include <stdlib.h>
4#include <unistd.h>
5
6extern char **environ;
7
8@interface AppDelegate : NSObject <NSApplicationDelegate>
9@property (nonatomic, assign) BOOL handledOpen;
10@end
11
12@implementation AppDelegate
13
14- (void)spawnPosprintWithArg:(NSString *)arg {
15 NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
16 NSString *binPath = [bundlePath stringByAppendingPathComponent:@"Contents/MacOS/posprint-bin"];
17 const char *bin = [binPath fileSystemRepresentation];
18
19 pid_t pid;
20 if (arg != nil) {
21 const char *cArg = [arg UTF8String];
22 char *const argv[] = { (char *)bin, (char *)cArg, NULL };
23 posix_spawn(&pid, bin, NULL, NULL, argv, environ);
24 } else {
25 char *const argv[] = { (char *)bin, NULL };
26 posix_spawn(&pid, bin, NULL, NULL, argv, environ);
27 }
28}
29
30- (void)application:(NSApplication *)application openURLs:(NSArray<NSURL *> *)urls {
31 self.handledOpen = YES;
32 for (NSURL *url in urls) {
33 if ([url isFileURL]) {
34 [self spawnPosprintWithArg:[url path]];
35 } else {
36 [self spawnPosprintWithArg:[url absoluteString]];
37 }
38 }
39 _exit(0);
40}
41
42- (void)applicationDidFinishLaunching:(NSNotification *)notification {
43 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(80 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
44 if (!self.handledOpen) {
45 [self spawnPosprintWithArg:nil];
46 }
47 _exit(0);
48 });
49}
50
51@end
52
53int main(int argc, const char * argv[]) {
54 @autoreleasepool {
55 if (argc > 1) {
56 NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
57 NSString *binPath = [bundlePath stringByAppendingPathComponent:@"Contents/MacOS/posprint-bin"];
58 const char *bin = [binPath fileSystemRepresentation];
59 char **newArgv = calloc((size_t)argc + 1, sizeof(char *));
60 newArgv[0] = (char *)bin;
61 for (int i = 1; i < argc; i++) {
62 newArgv[i] = (char *)argv[i];
63 }
64 newArgv[argc] = NULL;
65 pid_t pid;
66 posix_spawn(&pid, bin, NULL, NULL, newArgv, environ);
67 free(newArgv);
68 return 0;
69 }
70 NSApplication *app = [NSApplication sharedApplication];
71 AppDelegate *delegate = [[AppDelegate alloc] init];
72 [app setDelegate:delegate];
73 [app run];
74 }
75 return 0;
76}