Debian Codegraph @

garglk/launchmac.mm

raw
1 // Copyright (C) 2010 by Ben Cressey.
2 //
3 // This file is part of Gargoyle.
4 //
5 // Gargoyle is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // Gargoyle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Gargoyle; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 #include "format.h"
20
21 #include "garglk.h"
22 #include "garversion.h"
23 #include "launcher.h"
24
25 #include <cstdlib>
26 #include <sstream>
27 #include <string>
28 #include <unordered_map>
29
30 #import <Cocoa/Cocoa.h>
31 #import <OpenGL/gl.h>
32 #import <OpenGL/glu.h>
33 #include <libproc.h>
34 #include <unistd.h>
35 #import "sysmac.h"
36
37 static const char *AppName = "Gargoyle " GARGOYLE_VERSION;
38
39 // Qt's origin is the top-left, but Mac's is bottom left, so translate,
40 // since the config format is determined by Qt.
41 static int coord_flip(NSWindow *window)
42 {
43 auto screen_height = [NSScreen mainScreen].frame.size.height;
44 auto content = [NSWindow contentRectForFrameRect: window.frame styleMask: window.styleMask];
45 return screen_height - content.size.height;
46 }
47
48 static const std::unordered_map<FileFilter, std::string> winfilters = {
49 {FileFilter::Save, "glksave"},
50 {FileFilter::Text, "txt"},
51 {FileFilter::Data, "glkdata"},
52 };
53
54 @interface GargoyleView : NSOpenGLView
55 {
56 GLuint output;
57 unsigned int textureWidth;
58 unsigned int textureHeight;
59 }
60
61 @property (retain) NSColor *backgroundColor;
62
63 - (void) addFrame: (NSData *) frame
64 width: (unsigned int) width
65 height: (unsigned int) height;
66
67 - (void) drawRect: (NSRect) bounds;
68 - (void) reshape;
69 @end;
70
71 @implementation GargoyleView
72
73 - (void) addFrame: (NSData *) frame
74 width: (unsigned int) width
75 height: (unsigned int) height
76 {
77 [[self openGLContext] makeCurrentContext];
78
79 // allocate new texture
80 glDeleteTextures(1, &output);
81 glGenTextures(1, &output);
82
83 // bind target to texture
84 glEnable(GL_TEXTURE_RECTANGLE_ARB);
85 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, output);
86
87 // set target parameters
88 glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_STORAGE_HINT_APPLE, GL_STORAGE_CACHED_APPLE);
89 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
90
91 // create texture from data
92 glTexImage2D(GL_TEXTURE_RECTANGLE_ARB,
93 0, GL_RGB8, width, height, 0, GL_RGB,
94 GL_UNSIGNED_BYTE,
95 [frame bytes]);
96 textureWidth = width;
97 textureHeight = height;
98 }
99
100 - (id) initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat *)format
101 {
102 self = [super initWithFrame: frameRect pixelFormat: format];
103 if (self) {
104 self.backgroundColor = [NSColor colorWithCalibratedRed: 1.0f green: 1.0f blue: 1.0f alpha: 1.0f];
105 }
106 return self;
107 }
108
109 - (void) drawRect: (NSRect) bounds
110 {
111 if (textureHeight == 0) {
112 return;
113 }
114
115 [[self openGLContext] makeCurrentContext];
116
117 float viewScalingFactor = [self.window backingScaleFactor] / BACKING_SCALE_FACTOR;
118 glViewport(0.0, 0.0, textureWidth * viewScalingFactor, textureHeight * viewScalingFactor);
119
120 NSColor *clearColor = self.backgroundColor;
121 glClearColor([clearColor redComponent], [clearColor greenComponent], [clearColor blueComponent], [clearColor alphaComponent]);
122 glClear(GL_COLOR_BUFFER_BIT);
123
124 glBegin(GL_QUADS);
125 {
126 glTexCoord2f(0.0f, textureHeight);
127 glVertex2f(-1.0f, -1.0f);
128
129 glTexCoord2f(textureWidth, textureHeight);
130 glVertex2f(1.0f, -1.0f);
131
132 glTexCoord2f(textureWidth, 0);
133 glVertex2f(1.0f, 1.0f);
134
135 glTexCoord2f(0.0f, 0);
136 glVertex2f(-1.0f, 1.0f);
137 }
138 glEnd();
139
140 glFlush();
141 }
142
143 - (void)reshape
144 {
145 }
146
147 @end
148
149 @interface GargoyleWindow : NSWindow
150 {
151 NSMutableArray *eventlog;
152 NSTextView *textbuffer;
153 pid_t processID;
154 NSTimeInterval lastMouseMove;
155 }
156 - (id) initWithContentRect: (NSRect) contentRect
157 styleMask: (unsigned int) windowStyle
158 backing: (NSBackingStoreType) bufferingType
159 defer: (BOOL) deferCreation
160 process: (pid_t) pid
161 backgroundColor: (NSColor *) backgroundColor;
162 - (void) sendEvent: (NSEvent *) event;
163 - (NSEvent *) retrieveEvent;
164 - (void) sendChars: (NSEvent *) event;
165 - (NSString *) retrieveChars;
166 - (void) clearChars;
167 - (IBAction) cut: (id) sender;
168 - (IBAction) copy: (id) sender;
169 - (IBAction) paste: (id) sender;
170 - (void) moveWordBackward: (id) sender;
171 - (void) moveWordForward: (id) sender;
172 - (IBAction) performZoom: (id) sender;
173 - (void) saveWindows;
174 - (void) performRefresh: (NSNotification *) notice;
175 - (void) performMove: (NSNotification *) notice;
176 - (NSString *) openFileDialog: (NSString *) prompt
177 fileFilter: (FileFilter) filter
178 savedir: (NSString *) savedir;
179 - (NSString *) saveFileDialog: (NSString *) prompt
180 fileFilter: (FileFilter) filter
181 savedir: (NSString *) savedir;
182 - (pid_t) retrieveID;
183 - (void) quit;
184 @end
185
186 @implementation GargoyleWindow
187
188 - (id) initWithContentRect: (NSRect) contentRect
189 styleMask: (unsigned int) windowStyle
190 backing: (NSBackingStoreType) bufferingType
191 defer: (BOOL) deferCreation
192 process: (pid_t) pid
193 backgroundColor: (NSColor *) backgroundColor
194 {
195 self = [super initWithContentRect: contentRect
196 styleMask: windowStyle
197 backing: bufferingType
198 defer: deferCreation];
199
200 GargoyleView *view = [[GargoyleView alloc] initWithFrame: contentRect pixelFormat: [GargoyleView defaultPixelFormat]];
201 [view setWantsBestResolutionOpenGLSurface:YES];
202 view.backgroundColor = backgroundColor;
203 [self setContentView: view];
204
205 eventlog = [[NSMutableArray alloc] initWithCapacity: 100];
206 textbuffer = [[NSTextView alloc] init];
207 processID = pid;
208
209 [self setAcceptsMouseMovedEvents: YES];
210 lastMouseMove = 0;
211
212 std::vector<NSString *> names = {
213 NSWindowDidDeminiaturizeNotification,
214 NSWindowDidChangeScreenNotification,
215 NSWindowDidEndLiveResizeNotification,
216 };
217
218 for (const auto &name : names) {
219 [[NSNotificationCenter defaultCenter] addObserver: self
220 selector: @selector(performRefresh:)
221 name: name
222 object: self];
223 }
224
225 [[NSNotificationCenter defaultCenter] addObserver: self
226 selector: @selector(performRefresh:)
227 name: NSWindowDidMoveNotification
228 object: self];
229
230 return self;
231 }
232
233 static BOOL isTextbufferEvent(NSEvent *evt)
234 {
235 if ([evt type] != NSKeyDown) {
236 return NO;
237 }
238
239 // The following mirrors the checks in sysmac.m:winkey().
240
241 // check for arrow keys
242 if ([evt modifierFlags] & NSFunctionKeyMask) {
243 // alt/option modified key
244 if ([evt modifierFlags] & NSAlternateKeyMask) {
245 switch ([evt keyCode]) {
246 case NSKEY_LEFT:
247 case NSKEY_RIGHT:
248 case NSKEY_DOWN:
249 case NSKEY_UP:
250 return NO;
251 default:
252 break;
253 }
254 }
255
256 // command modified key
257 if ([evt modifierFlags] & NSCommandKeyMask) {
258 switch ([evt keyCode]) {
259 case NSKEY_LEFT:
260 case NSKEY_RIGHT:
261 case NSKEY_DOWN:
262 case NSKEY_UP:
263 return NO;
264 default:
265 break;
266 }
267 }
268
269 // unmodified key for line editing
270 switch ([evt keyCode]) {
271 case NSKEY_LEFT:
272 case NSKEY_RIGHT:
273 case NSKEY_DOWN:
274 case NSKEY_UP:
275 return NO;
276 default:
277 break;
278 }
279 }
280
281 // check for menu commands
282 if ([evt modifierFlags] & NSCommandKeyMask) {
283 switch ([evt keyCode]) {
284 case NSKEY_X:
285 case NSKEY_C:
286 case NSKEY_V:
287 return NO;
288 default:
289 break;
290 }
291 }
292
293 // check for command keys
294 switch ([evt keyCode]) {
295 case NSKEY_PGUP:
296 case NSKEY_PGDN:
297 case NSKEY_HOME:
298 case NSKEY_END:
299 case NSKEY_DEL:
300 case NSKEY_BACK:
301 case NSKEY_ESC:
302 case NSKEY_F1:
303 case NSKEY_F2:
304 case NSKEY_F3:
305 case NSKEY_F4:
306 case NSKEY_F5:
307 case NSKEY_F6:
308 case NSKEY_F7:
309 case NSKEY_F8:
310 case NSKEY_F9:
311 case NSKEY_F10:
312 case NSKEY_F11:
313 case NSKEY_F12:
314 return NO;
315 default:
316 break;
317 }
318
319 return YES;
320 }
321
322 - (void) sendEvent: (NSEvent *) event
323 {
324 int store = NO;
325 int forward = YES;
326
327 switch ([event type]) {
328 case NSKeyDown:
329 case NSApplicationDefined:
330 store = YES;
331 forward = NO;
332 break;
333
334 case NSLeftMouseDown:
335 case NSLeftMouseUp:
336 store = YES;
337 break;
338
339 case NSLeftMouseDragged:
340 case NSMouseMoved:
341 if (([event timestamp] - lastMouseMove) > 0.05) {
342 lastMouseMove = [event timestamp];
343 store = YES;
344 }
345 break;
346
347 case NSScrollWheel:
348 if ([event deltaY] > 0.05 || [event deltaY] < -0.05) {
349 store = YES;
350 }
351
352 break;
353
354 default:
355 break;
356 }
357
358 if (store) {
359 [eventlog insertObject: [event copy] atIndex: 0];
360 if (isTextbufferEvent(event)) {
361 [textbuffer interpretKeyEvents: [NSArray arrayWithObject: event]];
362 }
363 kill(processID, SIGUSR1);
364 }
365
366 if (forward) {
367 [super sendEvent: event];
368 }
369
370 return;
371 }
372
373 - (NSEvent *) retrieveEvent
374 {
375 NSEvent *event = nullptr;
376
377 if ([eventlog count]) {
378 event = [eventlog lastObject];
379 [eventlog removeLastObject];
380 }
381
382 return event;
383 }
384
385 - (void) sendChars: (NSEvent *) event
386 {
387 // Does not work on macOS 10.12 (Sierra)
388 //[textbuffer interpretKeyEvents: [NSArray arrayWithObject:event]];
389 }
390
391 - (NSString *) retrieveChars
392 {
393 return [[textbuffer textStorage] string];
394 }
395
396 - (void) clearChars
397 {
398 [[[textbuffer textStorage] mutableString] setString: @""];
399 }
400
401 - (IBAction) cut: (id) sender
402 {
403 [self sendEvent: [NSEvent keyEventWithType: NSKeyDown
404 location: NSZeroPoint
405 modifierFlags: NSCommandKeyMask
406 timestamp: NSTimeIntervalSince1970
407 windowNumber: [self windowNumber]
408 context: [self graphicsContext]
409 characters: @"X"
410 charactersIgnoringModifiers: @"X"
411 isARepeat: NO
412 keyCode: NSKEY_X]];
413 }
414
415 - (IBAction) copy: (id) sender
416 {
417 [self sendEvent: [NSEvent keyEventWithType: NSKeyDown
418 location: NSZeroPoint
419 modifierFlags: NSCommandKeyMask
420 timestamp: NSTimeIntervalSince1970
421 windowNumber: [self windowNumber]
422 context: [self graphicsContext]
423 characters: @"C"
424 charactersIgnoringModifiers: @"C"
425 isARepeat: NO
426 keyCode: NSKEY_C]];
427 }
428
429 - (IBAction) paste: (id) sender
430 {
431 [self sendEvent: [NSEvent keyEventWithType: NSKeyDown
432 location: NSZeroPoint
433 modifierFlags: NSCommandKeyMask
434 timestamp: NSTimeIntervalSince1970
435 windowNumber: [self windowNumber]
436 context: [self graphicsContext]
437 characters: @"V"
438 charactersIgnoringModifiers: @"V"
439 isARepeat: NO
440 keyCode: NSKEY_V]];
441 }
442
443 - (void) moveWordBackward: (id) sender
444 {
445 [self sendEvent: [NSEvent keyEventWithType: NSKeyDown
446 location: NSZeroPoint
447 modifierFlags: NSAlternateKeyMask
448 timestamp: NSTimeIntervalSince1970
449 windowNumber: [self windowNumber]
450 context: [self graphicsContext]
451 characters: @""
452 charactersIgnoringModifiers: @""
453 isARepeat: NO
454 keyCode: NSKEY_LEFT]];
455 }
456
457 - (void) moveWordForward: (id) sender
458 {
459 [self sendEvent: [NSEvent keyEventWithType: NSKeyDown
460 location: NSZeroPoint
461 modifierFlags: NSAlternateKeyMask
462 timestamp: NSTimeIntervalSince1970
463 windowNumber: [self windowNumber]
464 context: [self graphicsContext]
465 characters: @""
466 charactersIgnoringModifiers: @""
467 isARepeat: NO
468 keyCode: NSKEY_RIGHT]];
469 }
470
471 - (IBAction) performZoom: (id) sender
472 {
473 [self sendEvent: [NSEvent otherEventWithType: NSApplicationDefined
474 location: NSZeroPoint
475 modifierFlags: 0
476 timestamp: NSTimeIntervalSince1970
477 windowNumber: [self windowNumber]
478 context: [self graphicsContext]
479 subtype: 0
480 data1: 0
481 data2: 0]];
482 [super performZoom: sender];
483 }
484
485 - (void) saveWindows
486 {
487 if (gli_conf_save_window_location || gli_conf_save_window_size) {
488 auto path = get_qt_plist_path();
489 if (path != nil) {
490 NSMutableDictionary *config = [NSMutableDictionary dictionaryWithContentsOfFile: path];
491 if (config == nil) {
492 config = [NSMutableDictionary dictionary];
493 }
494
495 if (gli_conf_save_window_location) {
496 auto location = Format("@Point({} {})", self.frame.origin.x, coord_flip(self) - self.frame.origin.y);
497 [config setObject: [NSString stringWithUTF8String: location.c_str()] forKey: @"window.position"];
498 }
499
500 if (gli_conf_save_window_size) {
501 auto size = Format("@Size({} {})", self.frame.size.width, self.frame.size.height);
502 [config setObject: [NSString stringWithUTF8String: size.c_str()] forKey: @"window.size"];
503 }
504
505 if (gli_conf_save_window_location || gli_conf_save_window_size) {
506 auto is_fullscreen = (self.styleMask & NSWindowStyleMaskFullScreen) == NSWindowStyleMaskFullScreen;
507 auto as_object = [NSNumber numberWithBool: is_fullscreen];
508 [config setObject: as_object forKey: @"window.fullscreen"];
509 }
510
511 [config writeToFile: path atomically: YES];
512 }
513 }
514 }
515
516 - (void) performRefresh: (NSNotification *) notice
517 {
518 [self saveWindows];
519
520 [self sendEvent: [NSEvent otherEventWithType: NSApplicationDefined
521 location: NSZeroPoint
522 modifierFlags: 0
523 timestamp: NSTimeIntervalSince1970
524 windowNumber: [self windowNumber]
525 context: [self graphicsContext]
526 subtype: 0
527 data1: 0
528 data2: 0]];
529 }
530
531 - (void) performMove: (NSNotification *) notice
532 {
533 [self saveWindows];
534 }
535
536 static NSURL *get_save_dir(NSString *filename)
537 {
538
539 NSError *error = nil;
540 NSURL *dir = [[NSFileManager defaultManager] URLForDirectory: NSApplicationSupportDirectory
541 inDomain: NSUserDomainMask
542 appropriateForURL: nil
543 create: YES
544 error: &error];
545
546 if (error != nil) {
547 return nil;
548 }
549
550 dir = [dir URLByAppendingPathComponent: @"Gargoyle/gamedata"];
551 dir = [dir URLByAppendingPathComponent: filename];
552 NSFileManager *fm = [NSFileManager defaultManager];
553 [fm createDirectoryAtURL: dir withIntermediateDirectories: YES attributes: nil error: &error];
554
555 if (error == nil) {
556 return dir;
557 } else {
558 return nil;
559 }
560 }
561
562 static void maybe_set_save_dir(NSSavePanel *panel, NSString *savedir)
563 {
564 if (savedir == nil) {
565 return;
566 }
567
568 auto initial_directory = get_save_dir(savedir);
569
570 if (initial_directory != nil) {
571 NSURL *startingDirectoryURL = [NSURL fileURLWithPath: [initial_directory path]];
572 [panel setDirectoryURL: startingDirectoryURL];
573 }
574 }
575
576 - (NSString *) openFileDialog: (NSString *) prompt
577 fileFilter: (FileFilter) filter
578 savedir: (NSString *) savedir
579 {
580 int result;
581
582 NSOpenPanel *openDlg = [NSOpenPanel openPanel];
583
584 [openDlg setCanChooseFiles: YES];
585 [openDlg setCanChooseDirectories: NO];
586 [openDlg setAllowsMultipleSelection: NO];
587 [openDlg setTitle: prompt];
588
589 maybe_set_save_dir(openDlg, savedir);
590
591 if (filter != FileFilter::Data) {
592 NSArray *filterTypes = [NSArray arrayWithObject: [NSString stringWithCString: winfilters.at(filter).c_str()
593 encoding: NSUTF8StringEncoding]];
594 [openDlg setAllowedFileTypes: filterTypes];
595 [openDlg setAllowsOtherFileTypes: NO];
596 }
597 result = [openDlg runModal];
598
599 if (result == NSFileHandlingPanelOKButton) {
600 return [[openDlg URL] path];
601 }
602
603 return nil;
604 }
605
606 - (NSString *) saveFileDialog: (NSString *) prompt
607 fileFilter: (FileFilter) filter
608 savedir: (NSString *) savedir
609 {
610 int result;
611
612 NSSavePanel *saveDlg = [NSSavePanel savePanel];
613
614 [saveDlg setCanCreateDirectories: YES];
615 [saveDlg setTitle: prompt];
616
617 maybe_set_save_dir(saveDlg, savedir);
618
619 if (filter != FileFilter::Data) {
620 NSArray *filterTypes = [NSArray arrayWithObject: [NSString stringWithCString: winfilters.at(filter).c_str()
621 encoding: NSUTF8StringEncoding]];
622 [saveDlg setAllowedFileTypes: filterTypes];
623 [saveDlg setAllowsOtherFileTypes: NO];
624 }
625
626 result = [saveDlg runModal];
627
628 if (result == NSFileHandlingPanelOKButton) {
629 return [[saveDlg URL] path];
630 }
631
632 return nil;
633 }
634
635 - (pid_t) retrieveID
636 {
637 return processID;
638 }
639
640 - (void) quit
641 {
642 [[NSNotificationCenter defaultCenter] removeObserver: self];
643 [eventlog release];
644 [textbuffer release];
645
646 // shut interpreter down
647 kill(processID, SIGUSR2);
648 }
649
650 @end
651
652 @interface GargoyleApp : NSWindowController
653 <GargoyleApp, NSApplicationDelegate, NSWindowDelegate>
654 {
655 BOOL openedFirstGame;
656 NSMutableDictionary *windows;
657 NSConnection *link;
658 }
659 - (BOOL) launchFile: (NSString *) file;
660 - (BOOL) launchFileDialog;
661 @end
662
663 @implementation GargoyleApp
664
665 - (id) init
666 {
667 self = [super init];
668
669 // set internal variables
670 openedFirstGame = NO;
671 windows = [[NSMutableDictionary alloc] init];
672
673 // set up controller link
674 NSPort *port = [NSMachPort port];
675 link = [[NSConnection connectionWithReceivePort: port sendPort: port] retain];
676 [link setRootObject: self];
677 [link addRunLoop: [NSRunLoop currentRunLoop]];
678 [link registerName: [NSString stringWithFormat: @"com.googlecode.garglk-%04x", getpid()]];
679 [link retain];
680
681 // set environment variable
682 NSString *nsResources = [[NSBundle mainBundle] resourcePath];
683
684 auto etc = [nsResources UTF8String];
685 setenv("GARGLK_RESOURCES", etc, true);
686
687 // set preference defaults
688 [[NSUserDefaults standardUserDefaults] registerDefaults:
689 [NSDictionary dictionaryWithObject: [NSNumber numberWithBool: YES]
690 forKey: @"NSDisabledCharacterPaletteMenuItem"]];
691
692 // register for URL events
693 [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self
694 andSelector: @selector(openURL:withReplyEvent:)
695 forEventClass: kInternetEventClass
696 andEventID: kAEGetURL];
697
698 return self;
699 }
700
701 - (BOOL) initWindow: (pid_t) processID
702 move: (BOOL) move
703 x: (unsigned int) x
704 y: (unsigned int) y
705 width: (unsigned int) width
706 height: (unsigned int) height
707 fullscreen: (BOOL) fullscreen
708 backgroundColor: (NSColor *) backgroundColor
709 {
710 if (!(processID > 0)) {
711 return NO;
712 }
713
714 unsigned int style = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask;
715
716 // set up the window
717 NSRect rect = NSMakeRect(0, 0, width, height);
718 GargoyleWindow *window = [[GargoyleWindow alloc] initWithContentRect: rect
719 styleMask: style
720 backing: NSBackingStoreBuffered
721 defer: NO
722 process: processID
723 backgroundColor: backgroundColor];
724
725 [window setMinSize:NSMakeSize(gli_wmarginx * 2, gli_wmarginy * 2)];
726
727 [window makeKeyAndOrderFront: window];
728 if (move) {
729 rect = NSMakeRect(x, coord_flip(window) - y, width, height);
730 [window setFrame: rect display: YES];
731 } else {
732 [window center];
733 }
734 [window setReleasedWhenClosed: YES];
735 [window setDelegate: self];
736 if (fullscreen) {
737 [window toggleFullScreen: self];
738 }
739
740 [windows setObject: window forKey: [NSNumber numberWithInt: processID]];
741
742 return ([window isVisible]);
743 }
744
745 - (NSEvent *) getWindowEvent: (pid_t) processID
746 {
747 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
748
749 if (window) {
750 return [window retrieveEvent];
751 }
752
753 return nil;
754 }
755
756 - (NSRect) updateBackingSize: (pid_t) processID
757 {
758 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
759
760 if (window) {
761 id view = [window contentView];
762 NSRect viewRect = [view bounds];
763 NSRect backingRect = [window convertRectToBacking: viewRect];
764 return backingRect;
765 }
766
767 return NSZeroRect;
768 }
769
770 - (CGFloat) getBackingScaleFactor: (pid_t) processID
771 {
772 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
773
774 if (window) {
775 id view = [window contentView];
776 return [view backingScaleFactor];
777 }
778
779 return 1.0;
780 }
781
782 - (NSPoint) getWindowPoint: (pid_t) processID
783 forEvent: (NSEvent *) event;
784 {
785 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
786
787 if (window) {
788 NSPoint point = [event locationInWindow];
789 return point;
790 }
791
792 return NSZeroPoint;
793 }
794
795 - (NSString *) getWindowCharString: (pid_t) processID
796 {
797 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
798
799 if (window) {
800 return [window retrieveChars];
801 }
802
803 return nil;
804 }
805
806 - (BOOL) clearWindowCharString: (pid_t) processID
807 {
808 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
809
810 if (window) {
811 [window clearChars];
812 return YES;
813 }
814
815 return NO;
816 }
817
818 - (BOOL) setWindow: (pid_t) processID
819 charString: (NSEvent *) event;
820 {
821 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
822
823 if (window) {
824 [window sendChars: event];
825 return YES;
826 }
827
828 return NO;
829 }
830
831 - (BOOL) setWindow: (pid_t) processID
832 title: (NSString *) title;
833 {
834 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
835
836 if (window) {
837 [window setTitle: title];
838 return YES;
839 }
840
841 return NO;
842 }
843
844 - (BOOL) setWindow: (pid_t) processID
845 contents: (NSData *) frame
846 width: (unsigned int) width
847 height: (unsigned int) height;
848 {
849 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
850
851 if (window) {
852 [[window contentView] addFrame: frame
853 width: width
854 height: height];
855
856 NSRect rect = NSMakeRect(0, 0, width, height);
857 if ([[window contentView] wantsBestResolutionOpenGLSurface]) {
858 rect = [[window contentView] convertRectFromBacking: rect];
859 }
860 [[window contentView] drawRect: rect];
861 return YES;
862 }
863
864 return NO;
865 }
866
867 - (void) closeWindow: (pid_t) processID
868 {
869 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
870
871 if (window) {
872 [window performClose: self];
873 }
874 }
875
876 - (NSString *) openWindowDialog: (pid_t) processID
877 prompt: (NSString *) prompt
878 filter: (FileFilter) filter
879 savedir: (NSString *) savedir
880 {
881 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
882
883 if (window) {
884 return [window openFileDialog: prompt fileFilter: filter savedir: savedir];
885 }
886
887 return nil;
888 }
889
890 - (NSString *) saveWindowDialog: (pid_t) processID
891 prompt: (NSString *) prompt
892 filter: (FileFilter) filter
893 savedir: (NSString *) savedir
894 {
895 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
896
897 if (window) {
898 return [window saveFileDialog: prompt fileFilter: filter savedir: savedir];
899 }
900
901 return nil;
902 }
903
904 - (void) abortWindowDialog: (pid_t) processID
905 prompt: (NSString *) prompt
906 {
907 NSRunAlertPanel(@"Fatal error", @"%@", nil, nil, nil, prompt);
908 }
909
910 - (BOOL) isFullScreen: (pid_t) processID
911 {
912 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
913 return (window.styleMask & NSWindowStyleMaskFullScreen) == NSWindowStyleMaskFullScreen;
914 }
915
916 - (void) toggleFullScreen: (pid_t) processID
917 {
918 GargoyleWindow *window = [windows objectForKey: [NSNumber numberWithInt: processID]];
919 [window toggleFullScreen: self];
920 }
921
922 #define kArrowCursor 1
923 #define kIBeamCursor 2
924 #define kPointingHandCursor 3
925
926 - (void) setCursor: (unsigned int) cursor
927 {
928 switch (cursor) {
929 case kArrowCursor:
930 [[NSCursor arrowCursor] set];
931 break;
932
933 case kIBeamCursor:
934 [[NSCursor IBeamCursor] set];
935 break;
936
937 case kPointingHandCursor:
938 [[NSCursor pointingHandCursor] set];
939 break;
940
941 default:
942 break;
943 }
944 }
945
946 - (BOOL) launchFileDialog
947 {
948 int result;
949
950 NSOpenPanel *openDlg = [NSOpenPanel openPanel];
951
952 [openDlg setCanChooseFiles: YES];
953 [openDlg setCanChooseDirectories: NO];
954 [openDlg setAllowsMultipleSelection: NO];
955 [openDlg setTitle: [NSString stringWithCString: AppName encoding: NSUTF8StringEncoding]];
956
957 NSMutableArray *filterTypes = [NSMutableArray arrayWithCapacity:100];
958
959 NSEnumerator *docTypeEnum = [[[[NSBundle mainBundle] infoDictionary]
960 objectForKey:@"CFBundleDocumentTypes"] objectEnumerator];
961 NSDictionary *docType;
962
963 while (docType = [docTypeEnum nextObject]) {
964 [filterTypes addObjectsFromArray:[docType objectForKey: @"CFBundleTypeExtensions"]];
965 }
966
967 // Some advsys games have a .dat extension, but since that's so
968 // generic, it's not included in the .plist file, so it won't be
969 // registered system-wide for Gargoyle. Similarly, some Level9 games
970 // have a .sna (memory snapshot) extension, which is not exclusive
971 // to Level9 games, so it's also not in the .plist file. Add both
972 // of them here so the file picker can select them, at least.
973 [filterTypes addObject: @"dat"];
974 [filterTypes addObject: @"sna"];
975
976 [openDlg setAllowedFileTypes: filterTypes];
977 [openDlg setAllowsOtherFileTypes: NO];
978 result = [openDlg runModal];
979
980 if (result == NSFileHandlingPanelOKButton) {
981 return [self launchFile: [[openDlg URL] path]];
982 }
983
984 return NO;
985 }
986
987 - (BOOL) launchFile: (NSString *) file
988 {
989 if (![file length]) {
990 return NO;
991 }
992
993 // get story file
994 auto game = [file UTF8String];
995
996 // run story file
997 bool ran = garglk::rungame(game);
998
999 if (ran) {
1000 [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: file]];
1001 }
1002
1003 return ran;
1004 }
1005
1006 - (BOOL) applicationShouldOpenUntitledFile: (NSApplication *) sender
1007 {
1008 return (!openedFirstGame);
1009 }
1010
1011 - (BOOL) applicationOpenUntitledFile: (NSApplication *) theApplication
1012 {
1013 openedFirstGame = YES;
1014 return [self launchFileDialog];
1015 }
1016
1017 - (BOOL) application: (NSApplication *) theApplication openFile: (NSString *) file
1018 {
1019 openedFirstGame = YES;
1020 return [self launchFile:file];
1021 }
1022
1023 - (void) application: (NSApplication *) theApplication openFiles: (NSArray *) files
1024 {
1025 openedFirstGame = YES;
1026
1027 int i;
1028
1029 for (i = 0; i < [files count]; i++) {
1030 [self launchFile: [files objectAtIndex: i]];
1031 }
1032 }
1033
1034 - (void) openURL: (NSAppleEventDescriptor *) event withReplyEvent: (NSAppleEventDescriptor *) reply
1035 {
1036 NSArray *urlParts = [[[event paramDescriptorForKeyword: keyDirectObject] stringValue] componentsSeparatedByString: @"garglk://"];
1037
1038 if (urlParts && [urlParts count] == 2) {
1039 openedFirstGame = YES;
1040 NSString *game = [[urlParts objectAtIndex: 1] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
1041
1042 if ([[NSFileManager defaultManager] fileExistsAtPath: game] == YES) {
1043 [self launchFile: game];
1044 } else {
1045 NSRunAlertPanel(@"Could not open URL path:", @"%@", nil, nil, nil, game);
1046 }
1047 }
1048 }
1049
1050 - (BOOL) windowShouldClose: (id) sender
1051 {
1052 GargoyleWindow *window = sender;
1053 [windows removeObjectForKey: [NSNumber numberWithInt: [window retrieveID]]];
1054 [window quit];
1055 return YES;
1056 }
1057
1058 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
1059 {
1060 for (id key in windows) {
1061 GargoyleWindow *window = [windows objectForKey: key];
1062 [window quit];
1063 }
1064
1065 return NSTerminateNow;
1066 }
1067
1068
1069 - (IBAction) orderFrontStandardAboutPanel: (id) sender
1070 {
1071 }
1072
1073 - (IBAction) open: (id) sender
1074 {
1075 [self launchFileDialog];
1076 }
1077
1078 - (IBAction) toggle: (id) sender
1079 {
1080 try {
1081 auto config = [NSString stringWithUTF8String: garglk::user_config().c_str()];
1082 NSTask *task = [[NSTask alloc] init];
1083 task.launchPath = @"/usr/bin/open";
1084 task.arguments = @[@"-t", config];
1085 [task launch];
1086 } catch (const std::runtime_error &e) {
1087 garglk::winwarning("Warning", e.what());
1088 }
1089 }
1090
1091 @end
1092
1093 void garglk::winmsg(const std::string &msg)
1094 {
1095 NSString *nsMsg;
1096 nsMsg = [NSString stringWithCString: msg.c_str() encoding: NSUTF8StringEncoding];
1097 NSRunAlertPanel(@"Fatal error", @"%@", nil, nil, nil, nsMsg);
1098 }
1099
1100 static std::string winpath()
1101 {
1102 char exepath[PROC_PIDPATHINFO_MAXSIZE];
1103
1104 if (proc_pidpath(getpid(), exepath, sizeof exepath) == -1) {
1105 garglk::winmsg("Unable to locate executable path");
1106 }
1107
1108 std::string buffer = exepath;
1109
1110 auto slash = buffer.find_last_of('/');
1111 if (slash != std::string::npos) {
1112 buffer.erase(slash);
1113 }
1114
1115 return buffer;
1116 }
1117
1118 static int winexec(const std::string &cmd, const std::vector<std::string> &args)
1119 {
1120 NSTask *proc = [[NSTask alloc] init];
1121
1122 // prepare interpreter path
1123 NSArray *nsArray = [[NSString stringWithCString: cmd.c_str() encoding: NSUTF8StringEncoding] componentsSeparatedByString: @"/"];
1124 NSString *nsTerp = [nsArray objectAtIndex: [nsArray count] - 1];
1125 NSString *nsCmd = [NSString stringWithFormat: @"%@/%@", [[NSBundle mainBundle] builtInPlugInsPath], nsTerp];
1126
1127 // prepare interpreter arguments
1128 NSMutableArray *nsArgs = [NSMutableArray arrayWithCapacity:2];
1129
1130 // prepare environment
1131 NSMutableDictionary *nsEnv = [[[NSProcessInfo processInfo] environment] mutableCopy];
1132 [nsEnv setObject: [NSString stringWithFormat: @"com.googlecode.garglk-%04x", getpid()] forKey: @"GargoyleApp"];
1133
1134 for (const auto &arg : args) {
1135 [nsArgs addObject: [[NSString alloc] initWithCString: arg.c_str() encoding: NSUTF8StringEncoding]];
1136 }
1137
1138 if ([nsCmd length] && [nsArgs count]) {
1139 [proc setLaunchPath: nsCmd];
1140 [proc setArguments: nsArgs];
1141 [proc setEnvironment: nsEnv];
1142 [proc launch];
1143 }
1144
1145 return [proc isRunning];
1146 }
1147
1148 bool garglk::winterp(const std::string &exe, const std::vector<std::string> &flags, const std::string &game)
1149 {
1150 // get dir of executable
1151 auto interpreter_dir = winpath();
1152
1153 auto cmd = Format("{}/{}", interpreter_dir, exe);
1154
1155 auto args = flags;
1156
1157 args.push_back(game);
1158
1159 if (!winexec(cmd, args)) {
1160 garglk::winmsg("Could not start 'terp.\nSorry.");
1161 return false;
1162 }
1163
1164 return true;
1165 }
1166
1167 int main(int argc, char **argv)
1168 {
1169 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1170 [NSApplication sharedApplication];
1171 [NSApp setDelegate:[[GargoyleApp alloc] init]];
1172 [pool drain];
1173
1174 // Read the config file here so that the "save_window" settings are available.
1175 gli_read_config(argc, argv);
1176
1177 return NSApplicationMain(argc, const_cast<const char **>(argv));
1178 }