-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmacos.zig
More file actions
3925 lines (3561 loc) · 190 KB
/
Copy pathmacos.zig
File metadata and controls
3925 lines (3561 loc) · 190 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// macOS host — drop-down terminal entry point.
//
// 진행 상태는 이슈 #108 참고.
//
// M1 — host 골격 + fail-fast 메시지 (5a336db).
// M2 — NSWindow + CAMetalLayer 빈 화면 + Cmd+Q (ae2328b).
// M3 — borderless + dock rect + F1 글로벌 핫키 토글. (현재)
// M3.5 — config.zig platform-leak 정리, NSAlert 기반 config 에러.
// M4 — 모니터/DPI 변화 시 재적용.
// M5 — POSIX PTY + ghostty-vt + CoreText/Metal 글리프.
// M6 — 한글 IME.
//
// M3 의 검증 포인트 (옵션 D 핵심 가설):
// F1 두 번 → 윈도우 hide/show 토글에서 잔상 / 깜박임 없음.
// 사용자 드래그 리사이즈는 borderless + non-resizable styleMask 로 OS 차단.
// #75 가 6번 시도해도 못 풀던 \"드래그 중 잔상\" 시나리오를 원천 회피.
const std = @import("std");
const run_options = @import("../run_options.zig");
const build_options = @import("build_options");
const objc = @import("../macos_objc.zig");
const config = @import("../config.zig");
const ghostty = @import("ghostty-vt");
const display_width = @import("../font/display_width.zig");
const renderer_module = @import("../renderer.zig");
// macOS 전용 host — render present/합성 게이트(#255 Phase 2) free 함수 직접 접근.
const mac_renderer = @import("../renderer/macos.zig");
const ui_metrics = @import("../ui_metrics.zig");
const scrollbar = @import("../scrollbar.zig");
const terminal = @import("../terminal.zig");
const terminal_interaction = @import("../terminal_interaction.zig");
const tab_interaction = @import("../tab_interaction.zig");
const tab_layout = @import("../tab_layout.zig");
const tab_actions = @import("../tab_actions.zig");
const input_policy = @import("../input_policy.zig");
const session_core = @import("../session_core.zig");
const themes = @import("../themes.zig");
const dialog = @import("../dialog.zig");
const messages = @import("../messages.zig");
const command_menu = @import("../command_menu.zig");
const about = @import("../about.zig");
const log = @import("../log.zig");
const perf = @import("../perf.zig");
const instance_context = @import("../instance_context.zig");
const instances = @import("../instances.zig");
pub fn showPanic(msg: []const u8, addr: usize, _: ?*std.builtin.StackTrace) noreturn {
log.appendLine("panic", "{s} return_addr=0x{x}", .{ msg, addr });
var buf: [512]u8 = undefined;
const text = std.fmt.bufPrint(&buf, messages.panic_format, .{ msg, addr }) catch messages.panic_fallback_msg;
dialog.showError(messages.crash_title, text);
std.process.exit(1);
}
pub fn showFatalRunError(err: anyerror) void {
log.appendLine("fatal", "run failed: {s}", .{@errorName(err)});
var buf: [256]u8 = undefined;
const text = messages.runFailureMessage(&buf, err);
dialog.showError(messages.error_title, text);
}
// AppKit / Metal 상수.
const NSWindowStyleMaskBorderless: c_ulong = 0;
const NSWindowStyleMaskTitled: c_ulong = 1 << 0;
const NSWindowStyleMaskFullSizeContentView: c_ulong = 1 << 15;
const NSBackingStoreBuffered: c_ulong = 2;
// `Regular` (0) = Dock + Cmd+Tab + 메뉴바 등장 (일반 앱).
// `Accessory` (1) = Dock / Cmd+Tab 안 보임, 메뉴바도 우리 앱 메뉴 안 뜸. drop-down
// 터미널 정체성. Info.plist 의 LSUIElement = true 와 같은 효과지만 코드 레벨이라
// LaunchServices 캐시 / 직접 실행 / open 실행 무관하게 즉시 적용된다.
const NSApplicationActivationPolicyAccessory: c_long = 1;
const MTLPixelFormatBGRA8Unorm: c_ulong = 80;
// `standardWindowButton:` 인덱스 — close=0, miniaturize=1, zoom=2.
const NSWindowCloseButton: c_long = 0;
const NSWindowMiniaturizeButton: c_long = 1;
const NSWindowZoomButton: c_long = 2;
// `setTitleVisibility:` 의 NSWindowTitleHidden = 1.
const NSWindowTitleHidden: c_long = 1;
// CGEventFlags modifier 마스크 (CGEventTypes.h). Carbon modifier (1<<8 등) 와
// 다른 비트 위치. 예: command = 1<<20.
const kCGEventFlagMaskCommand: u64 = 0x00100000;
const kCGEventFlagMaskShift: u64 = 0x00020000;
const kCGEventFlagMaskAlternate: u64 = 0x00080000; // = Option
const kCGEventFlagMaskControl: u64 = 0x00040000;
const kCGEventFlagsAllModifiers: u64 = kCGEventFlagMaskCommand | kCGEventFlagMaskShift | kCGEventFlagMaskAlternate | kCGEventFlagMaskControl;
const CGFloat = f64;
const NSRect = extern struct { origin: NSPoint, size: NSSize };
const NSPoint = extern struct { x: CGFloat, y: CGFloat };
const NSSize = extern struct { width: CGFloat, height: CGFloat };
// CGEventTap FFI (CoreGraphics).
//
// Apple DTS 권장 패턴: CGEventTapCreate 로 system-wide 키보드 이벤트 가로채기
// + CFRunLoopAddSource 로 NSApp 의 main run loop 에 통합. Carbon RegisterEvent
// HotKey 와 달리 Apple Developer 인증서 sign 없이도 동작 (단 \"Input Monitoring\"
// 권한 필요 — 사용자가 시스템 설정에서 활성화).
//
// 참고: ghostty Quick Terminal 의 GlobalEventTap.swift 도 같은 길.
const CGEventRef = ?*anyopaque;
const CFMachPortRef = ?*anyopaque;
const CFRunLoopSourceRef = ?*anyopaque;
const CFRunLoopRef = ?*anyopaque;
const CFStringRef = ?*anyopaque;
const CGEventTapLocation = c_int;
const CGEventTapPlacement = c_int;
const CGEventTapOptions = c_int;
const CGEventMask = u64;
const CGEventField = u32;
const CGEventType = c_int;
const kCGSessionEventTap: CGEventTapLocation = 1;
const kCGHeadInsertEventTap: CGEventTapPlacement = 0;
const kCGEventTapOptionDefault: CGEventTapOptions = 0;
const kCGEventKeyDown: CGEventType = 10;
// CGEventTap 이 OS 에 의해 자동 비활성화될 때 callback 으로 들어오는 special
// type (#146). callback 응답 timeout 또는 user input race 시 발생. -1 / -2 의
// signed 값이라 c_int (= CGEventType).
const kCGEventTapDisabledByTimeout: CGEventType = -2;
const kCGEventTapDisabledByUserInput: CGEventType = -1;
const kCGKeyboardEventKeycode: CGEventField = 9;
const CGEventTapCallBack = *const fn (
proxy: ?*anyopaque,
event_type: CGEventType,
event: CGEventRef,
userInfo: ?*anyopaque,
) callconv(.c) CGEventRef;
extern fn CGEventTapCreate(
tap: CGEventTapLocation,
place: CGEventTapPlacement,
options: CGEventTapOptions,
eventsOfInterest: CGEventMask,
callback: CGEventTapCallBack,
userInfo: ?*anyopaque,
) CFMachPortRef;
extern fn CGEventTapEnable(tap: CFMachPortRef, enable: bool) void;
extern fn CGEventGetIntegerValueField(event: CGEventRef, field: CGEventField) i64;
extern fn CGEventGetFlags(event: CGEventRef) u64;
extern fn CFMachPortCreateRunLoopSource(
allocator: ?*anyopaque,
port: CFMachPortRef,
order: usize,
) CFRunLoopSourceRef;
extern fn CFRunLoopGetMain() CFRunLoopRef;
extern fn CFRunLoopAddSource(runloop: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef) void;
extern fn CFRunLoopRemoveSource(runloop: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef) void;
extern fn CFMachPortInvalidate(port: CFMachPortRef) void;
// GCD — 콜백 안에서 tap 자기 자신을 destroy 하기 위해 main run loop 의
// 다음 turn 으로 작업 deferral. `dispatch_get_main_queue()` 는 macOS 헤더에
// static inline 이라 link symbol 없음 — 실제 export 되는 `_dispatch_main_q`
// 글로벌 변수의 주소를 dispatch_queue_t 로 직접 사용 (Apple SDK 가 헤더에서
// 그렇게 풀어내는 것과 동일).
extern var _dispatch_main_q: anyopaque;
const dispatch_function_t = *const fn (?*anyopaque) callconv(.c) void;
extern fn dispatch_async_f(queue: *anyopaque, ctx: ?*anyopaque, work: dispatch_function_t) void;
// render 는 CADisplayLink (`NSWindow.displayLink(target:selector:)`, macOS 14+)
// 가 vsync 마다 main thread 에서 구동한다. 시스템이 합성 타이밍/재생률을 관리
// 하고, 창이 디스플레이에 없으면(hidden) AppKit 이 link 를 자동 suspend 해
// idle 시 render 0 — 옛 CFRunLoopTimer(60fps 무조건 fire)를 대체 (#255).
// kCFRunLoopCommonModes 는 CFString 상수 (Apple 의 CFRunLoop.h). NSString 과
// toll-free bridge 라 NSRunLoop addToRunLoop:forMode: 의 mode 로도 쓴다.
extern const kCFRunLoopCommonModes: CFStringRef;
// Input Monitoring 권한 (macOS 10.15+).
extern fn CGPreflightListenEventAccess() bool;
extern fn CGRequestListenEventAccess() bool;
// Accessibility (손쉬운 사용) 권한 — `kCGEventTapOptionDefault` (active tap)
// 으로 이벤트 변경 / 삼키기 시 macOS 가 추가로 요구. ListenOnly 면 Input
// Monitoring 만으로 충분하지만, 우리는 F1/Cmd+Q 를 다른 앱에 전달 안 되게
// consume 해야 하므로 active 가 필수.
extern fn AXIsProcessTrusted() bool;
extern "c" fn atexit(func: *const fn () callconv(.c) void) c_int;
/// `atexit` 핸들러 — Cmd+Q (NSApp `terminate:`) 가 defer 거치지 않고 `exit()`
/// 직행하므로 run() 의 `defer logStop` 이 안 불린다. `atexit` 는 `exit()`
/// 호출되면 동작하니 여기서 [exit] 라인 기록.
fn atExitLogStop() callconv(.c) void {
log.logStop(build_options.version);
}
// NSApplication delegate — `applicationShouldTerminate:` 한 메서드만 구현.
// 모든 `terminate:` 호출 (Cmd+Q / 메뉴 / 마지막 탭 종료) 가 진입하기 전에
// macOS 가 이 hook 을 거치게 해 사용자에게 confirm 을 물음 (#116).
const NSTerminateCancel: c_long = 0;
const NSTerminateNow: c_long = 1;
/// 종료 직전 confirm. count == 0 (마지막 탭 PTY exit 후 자동 종료) 만 skip —
/// 이미 사용자 의도된 종료 path. 단일 탭 (count==1) 도 confirm — 사용자 정책.
fn applicationShouldTerminate(_: objc.id, _: objc.SEL, _: objc.id) callconv(.c) c_long {
// #317 — programmatic `terminate:`도 confirm 전에 공통 shortcut 정책을
// 적용한다. 메뉴 Cmd+Q는 tildazQuit:에서 먼저 적용하므로 여기서는 no-op이고,
// Cancel 뒤 재시도도 첫 호출에서 pending 상태가 이미 비어 no-op이다.
applyShortcutInputPolicy(.quit);
const n = g_session.count();
if (n == 0) return NSTerminateNow;
var msg_buf: [256]u8 = undefined;
const msg = dialog.quitConfirmMessage(&msg_buf, n) orelse return NSTerminateNow;
return if (dialog.showConfirm(messages.quit_confirm_title, msg)) NSTerminateNow else NSTerminateCancel;
}
/// #195 — 다른 app 활성화 시 우리 NSWindow level 을 normal (0) 로 떨어뜨림.
/// 그 app 이 z-order 상 위로 올라오고, 우리는 *visible 유지* (drop-down 본분 —
/// hide 안 함, 다른 app 뒤에 보임). 다시 우리 app 활성화 (`DidBecomeActive`)
/// 시 popUpMenu (101) 로 복귀 — dock / menu bar 위에 우리가 다시 자리잡음.
///
/// IME 후보 panel (`lowerWindowForImePanel`) 경로와는 별개 — 그쪽은 우리 app
/// 활성 + IME 후보 표시 시 floating (3) 으로 잠깐 낮춤. `setPopupWindowLevel`
/// 호출 시 `g_ime_panel_window_lowered=false` 까지 한 번 reset — IME 가 다시
/// 후보 띄울 때 `lowerWindowForImePanel` 재호출.
fn applicationDidResignActive(_: objc.id, _: objc.SEL, _: objc.id) callconv(.c) void {
if (!g_visible) return;
const NSNormalWindowLevel: c_int = 0;
setMainWindowLevel(NSNormalWindowLevel);
}
fn applicationDidBecomeActive(_: objc.id, _: objc.SEL, _: objc.id) callconv(.c) void {
if (!g_visible) return;
setPopupWindowLevel();
}
fn createNewInstance() void {
if (@import("../instance_context.zig").requireWorkerIndex() == 0) {
repositionWindow();
showWindow();
@import("../new_instance.zig").handle(g_gpa.allocator());
} else {
@import("../instance_request.zig").send() catch {};
}
}
fn applicationShouldHandleReopen(_: objc.id, _: objc.SEL, _: objc.id, _: bool) callconv(.c) bool {
createNewInstance();
return false;
}
fn newInstanceNotification(_: objc.id, _: objc.SEL, _: objc.id) callconv(.c) void {
if (@import("../instance_context.zig").requireWorkerIndex() == 0) createNewInstance();
}
fn hotkeyCaptureBeginNotification(_: objc.id, _: objc.SEL, _: objc.id) callconv(.c) void {
@import("../hotkey_capture/macos.zig").setSuspended(true);
}
fn hotkeyCaptureEndNotification(_: objc.id, _: objc.SEL, _: objc.id) callconv(.c) void {
@import("../hotkey_capture/macos.zig").setSuspended(false);
}
var g_app_delegate_class: ?objc.Class = null;
var g_app_delegate_instance: objc.id = null;
var g_new_instance_observer_registered = false;
fn installAppDelegate() !void {
if (g_app_delegate_instance != null) return;
const NSObject = objc.getClass("NSObject");
const cls = objc.objc_allocateClassPair(NSObject, "TildazAppDelegate", 0) orelse
return error.AppDelegateAllocFailed;
// 시그니처: 반환 NSApplicationTerminateReply (NSUInteger 호환 c_long),
// self (id) + _cmd (SEL) + sender (NSApplication id).
if (!objc.class_addMethod(cls, objc.sel("applicationShouldTerminate:"), @ptrCast(&applicationShouldTerminate), "Q@:@"))
return error.AppDelegateAddMethodFailed;
// #195 — focus loss / regain z-order toggle. visible 유지, level 만 조정.
if (!objc.class_addMethod(cls, objc.sel("applicationDidResignActive:"), @ptrCast(&applicationDidResignActive), "v@:@"))
return error.AppDelegateAddMethodFailed;
if (!objc.class_addMethod(cls, objc.sel("applicationDidBecomeActive:"), @ptrCast(&applicationDidBecomeActive), "v@:@"))
return error.AppDelegateAddMethodFailed;
if (!objc.class_addMethod(cls, objc.sel("applicationShouldHandleReopen:hasVisibleWindows:"), @ptrCast(&applicationShouldHandleReopen), "B@:@B"))
return error.AppDelegateAddMethodFailed;
if (!objc.class_addMethod(cls, objc.sel("newInstanceNotification:"), @ptrCast(&newInstanceNotification), "v@:@"))
return error.AppDelegateAddMethodFailed;
if (!objc.class_addMethod(cls, objc.sel("hotkeyCaptureBeginNotification:"), @ptrCast(&hotkeyCaptureBeginNotification), "v@:@"))
return error.AppDelegateAddMethodFailed;
if (!objc.class_addMethod(cls, objc.sel("hotkeyCaptureEndNotification:"), @ptrCast(&hotkeyCaptureEndNotification), "v@:@"))
return error.AppDelegateAddMethodFailed;
objc.objc_registerClassPair(cls);
g_app_delegate_class = cls;
const alloc = objc.objcSend(fn (objc.Class, objc.SEL) callconv(.c) objc.id);
const init_obj = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) objc.id);
const inst = init_obj(alloc(cls, objc.sel("alloc")) orelse return error.AppDelegateInitFailed, objc.sel("init")) orelse
return error.AppDelegateInitFailed;
g_app_delegate_instance = inst;
const setDelegate = objc.objcSend(fn (objc.id, objc.SEL, objc.id) callconv(.c) void);
setDelegate(g_app, objc.sel("setDelegate:"), inst);
const Center = objc.getClass("NSDistributedNotificationCenter");
const getCenter = objc.objcSend(fn (objc.Class, objc.SEL) callconv(.c) objc.id);
if (getCenter(Center, objc.sel("defaultCenter"))) |center| {
const addObserver = objc.objcSend(fn (objc.id, objc.SEL, objc.id, objc.SEL, objc.id, objc.id) callconv(.c) void);
addObserver(
center,
objc.sel("addObserver:selector:name:object:"),
inst,
objc.sel("newInstanceNotification:"),
objc.nsString(@import("../instance_request/macos.zig").notification_name),
null,
);
g_new_instance_observer_registered = true;
const capture = @import("../hotkey_capture/macos.zig");
addObserver(center, objc.sel("addObserver:selector:name:object:"), inst, objc.sel("hotkeyCaptureBeginNotification:"), objc.nsString(capture.begin_notification_name), null);
addObserver(center, objc.sel("addObserver:selector:name:object:"), inst, objc.sel("hotkeyCaptureEndNotification:"), objc.nsString(capture.end_notification_name), null);
}
}
extern fn MTLCreateSystemDefaultDevice() objc.id;
// 글로벌 toggle 상태 — CGEventTap 콜백 (C 시그니처) 이 NSApp / window / config
// 에 접근하려면 어딘가 보관해야 함. M3 단계에서 host 가 한 인스턴스만 띄우므로
// 모듈 전역으로 충분. M5 이후 multi-window / multi-tab 으로 확장 시 userdata
// 포인터 패턴으로 옮길 예정.
var g_app: objc.id = null;
var g_window: objc.id = null;
var g_visible: bool = false;
var g_config: config.Config = .{};
var g_gpa: std.heap.GeneralPurposeAllocator(.{}) = .init;
/// 멀티탭 컬렉션 (#111 M11.1). 현재 단계는 데이터 모델만 도입 — 실제로는
/// 단일 탭만 생성. PTY / Terminal / Stream / 마우스 selection 은 모두 활성
/// 탭의 필드. host 코드는 `g_session.activeTab().?.{pty,terminal,...}` 로 access.
///
/// thread safety (M5.1 노트): UI thread 가 terminal 을 안 읽으므로 PTY read
/// thread 가 직접 stream parsing 해도 race 없음. 멀티탭 도입해도 활성 탭만
/// 렌더링 + 입력 받으니 동일 — 단 closeTab 은 read thread 가 살아 있을 때
/// 위험하므로 후속 milestone 에서 join 처리.
var g_session: session_core.SessionCore = undefined;
/// #382 — 측정용 실행 옵션. `run()` 이 받아 여기 저장하고, 아래 네 지점이 참조한다:
/// 전역 핫키 등록 · 창 표시 · 창 크기 (`dockRect`) · 첫 탭의 셸.
var g_run_opts: run_options.RunOptions = .{};
/// PTY 자식 종료 시 read thread 가 enqueue, main thread (renderFrameTick) 가
/// drain. session_core 의 tab_exit_fn 이 read thread context 에서 불리는데
/// 거기서 closeTabByPtr 직접 호출하면 self-join deadlock — read thread 가
/// 자기 자신을 join 하게 됨. Windows 의 PostMessage 패턴과 같은 의도이지만
/// CFRunLoop 우회 — 단순 mutex-protected queue 로 충분 (renderFrameTick 가
/// main thread 에서 매 frame drain).
var g_pending_close_buf: std.ArrayList(usize) = .{};
var g_pending_close_mutex: std.Thread.Mutex = .{};
/// #255 Phase 2 — visible-but-idle render skip. displayLink 가 vsync 마다 fire 해도
/// 변화 없으면 그릴 게 없다. 렌더 필요 = ① PTY 출력(drainOutputForRender 반환)
/// ② 로컬 UI 변화(키/마우스/창 — 이 플래그) ③ preedit/autoscroll(force_render).
/// 셋 다 아니고 화면 표시까지 확정(frameWasPresented)되면 그 frame 의 render 작업을
/// skip(GPU 안 씀) — displayLink 는 visible 동안 계속 돌아 다음 변화를 다음 frame 이
/// 즉시 잡는다. 입력 핸들러·renderFrameTick 모두 main thread 라 atomic 불필요.
/// init=true(첫 프레임). requestRender() 로 set, render 후 clear.
var g_needs_render: bool = true;
/// #376 — 직전 tick 의 blink 위상. 이 값이 **바뀌는 프레임에만** 렌더 게이트를
/// 연다. "화면에 blink 셀이 있다" 로 열면 매 vsync 그리게 돼 #255 의 절전이
/// 사라지지만, 위상 전환은 1초에 두 번뿐이라 추가 렌더가 초당 2프레임이다.
var g_last_blink_phase: bool = false;
/// #245 — drag-select auto-scroll (mac). 선택 드래그 중 포인터가 grid 위/아래 경계
/// 밖이면 방향(-1=위/older, +1=아래/newer, 0=비활성) + 마지막 drag px 저장. 60fps
/// 렌더 tick(renderFrameTick)이 이 동안 viewport 스크롤 + selection.update 재호출
/// → 포인터를 멈춰 둬도 연속 스크롤 + scrollback 까지 선택 연장. mouseUp 에서 0.
var g_sel_autoscroll_dir: i8 = 0;
var g_sel_autoscroll_next_ms: i64 = 0;
var g_last_drag_x: f32 = 0;
var g_last_drag_y: f32 = 0;
/// 윈도우 표시 모드 (#162). Windows `FullscreenMode` 와 동등 — cross-platform.
/// - .none: dock rect (config.dock_position / width / height / offset 기반)
/// - .monitor: NSScreen.frame 통째 = 메뉴바 + dock 까지 덮음 ("전체화면")
/// - .workarea: NSScreen.visibleFrame = 메뉴바 + dock 회피 ("풀스크린")
///
/// 토글 정책: 들어간 키로만 나옴 (self-symmetric). Cmd+Enter 로 .monitor 진입
/// 시 같은 키로만 dock 복귀, Shift+Cmd+Enter 는 no-op. 같은 패턴으로 .workarea.
/// `.monitor ↔ .workarea` 직접 transition 없음.
const FullscreenMode = enum { none, monitor, workarea };
var g_fullscreen_mode: FullscreenMode = .none;
/// 탭 drag-and-drop reorder state (#111 M11.6a). Windows `tab_interaction.DragState`
/// 그대로 사용 — cross-platform 모듈.
var g_drag: tab_interaction.DragState = .{};
/// 탭바 스크롤 오프셋 (픽셀, #117). 탭바 총 너비가 viewport 너비를 초과하면
/// 활성 탭이 보이도록 자동 이동. Windows `App.tab_scroll_x` 와 동일 정책 — 매
/// frame `renderFrameTick` 에서 `ensureActiveTabVisible` 가 갱신, drag 중에는
/// `tildazMouseDragged` 가 직접 갱신.
var g_tab_scroll_x_px: f32 = 0;
/// #268 2b — 탭바 컨트롤 버튼 (`<` `>` `×` `+`) 의 hover 대상. mouseMoved:
/// 마다 갱신, 변경 시에만 재렌더. 렌더러가 hover 배경 박스를 그림.
var g_tab_hover: tab_layout.Area = .none;
/// #329 command/shortcut menu 표시 상태.
var g_command_menu_open: bool = false;
var g_command_menu_hover: ?command_menu.Command = null;
/// #329 — 메뉴 keyboard focus (Up/Down/Home/End/Tab 이동, Enter/Space 실행).
var g_command_menu_focus: ?command_menu.Command = null;
/// #329 — 작은 viewport 에서 entry 단위 scroll 의 첫 표시 entry 인덱스.
var g_command_menu_first: usize = 0;
/// #334 — 메뉴 wheel delta 누적 (트랙패드 과민 방지 — 12pt 당 1 entry).
var g_command_menu_scroll_accum: f64 = 0;
/// 사용자가 `<` / `>` 화살표를 눌러 viewport 를 옮긴 상태 (#117). 이 동안
/// `ensureActiveTabVisible` skip — 활성 탭 가려져도 그대로 (Firefox).
/// 활성 탭 변경 / drag reorder 끝 / 새 탭 생성 시 false 로 리셋.
var g_tab_scroll_user_override: bool = false;
/// `tab_actions.Host` 인스턴스 — module-level state (g_session 등) 를 cross-
/// platform helper API 로 노출. 모든 콜백은 mac specific (NSPasteboard, NSApp
/// terminate). invalidate 는 noop — mac 60fps timer 가 자동 redraw.
var g_host: tab_actions.Host = .{
.session = &g_session,
.override_ptr = &g_tab_scroll_user_override,
.invalidate = macHostInvalidate,
.clipboard_copy = macHostClipboardCopy,
.terminate = macHostTerminate,
};
fn macHostInvalidate(_: *tab_actions.Host) void {
// mac 은 renderFrameTick 이 vsync 마다 자동 호출 — 즉시 redraw 트리거 불필요.
}
/// NSPasteboard.general → clearContents → setString:forType:NSPasteboardTypeString.
/// text 는 caller 가 비어있지 않음 보장 (`tab_actions.copyActiveSelection` 가
/// len==0 검사 후 호출).
fn macHostClipboardCopy(_: *tab_actions.Host, text: [:0]const u8) void {
const NSPasteboard = objc.getClass("NSPasteboard");
const get_general = objc.objcSend(fn (objc.Class, objc.SEL) callconv(.c) objc.id);
const pb = get_general(NSPasteboard, objc.sel("generalPasteboard"));
if (pb == null) return;
const clear = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) c_long);
_ = clear(pb, objc.sel("clearContents"));
// text 가 std.heap allocator 에서 온 non-null-terminated slice — NSString
// 의 stringWithBytes:length:encoding: 사용 (UTF8 = 4).
const NSString = objc.getClass("NSString");
const stringWithBytes = objc.objcSend(fn (objc.Class, objc.SEL, [*]const u8, usize, c_ulong) callconv(.c) objc.id);
const ns_text = stringWithBytes(NSString, objc.sel("stringWithBytes:length:encoding:"), text.ptr, text.len, NSUTF8StringEncoding);
if (ns_text == null) return;
const setString = objc.objcSend(fn (objc.id, objc.SEL, objc.id, objc.id) callconv(.c) bool);
const ns_type = objc.nsString("public.utf8-plain-text"); // = NSPasteboardTypeString
_ = setString(pb, objc.sel("setString:forType:"), ns_text, ns_type);
}
fn macHostTerminate(_: *tab_actions.Host) void {
log.appendLine("tab", "last tab closed, terminating tildaz", .{});
const terminate_sel = objc.objcSend(fn (objc.id, objc.SEL, objc.id) callconv(.c) void);
terminate_sel(g_app, objc.sel("terminate:"), null);
}
/// 새 탭 생성 시 재사용할 PTY 파라미터들. 첫 탭 init 시 채우고 그 후 변동 없음.
var g_shell_path: []const u8 = "";
var g_extra_env: [5]terminal.ExtraEnv = undefined;
// M5.3 — Metal 렌더러 + timer + cell metrics. cell_width/height 는 폰트의
// 'M' advance / ascent+descent+leading 으로 동적 측정 (Windows 와 동일 패턴).
var g_metal_layer: objc.id = null;
var g_renderer: ?renderer_module.RendererBackend = null;
/// CADisplayLink (NSWindow.displayLink) — vsync render driver. null = 미생성.
var g_display_link: objc.id = null;
// 터미널 영역 안쪽 padding — `ui_metrics.zig` 의 공통 상수. Windows /
// macOS 동일 값으로 시각적 일관성 유지. pixel 변환은 init 시 retina scale 곱.
const TERMINAL_PADDING_PT = ui_metrics.TERMINAL_PADDING_PT;
const TAB_BAR_HEIGHT_PT = ui_metrics.TAB_BAR_HEIGHT_PT;
/// 탭바가 현재 차지하는 픽셀 높이. 탭이 ≤ 1 개면 0 (자리 안 띄움) — 단일 탭
/// 사용자가 위쪽 빈 공간 거슬려 함 (#111 M11.4 사용자 보고).
/// 탭 ≥ 2 개로 전환 시 자리 등장 + 모든 탭 cols/rows 재계산은 호출처 책임
/// (`syncTerminalGeometry` 가 통합 처리).
fn tabBarHeightPx(scale: f32) i32 {
if (g_session.count() < 2) return 0;
return @intCast(ui_metrics.tabBarHeightPx(scale));
}
/// #329 — terminal grid y-offset과 분리된 scrollbar 전용 top inset. 단일
/// 탭에서도 항상-visible control strip 아래부터 track이 시작한다.
fn scrollbarTopInsetPx(scale: f32) i32 {
return if (g_session.count() > 0) @intCast(ui_metrics.tabBarHeightPx(scale)) else 0;
}
/// 픽셀 단위 탭 너비 (DPI scale 적용). hit-test / drag / scroll 모두 같은 값.
fn tabWidthPx() f32 {
if (g_renderer == null) return 0;
return ui_metrics.scaledPxF(ui_metrics.TAB_WIDTH_PT, g_renderer.?.scale);
}
/// `tab_layout.Layout` alias — 본문 정의는 cross-platform 모듈 (#159 Phase 1).
const TabBarLayout = tab_layout.Layout;
/// `Inputs` 채워서 tab_layout.compute 호출. host 별로 g_renderer.scale /
/// g_session.count / g_tab_scroll_x_px 같은 글로벌을 인자로 변환만 함.
fn tabBarLayoutInputs() ?tab_layout.Inputs {
if (g_renderer == null) return null;
const r = &g_renderer.?;
// #329 정책 변경 (2026-07-22) — count >= MAX_TABS 여도 `+` 는 자리를
// 유지하고 비활성 색 + click noop. `[+][×][…]` 세 버튼이 항상 같은 자리.
// 단축키 경로의 한도 dialog 는 그대로.
const at_limit = g_session.count() >= session_core.MAX_TABS;
return .{
.viewport_w = @floatFromInt(r.vp_width),
.tab_count = @intCast(g_session.count()),
.tab_w = tabWidthPx(),
.arrow_w = ui_metrics.scaledPxF(ui_metrics.TAB_ARROW_W_PT, r.scale),
.plus_w = ui_metrics.scaledPxF(ui_metrics.TAB_PLUS_W_PT, r.scale),
.plus_enabled = !at_limit,
.close_w = ui_metrics.scaledPxF(ui_metrics.TAB_CLOSE_W_PT, r.scale),
.more_w = ui_metrics.scaledPxF(ui_metrics.TAB_MORE_W_PT, r.scale),
.scroll_x = g_tab_scroll_x_px,
};
}
fn tabBarLayout() TabBarLayout {
const inputs = tabBarLayoutInputs() orelse return .{
.tab_area_x = 0,
.tab_area_w = 0,
.arrows_visible = false,
.arrow_w = 0,
.plus_w = 0,
.plus_x = 0,
.close_w = 0,
.close_x = 0,
.more_w = 0,
.more_x = 0,
};
return tab_layout.compute(inputs);
}
/// 활성 탭이 viewport 안에 보이도록 `g_tab_scroll_x_px` 갱신 (#117 정책 b).
/// drag / 사용자 화살표 override 중에는 호출 안 함.
fn ensureActiveTabVisible() void {
const inputs = tabBarLayoutInputs() orelse {
g_tab_scroll_x_px = 0;
return;
};
const layout = tab_layout.compute(inputs);
g_tab_scroll_x_px = tab_layout.ensureActiveVisible(inputs, layout, @intCast(g_session.active_tab));
}
/// `<` / `>` 화살표 클릭 처리 (#117). viewport 한 step (= 1 탭 너비) 이동 +
/// user_override 활성. 양 끝 clamp.
fn scrollTabsByArrow(dir: tab_layout.ArrowDir) void {
const inputs = tabBarLayoutInputs() orelse return;
const layout = tab_layout.compute(inputs);
if (tab_layout.scrollByArrow(inputs, layout, dir)) |sx| {
g_tab_scroll_x_px = sx;
g_tab_scroll_user_override = true;
}
}
/// #352 — 터미널 격자 크기. 계산은 공통 `ui_metrics` 가 한다 (열 수 #350 / 행 수 #352).
///
/// **세 호출처의 9줄 복붙을 없애려고 둔 지역 helper 다.** `syncTerminalGeometry` ·
/// `syncGeometryAfterScreenChange` · 첫 탭 생성 세 곳이 `cell_w` / `cell_h` / `pad` /
/// `tab_bar` / `top_reserved` / `usable_h` / `sb_px` / `cols` / `rows` 를 똑같이 적어
/// 두고 있었고, 실질 입력은 `(vp_w, vp_h, scale)` 셋뿐이었다. Linux `Client.gridSize` ·
/// Windows `App.getTerminalGridSize` 와 같은 모양이 된다.
///
/// `cell_*` 는 `g_renderer` 에서 읽는다 — 세 호출처가 모두 renderer 가 있는 시점이고,
/// 같은 파일의 `tabBarHeightPx` 도 이미 `g_session` 전역을 읽는다 (탭 < 2 면 0, #127).
fn terminalGrid(vp_w: u32, vp_h: u32, scale: f32) struct { cols: u16, rows: u16 } {
const font = &g_renderer.?.font;
const pad: u32 = ui_metrics.scaledPx(u32, TERMINAL_PADDING_PT, scale);
const sb_px: u32 = ui_metrics.scaledPx(u32, ui_metrics.SCROLLBAR_W_PT, scale);
return .{
.cols = ui_metrics.terminalCols(vp_w, pad, sb_px, font.cell_width_px),
.rows = ui_metrics.terminalRows(vp_h, tabBarHeightPx(scale), pad, font.cell_height_px),
};
}
/// 현재 viewport / cell 크기 + 탭 수에 따른 cols/rows 재계산 후 모든 탭의
/// terminal + pty 동기화. 탭 1↔2 전환 시 탭바 등장/사라짐으로 cell 영역이
/// 변하므로 호출 필요. screen change / 탭 추가 / 탭 닫기 모두 같은 함수 사용.
fn syncTerminalGeometry() void {
if (g_renderer == null) return;
if (g_session.count() == 0) return;
const r = &g_renderer.?;
const grid = terminalGrid(r.vp_width, r.vp_height, r.scale);
const new_cols = grid.cols;
const new_rows = grid.rows;
for (g_session.tabs.items) |t| {
if (new_cols == t.terminal.cols and new_rows == t.terminal.rows) continue;
t.terminal.resize(g_gpa.allocator(), new_cols, new_rows) catch |err| {
log.appendLine("geom", "terminal resize failed: {s}", .{@errorName(err)});
continue;
};
t.backend.resize(new_cols, new_rows) catch |err| {
log.appendLine("geom", "pty resize failed: {s}", .{@errorName(err)});
};
}
}
// NSWindow subclass — `canBecomeKeyWindow` 를 YES 로 override 해서 borderless
// styleMask 에서도 key window 가능하게. Default NSWindow 는 borderless 면
// canBecomeKey=NO 라 mainMenu Cmd+Q 등이 dispatch 안 됨. ghostty Quick Terminal
// 의 `class QuickTerminalWindow: NSPanel { override var canBecomeKey: Bool { true } }`
// 와 동일 효과.
fn tildazCanBecomeKey(_: objc.id, _: objc.SEL) callconv(.c) bool {
return true;
}
fn tildazCanBecomeMain(_: objc.id, _: objc.SEL) callconv(.c) bool {
return true;
}
fn registerTildazWindowClass() !objc.Class {
const NSWindow = objc.getClass("NSWindow");
const cls = objc.objc_allocateClassPair(NSWindow, "TildazWindow", 0) orelse
return error.WindowSubclassAllocFailed;
// Method signature: "B@:" = bool 반환, self (id) + _cmd (SEL) 만 인자.
if (!objc.class_addMethod(cls, objc.sel("canBecomeKeyWindow"), @ptrCast(&tildazCanBecomeKey), "B@:"))
return error.WindowSubclassAddMethodFailed;
if (!objc.class_addMethod(cls, objc.sel("canBecomeMainWindow"), @ptrCast(&tildazCanBecomeMain), "B@:"))
return error.WindowSubclassAddMethodFailed;
objc.objc_registerClassPair(cls);
return cls;
}
// TildazView = NSView subclass — keyDown / acceptsFirstResponder override.
// `acceptsFirstResponder` YES 안 하면 NSWindow 가 firstResponder 로 안 잡아
// 키 이벤트가 view 에 안 옴. keyDown: 에서 NSEvent.characters 추출 → PTY 로
// write. 특수 키 (화살표, F-key) 는 별도 escape sequence 매핑 필요 (M5.4b).
fn tildazAcceptsFirstResponder(_: objc.id, _: objc.SEL) callconv(.c) bool {
return true;
}
/// #317 — AppKit은 Command key equivalent를 keyDown:보다 먼저 key window의
/// view hierarchy에 보낸다. terminal marked input이 Cmd+Q를 소비하기 전에 custom
/// NSTextInputClient인 이 view가 공통 입력 정책을 적용한다. terminal marked-input
/// 첫 event는 mainMenu가 매칭하지 않는 것이 실기로 확인됐으므로, 기존 macOS
/// main-queue deferral로 custom Quit selector를 다음 turn에 실행한다. 다른 key는
/// false로 기존 NSMenu routing을 유지한다.
fn tildazPerformKeyEquivalent(_: objc.id, _: objc.SEL, event: objc.id) callconv(.c) bool {
if (event == null) return false;
const get_flags = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) c_ulong);
const flags = get_flags(event, objc.sel("modifierFlags"));
const NSEventModifierFlagShift: c_ulong = 1 << 17;
const NSEventModifierFlagControl: c_ulong = 1 << 18;
const NSEventModifierFlagOption: c_ulong = 1 << 19;
const NSEventModifierFlagCommand: c_ulong = 1 << 20;
const relevant = NSEventModifierFlagShift |
NSEventModifierFlagControl |
NSEventModifierFlagOption |
NSEventModifierFlagCommand;
if (flags & relevant != NSEventModifierFlagCommand) return false;
const get_kc = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) c_ushort);
if (get_kc(event, objc.sel("keyCode")) != 0x0C) return false; // Q
applyShortcutInputPolicy(.quit);
dispatch_async_f(&_dispatch_main_q, null, tildazQuitTrampoline);
return true;
}
const NSEventTypeKeyDown: c_long = 10;
const NSUTF8StringEncoding: usize = 4;
/// macOS hardware keyCode 별 xterm-compatible escape sequence. macOS 의
/// NSEvent.characters 는 화살표 / F-key 를 NSFunctionKey private codepoint
/// (U+F700~) 으로 보내는데 bash / vim / less 등은 표준 xterm escape sequence
/// 만 인식하므로 keyCode 직접 매핑이 필요.
fn keyCodeToEscape(keycode: c_ushort) ?[]const u8 {
return switch (keycode) {
// 화살표
126 => "\x1b[A", // up
125 => "\x1b[B", // down
124 => "\x1b[C", // right
123 => "\x1b[D", // left
// 네비게이션
115 => "\x1b[H", // home
119 => "\x1b[F", // end
116 => "\x1b[5~", // pgup
121 => "\x1b[6~", // pgdn
117 => "\x1b[3~", // forward delete
114 => "\x1b[2~", // insert/help (외장 PC 키보드 — Apple 키보드엔 없음, #282 A7 parity)
// F-keys
122 => "\x1bOP", // F1 (CGEventTap 이 가로채니 사실 도달 안 함)
120 => "\x1bOQ", // F2
99 => "\x1bOR", // F3
118 => "\x1bOS", // F4
96 => "\x1b[15~", // F5
97 => "\x1b[17~", // F6
98 => "\x1b[18~", // F7
100 => "\x1b[19~", // F8
101 => "\x1b[20~", // F9
109 => "\x1b[21~", // F10
103 => "\x1b[23~", // F11
111 => "\x1b[24~", // F12
else => null,
};
}
fn interpretSingleKeyEvent(self_view: objc.id, event: objc.id) void {
const NSArray = objc.getClass("NSArray");
const arrayWithObject = objc.objcSend(fn (objc.Class, objc.SEL, objc.id) callconv(.c) objc.id);
const array = arrayWithObject(NSArray, objc.sel("arrayWithObject:"), event);
const interpretKeyEvents = objc.objcSend(fn (objc.id, objc.SEL, objc.id) callconv(.c) void);
interpretKeyEvents(self_view, objc.sel("interpretKeyEvents:"), array);
}
/// #296 — 현재 입력 상태를 공통 입력 정책(input_policy)용으로.
fn macInputState() input_policy.State {
return .{ .terminal_preedit_active = g_marked_len > 0 };
}
/// #317 — macOS의 모든 shortcut 진입점이 같은 pending 입력 정책을 적용한다.
/// `keyDown:` Cmd shortcut뿐 아니라 NSMenu selector, Cmd+Q의
/// `applicationShouldTerminate:`, F1 event tap도 이 helper를 action 전에 호출한다.
/// read-only copy/perf의 `.leave`와 상태변경 action의 `.commit` 구분은 오직
/// `input_policy.resolve`가 결정한다.
fn applyShortcutInputPolicy(shortcut: input_policy.Shortcut) void {
const disposition = input_policy.resolve(.{ .shortcut = shortcut }, macInputState());
switch (disposition.pending) {
.leave => {},
.commit => {
if (g_window == null) return;
const contentView_get = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) objc.id);
const cv = contentView_get(g_window, objc.sel("contentView"));
if (cv != null) commitPendingInput(cv);
},
// shortcut 정책에는 discard 가 없다. Ctrl+C interrupt의 discard는
// tildazKeyDown의 별도 IME/SIGINT 순서가 담당한다.
.discard => unreachable,
}
}
/// #340 — paste semantic entry 의 pending 정책 적용. Cmd+V / 우클릭 공통 —
/// 예전엔 우클릭(tildazRightMouseDown)이 정책 없이 handlePaste 직행이라 터미널
/// 조합 중 우클릭 paste 가 'X하' 순서가 될 수 있었다 (#333 의 macOS 형제).
/// terminal preedit(.commit): 전체 commit (preedit → PTY flush) 후 payload 가
/// 이어져 '하X' (native textbox 동등).
fn applyPasteInputPolicy() void {
const disposition = input_policy.resolve(.paste, macInputState());
if (g_window == null) return;
const contentView_get = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) objc.id);
const cv = contentView_get(g_window, objc.sel("contentView"));
if (cv == null) return;
switch (disposition.pending) {
.leave => {},
.commit => commitPendingInput(cv),
// paste 정책에 discard 없음 (input_policy.resolve 참고).
.discard => unreachable,
}
}
/// #296 — macOS Cmd+keyCode 를 입력 정책 Shortcut 으로 분류. 인식 못한 조합은
/// null (→ mainMenu Cmd+Q 등). `tildazKeyDown` 의 dispatch switch 와 정확히 일치.
fn macCmdShortcut(kc: c_ushort, shift: bool) ?input_policy.Shortcut {
if (kc == 8) return .copy_selection; // Cmd+C
if (kc == 0x11 and !shift) return .new_tab; // Cmd+T
if (kc == 0x0D and !shift) return .close_tab; // Cmd+W
if (keycodeToTabIndex(kc) != null) return .switch_tab; // Cmd+1..9
if (shift and kc == 0x21) return .prev_tab; // Shift+Cmd+[
if (shift and kc == 0x1E) return .next_tab; // Shift+Cmd+]
if (shift and kc == 0x0F) return .reset_terminal; // Shift+Cmd+R
if (kc == 0x24) return .fullscreen; // Cmd+Enter / Shift+Cmd+Enter
if (shift and kc == 0x6F) return .dump_perf; // Shift+Cmd+F12
return null;
}
fn tildazKeyDown(self_view: objc.id, _: objc.SEL, event: objc.id) callconv(.c) void {
requestRender(); // #255 Phase2 — 키 입력 → 렌더 (스크롤백/탭조작 등 출력 없는 변화 포함).
const tab = g_session.activeTab() orelse return;
if (event == null) return;
// Cmd+C / Cmd+V 우선 — IME 와 무관하게 처리.
const get_flags = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) c_ulong);
const flags = get_flags(event, objc.sel("modifierFlags"));
// #329 — command menu 가 열려 있으면: Cmd 단축키와 Ctrl 조합(Ctrl+C
// interrupt — 2026-07-23 사용자 확정 (a): 메뉴 닫고 정상 실행)은 메뉴를
// 닫고 아래 기존 경로로 진행, 그 외 모든 키는 메뉴 계층이 소비 (Esc 닫기
// / 화살표·Tab 이동 / Enter·Space 실행 / 그 외 noop). Option 조합은 특수
// 문자·한자 입력이라 소비 유지. PTY 로 새지 않음 — SPEC §5.3.
if (g_command_menu_open) {
const NSEventModifierFlagControl: c_ulong = 1 << 18;
if ((flags & ((1 << 20) | NSEventModifierFlagControl)) != 0) {
closeCommandMenu();
} else {
const get_menu_kc = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) c_ushort);
const menu_kc = get_menu_kc(event, objc.sel("keyCode"));
const menu_shift = (flags & (1 << 17)) != 0;
handleCommandMenuKey(switch (menu_kc) {
0x35 => .escape,
0x7E => .up,
0x7D => .down,
0x73 => .home,
0x77 => .end,
0x30 => if (menu_shift) command_menu.MenuKey.shift_tab else .tab,
0x24, 0x4C => .enter, // Return / KP Enter
0x31 => .space,
else => command_menu.MenuKey.other,
});
return;
}
}
const NSEventModifierFlagCommand: c_ulong = 1 << 20;
const cmd = (flags & NSEventModifierFlagCommand) != 0;
if (cmd) {
const get_kc = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) c_ushort);
const kc = get_kc(event, objc.sel("keyCode"));
const NSEventModifierFlagShift: c_ulong = 1 << 17;
const shift = (flags & NSEventModifierFlagShift) != 0;
// #296 — Cmd 단축키의 preedit commit 여부는 입력 정책(input_policy.
// resolve) 한 곳에서 결정. copy(Cmd+C)/perf(Shift+Cmd+F12)는 read-only,
// 터미널 preedit 은 자모 보존 위해 flush. 그 외 단축키는 commit 후 실행
// (SPEC §4.1).
//
// #282 A3 / #340 — Cmd+V(paste): 조합을 먼저 확정하고 payload 를 잇는다.
// pending 적용은 우클릭과 공통 helper(applyPasteInputPolicy) 한 곳.
if (kc == 9) {
applyPasteInputPolicy();
handlePaste();
return;
}
// Cmd+kc → 입력 정책 Shortcut 분류. 인식 못한 Cmd+key 는 mainMenu(Cmd+Q 등).
const shortcut = macCmdShortcut(kc, shift) orelse return;
applyShortcutInputPolicy(shortcut);
switch (shortcut) {
.copy_selection => handleCopy(), // Cmd+C (kc 8)
.new_tab => handleNewTab(), // Cmd+T
.close_tab => handleCloseActiveTab(), // Cmd+W
.switch_tab => tab_actions.switchTab(&g_host, keycodeToTabIndex(kc).?), // Cmd+1..9
.prev_tab => tab_actions.prevTab(&g_host), // Shift+Cmd+[
.next_tab => tab_actions.nextTab(&g_host), // Shift+Cmd+]
.reset_terminal => tab_actions.resetActive(&g_host), // Shift+Cmd+R (#162)
.fullscreen => toggleFullscreenMode(if (shift) .workarea else .monitor), // Cmd/Shift+Cmd+Enter (#162)
.dump_perf => perf.dumpAndReset("snapshot"), // Shift+Cmd+F12 (#160)
else => {}, // macOS keyDown 이 안 내는 나머지(show_about/config/log/quit=mainMenu)
}
return;
}
const NSEventModifierFlagShift: c_ulong = 1 << 17;
const NSEventModifierFlagOption: c_ulong = 1 << 19;
const shift = (flags & NSEventModifierFlagShift) != 0;
const option = (flags & NSEventModifierFlagOption) != 0;
const get_keycode = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) c_ushort);
const keycode = get_keycode(event, objc.sel("keyCode"));
if (option and keycode == 0x24) {
const had_marked_text = g_marked_len > 0 and g_preedit_len > 0;
clearHanjaState();
g_hanja_preedit_commit_requested = had_marked_text;
defer g_hanja_preedit_commit_requested = false;
if (!had_marked_text) _ = beginHanjaReconversionTarget();
interpretSingleKeyEvent(self_view, event);
if (had_marked_text and g_hanja_pending_commit_active) {
g_hanja_reconversion_active = true;
g_hanja_reconversion_range = g_hanja_pending_commit_range;
g_hanja_reconversion_delete_count = g_hanja_pending_commit_delete_count;
interpretSingleKeyEvent(self_view, event);
if (!g_hanja_candidate_active) cancelHanjaState();
}
return;
}
// Ctrl+key (#121) — ASCII control char (예: Ctrl+C = 0x03 SIGINT).
// Windows `WM_CHAR` 가 자동 변환하는 패턴을 macOS 는 직접. NSEvent 의
// `characters` 가 modifier 적용된 char — Ctrl+C 누르면 characters="\x03".
//
// **IME 조합 중에도** Ctrl+key 는 그대로 PTY 로 보낸다 — shell 의 Ctrl+C
// 는 "현재 입력 라인 버리기" 의도라 한글 조합도 같이 버리는 게 자연스러움.
// IME 의 markedText 는 `discardMarkedText` 로 reset 한 후 PTY write.
// (이전 분기는 g_marked_len==0 일 때만 했어서 한글 조합 중 Ctrl+C 가 IME
// 의 interpretKeyEvents 로 흘러 SIGINT 안 갔음.)
const NSEventModifierFlagControl: c_ulong = 1 << 18;
const NSEventModifierFlagCommandKD: c_ulong = 1 << 20;
const ctrl = (flags & NSEventModifierFlagControl) != 0;
const cmd_too = (flags & NSEventModifierFlagCommandKD) != 0;
// Cmd 가 같이 눌린 ctrl+cmd 조합은 macOS system shortcut (Ctrl+Cmd+Space =
// Show Emoji & Symbols 등) 의 표식 — PTY 로 안 흘리고 mainMenu 의 menu
// item keyEquivalent 로 라우팅 (#130). 일반 Ctrl+C (Cmd 없음) 는 그대로
// PTY 직송.
if (ctrl and !cmd_too) {
const get_chars = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) objc.id);
const chars = get_chars(event, objc.sel("characters"));
if (chars != null) {
const get_len = objc.objcSend(fn (objc.id, objc.SEL, usize) callconv(.c) usize);
const len = get_len(chars, objc.sel("lengthOfBytesUsingEncoding:"), NSUTF8StringEncoding);
if (len > 0) {
const get_utf8 = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) [*:0]const u8);
const cstr = get_utf8(chars, objc.sel("UTF8String"));
const ctrl_c = (len == 1 and cstr[0] == 0x03);
if (g_marked_len > 0) {
// Ctrl+C 는 line abort 의미라 preedit *discard*. 다른
// Ctrl+key (Ctrl+A/E/L/D 등) 은 *commit* — 입력 중인 자모
// 보존 후 Ctrl char 발신 (native textbox / iTerm2 동등).
if (!ctrl_c) {
tab.queueWrite(g_preedit_buf[0..g_preedit_len]);
}
const get_ic = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) objc.id);
const ic = get_ic(self_view, objc.sel("inputContext"));
if (ic != null) {
const discard = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) void);
discard(ic, objc.sel("discardMarkedText"));
}
g_marked_len = 0;
g_preedit_len = 0;
clearHanjaState();
}
// Ctrl+C (SIGINT) 만 큐 우회 + 큐 reset — paste 등으로 가득찬
// write_queue 뒤에 enqueue 되면 셸이 SIGINT 늦게 받아 "Ctrl+C
// 안 먹힌다" 로 보임.
if (ctrl_c) {
tab.interruptWrite(cstr[0..len]);
// #242 — Ctrl+C 도 사용자 입력 → 맨 아래로(^C/새 prompt 보이게).
// interruptWrite 는 즉시 SIGINT 경로라 writeUserInput(queue) 대신
// scroll 만 별도.
tab.terminal.scrollViewport(.{ .bottom = {} });
} else {
writeUserInput(tab, cstr[0..len]);
}
return;
}
}
}
// IME 가 조합 중이 아니면 화살표 / F-key / nav 는 직접 escape sequence
// (성능 + 정확성). 조합 중이면 interpretKeyEvents 로 보내 IME 가 음절
// commit 후 doCommandBySelector 로 우리에게 위임 — 우리 imeDoCommand 가
// escape sequence write.
if (g_marked_len == 0) {
// Esc — emoji picker 가 떠 있으면 dismiss (#130 follow-up). modifier
// 없는 단순 Esc 만 — Cmd / ctrl 은 위 분기에서 처리 끝 (cmd 는 mainMenu,
// ctrl-only 는 PTY 직송). shift / option 도 없을 때만. picker 의 visibility
// 는 `isEmojiPickerOpen()` 이 NSApp.orderedWindows 직접 query — boolean
// 추적의 stale 문제 회피.
if (keycode == 53 and !shift and (flags & NSEventModifierFlagOption) == 0 and isEmojiPickerOpen()) {
const orderFront = objc.objcSend(fn (objc.id, objc.SEL, objc.id) callconv(.c) void);
orderFront(g_app, objc.sel("orderFrontCharacterPalette:"), null);
return;
}
// Shift+PgUp / Shift+PgDn — viewport scrollback. Windows
// `session_core.scrollActive` 와 같은 *한 페이지 (visible rows)* 단위.
// PTY 로 안 흘림.
if (shift) {
const rows: isize = @intCast(tab.terminal.rows);
if (keycode == 116) { // kVK_PageUp — 위쪽 (older).
tab.terminal.scrollViewport(.{ .delta = -rows });
return;
}
if (keycode == 121) { // kVK_PageDown — 아래쪽 (newer).
tab.terminal.scrollViewport(.{ .delta = rows });
return;
}
}
if (keyCodeToEscape(keycode)) |esc| {
writeUserInput(tab, esc);
return;
}
}
// preedit 활성 + nav 키 (Home/End/Arrows/PgUp/PgDn 등) — interpretKeyEvents
// 가 Home/End 같은 일부 키에 doCommandBySelector dispatch 안 하는 케이스
// (IME 가 finalize 만 하고 selector 안 보냄). 직접 keyCode 검사 후 preedit
// commit + escape 발신.
if (g_marked_len > 0) {
const get_keycode2 = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) c_ushort);
const keycode2 = get_keycode2(event, objc.sel("keyCode"));
if (keyCodeToEscape(keycode2)) |esc| {
if (g_hanja_candidate_active) {
interpretSingleKeyEvent(self_view, event);
return;
}
commitPreeditToPty(self_view);
writeUserInput(tab, esc);
return;
}
}
interpretSingleKeyEvent(self_view, event);
}
// IME (NSTextInputClient) 상태 — 조합 중 (preedit) 텍스트 buffer.
const NSRange = extern struct { location: usize, length: usize };
const CGRect = extern struct { x: f64, y: f64, w: f64, h: f64 };
const NSNotFound: usize = @as(usize, @intCast(std.math.maxInt(isize)));
var g_marked_len: usize = 0;
var g_marked_selected_range: NSRange = .{ .location = 0, .length = 0 };
var g_preedit_buf: [128]u8 = undefined;
var g_preedit_len: usize = 0;
var g_hanja_reconversion_active: bool = false;
var g_hanja_reconversion_range: NSRange = .{ .location = 0, .length = 0 };
var g_hanja_reconversion_delete_count: usize = 0;
var g_hanja_candidate_active: bool = false;
var g_hanja_candidate_range: NSRange = .{ .location = 0, .length = 0 };
var g_hanja_candidate_delete_count: usize = 0;
var g_hanja_preedit_commit_requested: bool = false;
var g_hanja_pending_commit_active: bool = false;
var g_hanja_pending_commit_buf: [128]u8 = undefined;
var g_hanja_pending_commit_len: usize = 0;