-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindow.zig
More file actions
2240 lines (2100 loc) · 111 KB
/
Copy pathwindow.zig
File metadata and controls
2240 lines (2100 loc) · 111 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
const std = @import("std");
const windows = std.os.windows;
const app_event = @import("app_event.zig");
const dialog = @import("dialog.zig");
const log = @import("log.zig");
const messages = @import("messages.zig");
const paths = @import("paths.zig");
const dwrite_font = @import("font/windows/font.zig");
const font_spec = @import("font/spec.zig");
const BOOL = windows.BOOL;
const DWORD = windows.DWORD;
const UINT = c_uint;
const WCHAR = u16;
const LONG = c_long;
const WPARAM = usize;
const LPARAM = isize;
const LRESULT = isize;
const HINSTANCE = ?*anyopaque;
const HWND = ?*anyopaque;
const HDC = ?*anyopaque;
const HBRUSH = ?*anyopaque;
const HFONT = ?*anyopaque;
const HGDIOBJ = ?*anyopaque;
const HMENU = ?*anyopaque;
const HICON = ?*anyopaque;
const HCURSOR = ?*anyopaque;
const LPVOID = ?*anyopaque;
const ATOM = u16;
const COLORREF = DWORD;
// Window Styles
const WS_POPUP: DWORD = 0x80000000;
const WS_VISIBLE: DWORD = 0x10000000;
const WS_EX_TOPMOST: DWORD = 0x00000008;
const WS_EX_TOOLWINDOW: DWORD = 0x00000080;
/// redirection bitmap 없는 창 (#89 2단계) — 반투명은 DirectComposition 이
/// 담당하므로 legacy layered(BitBlt) 표면이 아예 안 만들어지게.
const WS_EX_NOREDIRECTIONBITMAP: DWORD = 0x00200000;
const CS_DBLCLKS: UINT = 0x0008;
// Window Messages
const WM_CLOSE: UINT = 0x0010;
const WM_DESTROY: UINT = 0x0002;
const WM_PAINT: UINT = 0x000F;
const WM_KEYDOWN: UINT = 0x0100;
const WM_KEYUP: UINT = 0x0101;
const WM_CHAR: UINT = 0x0102;
const WM_HOTKEY: UINT = 0x0312;
pub const WM_NEW_INSTANCE_REQUEST: UINT = 0x8000 + 267;
pub const WM_HOTKEY_CAPTURE_BEGIN: UINT = 0x8000 + 268;
pub const WM_HOTKEY_CAPTURE_END: UINT = 0x8000 + 269;
const WM_TIMER: UINT = 0x0113;
const WM_SIZE: UINT = 0x0005;
const WM_USER: UINT = 0x0400;
pub const WM_PTY_OUTPUT: UINT = WM_USER + 1;
pub const WM_TAB_CLOSED: UINT = WM_USER + 2;
const WM_SYSKEYDOWN: UINT = 0x0104;
const WM_LBUTTONDBLCLK: UINT = 0x0203;
const WM_LBUTTONDOWN: UINT = 0x0201;
const WM_LBUTTONUP: UINT = 0x0202;
const WM_MOUSEMOVE: UINT = 0x0200;
const WM_RBUTTONDOWN: UINT = 0x0204;
const WM_MOUSEWHEEL: UINT = 0x020A;
const WM_DISPLAYCHANGE: UINT = 0x007E;
const WM_DPICHANGED: UINT = 0x02E0;
const WM_IME_STARTCOMPOSITION: UINT = 0x010D;
const WM_IME_ENDCOMPOSITION: UINT = 0x010E;
const WM_IME_COMPOSITION: UINT = 0x010F;
const GCS_COMPSTR: DWORD = 0x0008;
const GCS_RESULTSTR: DWORD = 0x0800;
const WM_SETTINGCHANGE: UINT = 0x001A;
const WM_WINDOWPOSCHANGING: UINT = 0x0046;
const WM_WINDOWPOSCHANGED: UINT = 0x0047;
const WM_NCCALCSIZE: UINT = 0x0083;
const WM_ERASEBKGND: UINT = 0x0014;
const WM_SETCURSOR: UINT = 0x0020;
const HTCLIENT: u16 = 1;
const WM_ACTIVATEAPP: UINT = 0x001C;
const SPI_SETWORKAREA: WPARAM = 0x002F;
const MK_LBUTTON: WPARAM = 0x0001;
// Other constants
const SW_SHOW: c_int = 5;
const SW_HIDE: c_int = 0;
const HWND_TOPMOST: HWND = @ptrFromInt(@as(usize, @bitCast(@as(isize, -1))));
const HWND_NOTOPMOST: HWND = @ptrFromInt(@as(usize, @bitCast(@as(isize, -2))));
const SWP_NOSIZE: UINT = 0x0001;
const SWP_NOMOVE: UINT = 0x0002;
const SWP_NOREDRAW: UINT = 0x0008;
const SWP_NOACTIVATE: UINT = 0x0010;
const SWP_FRAMECHANGED: UINT = 0x0020;
const SWP_SHOWWINDOW: UINT = 0x0040;
const SWP_NOCOPYBITS: UINT = 0x0100;
/// Fullscreen / dock rect 전환 시 DWM 이 이전 surface 를 캐시해 두고 logical
/// rect 만 바꾸는 상태 (터미널 grid 는 new rect 로 reflow 됐지만 visible frame
/// 은 old rect 에 고정) 를 방어. SWP_NOCOPYBITS 는 이전 client 영역 bit 를
/// 재사용하지 않고 전부 repaint 하도록 강제하고, SWP_FRAMECHANGED 는 DWM 에
/// non-client (window frame) 재계산을 요청 — 이 둘이 같이 들어가야 WS_POPUP +
/// WS_EX_LAYERED 조합에서 visual rect 가 logical rect 를 따라감.
const SWP_REPAINT: UINT = SWP_NOCOPYBITS | SWP_FRAMECHANGED;
const CW_USEDEFAULT: c_int = @bitCast(@as(c_uint, 0x80000000));
const COLOR_WINDOW: c_int = 5;
// LoadCursorW 의 두 번째 param 은 `MAKEINTRESOURCE(id)` — 실제 pointer 가 아닌
// resource id 로 reinterpret 됨. WCHAR (align 2) ptr 로 declare 하면 odd ID
// (`IDC_IBEAM = 32513`) 가 alignment 위반. `?*const anyopaque` 로 alignment
// 요구 제거.
const IDC_ARROW: ?*const anyopaque = @ptrFromInt(32512);
const IDC_IBEAM: ?*const anyopaque = @ptrFromInt(32513);
const GWL_USERDATA: c_int = -21;
const TRANSPARENT: c_int = 1;
/// DwmSetWindowAttribute 의 attribute id. Windows 에 "이 창은 transition 애니
/// 메이션 (hide/show/resize 시 shrink/grow 효과) 을 사용하지 말라" 고 알림.
/// WS_POPUP + WS_EX_TOPMOST + WS_EX_LAYERED 창이 Alt+Enter 로 rect 가 바뀐
/// 직후 SW_HIDE 하면 DWM 이 "이전 rect 로 shrink" 애니메이션을 재생하는 것
/// 으로 관측됨 — 그 중간 프레임이 사용자 눈에 "F1 눌렀는데 잠깐 이전 사이즈로
/// 보이는" 글리치로 잡힘.
const DWMWA_TRANSITIONS_FORCEDISABLED: DWORD = 3;
const MONITOR_DEFAULTTOPRIMARY: DWORD = 0x00000001;
const MONITOR_DEFAULTTONEAREST: DWORD = 0x00000002;
// GDI constants
const FW_NORMAL: c_int = 400;
const DEFAULT_CHARSET: DWORD = 1;
const OUT_DEFAULT_PRECIS: DWORD = 0;
const CLIP_DEFAULT_PRECIS: DWORD = 0;
const CLEARTYPE_QUALITY: DWORD = 5;
const FIXED_PITCH: DWORD = 1;
const FF_MODERN: DWORD = 0x30;
const POINT = extern struct { x: LONG, y: LONG };
pub const RECT = extern struct { left: LONG, top: LONG, right: LONG, bottom: LONG };
const MONITORINFO = extern struct {
cbSize: DWORD,
rcMonitor: RECT,
rcWork: RECT,
dwFlags: DWORD,
};
const PAINTSTRUCT = extern struct {
hdc: HDC,
fErase: BOOL,
rcPaint: RECT,
fRestore: BOOL,
fIncUpdate: BOOL,
rgbReserved: [32]u8,
};
/// `WM_WINDOWPOSCHANGING` / `WM_WINDOWPOSCHANGED` 의 `lParam` 이 가리키는
/// 구조체. 윈도우 매니저가 실제 적용하려는 rect 과 flag 를 관측하는 용도.
const WINDOWPOS = extern struct {
hwnd: HWND,
hwndInsertAfter: HWND,
x: c_int,
y: c_int,
cx: c_int,
cy: c_int,
flags: UINT,
};
const MSG = extern struct {
hwnd: HWND,
message: UINT,
wParam: WPARAM,
lParam: LPARAM,
time: DWORD,
pt: POINT,
};
const WNDCLASSEXW = extern struct {
cbSize: UINT,
style: UINT,
lpfnWndProc: *const fn (HWND, UINT, WPARAM, LPARAM) callconv(.c) LRESULT,
cbClsExtra: c_int,
cbWndExtra: c_int,
hInstance: HINSTANCE,
hIcon: HICON,
hCursor: HCURSOR,
hbrBackground: HBRUSH,
lpszMenuName: ?[*:0]const WCHAR,
lpszClassName: [*:0]const WCHAR,
hIconSm: HICON,
};
// Win32 function declarations
extern "user32" fn RegisterClassExW(*const WNDCLASSEXW) callconv(.c) ATOM;
extern "user32" fn CreateWindowExW(DWORD, [*:0]const WCHAR, [*:0]const WCHAR, DWORD, c_int, c_int, c_int, c_int, HWND, HMENU, HINSTANCE, LPVOID) callconv(.c) HWND;
extern "user32" fn ShowWindow(HWND, c_int) callconv(.c) BOOL;
extern "user32" fn DestroyWindow(HWND) callconv(.c) BOOL;
extern "user32" fn PostQuitMessage(c_int) callconv(.c) void;
extern "user32" fn DefWindowProcW(HWND, UINT, WPARAM, LPARAM) callconv(.c) LRESULT;
extern "user32" fn PostMessageW(HWND, UINT, WPARAM, LPARAM) callconv(.c) BOOL;
extern "user32" fn GetMessageW(*MSG, HWND, UINT, UINT) callconv(.c) BOOL;
extern "user32" fn TranslateMessage(*const MSG) callconv(.c) BOOL;
extern "user32" fn DispatchMessageW(*const MSG) callconv(.c) LRESULT;
extern "user32" fn BeginPaint(HWND, *PAINTSTRUCT) callconv(.c) HDC;
extern "user32" fn EndPaint(HWND, *const PAINTSTRUCT) callconv(.c) BOOL;
extern "user32" fn InvalidateRect(HWND, ?*const RECT, BOOL) callconv(.c) BOOL;
extern "user32" fn SetWindowPos(HWND, HWND, c_int, c_int, c_int, c_int, UINT) callconv(.c) BOOL;
extern "user32" fn SetForegroundWindow(HWND) callconv(.c) BOOL;
extern "user32" fn GetForegroundWindow() callconv(.c) HWND;
extern "user32" fn GetWindowThreadProcessId(HWND, ?*DWORD) callconv(.c) DWORD;
extern "kernel32" fn GetCurrentThreadId() callconv(.c) DWORD;
extern "user32" fn AttachThreadInput(DWORD, DWORD, BOOL) callconv(.c) BOOL;
extern "user32" fn BringWindowToTop(HWND) callconv(.c) BOOL;
extern "user32" fn SetFocus(HWND) callconv(.c) HWND;
extern "user32" fn RegisterHotKey(HWND, c_int, UINT, UINT) callconv(.c) BOOL;
extern "user32" fn UnregisterHotKey(HWND, c_int) callconv(.c) BOOL;
extern "user32" fn GetCursorPos(*POINT) callconv(.c) BOOL;
extern "user32" fn MonitorFromPoint(POINT, DWORD) callconv(.c) ?*anyopaque;
extern "user32" fn MonitorFromWindow(HWND, DWORD) callconv(.c) ?*anyopaque;
extern "user32" fn GetMonitorInfoW(?*anyopaque, *MONITORINFO) callconv(.c) BOOL;
extern "dwmapi" fn DwmSetWindowAttribute(HWND, DWORD, *const anyopaque, DWORD) callconv(.c) std.os.windows.HRESULT;
extern "dwmapi" fn DwmFlush() callconv(.c) std.os.windows.HRESULT;
extern "user32" fn SetWindowLongPtrW(HWND, c_int, isize) callconv(.c) isize;
extern "user32" fn GetWindowLongPtrW(HWND, c_int) callconv(.c) isize;
extern "user32" fn LoadCursorW(HINSTANCE, ?*const anyopaque) callconv(.c) HCURSOR;
extern "user32" fn SetCursor(HCURSOR) callconv(.c) HCURSOR;
extern "user32" fn ScreenToClient(HWND, *POINT) callconv(.c) BOOL;
extern "user32" fn SetTimer(HWND, usize, UINT, ?*anyopaque) callconv(.c) usize;
extern "user32" fn KillTimer(HWND, usize) callconv(.c) BOOL;
extern "user32" fn GetClientRect(HWND, *RECT) callconv(.c) BOOL;
extern "user32" fn GetWindowRect(HWND, *RECT) callconv(.c) BOOL;
extern "user32" fn GetDC(HWND) callconv(.c) HDC;
extern "user32" fn ReleaseDC(HWND, HDC) callconv(.c) c_int;
extern "kernel32" fn GetModuleHandleW(?[*:0]const WCHAR) callconv(.c) HINSTANCE;
extern "kernel32" fn OutputDebugStringA([*:0]const u8) callconv(.c) void;
extern "kernel32" fn GlobalLock(?*anyopaque) callconv(.c) ?*anyopaque;
extern "kernel32" fn GlobalUnlock(?*anyopaque) callconv(.c) BOOL;
extern "user32" fn OpenClipboard(HWND) callconv(.c) BOOL;
extern "user32" fn CloseClipboard() callconv(.c) BOOL;
extern "user32" fn GetClipboardData(UINT) callconv(.c) ?*anyopaque;
extern "user32" fn GetKeyState(c_int) callconv(.c) i16;
extern "user32" fn GetAsyncKeyState(c_int) callconv(.c) i16;
extern "user32" fn SetCapture(HWND) callconv(.c) HWND;
extern "user32" fn ReleaseCapture() callconv(.c) BOOL;
extern "user32" fn GetDpiForWindow(HWND) callconv(.c) UINT;
extern "user32" fn EmptyClipboard() callconv(.c) BOOL;
extern "user32" fn SetClipboardData(UINT, ?*anyopaque) callconv(.c) ?*anyopaque;
extern "kernel32" fn GlobalAlloc(UINT, usize) callconv(.c) ?*anyopaque;
extern "kernel32" fn GlobalFree(?*anyopaque) callconv(.c) ?*anyopaque;
const GMEM_MOVEABLE: UINT = 0x0002;
const CF_UNICODETEXT: UINT = 13;
const VK_CONTROL: c_int = 0x11;
const VK_SHIFT: c_int = 0x10;
const VK_MENU: c_int = 0x12; // Alt
const VK_LBUTTON: c_int = 0x01;
// GDI functions
extern "gdi32" fn CreateFontW(c_int, c_int, c_int, c_int, c_int, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, [*:0]const WCHAR) callconv(.c) HFONT;
extern "gdi32" fn SelectObject(HDC, HGDIOBJ) callconv(.c) HGDIOBJ;
extern "gdi32" fn DeleteObject(HGDIOBJ) callconv(.c) BOOL;
extern "gdi32" fn SetBkMode(HDC, c_int) callconv(.c) c_int;
extern "gdi32" fn SetBkColor(HDC, COLORREF) callconv(.c) COLORREF;
extern "gdi32" fn SetTextColor(HDC, COLORREF) callconv(.c) COLORREF;
extern "gdi32" fn TextOutW(HDC, c_int, c_int, [*]const WCHAR, c_int) callconv(.c) BOOL;
extern "gdi32" fn GetTextMetricsW(HDC, *TEXTMETRICW) callconv(.c) BOOL;
extern "gdi32" fn CreateSolidBrush(COLORREF) callconv(.c) HBRUSH;
extern "gdi32" fn FillRect(HDC, *const RECT, HBRUSH) callconv(.c) c_int;
extern "gdi32" fn CreateCompatibleDC(HDC) callconv(.c) HDC;
extern "gdi32" fn CreateCompatibleBitmap(HDC, c_int, c_int) callconv(.c) HGDIOBJ;
extern "gdi32" fn BitBlt(HDC, c_int, c_int, c_int, c_int, HDC, c_int, c_int, DWORD) callconv(.c) BOOL;
extern "gdi32" fn DeleteDC(HDC) callconv(.c) BOOL;
// === Imm32 (IME) ===
// HIMC = IME context handle. GCS_COMPSTR = preedit (조합 중), GCS_RESULTSTR =
// commit 결과. 둘 다 직접 추출한다. RESULTSTR를 DefWindowProcW에 넘기면 WM_CHAR가
// action 뒤에 queue되므로, 원래 입력 대상에 동기 dispatch한 뒤 message를 소비한다.
const HIMC = ?*opaque {};
extern "imm32" fn ImmGetContext(HWND) callconv(.c) HIMC;
extern "imm32" fn ImmReleaseContext(HWND, HIMC) callconv(.c) BOOL;
extern "imm32" fn ImmGetCompositionStringW(HIMC, DWORD, ?*anyopaque, DWORD) callconv(.c) c_long;
extern "imm32" fn ImmSetCompositionStringW(HIMC, DWORD, ?*const anyopaque, DWORD, ?*const anyopaque, DWORD) callconv(.c) BOOL;
extern "imm32" fn ImmNotifyIME(HIMC, DWORD, DWORD, DWORD) callconv(.c) BOOL;
extern "imm32" fn ImmSetCompositionWindow(HIMC, *COMPOSITIONFORM) callconv(.c) BOOL;
const NI_COMPOSITIONSTR: DWORD = 0x0015;
const CPS_COMPLETE: DWORD = 0x1;
const CPS_CANCEL: DWORD = 0x4;
const SCS_SETSTR: DWORD = 0x0009;
const CFS_POINT: DWORD = 0x0002;
/// IME composition / candidate window 위치 지정 (#164 1d). dwStyle = CFS_POINT
/// 면 IME 가 ptCurrentPos 근처에 popup. 일본 / 중국 IME 의 한자 후보 list 가
/// cursor 옆 자연스럽게 따라옴.
const COMPOSITIONFORM = extern struct {
dwStyle: DWORD,
ptCurrentPos: POINT,
rcArea: RECT,
};
const SRCCOPY: DWORD = 0x00CC0020;
const TEXTMETRICW = extern struct {
tmHeight: LONG,
tmAscent: LONG,
tmDescent: LONG,
tmInternalLeading: LONG,
tmExternalLeading: LONG,
tmAveCharWidth: LONG,
tmMaxCharWidth: LONG,
tmWeight: LONG,
tmOverhang: LONG,
tmDigitizedAspectX: LONG,
tmDigitizedAspectY: LONG,
tmFirstChar: WCHAR,
tmLastChar: WCHAR,
tmDefaultChar: WCHAR,
tmBreakChar: WCHAR,
tmItalic: u8,
tmUnderlined: u8,
tmStruckOut: u8,
tmPitchAndFamily: u8,
tmCharSet: u8,
};
pub const FullscreenMode = enum { none, monitor, workarea };
pub const Window = struct {
/// `WM_SETCURSOR` (#193) — client 영역 안의 위치별 cursor 분류. 결정은
/// host (app) 가 — cell 영역만 알면 되고, 그 외는 `.other` 로 default arrow.
pub const CursorRegion = enum { cell, other };
owner_hwnd: HWND = null,
hwnd: HWND = null,
visible: bool = false,
font: HFONT = null,
cell_width_px: c_int = 8,
cell_height_px: c_int = 16,
render_fn: ?*const fn (*Window) void = null,
/// #352 — "창 크기가 바뀌었다" 는 **알림만** 한다. 이전에는 `fn (u16, u16, …)` 로
/// 터미널 격자 cols/rows 를 인자로 넘겼는데, window layer 는 padding · scrollbar ·
/// 탭바를 몰라서 (그건 `App` 소유) 그 값을 만들려고 `getGridSize` 라는 *두 번째,
/// 틀린* 격자 함수를 길러야 했고 — 정작 콜백(`App.onResize`)은 인자를 버리고
/// `getTerminalGridSize` 로 다시 계산했다. 계약에서 격자를 빼면 그 함수와 그 안의
/// 가짜 fallback 이 함께 사라진다.
resize_fn: ?*const fn (?*anyopaque) void = null,
userdata: ?*anyopaque = null,
write_fn: ?*const fn ([]const u8, ?*anyopaque) void = null,
app_event_fn: ?*const fn (app_event.Event, ?*anyopaque) bool = null,
/// #245 — drag-select auto-scroll 상태. 타이머 활성 여부 + 마지막 마우스 위치
/// (타이머가 이 좌표로 synthetic mouse_move 재전송).
auto_scroll_active: bool = false,
last_mouse_x: c_int = 0,
last_mouse_y: c_int = 0,
/// 사용자가 윈도우 닫기를 요청 (Alt+F4 / 시스템 메뉴 / WM_CLOSE) 했을 때
/// 호출. true 반환 = 종료 진행 (DestroyWindow), false 반환 = 종료 취소.
/// macOS `applicationShouldTerminate:` 와 같은 역할 (#116). 다중 탭 confirm
/// 다이얼로그는 app 측에서 띄우고 결과만 반환.
quit_request_fn: ?*const fn (?*anyopaque) bool = null,
/// F1 hide 직전 호출 (#175). app 측이 preedit 등 진행 중인
/// 입력 상태를 commit 처리. show 분기는 호출 안 함.
before_hide_fn: ?*const fn (?*anyopaque) void = null,
/// #282 A11 — IME 조합 시작 시 활성 탭을 맨 아래로 (scroll-on-keystroke,
/// #242). 스크롤백 올린 상태에서 조합 시작 시 preedit 이 안 보이는 것 방지.
/// macOS/Linux 는 preedit 경로에서 이미 호출 — Windows 만 빠져 있었음.
scroll_to_bottom_fn: ?*const fn (?*anyopaque) void = null,
/// Invoked after `rebuildFontForDpi` finishes so the app (renderer / UI
/// layout) can re-raster glyphs and rescale DPI-dependent constants
/// before `SetWindowPos` cascades into `WM_SIZE`.
font_change_fn: ?*const fn (*Window, ?*anyopaque) void = null,
/// `WM_SETCURSOR` — client 영역 안 좌표 (`x`, `y`) 가 cell 영역인지 그 외인지
/// 결정하는 host callback. null 이면 항상 default arrow (#193). host 의
/// `effectiveTabBarHeight` / `SCROLLBAR_W` / `TERMINAL_PADDING` 를 다 알아야
/// 정확한 hit test 가능 — Window 가 모르는 정보라 callback 으로 외부화.
cursor_region_fn: ?*const fn (x: c_int, y: c_int, userdata: ?*anyopaque) CursorRegion = null,
/// `WM_SETCURSOR` 마다 LoadCursorW 호출 비용 피하려 init 에서 캐시 (#193).
cursor_arrow: HCURSOR = null,
cursor_ibeam: HCURSOR = null,
shell_exited: bool = false,
dc: HDC = null, // DC for GDI font measurement
// Font-creation parameters — remembered so `rebuildFontForDpi` can
// recreate the GDI font and re-measure cell metrics at the new DPI
// when `WM_DPICHANGED` fires.
/// font.family chain — `[0]` 이 primary (GDI CreateFontW 의 face name + 셀
/// 메트릭 측정 base). chain entry 1+ 는 renderer 의 DWriteFontContext 에서
/// codepoint glyph 폴백 우선순위로 사용. config.MAX_FONT_FAMILIES (8) 와
/// 동일 크기 — 동기화 유지.
font_chain: [8][*:0]const WCHAR = undefined,
font_chain_count: u8 = 0,
terminal_font: font_spec.Spec = .{
.size_logical = 15.0,
.cell_width_ratio = 1.0,
.line_height_ratio = 1.1,
},
current_dpi: UINT = 96,
// Last position parameters — re-applied on WM_DISPLAYCHANGE / WM_DPICHANGED /
// WM_SETTINGCHANGE(SPI_SETWORKAREA) and on show(), so the window tracks the
// current monitor's work area when resolution, DPI, or taskbar changes.
dock: DockPosition = .top,
width_percent: f32 = 50.0,
height_percent: f32 = 100.0,
offset_percent: f32 = 100.0,
position_set: bool = false,
// Alt+Enter 로 토글되는 fullscreen 상태. `show()` / `WM_DISPLAYCHANGE` /
// `WM_DPICHANGED` / `WM_SETTINGCHANGE(SPI_SETWORKAREA)` 핸들러가
// 이 값을 보고 `applyFullscreen` (현재 모니터 rcMonitor 전체) 혹은
// `repositionFromSaved` (저장된 dock/pct) 중 하나로 분기. F1 hide 는
// 이 값을 유지 — 다시 F1 show 하면 fullscreen 이 복원됨.
fullscreen_mode: FullscreenMode = .none,
// WM_DISPLAYCHANGE dedupe — 사용자 환경에 따라 Alt 키 단독 press 같은
// 이벤트에서도 WM_DISPLAYCHANGE 가 spurious 하게 broadcast 되는 경우가
// 있음 (Display-Fusion/Nvidia nView 류 유틸 훅 의심). lParam 의 해상도
// (LOWORD=w, HIWORD=h) 를 캐시해서 실제 해상도가 바뀐 경우에만
// applyLayout 을 호출 — 그래야 Alt+Enter 직후 spurious WM_DISPLAYCHANGE
// 가 fullscreen/dock 전환을 시각적으로 취소하는 race 를 피할 수 있음.
last_display_w: u32 = 0,
last_display_h: u32 = 0,
// 우리가 의도한 window rect. `applyRect` 가 매번 갱신. `WM_WINDOWPOSCHANGING`
// 핸들러가 이 값과 다른 rect 로 이동/리사이즈를 요청받으면 강제로 이 값으로
// 덮어써서 외부 프로그램 (Alt 키에 반응해 WS_EX_TOPMOST 창을 rcMonitor 전체로
// 확장시키는 display utility 류) 의 간섭을 차단. `expected_set` 은 최초
// `setPosition` 호출 전 CreateWindowExW 단계의 내부 resize 는 간섭하지 않기
// 위한 가드.
expected_x: c_int = 0,
expected_y: c_int = 0,
expected_w: c_int = 0,
expected_h: c_int = 0,
expected_set: bool = false,
layout_transition_active: bool = false,
/// BMP 밖 codepoint (이모지 U+1F300+ 등) 입력 시 Windows 가 UTF-16 surrogate
/// pair 로 두 번 WM_CHAR 를 보냄 — 첫 번째 high surrogate (0xD800..0xDBFF)
/// 는 단독으론 invalid codepoint 라 PTY 전송 실패. 첫
/// surrogate 를 보관 → 두 번째 (low surrogate, 0xDC00..0xDFFF) 도착하면
/// 결합해 단일 u21 codepoint 로 dispatch. emoji picker (`Win+.`) 입력이
/// 안 되던 사고 (시연 중 발견 — 2026-05-03).
pending_high_surrogate: u16 = 0,
/// WM_KEYDOWN 가 소비한 키가 TranslateMessage 로 동시에 WM_CHAR (Enter `\r`,
/// Escape `\x1b`, Backspace `\x08`) 를 큐에 넣는다. KEYDOWN 핸들러의 `return 0`
/// 만으로는 그 WM_CHAR 가 막히지 않아 PTY 로 새어 들어감 (예: command menu
/// 가 소비한 Enter 가 prompt 에 빈 줄 입력). KEYDOWN 에서 해당 키를 소비하면
/// 이 flag 를 set, WM_CHAR 진입 즉시 swallow + clear.
swallow_next_wm_char: bool = false,
/// IME composition (preedit) 버퍼 — UTF-8. WM_IME_COMPOSITION 의 GCS_COMPSTR
/// 를 ImmGetCompositionStringW 로 받아 UTF-16 → UTF-8 변환 후 저장 (#164).
/// renderer 가 매 frame 읽어 cursor 옆 inline overlay (mac 동등). 한글 / 일본
/// 어 / 중국어 등 모든 IMM 기반 IME 가 같은 path. GCS_RESULTSTR도 이 message
/// 안에서 동기 처리해 action보다 먼저 원래 입력 대상에 반영한다 (#313).
preedit_buf: [256]u8 = undefined,
preedit_len: usize = 0,
/// `imeCompleteComposition`의 ImmNotifyIME가 nested WM_IME_COMPOSITION을
/// 동기 발생시켰는지 확인한다. 결과를 동기 처리하지 못하면 caller가 action을
/// 보류해 queued WM_CHAR가 새 탭/새 prompt로 이동하지 않게 한다.
ime_complete_in_progress: bool = false,
ime_complete_result_ok: bool = false,
/// Ctrl chord의 실제 key가 preedit result보다 늦게 queue될 수 있어, 바로
/// 앞의 GCS_RESULTSTR를 target에 보내지 않고 잠깐 보관한다. 다음 non-modifier
/// key/action에서 input_policy에 따라 commit/discard/IMM composition 복원 중
/// 하나로 정확히 한 번 소비한다 (#313 B1).
ime_deferred_result: ?[]u8 = null,
ime_preserve_requested: bool = false,
hotkey_vkey: UINT = 0,
hotkey_modifiers: UINT = 0,
hotkey_registered: bool = false,
const CLASS_NAME = std.unicode.utf8ToUtf16LeStringLiteral(@import("instances.zig").window_class_name);
const HOTKEY_ID: c_int = 1;
const VK_F1: UINT = 0x70;
const VK_RETURN: WPARAM = 0x0D;
const RENDER_TIMER_ID: usize = 1;
// #245 — drag-select auto-scroll. 포인터가 터미널 경계 밖에 머무는 동안
// 마지막 mouse_move 를 주기적으로 재전송 → app 의 updateTerminalSelection 이
// 연속 스크롤 (이벤트 없어도 굴러감). app_controller 가 setAutoScroll 로 on/off.
const AUTOSCROLL_TIMER_ID: usize = 2;
const AUTOSCROLL_INTERVAL_MS: UINT = 40;
const LayoutMonitorTarget = enum { cursor, window };
pub fn init(self: *Window, font_chain: []const [*:0]const WCHAR, terminal_font: font_spec.Spec, opacity: u8) !void {
if (font_chain.len == 0) return error.EmptyFontChain;
const hInstance = GetModuleHandleW(null);
// #193 — cursor handle 캐시. WM_SETCURSOR 매 호출마다 LoadCursorW 안 함.
// LoadCursorW(null, IDC_*) 는 system shared resource — DestroyCursor 불필요.
self.cursor_arrow = LoadCursorW(null, IDC_ARROW);
self.cursor_ibeam = LoadCursorW(null, IDC_IBEAM);
const wc = WNDCLASSEXW{
.cbSize = @sizeOf(WNDCLASSEXW),
.style = CS_DBLCLKS,
.lpfnWndProc = wndProc,
.cbClsExtra = 0,
.cbWndExtra = 0,
.hInstance = hInstance,
.hIcon = null,
.hCursor = LoadCursorW(null, IDC_ARROW),
.hbrBackground = null,
.lpszMenuName = null,
.lpszClassName = CLASS_NAME,
.hIconSm = null,
};
if (RegisterClassExW(&wc) == 0) {
return error.RegisterClassFailed;
}
self.owner_hwnd = CreateWindowExW(
WS_EX_TOOLWINDOW,
CLASS_NAME,
std.unicode.utf8ToUtf16LeStringLiteral("TildaZOwner"),
WS_POPUP,
0,
0,
0,
0,
null,
null,
hInstance,
null,
);
if (self.owner_hwnd == null) {
return error.CreateWindowFailed;
}
var title_buf: [32]u16 = undefined;
var title_utf8_buf: [32]u8 = undefined;
// #382 — 타이틀은 이 프로세스의 **역할**에서 나온다 (`instance_context.Role`).
// Windows 는 worker 창을 타이틀로 찾으므로 (`instance_request.send` 의
// `FindWindowW(class, "TildaZ-0")` · `hotkey_capture.broadcast` 의 같은 조회)
// 측정 창이 worker 타이틀을 쓰면 그 조회가 측정 창을 집을 수 있다.
//
// Linux 도 같은 함수를 쓴다 — GNOME · Cinnamon extension 이 창 타이틀과 app_id 로
// worker 창을 찾기 때문이다 (`host/linux/wayland_minimal.zig` 의
// `createXdgToplevel`). host 마다 `switch` 를 두면 한쪽만 고쳐진다.
const title_utf8 = @import("instances.zig").windowTitleForCurrentRole(&title_utf8_buf) catch "TildaZ";
const title_len = std.unicode.utf8ToUtf16Le(&title_buf, title_utf8) catch 0;
title_buf[title_len] = 0;
// #89 — WS_EX_LAYERED 를 아예 쓰지 않는다. layered 창은 renderer 가
// 구형 BitBlt swap chain(DISCARD, redirection bitmap 경유)으로 강제되어
// fullscreen↔dock rect 전환 시 stale frame stretch 의 구조적 원인.
// - opacity 100% (기본값): 일반 창 → renderer 가 hwnd flip-model.
// - opacity <100% (#89 2단계): WS_EX_NOREDIRECTIONBITMAP 으로
// redirection bitmap 자체를 제거하고, renderer 가 DirectComposition
// swap chain + DComp visual SetOpacity(uniform) 로 반투명 합성 —
// LWA_ALPHA 와 같은 창 전체 균일 알파 의미론.
const ex_style: DWORD = WS_EX_TOPMOST | WS_EX_TOOLWINDOW |
(if (opacity < 255) WS_EX_NOREDIRECTIONBITMAP else 0);
self.hwnd = CreateWindowExW(
ex_style,
CLASS_NAME,
@ptrCast(title_buf[0..title_len :0]),
WS_POPUP,
0,
0,
800,
400,
self.owner_hwnd,
null,
hInstance,
null,
);
if (self.hwnd == null) {
_ = DestroyWindow(self.owner_hwnd);
self.owner_hwnd = null;
return error.CreateWindowFailed;
}
// Store self pointer in window userdata
_ = SetWindowLongPtrW(self.hwnd, GWL_USERDATA, @intCast(@intFromPtr(self)));
// DWM window transition 애니메이션 비활성화. Alt+Enter 로 fullscreen ↔
// dock rect 전환 직후 F1 로 SW_HIDE 하면, DWM 이 "현재 rect 에서 이전
// rect 로 shrink" 애니메이션을 재생하면서 중간 프레임의 WM_SIZE 를
// broadcast 하는 현상이 관측됨. 예: fullscreen 상태에서 hide → WM_SIZE
// 1440x1704 (직전 dock 사이즈) 가 hide 100ms 후 들어옴. 사용자 눈엔
// "F1 눌렀는데 반화면이 잠깐 나타났다 사라짐" 으로 보임.
// 이 속성을 켜면 DWM 이 transition 애니메이션을 건너뛰고 상태 전환이
// 즉시 반영됨.
const disable: BOOL = 1;
_ = DwmSetWindowAttribute(self.hwnd, DWMWA_TRANSITIONS_FORCEDISABLED, &disable, @sizeOf(BOOL));
// Remember font chain + font-creation parameters so `rebuildFontForDpi`
// can recreate the font + re-measure cell metrics on DPI changes.
const limit = @min(font_chain.len, self.font_chain.len);
for (font_chain[0..limit], 0..) |fam, i| self.font_chain[i] = fam;
self.font_chain_count = @intCast(limit);
self.terminal_font = terminal_font;
// DC must exist before `rebuildFontForDpi` measures cell metrics.
self.dc = GetDC(self.hwnd);
const dpi = GetDpiForWindow(self.hwnd);
const init_dpi: UINT = if (dpi > 0) dpi else 96;
self.rebuildFontForDpi(init_dpi);
// Start render timer (60fps)
_ = SetTimer(self.hwnd, RENDER_TIMER_ID, 16, null);
}
/// 전역 핫키 등록 (config 기본값 = F1, modifiers=0). 실패 사유 (시연 중 발견):
/// - Windows OS 가 예약: F12 = kernel debugger 용 (MSDN RegisterHotKey 명시).
/// - 다른 system shortcut 과 충돌: Win+Shift+S (Snip & Sketch) 등 일부 Win+Shift
/// 조합은 Windows shell 이 먼저 가로채서 우리 hotkey 가 안 도달.
/// - 다른 앱이 이미 같은 조합을 등록.
/// 이 셋은 외부 표시 없이 silent fail 하는 게 사고 — drop-down 정체상 hotkey 가
/// 없으면 토글 자체가 안 되어 사용자가 *왜 안 되는지* 모른 채 헤맴. fatal dialog 로
/// 종료 + config 파일 경로 + 알려진 reservation 안내.
///
/// ## 왜 `init` 밖으로 분리했는가 (#382)
///
/// 등록 여부는 **host 의 정책**이다 — 측정 모드는 등록하지 않는다 (평소 쓰는
/// TildaZ 와 같은 키에 두 프로세스가 반응하므로). 그 정책을 `init` 의 인자로
/// 넘기면서 `vkey 0` 을 "등록하지 않는다" 는 뜻으로 쓰고 `init` 한복판에서
/// `return` 했던 것이 사고였다: 그 `return` 이 뒤따르는 font chain 저장 · `GetDC` ·
/// `rebuildFontForDpi` · 렌더 타이머까지 함께 삼켜서, 측정 인스턴스가 **셀 메트릭을
/// 재지 않은 기본값** (`cell_width_px` / `cell_height_px` = 8x16) 으로 떴다
/// (Windows 실기: 같은 config 인데 정상 인스턴스 `cell=9x20` vs 측정 인스턴스
/// `cell=8x16`). 그 상태로 `-size` 가 창을 만들면 격자 *수*는 맞아도 셀당 픽셀이
/// 실제 폰트와 달라 (글리프 18px 이 16px 셀에 들어간다) "같은 격자 · 같은 폰트로
/// 다른 터미널과 비교" 라는 옵션의 목적이 깨진다.
///
/// 그래서 (1) 매직 값을 없애고 (2) 등록을 별도 단계로 뒀다. host 가
/// `if (!opts.isStressRun()) window.registerGlobalHotkey(...)` 로 정책을 드러내며,
/// macOS 의 `installEventTap` · Linux 의 `sway_ipc.registerToggleIfSway` 와 같은
/// 형태다. 이제 이 정책 분기가 창 초기화를 삼킬 구조 자체가 없다.
pub fn registerGlobalHotkey(self: *Window, hotkey_vkey: u32, hotkey_modifiers: u32) void {
self.hotkey_vkey = hotkey_vkey;
self.hotkey_modifiers = hotkey_modifiers;
if (RegisterHotKey(self.requireHwnd(), HOTKEY_ID, hotkey_modifiers, hotkey_vkey) == 0) {
var alloc_buf: [4096]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&alloc_buf);
const cfg_path = paths.configPath(fba.allocator()) catch messages.unknown_path_msg;
var msg_buf: [1024]u8 = undefined;
const msg = std.fmt.bufPrint(
&msg_buf,
messages.hotkey_registration_failed_format,
.{ hotkey_vkey, hotkey_modifiers, cfg_path },
) catch messages.hotkey_registration_failed_fallback_msg;
dialog.showFatal(messages.hotkey_registration_failed_title, msg);
}
// 등록에 성공한 경로에만 세운다 — `deinit` 의 `UnregisterHotKey` 와
// `WM_HOTKEY_CAPTURE_BEGIN` / `_END` 가 이 flag 를 본다.
//
// 측정 인스턴스에서는 `false` 로 남는데, **세 곳이 다 no-op 은 아니다.**
// `WM_HOTKEY_CAPTURE_END` 는 `!hotkey_registered` 일 때 등록을 *시도*하고
// (`RegisterHotKey(hwnd, HOTKEY_ID, hotkey_modifiers, hotkey_vkey)`), 측정
// 인스턴스는 두 필드가 기본값 0 이라 그 호출이 실패해 `0` 을 돌려준다 (호출자는
// `HotkeyCaptureSyncFailed` 로 읽는다). 그러니까 `vkey 0` 의 의미가 인자에서
// **필드 기본값**으로 옮겨간 것이고, 오늘 이 경로에 도달하지 않는 이유는 이 flag 가
// 아니라 **창 타이틀이 분리돼 있어서** 다 — `hotkey_capture.broadcast` 는
// `FindWindowW` 로 worker 타이틀을 찾으므로 측정 창을 집지 않는다
// (`instances.windowTitleForCurrentRole`).
self.hotkey_registered = true;
}
/// (Re)create the GDI font at `new_dpi` and re-measure cell metrics.
///
/// Called from `init` for the first build, and from the `WM_DPICHANGED`
/// handler when the window moves between monitors with different DPI
/// scales so glyphs are rasterized at the new monitor's pixel density
/// instead of the init-time monitor's.
///
/// After this returns, `cell_width` / `cell_height` reflect the new DPI;
/// call `font_change_fn` so the renderer can rebuild its DirectWrite
/// font context + glyph atlas at the matching `pixels_per_dip`.
pub fn rebuildFontForDpi(self: *Window, new_dpi: UINT) void {
// Release previous font (if any) before creating a replacement.
if (self.font) |prev| _ = DeleteObject(prev);
const effective_dpi: u32 = if (new_dpi > 0) new_dpi else 96;
const scaled_font_size: c_int = @intCast(self.terminal_font.physicalSizeRatioCeilPx(effective_dpi, 96));
// GDI CreateFontW 는 single face — chain 의 primary (chain[0]) 만 셀
// 메트릭 (advance width / line height) 측정에 사용. 글리프 폴백은
// renderer 의 DWriteFontContext 가 chain 전체로 처리.
//
// 음수 cHeight = *em-size 컨벤션* (DWrite native + WT BackendD3D 동등).
// 양수면 cell-height 컨벤션 — GDI 가 em 을 작게 잡아서 (Cascadia 18pt
// → em 15.5) tmHeight 가 작아짐. 그러면 cell_h < DWrite 가 raster 한
// glyph 의 ascent+descent 라 글자가 cell 밖으로 삐져나옴 (#148 B-2 후
// 발견). 음수면 GDI 도 em=18 → tmHeight ≈ 21 → cell_h 가 DWrite asc+desc
// 와 정합.
const primary_family = if (self.font_chain_count > 0) self.font_chain[0] else std.unicode.utf8ToUtf16LeStringLiteral("Consolas");
self.font = CreateFontW(
-scaled_font_size,
0,
0,
0,
FW_NORMAL,
0,
0,
0,
DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,
CLEARTYPE_QUALITY,
FIXED_PITCH | FF_MODERN,
primary_family,
);
// 정공 cell metric (#148 후속) — DWrite design metric 으로 직접 산출.
// GDI tm.tmHeight 는 ascent+descent rounding 에 더해 tmExternalLeading
// 까지 포함해서 cell_h 가 4px 정도 부풀려짐 (Cascadia em=24 기준 32 vs
// 자연 28). DWrite asc+desc+lineGap 으로 가면 28 — WT 와 정합.
const font_size_px = self.terminal_font.physicalSizeRatioPx(effective_dpi, 96);
const measured = dwrite_font.measureCell(primary_family, font_size_px) catch null;
if (measured) |m| {
self.cell_width_px = @intCast(font_spec.ceilPositivePx(m.cell_w * self.terminal_font.cell_width_ratio));
self.cell_height_px = @intCast(font_spec.ceilPositivePx(m.cell_h * self.terminal_font.line_height_ratio));
} else if (self.dc != null and self.font != null) {
// DWrite 측정 실패 fallback — GDI tm. 사용자 환경에서 이 path 거의
// 안 탐 (font 사전 검증 통과 후라).
const old_f = SelectObject(self.dc, self.font);
var tm: TEXTMETRICW = undefined;
_ = GetTextMetricsW(self.dc, &tm);
const base_w: f32 = @floatFromInt(tm.tmAveCharWidth);
const base_h: f32 = @floatFromInt(tm.tmHeight);
self.cell_width_px = @intCast(font_spec.ceilPositivePx(base_w * self.terminal_font.cell_width_ratio));
self.cell_height_px = @intCast(font_spec.ceilPositivePx(base_h * self.terminal_font.line_height_ratio));
_ = SelectObject(self.dc, old_f);
}
self.current_dpi = new_dpi;
}
/// #358 — `init` 성공 이후 `hwnd` 는 항상 있다. `CreateWindowExW` 실패는
/// `init` 이 `error.CreateWindowFailed` 로 올리고 host 의 `try` 가 `run()` 을
/// 중단시키므로 (`host/windows.zig` 의 `try app.window.init(...)`), 그 뒤로
/// "창이 없는 Window" 는 도달 불가다.
///
/// 그 불변식을 이 접근자 하나로 모은다. 이전에는 호출 지점 15곳이 각자
/// `orelse return` / `orelse return null` / `orelse return false` 로 조용히
/// no-op 해서 호출처가 실패를 구분할 수 없었고, "도달 불가 분기도 뭔가를
/// 돌려줘야 한다" 는 압력이 #352 에서 걷어낸 가짜 값 (`120x30` · `800x400`)
/// 을 낳은 원인이었다.
///
/// `.?` 가 아니라 `orelse @panic` 인 이유: `.?` 는 ReleaseFast 에서 검사가
/// 빠져 UB 가 된다. 공식 빌드가 ReleaseFast 라 그러면 "위반 시 즉시 드러난다"
/// 는 이 접근자의 취지가 사라진다.
///
/// 이름이 `handle` 이 아닌 이유: 이 파일에 `handle` 이라는 지역 상수가 이미
/// 둘 (`WM_SETCURSOR` 의 `HCURSOR`, `pasteClipboard` 의 clipboard handle) 있어
/// Zig 가 shadowing 을 거부한다.
fn requireHwnd(self: *const Window) *anyopaque {
return self.hwnd orelse @panic("Window used before init (#358)");
}
pub fn deinit(self: *Window) void {
self.imeClearDeferredResult(false);
// #358 — 여기는 `requireHwnd()` 로 바꾸지 않는다. 정리 함수가 불변식을 강제해
// panic 하면, 실패 처리 순서를 바꿀 때 곧바로 crash 가 된다. 이 검사는
// 도달 불가 방어가 아니라 "만들어졌으면 정리한다" 는 계약이다.
if (self.hwnd) |hwnd| {
_ = KillTimer(hwnd, RENDER_TIMER_ID);
if (self.hotkey_registered) _ = UnregisterHotKey(hwnd, HOTKEY_ID);
if (self.dc) |dc| _ = ReleaseDC(hwnd, dc);
_ = DestroyWindow(hwnd);
}
if (self.owner_hwnd) |owner_hwnd| {
_ = DestroyWindow(owner_hwnd);
}
if (self.font) |f| _ = DeleteObject(f);
}
/// F1 hide 에서 돌아오는 show. Windows visibility 를 `SW_SHOW` 로 전환하고,
/// `self.fullscreen` 상태에 따라 fullscreen rect 또는 저장된 dock 설정으로
/// layout 을 재적용한다.
///
/// `SW_SHOW` 를 쓰는 이유: 과거 한때 `DWMWA_CLOAK` 기반 cloak/uncloak 로
/// visibility 를 토글한 적이 있는데, cloak 은 DWM compositor 레벨에서만
/// 보였다/안 보였다를 바꾸고 Windows shell 의 visibility state (external
/// window manager 들이 enum 할 때 참조하는) 와는 sync 되지 않아서,
/// "Alt+Enter → F1 hide → F1 show → Alt+Enter" 순서에서 shell state 가
/// 고착돼 다음 rect 전환이 stale surface 위에 composite 되는 버그가
/// 있었음 (#87). `SW_SHOW` / `SW_HIDE` 는 Windows 가 공식 인정하는
/// visibility 전환이라 shell state 가 매 전환마다 clean 하게 재계산됨.
///
/// 과거 `SW_HIDE` 에서 보이던 "shrink transition animation" glitch 는
/// `init()` 에서 설정한 `DWMWA_TRANSITIONS_FORCEDISABLED` 로 DWM 이
/// 애니메이션 자체를 skip 하므로 재현되지 않음.
/// Restore a window hidden by F1.
/// The saved fullscreen mode is preserved while hidden.
/// 시작 직후 / F1 hide-show 등 모든 show 경로에서 keyboard focus 가
/// 안정적으로 우리 창에 잡히도록 강제. 단순 `SetForegroundWindow` 는 MSDN
/// 의 8 가지 조건 (foreground process 의 자식 / 마지막 input 받은 process /
/// foreground 무 / debug 중 등) 중 하나라도 안 맞으면 silently fail (return
/// 0). 진단 로깅으로 시작 직후 setfg_ret=0 + foreground 가 다른 창인 케이스
/// 직접 측정 확인 (PowerShell `Start-Process` 류로 띄울 때 발생) — 이때
/// Ctrl+Shift+T 등 단축키가 우리 창에 도달 안 함. F1 hide-show 는 사용자
/// input 직후라 #3 으로 통과해 setfg_ret=1 — 그래서 두 번째 F1 후엔 정상.
///
/// AttachThreadInput trick: 우리 thread 의 input queue 를 현재 foreground
/// thread 와 잠시 attach → 두 thread 가 같은 input context 안에 있는 셈이
/// 되어 SetForegroundWindow 가 통과 → detach. Raymond Chen 의 well-known
/// idiom. SetFocus 도 같이 호출해 popup 본체가 직접 keyboard focus 를 받도록.
fn forceForegroundActivation(hwnd: HWND) void {
const fg_hwnd = GetForegroundWindow();
const our_thread = GetCurrentThreadId();
if (fg_hwnd != null and fg_hwnd != hwnd) {
const fg_thread = GetWindowThreadProcessId(fg_hwnd, null);
if (fg_thread != 0 and fg_thread != our_thread) {
_ = AttachThreadInput(our_thread, fg_thread, 1);
_ = BringWindowToTop(hwnd);
_ = SetForegroundWindow(hwnd);
_ = SetFocus(hwnd);
_ = AttachThreadInput(our_thread, fg_thread, 0);
return;
}
}
_ = BringWindowToTop(hwnd);
_ = SetForegroundWindow(hwnd);
_ = SetFocus(hwnd);
}
pub fn show(self: *Window) void {
const hwnd = self.requireHwnd();
self.layout_transition_active = true;
defer self.layout_transition_active = false;
self.visible = true;
_ = ShowWindow(hwnd, SW_SHOW);
// fullscreen 상태였으면 fullscreen 을 복원, 아니면 dock 설정 복원.
// F1 hide 는 fullscreen 필드를 건드리지 않으므로 "Alt+Enter → F1
// hide → F1 show" 는 여전히 fullscreen 상태로 돌아옴.
// show() 만 cursor-follow 를 유지하고, visible 상태의 relayout 은
// 창이 이미 올라가 있는 모니터를 기준으로 재계산한다.
self.applyLayoutFor(.cursor);
self.syncLayout();
forceForegroundActivation(hwnd);
// `applyLayout` 의 SetWindowPos 가 현재 rect 과 동일해서 WM_SIZE
// 를 생략한 경우 대비 safety net — swap chain / terminal grid 를
// idempotent 하게 재동기화.
self.presentNow();
_ = SetTimer(hwnd, RENDER_TIMER_ID, 16, null);
}
/// F1 으로 호출되는 hide. `SW_HIDE` 로 Windows 가 창을 공식적으로 hidden
/// 으로 인식하게 한다 — external window manager (FancyZones 등) 가 창을
/// enum 에서 빼고 간섭을 멈추며, shell state 도 clean 해짐.
///
/// `self.fullscreen` 은 건드리지 않음 — 다음 `show()` 에서 `applyLayout` 이
/// fullscreen 을 그대로 복원한다.
/// Hide the window without changing the saved fullscreen mode.
pub fn hide(self: *Window) void {
const hwnd = self.requireHwnd();
self.breakMonitorFullscreenSurface();
_ = KillTimer(hwnd, RENDER_TIMER_ID);
self.visible = false;
_ = ShowWindow(hwnd, SW_HIDE);
_ = DwmFlush();
}
/// `WS_EX_TOPMOST` 를 잠시 해제 — TildaZ 는 그대로 보이지만 z-order 가
/// normal 그룹으로 내려가서, 새로 launch 되는 editor (config / log 의 default
/// app) 가 자연스럽게 우리 위로 올라옴. config / log 단축키 (Ctrl+Shift+P/L)
/// 직후 사용자가 editor 를 즉시 보도록 (시연 중 발견 — editor 가 우리 창
/// 뒤로 가려져 안 보였던 사고). 사용자가 F1 toggle 해 다시 show() 가 호출
/// 되면 `applyRect` 의 `HWND_TOPMOST` 가 다시 topmost 로 복귀시킴.
pub fn yieldTopmostUntilNextShow(self: *Window) void {
_ = SetWindowPos(self.requireHwnd(), HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
pub fn toggle(self: *Window) void {
if (self.visible) {
// #175 — F1 hide 도 focus_loss = commit. show 분기에선 호출 안 함.
if (self.before_hide_fn) |f| f(self.userdata);
// per-toggle — verbose (#197 Option B, 3 플랫폼 공통 category "toggle").
log.appendLineVerbose("toggle", "hide", .{});
self.hide();
} else {
log.appendLineVerbose("toggle", "show", .{});
self.show();
}
}
pub fn setPosition(self: *Window, dock: DockPosition, width_percent: f32, height_percent: f32, offset_percent: f32) void {
// Remember parameters so WM_DISPLAYCHANGE / WM_DPICHANGED /
// WM_SETTINGCHANGE(SPI_SETWORKAREA) and show() can re-apply them on
// resolution / monitor / DPI / taskbar changes.
self.dock = dock;
self.width_percent = width_percent;
self.height_percent = height_percent;
self.offset_percent = offset_percent;
self.position_set = true;
self.applyDockedRect(dock, width_percent, height_percent, offset_percent, .cursor);
}
/// #382 — 셀 개수로 창을 잡을 때 쓰는 환산. 창 크기 경로는 퍼센트 기반이고 (DPI ·
/// 해상도 변경 시 그 값으로 재적용된다) 그 구조를 그대로 두는 게 안전하므로, 필요한
/// 픽셀을 현재 모니터 작업영역 대비 퍼센트로 바꿔 기존 경로에 넣는다.
///
/// 호출자는 **여유를 더한 픽셀**을 넘겨야 한다. `viewportForGrid` 는 요청한 격자가
/// 나오는 *가장 작은* 크기를 내는데, 퍼센트 환산에서 1 px 이라도 줄면 격자가 한 칸
/// 줄어든다. 셀 크기의 절반을 더하면 내림이 흡수한다.
pub fn percentForPixels(self: *Window, w_px: i64, h_px: i64) ?struct { w: f32, h: f32 } {
const mi = self.monitorInfoFor(.cursor) orelse return null;
const sw: i64 = mi.rcWork.right - mi.rcWork.left;
const sh: i64 = mi.rcWork.bottom - mi.rcWork.top;
if (sw <= 0 or sh <= 0) return null;
return .{
.w = @min(100.0, @as(f32, @floatFromInt(w_px)) / @as(f32, @floatFromInt(sw)) * 100.0),
.h = @min(100.0, @as(f32, @floatFromInt(h_px)) / @as(f32, @floatFromInt(sh)) * 100.0),
};
}
fn applyDockedRect(
self: *Window,
dock: DockPosition,
width_percent: f32,
height_percent: f32,
offset_percent: f32,
target: LayoutMonitorTarget,
) void {
const mi = self.monitorInfoFor(target) orelse return;
const rect = dockRectForMonitor(dock, width_percent, height_percent, offset_percent, &mi);
self.applyRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
}
fn dockRectForMonitor(
dock: DockPosition,
width_percent: f32,
height_percent: f32,
offset_percent: f32,
mi: *const MONITORINFO,
) RECT {
const sw = mi.rcWork.right - mi.rcWork.left;
const sh = mi.rcWork.bottom - mi.rcWork.top;
const sx = mi.rcWork.left;
const sy = mi.rcWork.top;
const sw_f: f32 = @floatFromInt(sw);
const sh_f: f32 = @floatFromInt(sh);
// width = always horizontal %, height = always vertical %.
// f32 percent → pixel: round 후 c_int. 정수 나눗셈 보다 정확한 세밀 조정
// (예: 33.3% 가 sw=1920 일 때 639.36 → 639 px).
const w: c_int = @intFromFloat(@round(sw_f * width_percent / 100.0));
const h: c_int = @intFromFloat(@round(sh_f * height_percent / 100.0));
const x: c_int = switch (dock) {
.left => sx,
.right => sx + sw - w,
.top, .bottom => sx + @as(c_int, @intFromFloat(@round(@as(f32, @floatFromInt(sw - w)) * offset_percent / 100.0))),
};
const y: c_int = switch (dock) {
.top => sy,
.bottom => sy + sh - h,
.left, .right => sy + @as(c_int, @intFromFloat(@round(@as(f32, @floatFromInt(sh - h)) * offset_percent / 100.0))),
};
return .{
.left = x,
.top = y,
.right = x + w,
.bottom = y + h,
};
}
/// Re-apply the last `setPosition` parameters. Used by display/DPI/work-area
/// change handlers and by `show()` so the window tracks the current monitor
/// and re-fits after resolution / taskbar / monitor-configuration changes.
/// No-op if `setPosition` was never called.
///
/// After `SetWindowPos` we explicitly invoke `resize_fn` to guarantee the
/// terminal grid reflows. `SetWindowPos` skips `WM_SIZE` when the new rect
/// matches the current one — which happens when:
/// - an external monitor is disconnected and Windows has already
/// auto-moved the window to the primary monitor, so the saved-%
/// rect we compute equals the rect the window is already at
/// - DPI changes between monitors of identical pixel resolution (the
/// saved % yields the same pixel dimensions)
/// In those cases `cell_width` / `cell_height` may have changed under
/// the window but the terminal grid stays stuck at the old rows/cols.
/// Calling `resize_fn` unconditionally is idempotent: when `WM_SIZE`
/// does fire, the second invocation hits no-op fast paths in
/// terminal resize / backend resize / swapchain resize.
pub fn repositionFromSaved(self: *Window) void {
if (!self.position_set) return;
self.applyDockedRect(self.dock, self.width_percent, self.height_percent, self.offset_percent, .window);
if (!self.layout_transition_active) {
if (self.resize_fn) |resize_fn| resize_fn(self.userdata);
}
}
/// `applyFullscreen` / `setPosition` 이 공유하는 단일 rect 적용 경로.
///
/// 하는 일:
/// 1. `expected_*` 필드를 새 rect 로 갱신 — `WM_WINDOWPOSCHANGING` 핸들러가
/// 이 값을 source-of-truth 로 삼아 외부 프로그램 (display utility / window
/// manager 류) 의 rect 간섭을 clamp 한다.
/// 2. `SetWindowPos(HWND_TOPMOST, ..., SWP_REPAINT)` 호출 — WS_POPUP +
/// WS_EX_LAYERED 조합에서 visual rect 가 logical rect 를 따라가도록
/// `SWP_NOCOPYBITS | SWP_FRAMECHANGED` 를 같이 걸어 DWM 이 이전 surface
/// 를 재사용하지 않고 non-client 영역도 재계산하게 강제.
///
/// 모든 rect 변경 경로 (dock 재배치 / fullscreen 토글 / display 변경 후
/// 재적용) 가 이 함수를 지나게 해서 "커지는 방향 / 줄어드는 방향" 동작을
/// 대칭으로 유지.
fn applyRect(self: *Window, x: c_int, y: c_int, w: c_int, h: c_int) void {