Test ocaml's version
[llpp.git] / main_osx.m
blob958181ba72e130335dac5efd657fc8b28c04d5f2
1 #include <Cocoa/Cocoa.h>
2 #include <OpenGL/gl.h>
4 #define CAML_NAME_SPACE
6 #include <sys/types.h>
7 #include <sys/socket.h>
8 #include <pthread.h>
9 #include <string.h>
11 #include <caml/mlvalues.h>
12 #include <caml/memory.h>
13 #include <caml/callback.h>
14 #include <caml/alloc.h>
15 #include <caml/fail.h>
17 enum {
18   EVENT_EXPOSE = 1,
19   EVENT_RESHAPE = 3,
20   EVENT_MOUSE = 4,
21   EVENT_MOTION = 5,
22   EVENT_PMOTION = 6,
23   EVENT_KEYDOWN = 7,
24   EVENT_ENTER = 8,
25   EVENT_LEAVE = 9,
26   EVENT_WINSTATE = 10,
27   EVENT_QUIT = 11,
28   EVENT_SCROLL = 12,
29   EVENT_ZOOM = 13,
30   EVENT_OPEN = 20
33 enum {
34   BUTTON_LEFT = 1,
35   BUTTON_RIGHT = 3,
36   BUTTON_WHEEL_UP = 4,
37   BUTTON_WHEEL_DOWN = 5
40 static int terminating = 0;
41 static pthread_mutex_t terminate_mutex = PTHREAD_MUTEX_INITIALIZER;
42 static int server_fd = -1;
43 static CGFloat backing_scale_factor = -1.0;
45 #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 10120
47 #define NS_CRITICAL_ALERT_STYLE NSAlertStyleCritical
48 #define NS_FULL_SCREEN_WINDOW_MASK NSWindowStyleMaskFullScreen
49 #define NS_DEVICE_INDEPENDENT_MODIFIER_FLAGS_MASK NSEventModifierFlagDeviceIndependentFlagsMask
50 #define NS_FUNCTION_KEY_MASK NSEventModifierFlagFunction
51 #define NS_ALTERNATE_KEY_MASK NSEventModifierFlagOption
52 #define NS_COMMAND_KEY_MASK NSEventModifierFlagCommand
53 #define NS_CLOSABLE_WINDOW_MASK NSWindowStyleMaskClosable
54 #define NS_MINIATURIZABLE_WINDOW_MASK NSWindowStyleMaskMiniaturizable
55 #define NS_TITLED_WINDOW_MASK NSWindowStyleMaskTitled
56 #define NS_RESIZABLE_WINDOW_MASK NSWindowStyleMaskResizable
58 #else
60 #define NS_CRITICAL_ALERT_STYLE NSCriticalAlertStyle
61 #define NS_FULL_SCREEN_WINDOW_MASK NSFullScreenWindowMask
62 #define NS_DEVICE_INDEPENDENT_MODIFIER_FLAGS_MASK NSDeviceIndependentModifierFlagsMask
63 #define NS_FUNCTION_KEY_MASK NSFunctionKeyMask
64 #define NS_ALTERNATE_KEY_MASK NSAlternateKeyMask
65 #define NS_COMMAND_KEY_MASK NSCommandKeyMask
66 #define NS_CLOSABLE_WINDOW_MASK NSClosableWindowMask
67 #define NS_MINIATURIZABLE_WINDOW_MASK NSMiniaturizableWindowMask
68 #define NS_TITLED_WINDOW_MASK NSTitledWindowMask
69 #define NS_RESIZABLE_WINDOW_MASK NSResizableWindowMask
71 #endif
73 void Abort (NSString *format, ...)
75   va_list argList;
76   va_start (argList, format);
77   NSString *str = [[NSString alloc] initWithFormat:format arguments:argList];
78   va_end (argList);
79   NSLog (@"%@", str);
80   NSAlert *alert = [[NSAlert alloc] init];
81   [alert addButtonWithTitle:@"Quit"];
82   [alert setMessageText:@"Internal Error"];
83   [alert setInformativeText:str];
84   [alert setAlertStyle:NS_CRITICAL_ALERT_STYLE];
85   [alert runModal];
86   [NSApp terminate:nil];
89 void *caml_main_thread (void *argv)
91   @autoreleasepool {
92     caml_main (argv);
93     pthread_mutex_lock (&terminate_mutex);
94     if (terminating == 0) {
95       terminating = 1;
96       [NSApp performSelectorOnMainThread:@selector(terminate:)
97                               withObject:nil
98                            waitUntilDone:NO];
99     }
100     pthread_mutex_unlock (&terminate_mutex);
101   }
102   pthread_exit (NULL);
105 NSCursor *GetCursor (int idx)
107   static NSCursor *cursors[5];
108   static BOOL initialised = NO;
110   if (initialised == NO) {
111     cursors[0] = [NSCursor arrowCursor];
112     cursors[1] = [NSCursor pointingHandCursor];
113     cursors[2] = [NSCursor arrowCursor];
114     cursors[3] = [NSCursor closedHandCursor];
115     cursors[4] = [NSCursor IBeamCursor];
116     initialised = YES;
117   }
119   return cursors[idx];
122 @implementation NSWindow (CategoryNSWindow)
124 - (BOOL)isFullScreen
126   return ([self styleMask] & NS_FULL_SCREEN_WINDOW_MASK) == NS_FULL_SCREEN_WINDOW_MASK;
129 @end
131 @implementation NSView (CategoryNSView)
133 - (NSPoint)locationFromEvent:(NSEvent *)event
135   NSPoint point =
136     [self convertPointToBacking:[self convertPoint:[event locationInWindow] fromView:nil]];
137   NSRect bounds = [self convertRectToBacking:[self bounds]];
138   point.y = bounds.size.height - point.y;
139   return point;
142 - (NSRect)convertFrameToBacking
144   return [self convertRectToBacking:[self frame]];
147 @end
149 @implementation NSEvent (CategoryNSEvent)
151 - (int)deviceIndependentModifierFlags
153   return [self modifierFlags] & NS_DEVICE_INDEPENDENT_MODIFIER_FLAGS_MASK;
156 @end
158 @interface Connector : NSObject
160 - (instancetype)initWithFileDescriptor:(int)fd;
162 - (void)notifyReshapeWidth:(int)w height:(int)h;
163 - (void)notifyExpose;
164 - (void)keyDown:(uint32_t)key modifierFlags:(NSEventModifierFlags)mask;
165 - (void)notifyQuit;
166 - (void)mouseEntered:(NSPoint)loc;
167 - (void)mouseExited;
168 - (void)mouseMoved:(NSPoint)aPoint modifierFlags:(NSEventModifierFlags)flags;
169 - (void)mouseDown:(NSUInteger)buttons atPoint:(NSPoint)aPoint modifierFlags:(NSEventModifierFlags)flags;
170 - (void)mouseUp:(NSUInteger)buttons atPoint:(NSPoint)aPoint modifierFlags:(NSEventModifierFlags)flags;
171 @end
173 @implementation Connector
175   NSMutableData *data;
176   NSFileHandle *fileHandle;
179 - (instancetype)initWithFileDescriptor:(int)fd
181   self = [super init];
182   data = [NSMutableData dataWithLength:32];
183   fileHandle = [[NSFileHandle alloc] initWithFileDescriptor:fd];
184   return self;
187 - (void)setByte:(int8_t)b offset:(int)off
189   [data replaceBytesInRange:NSMakeRange (off, 1) withBytes:&b];
192 - (void)setShort:(int16_t)s offset:(int)off
194   [data replaceBytesInRange:NSMakeRange (off, 2) withBytes:&s];
197 - (void)setInt:(int32_t)n offset:(int)off
199   [data replaceBytesInRange:NSMakeRange (off, 4) withBytes:&n];
202 - (void)writeData
204   [fileHandle writeData:data];
207 - (void)notifyReshapeWidth:(int)w height:(int)h
209   [self setByte:EVENT_RESHAPE offset:0];
210   [self setShort:w offset:16];
211   [self setShort:h offset:18];
212   [self writeData];
215 - (void)notifyExpose
217   [self setByte:EVENT_EXPOSE offset:0];
218   [self writeData];
221 - (void)keyDown:(uint32_t)key modifierFlags:(NSEventModifierFlags)mask
223   [self setByte:EVENT_KEYDOWN offset:0];
224   [self setInt:key offset:16];
225   [self setInt:mask offset:20];
226   [self writeData];
229 - (void)notifyWinstate:(BOOL)fullScreen
231   [self setByte:EVENT_WINSTATE offset:0];
232   [self setInt:fullScreen offset:16];
233   [self writeData];
236 - (void)notifyQuit
238   [self setByte:EVENT_QUIT offset:0];
239   [self writeData];
242 - (void)mouseEntered:(NSPoint)loc
244   [self setByte:EVENT_ENTER offset:0];
245   [self setShort:loc.x offset:16];
246   [self setShort:loc.y offset:20];
247   [self writeData];
250 - (void)mouseExited
252   [self setByte:EVENT_LEAVE offset:0];
253   [self writeData];
256 - (void)mouseDragged:(NSPoint)aPoint modifierFlags:(NSEventModifierFlags)flags
258   [self setByte:EVENT_MOTION offset:0];
259   [self setShort:aPoint.x offset:16];
260   [self setShort:aPoint.y offset:20];
261   [self setInt:flags offset:24];
262   [self writeData];
265 - (void)mouseMoved:(NSPoint)aPoint modifierFlags:(NSEventModifierFlags)flags
267   [self setByte:EVENT_PMOTION offset:0];
268   [self setShort:aPoint.x offset:16];
269   [self setShort:aPoint.y offset:20];
270   [self setInt:flags offset:24];
271   [self writeData];
274 - (void)mouseDown:(NSUInteger)buttons atPoint:(NSPoint)aPoint modifierFlags:(NSEventModifierFlags)flags
276   [self setByte:EVENT_MOUSE offset:0];
277   [self setShort:1 offset:10];
278   [self setInt:buttons offset:12];
279   [self setShort:aPoint.x offset:16];
280   [self setShort:aPoint.y offset:20];
281   [self setInt:flags offset:24];
282   [self writeData];
285 - (void)mouseUp:(NSUInteger)buttons atPoint:(NSPoint)aPoint modifierFlags:(NSEventModifierFlags)flags
287   [self setByte:EVENT_MOUSE offset:0];
288   [self setShort:0 offset:10];
289   [self setInt:buttons offset:12];
290   [self setShort:aPoint.x offset:16];
291   [self setShort:aPoint.y offset:20];
292   [self setInt:flags offset:24];
293   [self writeData];
296 - (void)scrollByDeltaX:(CGFloat)deltaX deltaY:(CGFloat)deltaY
298   [self setByte:EVENT_SCROLL offset:0];
299   [self setInt:(int32_t) deltaX offset:16];
300   [self setInt:(int32_t) deltaY offset:20];
301   [self writeData];
304 - (void)zoom:(CGFloat)z at:(NSPoint)p
306   [self setByte:EVENT_ZOOM offset:0];
307   [self setInt:(int32_t) (z * 1000) offset:16];
308   [self setShort:p.x offset:20];
309   [self setShort:p.y offset:22];
310   [self writeData];
313 - (void)openFile:(NSString *)filename
315   const char *utf8 = [filename UTF8String];
316   unsigned len = [filename lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
317   [self setByte:EVENT_OPEN offset:0];
318   unsigned off = 0;
319   unsigned data_len = [data length] - 4;
320   while (off < len) {
321     unsigned chunk_len = MIN (data_len - 4, len - off);
322     [self setShort:chunk_len offset:2];
323     [data replaceBytesInRange:NSMakeRange (4, chunk_len) withBytes:(utf8 + off)];
324     [self writeData];
325     off += chunk_len;
326   }
327   [self setShort:0 offset:2];
328   [self writeData];
331 @end
333 @interface MyDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>
335 - (int)getw;
336 - (int)geth;
337 - (void)swapb;
338 - (void)applicationWillFinishLaunching:(NSNotification *)not;
339 - (void)applicationDidFinishLaunching:(NSNotification *)not;
340 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication;
341 - (void)makeCurrentContext;
343 @end
345 @interface MyWindow : NSWindow
347 @end
349 @interface MyView : NSView
351   Connector *connector;
352   NSCursor *cursor;
355 - (instancetype)initWithFrame:(NSRect)frame connector:(Connector *)aConnector;
356 - (void)setCursor:(NSCursor *)aCursor;
358 @end
360 @implementation MyView
362 - (instancetype)initWithFrame:(NSRect)frame connector:(Connector *)aConnector
364   self = [super initWithFrame:frame];
366   if (self != NULL) {
367     connector = aConnector;
368     cursor = [NSCursor arrowCursor];
369     self.acceptsTouchEvents = YES;
370   }
372   return self;
375 - (void)setCursor:(NSCursor *)aCursor
377   cursor = aCursor;
380 -(void)resetCursorRects
382   [self addCursorRect:[self bounds] cursor:cursor];
385 - (void)drawRect:(NSRect)bounds
387   // NSLog(@"drawRect: %@", [NSValue valueWithRect:bounds]);
388   [connector notifyExpose];
391 - (void)viewWillMoveToWindow:(NSWindow *)newWindow {
392   NSTrackingArea* trackingArea = [[NSTrackingArea alloc]
393                                    initWithRect:[self bounds]
394                                  options:(NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp | NSTrackingInVisibleRect)
395                                           owner:self
396                                        userInfo:nil];
397   [self addTrackingArea:trackingArea];
400 - (void)keyDown:(NSEvent *)event
402   // int key = [event keyCode];
403   NSEventModifierFlags mask = [event deviceIndependentModifierFlags];
404   NSString *chars = [event charactersIgnoringModifiers];
405   const uint32_t *c = (uint32_t *) [chars cStringUsingEncoding:NSUTF32LittleEndianStringEncoding];
406   while (*c) {
407     if (*c == 0x7f && !(mask & NS_FUNCTION_KEY_MASK)) {
408       [connector keyDown:0x8 modifierFlags:mask];
409     } else {
410       [connector keyDown:*c modifierFlags:mask];
411     }
412     c++;
413   }
416 - (void)flagsChanged:(NSEvent *)event
418   NSEventModifierFlags mask = [event deviceIndependentModifierFlags];
419   NSLog (@"flagsChanged: 0x%lx", mask);
420   if (mask != 0) {
421     [connector keyDown:0 modifierFlags:mask];
422   }
425 - (void)mouseDown:(NSEvent *)event
427   [connector mouseDown:BUTTON_LEFT
428                atPoint:[self locationFromEvent:event]
429          modifierFlags:[event deviceIndependentModifierFlags]];
432 - (void)mouseUp:(NSEvent *)event
434   [connector mouseUp:BUTTON_LEFT
435              atPoint:[self locationFromEvent:event]
436        modifierFlags:[event deviceIndependentModifierFlags]];
439 - (void)rightMouseDown:(NSEvent *)event
441   [connector mouseDown:BUTTON_RIGHT
442                atPoint:[self locationFromEvent:event]
443          modifierFlags:[event deviceIndependentModifierFlags]];
446 - (void)rightMouseUp:(NSEvent *)event
448   [connector mouseUp:BUTTON_RIGHT
449              atPoint:[self locationFromEvent:event]
450        modifierFlags:[event deviceIndependentModifierFlags]];
453 - (void)rightMouseDragged:(NSEvent *)event
455   [connector mouseDragged:[self locationFromEvent:event]
456             modifierFlags:[event deviceIndependentModifierFlags]];
459 - (void)mouseDragged:(NSEvent *)event
461   [connector mouseDragged:[self locationFromEvent:event]
462             modifierFlags:[event deviceIndependentModifierFlags]];
465 - (void)mouseMoved:(NSEvent *)event
467   [connector mouseMoved:[self locationFromEvent:event]
468           modifierFlags:[event deviceIndependentModifierFlags]];
471 - (void)mouseEntered:(NSEvent *)event
473   [connector mouseEntered:[self locationFromEvent:event]];
476 - (void)mouseExited:(NSEvent *)event
478   [connector mouseExited];
481 - (void)scrollWheel:(NSEvent *)event
483   CGFloat deltaX = [event scrollingDeltaX];
484   CGFloat deltaY = -[event scrollingDeltaY];
486   if ([event hasPreciseScrollingDeltas]) {
487     [connector scrollByDeltaX:(backing_scale_factor * deltaX)
488                        deltaY:(backing_scale_factor * deltaY)];
489   } else {
490     NSPoint loc = [self locationFromEvent:event];
491     NSEventModifierFlags mask = [event deviceIndependentModifierFlags];
492     if (deltaY > 0.0) {
493       [connector mouseDown:BUTTON_WHEEL_DOWN atPoint:loc modifierFlags:mask];
494       [connector mouseUp:BUTTON_WHEEL_DOWN atPoint:loc modifierFlags:mask];
495     } else if (deltaY < 0.0) {
496       [connector mouseDown:BUTTON_WHEEL_UP atPoint:loc modifierFlags:mask];
497       [connector mouseUp:BUTTON_WHEEL_UP atPoint:loc modifierFlags:mask];
498     }
499   }
502 - (void)magnifyWithEvent:(NSEvent *)event
504   [connector zoom:[event magnification] at:[self locationFromEvent:event]];
507 @end
509 @implementation MyWindow
511 - (BOOL)canBecomeKeyWindow
513   return YES;
516 @end
518 @implementation MyDelegate
520   char **argv;
521   MyWindow *window;
522   NSOpenGLContext *glContext;
523   pthread_t thread;
524   Connector *connector;
527 - (instancetype)initWithArgv:(char **)theArgv fileDescriptor:(int)fd
529   self = [super init];
530   if (self != NULL) {
531     argv = theArgv;
532     connector = [[Connector alloc] initWithFileDescriptor:fd];
533   }
534   return self;
537 - (void)setTitle:(NSString *)title
539   [window setTitle:title];
542 - (void)mapwin
544   [window makeKeyAndOrderFront:self];
547 - (int)getw
549   return [[window contentView] convertFrameToBacking].size.width;
552 - (int)geth
554   return [[window contentView] convertFrameToBacking].size.height;
557 - (void)applicationWillFinishLaunching:(NSNotification *)not
559   NSLog(@"applicationWillFinishLaunching");
560   id menubar = [NSMenu new];
561   id appMenuItem = [NSMenuItem new];
562   id fileMenuItem = [NSMenuItem new];
563   id windowMenuItem = [NSMenuItem new];
564   id helpMenuItem = [NSMenuItem new];
565   [menubar addItem:appMenuItem];
566   [menubar addItem:fileMenuItem];
567   [menubar addItem:windowMenuItem];
568   [menubar addItem:helpMenuItem];
569   [NSApp setMainMenu:menubar];
570   id appMenu = [NSMenu new];
571   id appName = [[NSProcessInfo processInfo] processName];
572   id aboutMenuItem = [[NSMenuItem alloc] initWithTitle:[@"About " stringByAppendingString:appName]
573                                                 action:@selector(orderFrontStandardAboutPanel:)
574                                          keyEquivalent:@""];
575   id hideMenuItem = [[NSMenuItem alloc] initWithTitle:[@"Hide " stringByAppendingString:appName]
576                                                action:@selector(hide:)
577                                         keyEquivalent:@"h"];
578   id hideOthersMenuItem = [[NSMenuItem alloc] initWithTitle:@"Hide Others"
579                                                      action:@selector(hideOtherApplications:)
580                                               keyEquivalent:@"h"];
581   [hideOthersMenuItem setKeyEquivalentModifierMask:(NS_ALTERNATE_KEY_MASK | NS_COMMAND_KEY_MASK)];
582   id showAllMenuItem = [[NSMenuItem alloc] initWithTitle:@"Show All"
583                                                   action:@selector(unhideAllApplications:)
584                                            keyEquivalent:@""];
585   id quitMenuItem = [[NSMenuItem alloc] initWithTitle:[@"Quit " stringByAppendingString:appName]
586                                                action:@selector(terminate:)
587                                         keyEquivalent:@"q"];
588   [appMenu addItem:aboutMenuItem];
589   [appMenu addItem:[NSMenuItem separatorItem]];
590   [appMenu addItem:hideMenuItem];
591   [appMenu addItem:hideOthersMenuItem];
592   [appMenu addItem:showAllMenuItem];
593   [appMenu addItem:[NSMenuItem separatorItem]];
594   [appMenu addItem:quitMenuItem];
595   [appMenuItem setSubmenu:appMenu];
597   id fileMenu = [[NSMenu alloc] initWithTitle:@"File"];
598   id openMenuItem = [[NSMenuItem alloc] initWithTitle:@"Open..."
599                                                action:@selector(openDocument:)
600                                         keyEquivalent:@"o"];
601   id closeMenuItem = [[NSMenuItem alloc] initWithTitle:@"Close"
602                                                 action:@selector(performClose:)
603                                          keyEquivalent:@"w"];
604   [fileMenu addItem:openMenuItem];
605   [fileMenu addItem:[NSMenuItem separatorItem]];
606   [fileMenu addItem:closeMenuItem];
607   [fileMenuItem setSubmenu:fileMenu];
609   id windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
610   id miniaturizeMenuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize"
611                                                    action:@selector(performMiniaturize:)
612                                             keyEquivalent:@"m"];
613   id zoomMenuItem = [[NSMenuItem alloc] initWithTitle:@"Zoom"
614                                                action:@selector(performZoom:)
615                                         keyEquivalent:@""];
617   [windowMenu addItem:miniaturizeMenuItem];
618   [windowMenu addItem:zoomMenuItem];
619   [windowMenuItem setSubmenu:windowMenu];
621   id helpMenu = [[NSMenu alloc] initWithTitle:@"Help"];
622   id reportIssueMenuItem = [[NSMenuItem alloc] initWithTitle:@"Report an issue..."
623                                                       action:@selector(reportIssue:)
624                                                keyEquivalent:@""];
625   [helpMenu addItem:reportIssueMenuItem];
626   [helpMenuItem setSubmenu:helpMenu];
628   window = [[MyWindow alloc] initWithContentRect:NSMakeRect(0, 0, 400, 400)
629                                        styleMask:(NS_CLOSABLE_WINDOW_MASK | NS_MINIATURIZABLE_WINDOW_MASK | NS_TITLED_WINDOW_MASK | NS_RESIZABLE_WINDOW_MASK)
630                                          backing:NSBackingStoreBuffered
631                                            defer:NO];
633   [window center];
634   [window setAcceptsMouseMovedEvents:YES];
635   [window setDelegate:self];
638   [[NSNotificationCenter defaultCenter] addObserver:self
639                                            selector:@selector(didEnterFullScreen)
640                                                name:NSWindowDidEnterFullScreenNotification
641                                              object:window];
642   [[NSNotificationCenter defaultCenter] addObserver:self
643                                            selector:@selector(didExitFullScreen)
644                                                name:NSWindowDidExitFullScreenNotification
645                                              object:window];
647   MyView *myView = [[MyView alloc] initWithFrame:[[window contentView] bounds]
648                                        connector:connector];
650   [window setContentView:myView];
651   [window makeFirstResponder:myView];
653   [myView setWantsBestResolutionOpenGLSurface:YES];
655   NSOpenGLPixelFormatAttribute attrs[] =
656     {
657       NSOpenGLPFAAccelerated,
658       NSOpenGLPFADoubleBuffer,
659       NSOpenGLPFAColorSize, 24,
660       NSOpenGLPFAAlphaSize, 8,
661       NSOpenGLPFADepthSize, 24,
662       0
663     };
664   NSOpenGLPixelFormat *pixFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
665   glContext = [[NSOpenGLContext alloc] initWithFormat:pixFormat shareContext:nil];
666   GLint swapInt = 1;
667   [glContext setValues:&swapInt forParameter:NSOpenGLCPSwapInterval];
668   [glContext setView:myView];
670   backing_scale_factor = [window backingScaleFactor];
673 - (void)reshape:(NSValue *)val
675   // NSLog (@"reshape: %@ isFullScreen: %d", val, [window isFullScreen]);
676   if ([window isFullScreen]) {
677     [window toggleFullScreen:self];
678   }
679   [window setFrame:[window frameRectForContentRect:[val rectValue]]
680            display:YES];
683 - (void)makeCurrentContext
685   [glContext makeCurrentContext];
686   NSLog (@"OpenGL Version: %s", glGetString(GL_VERSION));
689 - (void)swapb
691   [glContext flushBuffer];
694 - (void)didEnterFullScreen
696   // NSLog (@"didEnterFullScreen: %d", [window isFullScreen]);
697   [connector notifyWinstate:YES];
700 - (void)didExitFullScreen
702   // NSLog (@"didExitFullScreen: %d", [window isFullScreen]);
703   [connector notifyWinstate:NO];
706 - (void)fullscreen
708   // NSLog (@"fullscreen: %d", [window isFullScreen]);
709   if ([window isFullScreen] == NO) {
710     [window toggleFullScreen:self];
711   }
714 - (void)setCursor:(NSCursor *)aCursor
716   [[window contentView] setCursor: aCursor];
717   [window invalidateCursorRectsForView:[window contentView]];
720 - (void)windowDidResize:(NSNotification *)notification
722   [glContext update];
723   NSRect frame = [[window contentView] convertFrameToBacking];
724   [connector notifyReshapeWidth:frame.size.width height:frame.size.height];
727 - (void)windowDidMove:(NSNotification *)notification
729   [glContext update];
732 - (void)applicationWillTerminate:(NSDictionary *)userInfo
734   pthread_mutex_lock (&terminate_mutex);
735   if (terminating == 0) {
736     terminating = 1;
737     [connector notifyQuit];
738   }
739   pthread_mutex_unlock (&terminate_mutex);
740   pthread_join (thread, NULL);
743 - (void)windowDidChangeOcclusionState:(NSNotification *)notification
747 - (void)applicationDidFinishLaunching:(NSNotification *)not
749   NSLog(@"applicationDidFinishLaunching");
750   int ret = pthread_create (&thread, NULL, caml_main_thread, argv);
751   if (ret != 0) {
752     Abort (@"pthread_create: %s.", strerror (ret));
753   }
756 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
758   return YES;
761 - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
763   NSLog (@"openFile: %@", filename);
764   [connector openFile:filename];
765   return YES;
768 - (void)openDocument:(id)sender
770   NSOpenPanel *openPanel = [NSOpenPanel openPanel];
771   [openPanel beginSheetModalForWindow:window
772                     completionHandler:^(NSInteger result){
773       if (result == NSFileHandlingPanelOKButton) {
774          NSString *filename = [[[openPanel URLs] objectAtIndex:0] path];
775          if (filename != nil) {
776            [self application:NSApp openFile:filename];
777          }
778       }
779     }];
782 - (void)reportIssue:(id)sender
784   [[NSWorkspace sharedWorkspace]
785     openURL:[NSURL URLWithString:@"https://github.com/moosotc/llpp/issues"]];
788 @end
790 CAMLprim value ml_mapwin (value unit)
792   CAMLparam1 (unit);
793   [(MyDelegate *)[NSApp delegate] performSelectorOnMainThread:@selector(mapwin)
794                                                    withObject:nil
795                                                 waitUntilDone:YES];
796   CAMLreturn (Val_unit);
799 CAMLprim value ml_swapb (value unit)
801   CAMLparam1 (unit);
802   [(MyDelegate *)[NSApp delegate] swapb];
803   CAMLreturn (Val_unit);
806 CAMLprim value ml_getw (value unit)
808   return Val_int([(MyDelegate *)[NSApp delegate] getw]);
811 CAMLprim value ml_geth (value unit)
813   return Val_int([(MyDelegate *)[NSApp delegate] geth]);
816 CAMLprim value ml_makecurrentcontext (value unit)
818   CAMLparam1 (unit);
819   [(MyDelegate *)[NSApp delegate] makeCurrentContext];
820   CAMLreturn (Val_unit);
823 CAMLprim value ml_settitle (value title)
825   CAMLparam1 (title);
826   NSString *str = [NSString stringWithUTF8String:String_val(title)];
827   [(MyDelegate *)[NSApp delegate] performSelectorOnMainThread:@selector(setTitle:)
828                                                    withObject:str
829                                                 waitUntilDone:YES];
830   CAMLreturn (Val_unit);
833 CAMLprim value ml_reshape (value w, value h)
835   CAMLparam2 (w, h);
836   NSRect r = NSMakeRect (0, 0, Int_val (w), Int_val (h));
837   [(MyDelegate *)[NSApp delegate] performSelectorOnMainThread:@selector(reshape:)
838                                                    withObject:[NSValue valueWithRect:r]
839                                                 waitUntilDone:YES];
840   CAMLreturn (Val_unit);
843 CAMLprim value ml_fullscreen (value unit)
845   CAMLparam1 (unit);
846   [(MyDelegate *)[NSApp delegate] performSelectorOnMainThread:@selector(fullscreen)
847                                                    withObject:nil
848                                                 waitUntilDone:YES];
849   CAMLreturn (Val_unit);
852 CAMLprim value ml_setcursor (value curs)
854   CAMLparam1 (curs);
855   // NSLog (@"ml_setcursor: %d", Int_val (curs));
856   NSCursor *cursor = GetCursor (Int_val (curs));
857   [(MyDelegate *)[NSApp delegate] performSelectorOnMainThread:@selector(setCursor:)
858                                                    withObject:cursor
859                                                 waitUntilDone:YES];
860   CAMLreturn (Val_unit);
863 CAMLprim value ml_get_server_fd (value unit)
865   CAMLparam1 (unit);
866   CAMLreturn (Val_int (server_fd));
869 CAMLprim value ml_get_backing_scale_factor (value unit)
871   CAMLparam1 (unit);
872   CAMLreturn (Val_int ((int) backing_scale_factor));
875 CAMLprim value ml_nslog (value str)
877   CAMLparam1 (str);
878   NSLog (@"%s", String_val (str));
879   CAMLreturn (Val_unit);
882 // HACK to eliminate arg injected by OS X -psn_...
883 int adjust_argv (int argc, char **argv)
885   if (argc > 1 && strncmp (argv[1], "-psn", 4) == 0) {
886     for (unsigned i = 1; i < argc - 1; i ++) {
887       argv[i] = argv[i+1];
888     }
889     argv[-- argc] = 0;
890   }
891   for (int i = 0; i < argc; i ++) {
892     NSLog (@"arg %d: %s", i, argv[i]);
893   }
894   return argc;
897 int main(int argc, char **argv)
899   @autoreleasepool {
900     int sv[2];
901     int ret = socketpair (AF_UNIX, SOCK_STREAM, 0, sv);
902     if (ret != 0) {
903       Abort (@"socketpair: %s", strerror (errno));
904     }
905     // NSLog (@"socketpair sv0 %d sv1 %d", sv[0], sv[1]);
906     server_fd = sv[0];
907     argc = adjust_argv (argc, argv);
908     [NSApplication sharedApplication];
909     [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
910     id delegate = [[MyDelegate alloc] initWithArgv:argv fileDescriptor:sv[1]];
911     [NSApp setDelegate:delegate];
912     [NSApp activateIgnoringOtherApps:YES];
913     [NSApp run];
914   }
915   return EXIT_SUCCESS;