Debian Codegraph @

garglk/sysmac.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 <algorithm>
20 #include <cstdlib>
21 #include <fstream>
22 #include <functional>
23 #include <map>
24 #include <regex>
25 #include <stdexcept>
26 #include <string>
27 #include <utility>
28 #include <vector>
29
30 #include <mach/port.h>
31 #include <mach/message.h>
32 #include <unistd.h>
33
34 #include "glk.h"
35 #include "garglk.h"
36 #include "garversion.h"
37
38 #include "format.h"
39 #include "optional.hpp"
40
41 #import "Cocoa/Cocoa.h"
42 #import "sysmac.h"
43
44 static volatile sig_atomic_t gli_event_waiting = false;
45 static volatile sig_atomic_t gli_mach_allowed = false;
46 static volatile sig_atomic_t gli_window_alive = true;
47
48 #define kArrowCursor 1
49 #define kIBeamCursor 2
50 #define kPointingHandCursor 3
51
52 static void wintick(CFRunLoopTimerRef timer, void *info);
53 static void winhandler(int signal);
54
55 @interface GargoyleMonitor : NSObject
56 {
57 NSRect size;
58 CFRunLoopTimerRef timerid;
59 int timeouts;
60 }
61 - (id) init;
62 - (void) sleep;
63 - (void) track: (CFTimeInterval) seconds;
64 - (void) tick;
65 - (BOOL) timeout;
66 - (void) reset;
67 - (void) connectionDied: (NSNotification *) notice;
68 @end
69
70 @implementation GargoyleMonitor
71
72 - (id) init
73 {
74 self = [super init];
75
76 timerid = nullptr;
77 timeouts = 0;
78
79 return self;
80 }
81
82 - (void) sleep
83 {
84 while (!timeouts && !gli_event_waiting) {
85 if (!gli_window_alive) {
86 std::exit(1);
87 }
88
89 gli_mach_allowed = true;
90 [[NSRunLoop currentRunLoop] acceptInputForMode: NSDefaultRunLoopMode beforeDate: [NSDate distantFuture]];
91 gli_mach_allowed = false;
92 }
93 }
94
95 - (void) track: (CFTimeInterval) seconds
96 {
97 if (timerid) {
98 if (CFRunLoopTimerIsValid(timerid)) {
99 CFRunLoopTimerInvalidate(timerid);
100 }
101 CFRelease(timerid);
102 timerid = nullptr;
103 timeouts = 0;
104 }
105
106 if (seconds) {
107 timerid = CFRunLoopTimerCreate(nullptr, CFAbsoluteTimeGetCurrent() + seconds, seconds,
108 0, 0, &wintick, nullptr);
109 if (timerid) {
110 CFRunLoopAddTimer([[NSRunLoop currentRunLoop] getCFRunLoop], timerid, kCFRunLoopDefaultMode);
111 }
112 }
113 }
114
115 - (void) tick
116 {
117 timeouts++;
118 CFRunLoopStop([[NSRunLoop currentRunLoop] getCFRunLoop]);
119 }
120
121 - (BOOL) timeout
122 {
123 return timeouts != 0;
124 }
125
126 - (void) reset
127 {
128 timeouts = 0;
129 }
130
131 - (void) connectionDied: (NSNotification *) notice
132 {
133 std::exit(1);
134 }
135
136 @end
137
138 static NSObject<GargoyleApp> *gargoyle = nullptr;
139 static GargoyleMonitor *monitor = nullptr;
140 static NSString *cliptext = nullptr;
141 static pid_t processID = 0;
142
143 static bool gli_refresh_needed = true;
144
145 void glk_request_timer_events(glui32 millisecs)
146 {
147 [monitor track: millisecs / 1000.0];
148 }
149
150 static void wintick(CFRunLoopTimerRef timer, void *info)
151 {
152 [monitor tick];
153 }
154
155 void gli_notification_waiting()
156 {
157 winhandler(SIGUSR1);
158 }
159
160 void garglk::winabort(const std::string &msg)
161 {
162 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
163 [gargoyle abortWindowDialog: processID
164 prompt: [NSString stringWithCString: msg.c_str() encoding: NSUTF8StringEncoding]];
165 [pool drain];
166
167 std::exit(1);
168 }
169
170 void garglk::winwarning(const std::string &title, const std::string &msg)
171 {
172 auto *nsTitle = [NSString stringWithCString: title.c_str() encoding: NSUTF8StringEncoding];
173 auto *nsMsg = [NSString stringWithCString: msg.c_str() encoding: NSUTF8StringEncoding];
174 NSRunAlertPanel(nsTitle, @"%@", nil, nil, nil, nsMsg);
175 }
176
177 void winexit()
178 {
179 [gargoyle closeWindow:processID];
180 gli_exit(0);
181 }
182
183 static NSString *get_savedir(FileFilter filter)
184 {
185 if (gli_conf_gamedata_location == GamedataLocation::Dedicated && gli_workfile.has_value()) {
186 return [NSString stringWithUTF8String: gli_workfile->c_str()];
187 } else if (gli_conf_gamedata_location == GamedataLocation::Gamedir) {
188 return [NSString stringWithUTF8String: gli_workdir.c_str()];
189 }
190
191 return nil;
192 }
193
194 std::string garglk::winopenfile(const char *prompt, FileFilter filter)
195 {
196 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
197
198 NSString *fileref = [gargoyle openWindowDialog: processID
199 prompt: [NSString stringWithCString: prompt encoding: NSUTF8StringEncoding]
200 filter: filter
201 savedir: get_savedir(filter)];
202
203 std::string buf;
204
205 if (fileref) {
206 buf = [fileref UTF8String];
207 }
208
209 [pool drain];
210
211 return buf;
212 }
213
214 std::string garglk::winsavefile(const char *prompt, FileFilter filter)
215 {
216 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
217
218 NSString *fileref = [gargoyle saveWindowDialog: processID
219 prompt: [NSString stringWithCString: prompt encoding: NSUTF8StringEncoding]
220 filter: filter
221 savedir: get_savedir(filter)];
222
223 std::string buf;
224
225 if (fileref) {
226 buf = [fileref UTF8String];
227 }
228
229 [pool drain];
230
231 return buf;
232 }
233
234 void winclipstore(const std::vector<glui32> &text)
235 {
236 if (text.empty()) {
237 return;
238 }
239
240 if (cliptext) {
241 [cliptext release];
242 cliptext = nil;
243 }
244
245 cliptext = [[NSString alloc] initWithBytes: text.data()
246 length: (text.size() * sizeof(glui32))
247 encoding: UTF32StringEncoding];
248 }
249
250 void winclipsend()
251 {
252 if (cliptext) {
253 NSPasteboard *clipboard = [NSPasteboard generalPasteboard];
254 [clipboard declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner:nil];
255 [clipboard setString: cliptext forType: NSStringPboardType];
256 }
257 }
258
259 void winclipreceive()
260 {
261 int i, len;
262 glui32 ch;
263
264 NSPasteboard *clipboard = [NSPasteboard generalPasteboard];
265
266 if ([clipboard availableTypeFromArray: [NSArray arrayWithObject: NSStringPboardType]]) {
267 NSString *input = [clipboard stringForType: NSStringPboardType];
268 if (input) {
269 len = [input length];
270 for (i = 0; i < len; i++) {
271 if ([input getBytes: &ch maxLength: sizeof ch usedLength: nullptr
272 encoding: UTF32StringEncoding
273 options: 0
274 range: NSMakeRange(i, 1)
275 remainingRange: nullptr]) {
276 switch (ch) {
277 case '\0':
278 return;
279
280 case '\b':
281 case '\t':
282 break;
283
284 case '\r':
285 case '\n':
286 gli_input_handle_key_paste(keycode_Return);
287 break;
288
289 default:
290 gli_input_handle_key_paste(ch);
291 }
292 }
293 }
294 }
295 }
296 }
297
298 void wintitle()
299 {
300 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
301
302 NSString *story_title = [NSString stringWithCString: gli_story_title.c_str() encoding: NSUTF8StringEncoding];
303 NSString *story_name = [NSString stringWithCString: gli_story_name.c_str() encoding: NSUTF8StringEncoding];
304 NSString *program_name = [NSString stringWithCString: gli_program_name.c_str() encoding: NSUTF8StringEncoding];
305
306 NSString *title = nil;
307 if ([story_title length]) {
308 title = story_title;
309 } else if ([story_name length]) {
310 title = [NSString stringWithFormat:@"%@ - %@", story_name, program_name];
311 } else {
312 title = program_name;
313 }
314
315 [gargoyle setWindow: processID
316 title: title];
317
318 [pool drain];
319 }
320
321 void winresize()
322 {
323 NSRect viewRect = [gargoyle updateBackingSize: processID];
324 float textureFactor = BACKING_SCALE_FACTOR / [gargoyle getBackingScaleFactor: processID];
325
326 unsigned int vw = NSWidth(viewRect) * textureFactor;
327 unsigned int vh = NSHeight(viewRect) * textureFactor;
328
329 if (gli_image_rgb.width() == vw && gli_image_rgb.height() == vh) {
330 return;
331 }
332
333 gli_windows_size_change(vw, vh, true);
334
335 // redraw window content
336 gli_refresh_needed = true;
337 }
338
339 static mach_port_t gli_signal_port = 0;
340
341 void winmach(CFMachPortRef port, void *msg, CFIndex size, void *info)
342 {
343 mach_msg_header_t *hdr = static_cast<mach_msg_header_t *>(msg);
344 switch (hdr->msgh_id) {
345 case SIGUSR1:
346 gli_event_waiting = true;
347 break;
348
349 default:
350 break;
351 }
352 }
353
354 static void winhandler(int signal)
355 {
356 if (signal == SIGUSR1) {
357 if (gli_mach_allowed) {
358 mach_msg_header_t header;
359 header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND, 0);
360 header.msgh_size = sizeof(header);
361 header.msgh_remote_port = gli_signal_port;
362 header.msgh_local_port = MACH_PORT_NULL;
363 header.msgh_reserved = 0;
364 header.msgh_id = signal;
365
366 mach_msg_send(&header);
367 } else {
368 gli_event_waiting = true;
369 }
370 }
371
372 if (signal == SIGUSR2) {
373 gli_window_alive = false;
374
375 // Stop all sound channels
376 for (channel_t *chan = glk_schannel_iterate(nullptr, nullptr); chan; chan = glk_schannel_iterate(chan, nullptr)) {
377 glk_schannel_stop(chan);
378 }
379 }
380 }
381
382 void wininit()
383 {
384 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
385 gli_backingscalefactor = BACKING_SCALE_FACTOR;
386
387 // establish link to launcher
388 NSString *linkName = [NSString stringWithUTF8String: std::getenv("GargoyleApp")];
389 NSConnection *link = [NSConnection connectionWithRegisteredName: linkName host: nullptr];
390 [link retain];
391
392 // monitor link for failure
393 monitor = [[GargoyleMonitor alloc] init];
394 [[NSNotificationCenter defaultCenter] addObserver: monitor
395 selector: @selector(connectionDied:)
396 name: NSConnectionDidDieNotification
397 object: link];
398
399 // attach to app controller
400 gargoyle = (NSObject<GargoyleApp> *)[link rootProxy];
401 [gargoyle retain];
402
403 // listen for mach messages
404 CFMachPortRef sigPort = CFMachPortCreate(nullptr, winmach, nullptr, nullptr);
405 gli_signal_port = CFMachPortGetPort(sigPort);
406 [[NSRunLoop currentRunLoop] addPort: [NSMachPort portWithMachPort: gli_signal_port] forMode: NSDefaultRunLoopMode];
407
408 // load signal handler
409 signal(SIGUSR1, winhandler);
410 signal(SIGUSR2, winhandler);
411
412 processID = getpid();
413
414 [pool drain];
415 }
416
417 NSString *get_qt_plist_path()
418 {
419 const char *home = std::getenv("HOME");
420 if (home != nullptr) {
421 // Optimistically use the path that Qt uses with the hope/plan
422 // of moving macOS to Qt one of these days.
423 auto path = Format("{}/Library/Preferences/com.io-github-garglk.Gargoyle.plist", home);
424 return [NSString stringWithUTF8String: path.c_str()];
425 }
426
427 return nil;
428 }
429
430 void winopen()
431 {
432 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
433
434 auto do_fullscreen = gli_conf_fullscreen;
435
436 bool move = false;
437 int x = 0;
438 int y = 0;
439 unsigned int width = gli_wmarginx * 2 + gli_cellw * gli_cols / BACKING_SCALE_FACTOR;
440 unsigned int height = gli_wmarginy * 2 + gli_cellh * gli_rows / BACKING_SCALE_FACTOR;
441 NSColor *windowColor = [NSColor colorWithCalibratedRed: (float) gli_window_color[0] / 255.0f
442 green: (float) gli_window_color[1] / 255.0f
443 blue: (float) gli_window_color[2] / 255.0f
444 alpha: 1.0f];
445
446 auto path = get_qt_plist_path();
447 if (path != nil) {
448 NSDictionary *config = [NSDictionary dictionaryWithContentsOfFile: path];
449
450 if (gli_conf_save_window_location) {
451 NSString *positionobj = config[@"window.position"];
452 if (positionobj) {
453 std::string position = [positionobj UTF8String];
454 std::regex position_re(R"(^@Point\((\d+) (\d+)\)$)");
455 std::smatch cm;
456 if (std::regex_match(position, cm, position_re) && cm.size() == 3) {
457 try {
458 auto tmpx = std::stoi(cm[1]);
459 auto tmpy = std::stoi(cm[2]);
460
461 x = tmpx;
462 y = tmpy;
463 move = true;
464 } catch (...) {
465 }
466 }
467 }
468 }
469
470 if (gli_conf_save_window_size) {
471 NSString *sizeobj = config[@"window.size"];
472 if (sizeobj) {
473 std::string size = [sizeobj UTF8String];
474 std::regex size_re(R"(^@Size\((\d+) (\d+)\)$)");
475 std::smatch cm;
476 if (std::regex_match(size, cm, size_re) && cm.size() == 3) {
477 try {
478 auto tmpwidth = std::stoi(cm[1]);
479 auto tmpheight = std::stoi(cm[2]);
480
481 width = tmpwidth;
482 height = tmpheight;
483 } catch (...) {
484 }
485 }
486 }
487 }
488
489 if (gli_conf_save_window_location || gli_conf_save_window_size) {
490 NSNumber *fsobj = config[@"window.fullscreen"];
491 if (fsobj) {
492 do_fullscreen = [fsobj boolValue];
493 }
494 }
495 }
496
497 [gargoyle initWindow: processID
498 move: move
499 x: x
500 y: y
501 width: width
502 height: height
503 fullscreen: do_fullscreen
504 backgroundColor: windowColor];
505
506 wintitle();
507 winresize();
508
509 [pool drain];
510 }
511
512 void winrepaint(int x0, int y0, int x1, int y1)
513 {
514 gli_refresh_needed = true;
515 }
516
517 bool windark()
518 {
519 NSString *theme = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
520
521 return [theme isEqualToString:@"Dark"];
522 }
523
524 void winrefresh()
525 {
526 gli_windows_redraw();
527
528 NSData *frame = [NSData dataWithBytesNoCopy: gli_image_rgb.data()
529 length: gli_image_rgb.size()
530 freeWhenDone: NO];
531
532 int refreshed = [gargoyle setWindow: processID
533 contents: frame
534 width: gli_image_rgb.width()
535 height: gli_image_rgb.height()];
536
537 gli_refresh_needed = !refreshed;
538 }
539
540 static void show_alert(NSAlertStyle style, NSString *title, const std::string &text)
541 {
542 NSAlert *alert = [[NSAlert alloc] init];
543 alert.alertStyle = style;
544 alert.messageText = title;
545 alert.informativeText = [NSString stringWithUTF8String: text.c_str()];
546 alert.window.level = NSModalPanelWindowLevel;
547 [alert runModal];
548 [alert release];
549 }
550
551 static void show_info(NSString *title, const std::string &text)
552 {
553 show_alert(NSAlertStyleInformational, title, text);
554 }
555
556 static void show_warning(NSString *title, const std::string &text)
557 {
558 show_alert(NSAlertStyleWarning, title, text);
559 }
560
561 static void show_error(NSString *title, const std::string &text)
562 {
563 show_alert(NSAlertStyleCritical, title, text);
564 }
565
566 static void show_paths()
567 {
568 std::string text = "Configuration file paths:\n\n";
569 for (const auto &config : garglk::all_configs) {
570 text += Format("• {} {}\n", config.path, config.format_type());
571 }
572
573 text += "\nTheme paths:\n\n";
574 auto theme_paths = garglk::theme::paths();
575 std::reverse(theme_paths.begin(), theme_paths.end());
576 for (const auto &path : theme_paths) {
577 text += Format("• {}\n", path);
578 }
579
580 show_info(@"Paths", text);
581 }
582
583 static void show_themes()
584 {
585 std::string text = "The following themes are available:\n\n";
586 auto theme_names = garglk::theme::names();
587
588 std::sort(theme_names.begin(), theme_names.end());
589 for (const auto &theme_name : theme_names) {
590 text += Format("• {}\n", theme_name);
591 }
592
593 show_info(@"Themes", text);
594 }
595
596 void winkey(NSEvent *evt)
597 {
598 NSEventModifierFlags modifiers = [evt modifierFlags];
599 NSEventModifierFlags modmasked = modifiers & (NSEventModifierFlagOption | NSEventModifierFlagShift | NSEventModifierFlagCommand | NSEventModifierFlagControl);
600
601 // queue a screen refresh
602 gli_refresh_needed = true;
603
604 // special key combinations
605 static const std::map<std::pair<decltype(modmasked), decltype([evt keyCode])>, std::function<void()>> keys = {
606 // alt/option modified arrow key
607 {{NSEventModifierFlagOption, NSKEY_LEFT}, []{ gli_input_handle_key(keycode_SkipWordLeft); }},
608 {{NSEventModifierFlagOption, NSKEY_RIGHT}, []{ gli_input_handle_key(keycode_SkipWordRight); }},
609 {{NSEventModifierFlagOption, NSKEY_DOWN}, []{ gli_input_handle_key(keycode_PageDown); }},
610 {{NSEventModifierFlagOption, NSKEY_UP}, []{ gli_input_handle_key(keycode_PageUp); }},
611
612 // command modified arrow key
613 {{NSEventModifierFlagCommand, NSKEY_LEFT}, []{ gli_input_handle_key(keycode_Home); }},
614 {{NSEventModifierFlagCommand, NSKEY_RIGHT}, []{ gli_input_handle_key(keycode_End); }},
615 {{NSEventModifierFlagCommand, NSKEY_DOWN}, []{ gli_input_handle_key(keycode_PageDown); }},
616 {{NSEventModifierFlagCommand, NSKEY_UP}, []{ gli_input_handle_key(keycode_PageUp); }},
617
618 // menu commands
619 {{NSEventModifierFlagCommand, NSKEY_X}, []{ winclipsend(); }},
620 {{NSEventModifierFlagCommand, NSKEY_C}, []{ winclipsend(); }},
621 {{NSEventModifierFlagCommand, NSKEY_V}, []{ winclipreceive(); }},
622
623 // info
624 {{NSEventModifierFlagCommand, NSKEY_PERIOD}, show_paths},
625 {{NSEventModifierFlagShift | NSEventModifierFlagCommand, NSKEY_T}, show_themes},
626
627 // readline/emacs-style controls
628 {{NSEventModifierFlagControl, NSKEY_A}, []{ gli_input_handle_key(keycode_Home); }},
629 {{NSEventModifierFlagControl, NSKEY_B}, []{ gli_input_handle_key(keycode_Left); }},
630 {{NSEventModifierFlagControl, NSKEY_D}, []{ gli_input_handle_key(keycode_Erase); }},
631 {{NSEventModifierFlagControl, NSKEY_E}, []{ gli_input_handle_key(keycode_End); }},
632 {{NSEventModifierFlagControl, NSKEY_F}, []{ gli_input_handle_key(keycode_Right); }},
633 {{NSEventModifierFlagControl, NSKEY_H}, []{ gli_input_handle_key(keycode_Delete); }},
634 {{NSEventModifierFlagControl, NSKEY_N}, []{ gli_input_handle_key(keycode_Down); }},
635 {{NSEventModifierFlagControl, NSKEY_P}, []{ gli_input_handle_key(keycode_Up); }},
636 {{NSEventModifierFlagControl, NSKEY_U}, []{ gli_input_handle_key(keycode_Escape); }},
637
638 // unmodified key for line editing
639 {{0, NSKEY_LEFT}, []{ gli_input_handle_key(keycode_Left); }},
640 {{0, NSKEY_RIGHT}, []{ gli_input_handle_key(keycode_Right); }},
641 {{0, NSKEY_DOWN}, []{ gli_input_handle_key(keycode_Down); }},
642 {{0, NSKEY_UP}, []{ gli_input_handle_key(keycode_Up); }},
643
644 // command keys
645 {{0, NSKEY_PGUP}, []{ gli_input_handle_key(keycode_PageUp); }},
646 {{0, NSKEY_PGDN}, []{ gli_input_handle_key(keycode_PageDown); }},
647 {{0, NSKEY_HOME}, []{ gli_input_handle_key(keycode_Home); }},
648 {{0, NSKEY_END}, []{ gli_input_handle_key(keycode_End); }},
649 {{0, NSKEY_DEL}, []{ gli_input_handle_key(keycode_Erase); }},
650 {{0, NSKEY_BACK}, []{ gli_input_handle_key(keycode_Delete); }},
651 {{0, NSKEY_ESC}, []{ gli_input_handle_key(keycode_Escape); }},
652 {{0, NSKEY_F1}, []{ gli_input_handle_key(keycode_Func1); }},
653 {{0, NSKEY_F2}, []{ gli_input_handle_key(keycode_Func2); }},
654 {{0, NSKEY_F3}, []{ gli_input_handle_key(keycode_Func3); }},
655 {{0, NSKEY_F4}, []{ gli_input_handle_key(keycode_Func4); }},
656 {{0, NSKEY_F5}, []{ gli_input_handle_key(keycode_Func5); }},
657 {{0, NSKEY_F6}, []{ gli_input_handle_key(keycode_Func6); }},
658 {{0, NSKEY_F7}, []{ gli_input_handle_key(keycode_Func7); }},
659 {{0, NSKEY_F8}, []{ gli_input_handle_key(keycode_Func8); }},
660 {{0, NSKEY_F9}, []{ gli_input_handle_key(keycode_Func9); }},
661 {{0, NSKEY_F10}, []{ gli_input_handle_key(keycode_Func10); }},
662 {{0, NSKEY_F11}, []{ gli_input_handle_key(keycode_Func11); }},
663 {{0, NSKEY_F12}, []{ gli_input_handle_key(keycode_Func12); }},
664
665 // save transcript
666 {{NSEventModifierFlagShift | NSEventModifierFlagCommand, NSKEY_S}, []{
667 auto text = gli_get_scrollback();
668 if (text.has_value()) {
669 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
670
671 NSString *fileref = [gargoyle saveWindowDialog: processID
672 prompt: @"Save transcript"
673 filter: FileFilter::Text
674 savedir: nil];
675
676 if (fileref != nullptr) {
677 std::string filename = [fileref UTF8String];
678
679 std::ofstream file(filename, std::ios::binary);
680 if (file.is_open()) {
681 if (!file.write(text->data(), text->size())) {
682 show_error(@"Error", "Error writing entire transcript.");
683 }
684 } else {
685 show_error(@"Error", "Unable to open file for writing.");
686 }
687 }
688
689 [pool drain];
690 } else {
691 show_warning(@"Warning", "Could not find appropriate window for scrollback.");
692 }
693 }},
694
695 // toggle fullscreen
696 {{NSEventModifierFlagControl | NSEventModifierFlagCommand, NSKEY_F}, []{
697 [gargoyle toggleFullScreen: processID];
698 }},
699 };
700
701 try {
702 keys.at(std::make_pair(modmasked, [evt keyCode]))();
703 return;
704 } catch (const std::out_of_range &) {
705 }
706
707 // send combined keystrokes to text buffer
708 [gargoyle setWindow: processID charString: evt];
709
710 // retrieve character from buffer as string
711 NSString *evt_char = [gargoyle getWindowCharString: processID];
712
713 // convert character to UTF-32 value
714 glui32 ch;
715 NSUInteger used;
716 if ([evt_char getBytes: &ch maxLength: sizeof ch usedLength: &used
717 encoding: UTF32StringEncoding
718 options: 0
719 range: NSMakeRange(0, [evt_char length])
720 remainingRange: nullptr]) {
721 if (used != 0) {
722 switch (ch) {
723 case '\n':
724 gli_input_handle_key(keycode_Return);
725 break;
726 case '\t':
727 gli_input_handle_key(keycode_Tab);
728 break;
729 default:
730 gli_input_handle_key(ch);
731 break;
732 }
733 }
734 }
735
736 // discard contents of text buffer
737 [gargoyle clearWindowCharString: processID];
738 }
739
740 void winmouse(NSEvent *evt)
741 {
742 NSPoint coords = [gargoyle getWindowPoint: processID forEvent: evt];
743
744 int x = coords.x * gli_backingscalefactor;
745 int y = gli_image_rgb.height() - (coords.y * gli_backingscalefactor);
746
747 // disregard most events outside of content window
748 if ((coords.y < 0 || y < 0 || x < 0 || x > gli_image_rgb.width())
749 && ([evt type] != NSEventTypeLeftMouseUp)) {
750 return;
751 }
752
753 switch ([evt type]) {
754 case NSEventTypeLeftMouseDown: {
755 gli_input_handle_click(x, y);
756 [gargoyle setCursor:kArrowCursor];
757 break;
758 }
759
760 case NSEventTypeLeftMouseDragged: {
761 if (gli_copyselect) {
762 [gargoyle setCursor:kIBeamCursor];
763 gli_move_selection(x, y);
764 }
765 break;
766 }
767
768 case NSEventTypeMouseMoved: {
769 if (gli_get_hyperlink(x, y)) {
770 [gargoyle setCursor:kPointingHandCursor];
771 } else {
772 [gargoyle setCursor:kArrowCursor];
773 }
774 break;
775 }
776
777 case NSEventTypeLeftMouseUp: {
778 gli_copyselect = false;
779 [gargoyle setCursor:kArrowCursor];
780 break;
781 }
782
783 case NSEventTypeScrollWheel: {
784 if ([evt deltaY] > 0) {
785 gli_input_handle_key(keycode_MouseWheelUp);
786 } else if ([evt deltaY] < 0) {
787 gli_input_handle_key(keycode_MouseWheelDown);
788 }
789 break;
790 }
791
792 default:
793 break;
794 }
795 }
796
797 void winevent(NSEvent *evt)
798 {
799 if (!evt) {
800 gli_event_waiting = false;
801 return;
802 }
803
804 switch ([evt type]) {
805 case NSEventTypeKeyDown: {
806 winkey(evt);
807 return;
808 }
809
810 case NSEventTypeLeftMouseDown:
811 case NSEventTypeLeftMouseDragged:
812 case NSEventTypeLeftMouseUp:
813 case NSEventTypeMouseMoved:
814 case NSEventTypeScrollWheel: {
815 winmouse(evt);
816 return;
817 }
818
819 case NSEventTypeApplicationDefined: {
820 gli_refresh_needed = true;
821 winresize();
822 return;
823 }
824
825 default:
826 return;
827 }
828 }
829
830 // winloop handles at most one event
831 void winloop()
832 {
833 NSEvent *evt = nullptr;
834
835 if (gli_refresh_needed) {
836 winrefresh();
837 }
838
839 if (gli_event_waiting) {
840 evt = [gargoyle getWindowEvent:processID];
841 }
842
843 winevent(evt);
844 }
845
846 // winpoll handles all queued events
847 void winpoll()
848 {
849 NSEvent *evt = nullptr;
850
851 do {
852 if (gli_refresh_needed) {
853 winrefresh();
854 }
855
856 if (gli_event_waiting) {
857 evt = [gargoyle getWindowEvent: processID];
858 }
859
860 winevent(evt);
861 } while (evt);
862 }
863
864 nonstd::optional<std::string> garglk::winfontpath(const std::string &filename)
865 {
866 char *resources = std::getenv("GARGLK_RESOURCES");
867
868 if (resources != nullptr) {
869 return Format("{}/Fonts/{}", resources, filename);
870 }
871
872 return nonstd::nullopt;
873 }
874
875 std::string garglk::windatadir()
876 {
877 char *resources = std::getenv("GARGLK_RESOURCES");
878
879 if (resources != nullptr) {
880 return resources;
881 }
882
883 return ".";
884 }
885
886 std::vector<std::string> garglk::winthemedirs()
887 {
888 NSArray *appdir_paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
889 char *resources = std::getenv("GARGLK_RESOURCES");
890 std::vector<std::string> paths;
891
892 if (resources != nullptr) {
893 paths.push_back(Format("{}/themes", resources));
894 }
895
896 // This is what Qt returns for AppDataLocation (though Qt adds a
897 // few more directories that aren't particularly relevant).
898 for (NSString *appdir_path in appdir_paths) {
899 paths.push_back(Format("{}/Gargoyle/themes", [appdir_path UTF8String]));
900 }
901
902 return paths;
903 }
904
905 nonstd::optional<std::string> garglk::winlegacythemedir() {
906 return [[NSHomeDirectory() stringByAppendingPathComponent: @"Library/Application Support/io.github.garglk/Gargoyle/themes"] UTF8String];
907 }
908
909 nonstd::optional<std::string> garglk::winappdir()
910 {
911 // This is only used on Windows.
912 return nonstd::nullopt;
913 }
914
915 bool garglk::winisfullscreen()
916 {
917 return [gargoyle isFullScreen: processID];
918 }
919
920 void gli_select(event_t *event, bool polled)
921 {
922 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
923
924 gli_event_clearevent(event);
925
926 winpoll();
927 gli_dispatch_event(event, polled);
928
929 if (event->type == evtype_None && !polled) {
930 while (![monitor timeout]) {
931 winloop();
932 gli_dispatch_event(event, polled);
933
934 if (event->type == evtype_None) {
935 [monitor sleep];
936 } else {
937 break;
938 }
939 }
940 }
941
942 if (event->type == evtype_None && [monitor timeout]) {
943 gli_event_store(evtype_Timer, nullptr, 0, 0);
944 gli_dispatch_event(event, polled);
945 [monitor reset];
946 }
947
948 [pool drain];
949 }