// // gui_ocamlmsgAppDelegate.m // gui-ocamlmsg // // Created by Tony Garnock-Jones on 2012-05-01. // Copyright 2012 n/a. All rights reserved. // #import "gui_ocamlmsgAppDelegate.h" #include #define HOP_STARTUP_DEADLINE_SECONDS 30 @implementation gui_ocamlmsgAppDelegate @synthesize window; @synthesize webview; - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { task = [NSTask new]; [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(mainWindowClosed:) name: NSWindowWillCloseNotification object: window]; [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(taskStatusChanged:) name: NSTaskDidTerminateNotification object: nil]; NSString *serverBinaryPath = [[NSBundle mainBundle] resourcePath]; [task setCurrentDirectoryPath: serverBinaryPath]; NSString *serverBinary = [serverBinaryPath stringByAppendingPathComponent: @"hop_server.native"]; [task setLaunchPath: serverBinary]; NSString *readyFile = [NSTemporaryDirectory() stringByAppendingPathComponent: @"hop.ready."]; readyFile = [readyFile stringByAppendingFormat: @"%d", getpid()]; char const *readyFileUtf8 = [readyFile UTF8String]; unlink(readyFileUtf8); [task setArguments: [NSArray arrayWithObjects: @"--ready-file", readyFile, nil]]; @try { [task launch]; } @catch (NSException *e) { NSLog(@"Could not launch server %@: %@", serverBinary, [e reason]); [NSApp terminate: self]; @throw; } int foundReadyFile = 0; time_t startTime = time(NULL); while ([task isRunning] && time(NULL) - startTime < HOP_STARTUP_DEADLINE_SECONDS) { struct stat s; if (lstat(readyFileUtf8, &s) != -1) { foundReadyFile = 1; break; } if (errno != ENOENT) { perror("lstat of readyFileUtf8"); exit(EXIT_FAILURE); } usleep(100000); } unlink(readyFileUtf8); if (!foundReadyFile) { NSLog(@"Server did not start up within %d seconds.", HOP_STARTUP_DEADLINE_SECONDS); [NSApp terminate: self]; return; } [[webview mainFrame] loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: @"http://localhost:5678/"]]]; } - (void) applicationWillTerminate: (NSNotification *) notification { if ([task isRunning]) { [task terminate]; } } - (void) taskStatusChanged: (NSNotification *) aNotification { [NSApp terminate: self]; } - (void) mainWindowClosed: (NSNotification *) aNotification { [NSApp terminate: self]; } @end