-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmacos.zig
More file actions
1825 lines (1662 loc) · 91.6 KB
/
Copy pathmacos.zig
File metadata and controls
1825 lines (1662 loc) · 91.6 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
// Metal terminal renderer — Windows 의 `src/d3d11_renderer.zig` 와 같은 역할.
// 인스턴스드 쿼드 (한 cell = 한 quad instance) 로 배경 + 글리프 텍스트 그림.
// macOS 는 grayscale antialias 만 지원 (Mojave+) 이라 ClearType 서브픽셀 셰이더
// 불필요. 셰이더 / 셀 파이프라인이 Windows 보다 단순.
//
// #75 (claude/infallible-swartz) 의 macos/renderer.zig 패턴 그대로 차용 +
// 우리 nullable `id` (?*opaque) 와 평면 모듈 구조에 맞춰 정리.
const std = @import("std");
const objc = @import("../macos_objc.zig");
const perf = @import("../perf.zig");
const ct = @import("../font/macos/coretext.zig");
const mac_font = @import("../font/macos/font.zig");
const CoreTextFontContext = mac_font.CoreTextFontContext;
const font_spec = @import("../font/spec.zig");
const font_constants = @import("../font/constants.zig");
const macos_glyph_atlas = @import("macos/glyph_atlas.zig");
const ui_metrics = @import("../ui_metrics.zig");
const chrome_palette = @import("../chrome_palette.zig");
const themes = @import("../themes.zig");
const scrollbar = @import("../scrollbar.zig");
const GlyphAtlas = macos_glyph_atlas.GlyphAtlas;
const ATLAS_SIZE = macos_glyph_atlas.ATLAS_SIZE;
const ghostty = @import("ghostty-vt");
const display_width = @import("../font/display_width.zig");
const block_element = @import("block_element.zig");
const box_drawing = @import("../box_drawing.zig");
const cell_color = @import("cell_color.zig");
const cell_decoration = @import("cell_decoration.zig");
const tab_layout = @import("../tab_layout.zig");
const tab_chrome = @import("../tab_chrome.zig");
const ui_rect = @import("../ui_rect.zig");
const tab_icons = @import("../tab_icons.zig");
const session_core = @import("../session_core.zig");
const tab_interaction = @import("../tab_interaction.zig");
const command_menu = @import("../command_menu.zig");
const ligature_mod = @import("../font/ligature.zig");
const isLigatureCandidate = ligature_mod.isLigatureCandidate;
const MAX_INSTANCES: u32 = 32768;
// --- #255 Phase 2: CADisplayLink pause 합성 게이트 ---
// drawable 이 *실제로 화면에 표시*됐는지 확인하는 신호. host 가 idle 시 displayLink
// 를 pause 하려면 "show 직후 첫 프레임이 합성(composite)됐다"를 알아야 한다 — 안
// 그러면 합성 전 1프레임만 그리고 멈춰 빈 화면(#252 의 근본). `addPresentedHandler:`
// 는 drawable 이 표시된 *직후* 호출되고 `presentedTime>0` 이면 표시 확정. 핸들러는
// CoreAnimation presentation 스레드에서 불리므로 atomic. captures 없는 global block.
const BlockDescriptor = extern struct {
reserved: c_ulong = 0,
size: c_ulong,
};
const PresentedBlock = extern struct {
isa: ?*const anyopaque,
flags: c_int,
reserved: c_int = 0,
invoke: *const fn (*PresentedBlock, objc.id) callconv(.c) void,
descriptor: *const BlockDescriptor,
};
extern const _NSConcreteGlobalBlock: anyopaque;
const BLOCK_IS_GLOBAL: c_int = 1 << 28;
var g_frame_presented = std.atomic.Value(bool).init(false);
fn presentedInvoke(_: *PresentedBlock, drawable: objc.id) callconv(.c) void {
if (drawable == null) return;
const presentedTimeOf = objc.objcSend(fn (objc.id, objc.SEL) callconv(.c) f64);
if (presentedTimeOf(drawable, objc.sel("presentedTime")) > 0)
g_frame_presented.store(true, .seq_cst);
}
var presented_block_descriptor: BlockDescriptor = .{ .reserved = 0, .size = @sizeOf(PresentedBlock) };
var presented_block: PresentedBlock = .{
.isa = null, // 런타임에 _NSConcreteGlobalBlock 로 설정 (extern 주소는 comptime 불가).
.flags = BLOCK_IS_GLOBAL,
.reserved = 0,
.invoke = &presentedInvoke,
.descriptor = &presented_block_descriptor,
};
/// 마지막 show 이후 drawable 이 화면에 표시된 적 있나 (host 의 pause 게이트).
pub fn frameWasPresented() bool {
return g_frame_presented.load(.seq_cst);
}
/// show(hidden→visible) 시 host 가 호출 — 재합성 필요하므로 표시 확정 리셋.
pub fn resetFramePresented() void {
g_frame_presented.store(false, .seq_cst);
}
// --- Instance data layouts (MSL struct 와 일치해야 함) ---
const BgInstance = extern struct {
pos: [2]f32,
size: [2]f32,
color: [4]f32,
/// 0 = solid fill. 1/2/3 = U+2591/2/3 LIGHT/MEDIUM/DARK SHADE — fragment
/// 셰이더가 픽셀 parity 로 dot mask 계산 + discard. block_element.zig 와
/// d3d11 의 BgInstance.shade 와 동일 의미 (#155).
shade: f32 = 0,
/// MSL `float4` 16-byte align — 36 bytes 면 다음 multiple-of-16 (48) 으로
/// stride padding 되어 instance[1] 부터 깨짐. 12 bytes 명시 padding 으로
/// stride = 48 고정.
_pad: [3]f32 = .{ 0, 0, 0 },
};
/// #343 — 공통 `tab_chrome.Rect` 를 Metal `BgInstance` 로. 필드가 이미 같은
/// shape 라 옮기기만 한다 (`shade` / `_pad` 는 기본값).
fn bgFromChrome(r: tab_chrome.Rect) BgInstance {
return .{ .pos = .{ r.x, r.y }, .size = .{ r.w, r.h }, .color = r.color };
}
const TextInstance = extern struct {
pos: [2]f32,
size: [2]f32,
uv_pos: [2]f32,
uv_size: [2]f32,
fg_color: [4]f32,
/// 0 = 일반 글리프 (atlas × fg 로 색 입힘), 1 = 컬러 글리프 (SBIX/COLR — atlas
/// 그대로 출력, fg 무시). MSL 의 분기에서 0.5 임계값으로 판단. f32 인 이유는
/// MSL struct 의 alignment 단순화 + vertex output interpolation.
color_flag: f32,
/// MSL 의 `float4` 는 16-byte aligned. struct 사이즈가 16 의 배수가 아니면
/// MSL 은 그 다음 배수로 padding 한 stride 로 inst[iid] 인덱싱 (e.g., 52 bytes
/// 작성 → 64 bytes 로 읽음 → instance[1] 부터 모든 필드 깨짐).
/// 기존 5-field TextInstance (48 bytes) 는 16 배수라 padding 불필요했지만
/// color_flag 추가로 52 bytes 가 되어 12 bytes 명시적 padding 필요.
_pad: [3]f32 = .{ 0, 0, 0 },
};
// --- MSL 셰이더 ---
// === KNOWN ISSUE: layer 의 (0, 0) 픽셀 미렌더링 ===
//
// 진단 마커로 확인된 quirk: pos=(0,0) 위치에 그린 instance 의 좌상 1px 모서리
// (정확히 NDC(-1, +1) corner) 만 화면에 안 그려진다. pos=(1,1) 부터는 정상.
// 다른 모서리 (NDC (+1,+1), (-1,-1), (+1,-1)) 는 영향 없음 — 좌상 corner 만.
//
// 영향: TERMINAL_PADDING_PT >= 1 이면 글자가 항상 (1, 1) 안쪽에 있어 사용자가
// 인지하지 못 함. padding=0 으로 두고 셀 (0, 0) 부터 그릴 때만 1px 누락 보임.
//
// 추정 원인: Metal 의 `-px.y` NDC 변환 + viewport rasterization 의 좌상
// corner sample point 처리. 정확한 NDC corner vertex 가 fragment 에 sample
// 되지 않거나 `kCAGravityResize` 의 sub-pixel rounding 에서 누락되는 가능성.
// CAMetalLayer.contentsGravity = kCAGravityTopLeft 또는 viewport 명시적 설정
// 으로 회피 가능할 수 있으나 미검증. follow-up 으로 추적.
//
// === Shader ===
// Atlas 가 BGRA8 premultiplied 라 fragment 출력도 모두 premultiplied 로 통일.
// blend mode 도 (One, OneMinusSourceAlpha) — `createPipeline` 참조.
//
// - bg_fs: input color 는 plain (r,g,b,a). premultiply 해서 출력.
// - text_fs: atlas sample 이 이미 premult.
// - 일반 글리프 (color_flag = 0): atlas = (a, a, a, a) 흰색 premult. fg 와 곱
// → (a*fg.r, a*fg.g, a*fg.b, a*fg.a) = premult 결과.
// - 컬러 글리프 (color_flag = 1, Apple Color Emoji 등): atlas = SBIX 의 본래
// 색깔 premult. fg 무시하고 그대로 출력.
const shader_source =
\\#include <metal_stdlib>
\\using namespace metal;
\\
\\struct BgInst { float2 pos; float2 size; float4 color; float shade; };
\\struct BgOut { float4 position [[position]]; float4 color; float shade; };
\\
\\vertex BgOut bg_vs(uint vid [[vertex_id]], uint iid [[instance_id]],
\\ const device BgInst* inst [[buffer(0)]], constant float4& sa [[buffer(1)]]) {
\\ float2 c = float2(vid & 1, vid >> 1);
\\ float2 px = (inst[iid].pos + c * inst[iid].size) / sa.xy * 2.0 - 1.0;
\\ BgOut o; o.position = float4(px.x, -px.y, 0, 1);
\\ o.color = inst[iid].color;
\\ o.shade = inst[iid].shade;
\\ return o;
\\}
\\fragment float4 bg_fs(BgOut in [[stage_in]]) {
\\ if (in.shade > 0.5) {
\\ // Procedural shade pattern — d3d11_renderer.zig bg_shader_src 동등.
\\ // 픽셀 parity 로 dot mask 계산 후 discard. 폰트 무관.
\\ int2 px = int2(in.position.xy);
\\ if (in.shade < 1.5) {
\\ // U+2591 LIGHT 25% — diagonal sparse: ON at (px + 2*py) % 4 == 0
\\ if (((px.x + 2 * px.y) & 3) != 0) discard_fragment();
\\ } else if (in.shade < 2.5) {
\\ // U+2592 MEDIUM 50% — checkerboard
\\ if (((px.x + px.y) & 1) != 0) discard_fragment();
\\ } else {
\\ // U+2593 DARK 75% — LIGHT 의 inverse (diagonal dense)
\\ if (((px.x + 2 * px.y) & 3) == 0) discard_fragment();
\\ }
\\ }
\\ return float4(in.color.rgb * in.color.a, in.color.a);
\\}
\\
\\struct TxInst { float2 pos; float2 size; float2 uvp; float2 uvs; float4 fg; float color_flag; };
\\struct TxOut { float4 position [[position]]; float2 uv; float4 fg; float color_flag; };
\\
\\vertex TxOut text_vs(uint vid [[vertex_id]], uint iid [[instance_id]],
\\ const device TxInst* inst [[buffer(0)]], constant float4& sa [[buffer(1)]]) {
\\ float2 c = float2(vid & 1, vid >> 1);
\\ float2 px = (inst[iid].pos + c * inst[iid].size) / sa.xy * 2.0 - 1.0;
\\ TxOut o; o.position = float4(px.x, -px.y, 0, 1);
\\ o.uv = (inst[iid].uvp + c * inst[iid].uvs) / sa.zw;
\\ o.fg = inst[iid].fg;
\\ o.color_flag = inst[iid].color_flag;
\\ return o;
\\}
\\fragment float4 text_fs(TxOut in [[stage_in]], texture2d<float> atlas [[texture(0)]]) {
\\ constexpr sampler smp(mag_filter::nearest, min_filter::nearest);
\\ float4 s = atlas.sample(smp, in.uv);
\\ if (in.color_flag > 0.5) return s;
\\ return s * in.fg;
\\}
;
// --- Renderer ---
/// 탭바 layout (#117 Firefox 패턴) — cross-platform `tab_layout.Layout` 그대로
/// 사용 (#163 4-i-2). 호출처 host 가 `tab_layout.compute()` 결과를 그대로 넘김
/// — renderer struct 변환 cast block 사라짐.
pub const TabBarLayout = tab_layout.Layout;
/// renderTabBar 가 받은 인자를 renderTerminal 까지 전달. tabs 는 z-order 상
/// terminal 위에 그려져야 하므로 실제 encode 는 renderTerminal 끝에서.
const PendingTabs = struct {
titles: []const []const u8,
active: usize,
drag_view: ?tab_interaction.DragView,
scroll_x_px: f32,
layout: TabBarLayout,
hover: tab_layout.Area,
};
pub const MetalRenderer = struct {
alloc: std.mem.Allocator,
font: CoreTextFontContext,
atlas: GlyphAtlas,
tab_font: CoreTextFontContext,
tab_atlas: GlyphAtlas,
render_state: ghostty.RenderState = .empty,
// Metal 객체 (모두 ObjC id, 우리는 ARC 안 쓰지만 process 종료 시 회수).
device: objc.id,
/// CAMetalLayer — init 에서 받아 보관. drawable 획득 시점이 매 frame
/// 다르므로 host 가 매번 인자로 줄 필요 없도록 self 안에 보관 (Windows
/// D3d11Renderer 의 hwnd / rtv 보관 패턴과 같은 의도).
layer: objc.id,
command_queue: objc.id,
bg_pipeline: objc.id,
text_pipeline: objc.id,
bg_buffer: objc.id,
text_buffer: objc.id,
atlas_texture: objc.id,
tab_atlas_texture: objc.id,
constants_buffer: objc.id,
// frame 내 누적된 instance 수. 매 drawBgInstances / drawTextInstances 호출이
// 같은 buffer 의 *다음 offset* 에 쓰고 setVertexBuffer offset 도 그에 맞게.
// 같은 frame 안에서 여러 호출 (cell bg → cursor → scrollbar → preedit) 의
// 데이터가 buffer 안에서 서로 덮어쓰지 않게. renderTabBar 시작 시 0 reset.
bg_used: u32 = 0,
text_used: u32 = 0,
// 현재 buffer 가 담을 수 있는 instance 수. 초기 MAX_INSTANCES, 수요 초과 시
// frame 시작에서 키운다 (monotonic). box-drawing 은 MAX_RECTS=384 까지 분해돼
// 화면 가득 + 큰 선택(선택 cell 마다 배경 instance)이 겹치면 32768 을 쉽게
// 넘어, 초과분 draw 가 silent drop 되어 선택과 무관한 box 선까지 사라졌었다.
bg_capacity: u32 = MAX_INSTANCES,
text_capacity: u32 = MAX_INSTANCES,
// 이번 frame 이 그리려 *요청한* 총 instance 수 (drop 포함). frame 시작에서
// capacity 와 비교해 버퍼 확대 판단 후 0 reset. capacity 와 달리 drop 된 것도 셈.
bg_needed: u32 = 0,
text_needed: u32 = 0,
// Frame in progress — renderTabBar 가 begin (drawable + cmd_buf + encoder
// 생성 + clear), renderTerminal 이 end (encode + present + commit).
// Windows 의 self.rtv 패턴과 같은 의도. null = frame 진행 중 아님.
current_drawable: objc.id = null,
current_cmd_buf: objc.id = null,
current_encoder: objc.id = null,
/// renderTabBar 가 받은 args 보관. renderTerminal 끝에서 z-order 상 terminal
/// 위에 tabs 가 그려지도록 마지막에 encode (Windows 와 layout 자체가 분리
/// 영역이라 z-order 무관하지만, 같은 frame state 의 일부로 처리).
pending_tabs: ?PendingTabs = null,
// active terminal 이 배경색을 제공하지 않을 때만 쓰는 init theme fallback.
fallback_bg: [3]f32,
/// #335 — theme 배경에서 파생한 탭바 / command menu chrome 색. theme 은
/// runtime 에 바뀌지 않으므로 init 에서 한 번 계산해 보관한다. 탭바 그리기는
/// `ui_metrics` 색 상수를 직접 참조하지 않고 이 값만 쓴다.
chrome: chrome_palette.Palette,
// viewport (pixel 단위).
vp_width: u32 = 0,
vp_height: u32 = 0,
// Retina backing scale.
scale: f32,
/// #376 — 직전 프레임에 blink 셀이 화면에 있었나. host 의 렌더 게이트가 이
/// 값과 위상 전환을 **함께** 봐서, blink 이 실제로 보일 때만 초당 2프레임을
/// 추가로 그린다. "blink 셀이 있다" 만으로 게이트를 열면 매 vsync 그리게 돼
/// #255 의 절전 이득이 사라진다.
saw_blink_cell: bool = false,
// #253 — 다른 scale 모니터로 이동 시 cell 재측정(applyScale)에 필요한 init
// 파라미터 보관. font_families 슬라이스/문자열은 host 가 process lifetime 으로
// 보유(g_config 또는 run() 의 env_chain) — 재init 시 그대로 재사용.
font_families: []const []const u8,
terminal_font: font_spec.Spec,
pub fn colorF(v: u8) f32 {
return @as(f32, @floatFromInt(v)) / 255.0;
}
pub fn init(
alloc: std.mem.Allocator,
device: objc.id,
layer: objc.id,
font_families: []const []const u8,
terminal_font: font_spec.Spec,
bg_rgb: ?[3]u8,
scale: f32,
) !MetalRenderer {
const bg = bg_rgb orelse [3]u8{ 30, 30, 30 };
const cmd_queue = objc.msgSend(device, objc.sel("newCommandQueue"));
var font_ctx = try CoreTextFontContext.init(
alloc,
font_families,
terminal_font,
scale,
);
errdefer font_ctx.deinit();
var glyph_atlas = try GlyphAtlas.init(alloc, terminal_font.size_logical, scale);
errdefer glyph_atlas.deinit();
const tab_spec = ui_metrics.tabLabelFontSpec();
var tab_font_ctx = try CoreTextFontContext.init(
alloc,
font_families,
tab_spec,
scale,
);
errdefer tab_font_ctx.deinit();
var tab_glyph_atlas = try GlyphAtlas.init(alloc, tab_spec.size_logical, scale);
errdefer tab_glyph_atlas.deinit();
// Metal 셰이더 컴파일.
const source_str = objc.nsString(shader_source);
var err: objc.id = null;
const library = objc.msgSend3(
device,
objc.sel("newLibraryWithSource:options:error:"),
source_str,
@as(objc.id, null),
@as(*objc.id, &err),
);
if (library == null) {
if (err) |e| {
const desc = objc.msgSend(e, objc.sel("localizedDescription"));
if (desc) |d| {
const cstr_ptr = objc.msgSend(d, objc.sel("UTF8String"));
if (cstr_ptr) |p| {
const cstr: [*:0]const u8 = @ptrCast(p);
std.log.err("Metal shader error: {s}", .{cstr});
}
}
}
return error.ShaderCompileFailed;
}
const bg_vs_fn = objc.msgSend1(library, objc.sel("newFunctionWithName:"), objc.nsString("bg_vs"));
const bg_fs_fn = objc.msgSend1(library, objc.sel("newFunctionWithName:"), objc.nsString("bg_fs"));
const text_vs_fn = objc.msgSend1(library, objc.sel("newFunctionWithName:"), objc.nsString("text_vs"));
const text_fs_fn = objc.msgSend1(library, objc.sel("newFunctionWithName:"), objc.nsString("text_fs"));
const bg_pipeline = try createPipeline(device, bg_vs_fn, bg_fs_fn);
const text_pipeline = try createPipeline(device, text_vs_fn, text_fs_fn);
const bg_buf = createBuffer(device, MAX_INSTANCES * @sizeOf(BgInstance));
const text_buf = createBuffer(device, MAX_INSTANCES * @sizeOf(TextInstance));
// constants buffer = float4 (screen_w, screen_h, atlas_w, atlas_h).
const const_buf = createBuffer(device, 16);
const atlas_tex = createAtlasTexture(device);
const tab_atlas_tex = createAtlasTexture(device);
// CAMetalLayer 설정 (device 등록 + pixel format).
objc.msgSendVoid1(layer, objc.sel("setDevice:"), device);
objc.msgSendVoid1(layer, objc.sel("setPixelFormat:"), @as(objc.NSUInteger, 80)); // BGRA8Unorm
// #349 — layer 색공간을 sRGB 로 명시. 우리 색 상수는 sRGB 로 설계 · 튜닝됐고
// (#334 / #342 anchor, #335 파생식) window server 는 이 태그를 보고 디스플레이
// 색공간으로 변환한다.
//
// 명시하는 이유: 바로 위 `setPixelFormat:` 호출이 colorspace 를 자동으로
// `kCGColorSpaceSRGB` 로 채우는데 (실측) 이건 문서에 없는 동작이다. Apple 문서와
// `CAMetalLayer.h` 가 적어 둔 기본값은 `nil` = "no colormatching" 이라, 문서만
// 읽으면 우리가 색 변환을 안 한다고 정반대로 이해하게 된다. 자동 기본값에
// 색 정확성을 맡기지 않고 같은 값을 직접 넣는다 — 실측으로 자동값과 **같은
// 싱글턴 인스턴스**라 픽셀은 한 비트도 바뀌지 않는다.
//
// null 이면 지정하지 않는다: `colorspace = nil` 은 변환을 없애서 wide-gamut
// 디스플레이에서 실제로 색이 진해진다 (실측: amber `#F7A41D` 가 P3 원색으로).
if (ct.CGColorSpaceCreateWithName(ct.kCGColorSpaceSRGB)) |cs| {
defer ct.CGColorSpaceRelease(cs);
objc.msgSendVoid1(layer, objc.sel("setColorspace:"), cs);
} else {
std.log.warn("sRGB 색공간 생성 실패 — layer colorspace 를 그대로 둠", .{});
}
return .{
.alloc = alloc,
.font = font_ctx,
.atlas = glyph_atlas,
.tab_font = tab_font_ctx,
.tab_atlas = tab_glyph_atlas,
.device = device,
.layer = layer,
.command_queue = cmd_queue,
.bg_pipeline = bg_pipeline,
.text_pipeline = text_pipeline,
.bg_buffer = bg_buf,
.text_buffer = text_buf,
.atlas_texture = atlas_tex,
.tab_atlas_texture = tab_atlas_tex,
.constants_buffer = const_buf,
.fallback_bg = .{ colorF(bg[0]), colorF(bg[1]), colorF(bg[2]) },
.chrome = chrome_palette.derive(bg, themes.isDarkRgb(bg[0], bg[1], bg[2])),
.scale = scale,
.font_families = font_families,
.terminal_font = terminal_font,
};
}
/// #253 — backingScaleFactor 가 바뀐 모니터로 이동했을 때 호출. 새 scale 의
/// pixel 크기로 폰트 cell 을 재측정하고 glyph atlas 를 재구성한다(Windows
/// `rebuildFontForDpi` / Linux `applyScale` 동등). 안 하면 init scale 의 cell·
/// glyph·UI metric 을 그대로 써서 다른 scale 모니터에서 글자/탭바가 배율만큼
/// 틀어진다. scale 이 실제로 바뀐 경우에만 호출(같은 scale 이동은 viewport 만).
pub fn applyScale(self: *MetalRenderer, new_scale: f32) !void {
if (new_scale == self.scale) return;
// 1. 새 scale 로 폰트 cell 재측정. 성공 후에만 기존 font 교체(실패 시 unchanged).
var new_font = try CoreTextFontContext.init(
self.alloc,
self.font_families,
self.terminal_font,
new_scale,
);
errdefer new_font.deinit();
var new_tab_font = try CoreTextFontContext.init(
self.alloc,
self.font_families,
ui_metrics.tabLabelFontSpec(),
new_scale,
);
errdefer new_tab_font.deinit();
self.tab_font.deinit();
self.font.deinit();
self.font = new_font;
self.tab_font = new_tab_font;
// 2. atlas 를 새 scale 로 재구성 — cache/packing/pixels clear + scale 갱신.
// 다음 render 에서 글리프가 새 scale 로 재라스터되고 dirty 로 재업로드됨.
// (atlas_texture 자체는 ATLAS_SIZE 고정이라 재사용.)
self.atlas.scale = new_scale;
self.atlas.reset();
self.tab_atlas.scale = new_scale;
self.tab_atlas.reset();
// 3. renderer scale 갱신 — 탭바/스크롤바/패딩 등 UI metric 이 곱해 쓰는 값.
self.scale = new_scale;
}
pub fn deinit(self: *MetalRenderer) void {
self.tab_atlas.deinit();
self.tab_font.deinit();
self.atlas.deinit();
self.font.deinit();
// Metal 객체는 ARC / process exit 으로 정리.
}
pub fn resize(self: *MetalRenderer, width: u32, height: u32) void {
self.vp_width = width;
self.vp_height = height;
}
/// Frame begin — drawable + cmd_buf + encoder 생성, clear color 설정. 받은
/// tab args 는 self.pending_tabs 에 보관, 실제 encode 는 `renderTerminal` 끝에
/// (terminal 위에 그려지도록). Windows D3d11Renderer.renderTabBar 의 setupFrame
/// + clear 패턴과 같은 의도 — host 가 두 fn 사이의 frame lifecycle 을 신경
/// 쓰지 않게.
///
/// host 는 *항상* renderTabBar → renderTerminal 순서로 호출. tab_titles.len <
/// 2 면 단일 탭이라 탭바 자체는 안 그림 (#127) 단 frame begin 은 동일.
pub fn renderTabBar(
self: *MetalRenderer,
/// 멀티탭 (#111). 길이 ≥ 2 일 때만 탭바 그림. 길이 0 / 1 이면 single-tab
/// 으로 보고 cell grid 가 풀 화면 사용.
tab_titles: []const []const u8,
active_tab: usize,
/// #282 B8 — active terminal 의 현재 background (OSC 11 포함).
/// null 은 terminal 에 배경이 없을 때만 init theme fallback 사용.
terminal_background: ?ghostty.color.RGB,
/// drag 진행 중이면 그 탭을 마우스 위치 따라 이동시켜 그림. null = drag
/// 안 함 또는 5px 임계 미만. `current_x` (c_int) 는 *world* 좌표 (#117) —
/// 화면 위치는 `current_x - tab_scroll_x_px + tab_area_x`.
drag_view: ?tab_interaction.DragView,
/// 탭바 스크롤 오프셋 (픽셀, #117). 각 탭 / drag 탭의 화면 x = world -
/// 이 값 + tab_area_x.
tab_scroll_x_px: f32,
/// 탭바 layout — `<` `>` `×` `+` 버튼 위치, 탭 viewport 영역.
tab_bar_layout: TabBarLayout,
/// #268 2b — hover 중인 컨트롤 버튼 (.none = 없음). 강조 배경 박스.
tab_hover: tab_layout.Area,
) void {
const frame_bg = cell_color.resolveFrameBackground(terminal_background, self.fallback_bg);
const drawable = objc.msgSend(self.layer, objc.sel("nextDrawable"));
if (drawable == null) {
self.pending_tabs = null;
return;
}
self.current_drawable = drawable;
// 직전 frame 이 요청한 instance 수가 buffer 용량을 넘었으면 키운다. 누적-offset
// 방식이라 buffer 는 frame 전체 instance 를 동시에 담아야 하는데, 초과 시
// drawBgInstances 가 그 호출을 통째 drop 해 box-drawing 등 뒷 draw 가 사라졌다.
// frame 시작(아직 draw 없음)에서만 재할당 — 진행 중 swap 회피. 직전 frame 의
// command buffer 가 옛 buffer 를 retain 하므로 즉시 release 안전.
self.growInstanceBuffers();
// frame 내 buffer overwrite 방지 — 매 frame 시작 시 누적 offset 리셋.
self.bg_used = 0;
self.text_used = 0;
self.bg_needed = 0;
self.text_needed = 0;
const texture = objc.msgSend(drawable, objc.sel("texture"));
const cmd_buf = objc.msgSend(self.command_queue, objc.sel("commandBuffer"));
self.current_cmd_buf = cmd_buf;
const rpd_class = objc.getClass("MTLRenderPassDescriptor");
const rpd = objc.msgSend(rpd_class, objc.sel("renderPassDescriptor"));
const attachments = objc.msgSend(rpd, objc.sel("colorAttachments"));
const att0 = objc.msgSend1(attachments, objc.sel("objectAtIndexedSubscript:"), @as(objc.NSUInteger, 0));
objc.msgSendVoid1(att0, objc.sel("setTexture:"), texture);
objc.msgSendVoid1(att0, objc.sel("setLoadAction:"), @as(objc.NSUInteger, 2)); // Clear
objc.msgSendVoid1(att0, objc.sel("setStoreAction:"), @as(objc.NSUInteger, 1)); // Store
const ClearColor = extern struct { r: f64, g: f64, b: f64, a: f64 };
const clear = ClearColor{
.r = @floatCast(frame_bg[0]),
.g = @floatCast(frame_bg[1]),
.b = @floatCast(frame_bg[2]),
.a = 1.0,
};
const setClearColorFn: *const fn (objc.id, objc.SEL, ClearColor) callconv(.c) void = @ptrCast(objc.msgSend_raw);
setClearColorFn(att0, objc.sel("setClearColor:"), clear);
const encoder = objc.msgSend1(cmd_buf, objc.sel("renderCommandEncoderWithDescriptor:"), rpd);
if (encoder == null) {
self.current_drawable = null;
self.current_cmd_buf = null;
self.pending_tabs = null;
return;
}
self.current_encoder = encoder;
self.pending_tabs = .{
.titles = tab_titles,
.active = active_tab,
.drag_view = drag_view,
.scroll_x_px = tab_scroll_x_px,
.layout = tab_bar_layout,
.hover = tab_hover,
};
}
/// Frame end — terminal encode → pending tabs encode → endEncoding + present
/// + commit. `renderTabBar` 가 drawable 획득에 실패했으면 (`current_encoder`
/// 가 null) no-op (frame skip).
pub fn renderTerminal(
self: *MetalRenderer,
terminal: *ghostty.Terminal,
cell_w: i32,
cell_h: i32,
y_offset: i32,
scrollbar_y_offset: i32,
padding: i32,
preedit_utf8: []const u8,
menu_ui: command_menu.Ui,
toggle_hotkey: []const u8,
) void {
const encoder = self.current_encoder;
if (encoder == null) return;
// #160 — render(그리기, present 제외) 계측. Windows renderer/windows.zig 동등.
const render_t0 = perf.now();
self.updateConstants();
if (self.atlas.dirty) {
self.uploadAtlas(&self.atlas, self.atlas_texture);
self.atlas.dirty = false;
}
// 탭 glyph/icon atlas도 main atlas와 같은 2-frame 정책: 이전 frame에서
// 만든 내용을 draw 전에 upload한다. 삽입 직후 같은 Metal encoder에서
// sample하면 정적인 단일 탭 최초 frame의 icon이 투명하게 남았다.
self.uploadTabAtlasIfDirty();
self.renderTerminalContent(encoder, terminal, cell_w, cell_h, y_offset, scrollbar_y_offset, padding, preedit_utf8);
if (self.pending_tabs) |t| {
if (t.titles.len >= 2) {
self.drawTabBar(encoder, t.titles, t.active, t.drag_view, t.scroll_x_px, t.layout, t.hover);
} else if (t.titles.len == 1) {
self.drawSingleControlStrip(encoder, t.layout, t.hover);
}
}
if (menu_ui.open) self.drawCommandMenu(encoder, menu_ui, toggle_hotkey);
objc.msgSendVoid(encoder, objc.sel("endEncoding"));
perf.addTimed(&perf.render, render_t0);
// #255 Phase 2 — 표시 확정 전이면 presented handler 부착(present *전*에 등록).
// 표시 확정되면 더는 안 닮 — host 가 idle 시 frameWasPresented() 로 pause 판단.
if (!g_frame_presented.load(.seq_cst)) {
presented_block.isa = &_NSConcreteGlobalBlock;
const addHandler = objc.objcSend(fn (objc.id, objc.SEL, *PresentedBlock) callconv(.c) void);
addHandler(self.current_drawable, objc.sel("addPresentedHandler:"), &presented_block);
}
// #160 — present(drawable 표시 + commit) 계측.
const present_t0 = perf.now();
objc.msgSendVoid1(self.current_cmd_buf, objc.sel("presentDrawable:"), self.current_drawable);
objc.msgSendVoid(self.current_cmd_buf, objc.sel("commit"));
perf.addTimed(&perf.present, present_t0);
// Frame end — state reset.
self.current_encoder = null;
self.current_cmd_buf = null;
self.current_drawable = null;
self.pending_tabs = null;
}
fn renderTerminalContent(
self: *MetalRenderer,
encoder: objc.id,
terminal: *ghostty.Terminal,
cell_w: i32,
cell_h: i32,
y_offset: i32,
scrollbar_y_offset: i32,
padding: i32,
preedit_utf8: []const u8,
) void {
self.render_state.update(self.alloc, terminal) catch return;
const rows = self.render_state.rows;
const cols = self.render_state.cols;
const colors = self.render_state.colors;
const row_slice = self.render_state.row_data.slice();
const cw: f32 = @floatFromInt(cell_w);
const ch: f32 = @floatFromInt(cell_h);
// 위쪽 padding 보정: 폰트의 ascent 가 cap_height 보다 위쪽 internal
// leading 만큼 더 큰데 cell box top 부터 ascent 만큼 내려간 위치가
// baseline 이라, 대문자 visible top 은 cell top + (ascent − cap_height)
// 위치. 좌/우 padding 은 글자에 딱 붙는데 위쪽만 (ascent − cap_height)
// 만큼 추가 여백이 생겨 비대칭. 모든 row 의 fy 를 위로 그만큼 shift
// 해서 첫 행 글자 visible top 이 정확히 padding 위치에 오게.
const y_off: f32 = @as(f32, @floatFromInt(y_offset + padding)) - self.font.top_pad_px;
const x_pad: f32 = @floatFromInt(padding);
const all_cells = row_slice.items(.cells);
const all_sels = row_slice.items(.selection);
const dbg_r = colorF(colors.background.r);
const dbg_g = colorF(colors.background.g);
const dbg_b = colorF(colors.background.b);
const MAX_CELLS = 4096;
var bg_buf: [MAX_CELLS]BgInstance = undefined;
var bg_count: u32 = 0;
var text_buf: [MAX_CELLS]TextInstance = undefined;
var text_count: u32 = 0;
// #376 — blink 위상은 **프레임 단위** 값이다 (셀마다 다르지 않다). 한 번
// 구해서 모든 셀이 같은 값을 쓰게 해야 한 화면 안에서 위상이 갈리지 않는다.
const blink_faint = ui_metrics.blinkFaintPhase(std.time.milliTimestamp());
self.saw_blink_cell = false;
// --- Background pass ---
for (0..rows) |y| {
if (y >= all_cells.len) break;
const cell_slice = all_cells[y].slice();
const raws = cell_slice.items(.raw);
const styles = cell_slice.items(.style);
const sel_range: ?[2]u16 = if (y < all_sels.len) all_sels[y] else null;
for (0..cols) |x| {
if (x >= raws.len) break;
const raw = raws[x];
if (raw.wide == .spacer_tail) continue;
// #376 — bg pass 는 **모든 셀**을 돌므로 blink 셀 존재 판정을 여기서
// 한다 (text pass 는 글자 있는 셀만 본다). 위상이 off 면 `faint` 를
// 세워 fg 해석과 선 색이 한 번에 흐려지게 한다.
const raw_style = if (raw.style_id != 0) styles[x] else ghostty.Style{};
if (raw_style.flags.blink) self.saw_blink_cell = true;
const style = cell_color.applyBlinkPhase(raw_style, blink_faint);
const is_inverse = style.flags.inverse;
const x16: u16 = @intCast(x);
const is_selected = if (sel_range) |sr| (x16 >= sr[0] and x16 <= sr[1]) else false;
const is_custom_bg = is_selected or is_inverse or (style.bg(&raw, &colors.palette) != null);
// #365 — SGR 선 속성 (밑줄 · 취소선 · 윗줄) 도 이 pass 에서 만든다.
// **text pass 가 아니라 bg pass 인 것이 핵심** — 선이 글리프보다 먼저
// 그려져야 색 밑줄이 글자를 가로지르지 않는다 (ghostty 와 같은 선택,
// [`cell_decoration`](cell_decoration.zig) 주석). text pass 의
// `bg_buf` 에 넣으면 글리프 *위*로 올라가 정반대가 된다.
const has_deco = cell_decoration.hasDecoration(style);
if (!is_custom_bg and !has_deco) continue;
const width: f32 = if (raw.wide == .wide) 2.0 * cw else cw;
const fx: f32 = @as(f32, @floatFromInt(x)) * cw + x_pad;
const fy: f32 = @as(f32, @floatFromInt(y)) * ch + y_off;
if (is_custom_bg) {
if (bg_count >= MAX_CELLS) {
self.drawBgInstances(encoder, bg_buf[0..bg_count]);
bg_count = 0;
}
const cell_bg = resolveBg(style, &raw, &colors, is_selected, is_inverse, dbg_r, dbg_g, dbg_b);
bg_buf[bg_count] = .{
.pos = .{ fx, fy },
.size = .{ width, ch },
.color = .{ cell_bg[0], cell_bg[1], cell_bg[2], 1 },
};
bg_count += 1;
}
if (has_deco) {
var deco: [cell_decoration.MAX_RECTS]cell_decoration.Rect = undefined;
const dn = cell_decoration.rects(
style,
resolveFg(style, &raw, &colors, is_selected, is_inverse),
&colors.palette,
self.font.ascent_px,
width,
ch,
if (raw.wide == .wide) 2 else 1,
&deco,
);
// 셀 하나가 최대 4 개를 만들므로 남은 자리를 미리 확인한다 —
// box drawing 이 같은 이유로 `bg_count + bn` 을 검사한다.
if (bg_count + dn > MAX_CELLS) {
self.drawBgInstances(encoder, bg_buf[0..bg_count]);
bg_count = 0;
}
// #374 — 물결은 곡선이라 가장자리 픽셀의 `cov` 가 1 미만이다.
// box drawing 과 같은 처리 — 공통 `blendOverRgb` 로 셀 배경과
// **미리** 합성해 알파 1.0 solid 로 그린다 (#353). `cov == 1` 인
// 나머지 선은 합성 결과가 원래 색 그대로다.
const deco_bg = cell_color.resolveBg(style, &raw, &colors, is_selected, is_inverse) orelse colors.background;
for (deco[0..dn]) |d| {
const blended = ui_metrics.blendOverRgb(
.{ d.color.r, d.color.g, d.color.b },
.{ deco_bg.r, deco_bg.g, deco_bg.b },
d.cov,
);
bg_buf[bg_count] = .{
.pos = .{ fx + d.x, fy + d.y },
.size = .{ d.w, d.h },
.color = .{ colorF(blended[0]), colorF(blended[1]), colorF(blended[2]), 1 },
};
bg_count += 1;
}
}
}
}
if (bg_count > 0) self.drawBgInstances(encoder, bg_buf[0..bg_count]);
// bg pass 끝났으니 block element pass 가 같은 buffer 재사용 (Windows 동등).
bg_count = 0;
// --- Text pass (block element 도 여기서 처리) ---
for (0..rows) |y| {
if (y >= all_cells.len) break;
const cell_slice = all_cells[y].slice();
const raws = cell_slice.items(.raw);
const styles = cell_slice.items(.style);
const graphemes = cell_slice.items(.grapheme);
const sel_range: ?[2]u16 = if (y < all_sels.len) all_sels[y] else null;
const fy: f32 = @as(f32, @floatFromInt(y)) * ch + y_off;
var x: usize = 0;
while (x < cols) {
if (x >= raws.len) break;
const raw = raws[x];
const is_text = raw.hasText() and raw.wide != .spacer_tail and raw.wide != .spacer_head and raw.codepoint() != 0;
if (!is_text) {
x += 1;
continue;
}
// #365 — `invisible` (SGR 8) 은 전경 요소를 하나도 내보내지 않는다.
// 글리프뿐 아니라 block element · box drawing 도 전경이라 여기서 함께
// 막는다. 선은 bg pass 가 이미 걸렀다 (`hasDecoration` 이 false).
// xterm · ghostty 와 같은 정책 — "아무것도 안 보임" 이 SGR 8 의 의미다.
if (raw.style_id != 0 and styles[x].flags.invisible) {
x += 1;
continue;
}
const cp = raw.codepoint();
// Block element / shade — font glyph 대신 cell-aligned procedural
// rectangle (#155). Windows d3d11 와 동일 path. 폰트 의존 제거 +
// 인접 셀 사이 갭 없음.
if (block_element.isBlockElement(cp)) {
if (bg_count >= MAX_CELLS) {
self.drawBgInstances(encoder, bg_buf[0..bg_count]);
bg_count = 0;
}
const style_b = cell_color.applyBlinkPhase(if (raw.style_id != 0) styles[x] else ghostty.Style{}, blink_faint);
const is_inverse_b = style_b.flags.inverse;
const x16_b: u16 = @intCast(x);
const is_selected_b = if (sel_range) |sr| (x16_b >= sr[0] and x16_b <= sr[1]) else false;
const fg_rgb = resolveFg(style_b, &raw, &colors, is_selected_b, is_inverse_b);
const rect = block_element.blockElementRect(cp) orelse {
x += 1;
continue;
};
const block_w: f32 = if (raw.wide == .wide) 2.0 * cw else cw;
const block_x: f32 = @as(f32, @floatFromInt(x)) * cw + x_pad;
// #353 — 음영 ░▒▓ (alpha 0.25/0.5/0.75) 을 공통
// `ui_metrics.blendOverRgb` 로 **여기서 한 번** 합성하고 알파 1.0
// 으로 그린다. 이전에는 알파를 blend unit 에 맡겨 세 platform 이
// 서로 다른 정밀도로 8bit 를 만들었다 (최대 차 2).
//
// 합성 대상은 bg pass 가 이 셀에 칠한 색과 같아야 한다 — 같은
// `cell_color.resolveBg` 를 쓰고 null 이면 `colors.background`
// (bg pass 의 `dbg_*` 와 동일) 로 떨어진다. 솔리드 블록
// (alpha 1.0) 은 합성 결과가 `fg_rgb` 그대로다.
const block_bg = cell_color.resolveBg(style_b, &raw, &colors, is_selected_b, is_inverse_b) orelse colors.background;
const blended = ui_metrics.blendOverRgb(
.{ fg_rgb.r, fg_rgb.g, fg_rgb.b },
.{ block_bg.r, block_bg.g, block_bg.b },
rect.alpha,
);
bg_buf[bg_count] = .{
.pos = .{ block_x + rect.x0 * block_w, fy + rect.y0 * ch },
.size = .{ (rect.x1 - rect.x0) * block_w, (rect.y1 - rect.y0) * ch },
.color = .{ colorF(blended[0]), colorF(blended[1]), colorF(blended[2]), 1 },
.shade = rect.shade,
};
bg_count += 1;
x += 1;
continue;
}
// Box-drawing (선/모서리/junction, U+2500–257F) — block element 과
// 같은 이유로 procedural 사각형 (#258). 대각선은 null → 글리프 path.
if (cp >= 0x2500 and cp <= 0x257F) {
const box_w: f32 = if (raw.wide == .wide) 2.0 * cw else cw;
var box_rects: [box_drawing.MAX_RECTS]box_drawing.Rect = undefined;
if (box_drawing.boxRects(cp, box_w, ch, &box_rects)) |bn| {
if (bg_count + bn > MAX_CELLS) {
self.drawBgInstances(encoder, bg_buf[0..bg_count]);
bg_count = 0;
}
const style_x = cell_color.applyBlinkPhase(if (raw.style_id != 0) styles[x] else ghostty.Style{}, blink_faint);
const is_inverse_x = style_x.flags.inverse;
const x16_x: u16 = @intCast(x);
const is_selected_x = if (sel_range) |sr| (x16_x >= sr[0] and x16_x <= sr[1]) else false;
const fg_rgb_x = resolveFg(style_x, &raw, &colors, is_selected_x, is_inverse_x);
const box_x: f32 = @as(f32, @floatFromInt(x)) * cw + x_pad;
// #353 — `br.cov` (AA coverage) 를 공통 `ui_metrics.blendOverRgb`
// 로 미리 합성하고 알파 1.0 으로 그린다. **emitter 가 픽셀당
// rect 를 하나만 내보내므로** (대각선은 두 선을 `@max` 로, 호는
// arm·arc 거리를 `@min` 으로 합친 *뒤* emit) 한 픽셀에 blend 가
// 한 번뿐이고, 배경과 미리 합성한 결과가 순차 blend 와 같다.
const box_bg = cell_color.resolveBg(style_x, &raw, &colors, is_selected_x, is_inverse_x) orelse colors.background;
for (box_rects[0..bn]) |br| {
const cov_blend = ui_metrics.blendOverRgb(
.{ fg_rgb_x.r, fg_rgb_x.g, fg_rgb_x.b },
.{ box_bg.r, box_bg.g, box_bg.b },
br.cov,
);
bg_buf[bg_count] = .{
.pos = .{ box_x + br.x, fy + br.y },
.size = .{ br.w, br.h },
.color = .{ colorF(cov_blend[0]), colorF(cov_blend[1]), colorF(cov_blend[2]), 1 },
.shade = 0,
};
bg_count += 1;
}
x += 1;
continue;
}
}
const style = cell_color.applyBlinkPhase(if (raw.style_id != 0) styles[x] else ghostty.Style{}, blink_faint);
const is_inverse = style.flags.inverse;
const x16: u16 = @intCast(x);
const is_selected = if (sel_range) |sr| (x16 >= sr[0] and x16 <= sr[1]) else false;
const fg_rgb = resolveFg(style, &raw, &colors, is_selected, is_inverse);
// grapheme cluster (VS-16 / skin tone modifier / ZWJ 시퀀스) — cell 의
// base + extras 를 CTLine 으로 shape, 단일 representative glyph 으로
// reduce. 일반 cell 은 빠른 single-codepoint path 또는 ligature
// lookahead 분기.
if (raw.hasGrapheme() and x < graphemes.len) {
if (text_count >= MAX_CELLS) {
self.drawTextInstances(encoder, text_buf[0..text_count]);
text_count = 0;
}
var cluster: [16]u21 = undefined;
cluster[0] = cp;
const extras = graphemes[x];
const take = @min(extras.len, cluster.len - 1);
@memcpy(cluster[1..][0..take], extras[0..take]);
const r_opt = self.font.resolveGrapheme(cluster[0 .. 1 + take]);
if (r_opt) |result| {
const entry_opt = self.atlas.getOrInsert(result.font, @intCast(result.index));
if (result.owned) ct.CFRelease(result.font);
if (entry_opt) |entry| {
if (entry.w > 0 and entry.h > 0) {
emitTextInstance(text_buf[0..], &text_count, entry, x, fy, cw, x_pad, self.font.ascent_px, fg_rgb, glyphCenterDx(entry, raw.wide == .wide, cw), 0);
}
}
x += 1;
continue;
}
}
// SPEC § 12.2 — N-char ligature lookahead. 3-char → 2-char 순서.
// 모든 cell narrow + single codepoint + same style_id + ASCII
// candidate. 매치 시 `.single` 은 N-cell 너비 1 glyph, `.spacer`
// 는 각 cell 별 1 glyph.
if (x + 2 < cols and x + 2 < raws.len and raw.wide == .narrow and isLigatureCandidate(cp)) {
const next = raws[x + 1];
const next2 = raws[x + 2];
if (next.wide == .narrow and next.hasText() and next.codepoint() != 0 and
next.style_id == raw.style_id and isLigatureCandidate(next.codepoint()) and
next2.wide == .narrow and next2.hasText() and next2.codepoint() != 0 and
next2.style_id == raw.style_id and isLigatureCandidate(next2.codepoint()))
{
if (self.font.ligatureTriple(cp, next.codepoint(), next2.codepoint())) |lm| {
emitLigatureMatch(self, encoder, text_buf[0..], &text_count, x, 3, lm, fy, cw, x_pad, fg_rgb);
x += 3;
continue;
}
}
}
if (x + 1 < cols and x + 1 < raws.len and raw.wide == .narrow and isLigatureCandidate(cp)) {
const next = raws[x + 1];
if (next.wide == .narrow and next.hasText() and next.codepoint() != 0 and
next.style_id == raw.style_id and isLigatureCandidate(next.codepoint()))
{
if (self.font.ligaturePair(cp, next.codepoint())) |lm| {
emitLigatureMatch(self, encoder, text_buf[0..], &text_count, x, 2, lm, fy, cw, x_pad, fg_rgb);
x += 2;
continue;
}
}
}
if (text_count >= MAX_CELLS) {
self.drawTextInstances(encoder, text_buf[0..text_count]);
text_count = 0;
}
const result = self.font.resolveGlyph(
cp,
// #375 — SGR 1 / 3 이 요구하는 face 변종. 없는 family 는 폰트
// 모듈이 regular 로 떨어뜨린다.
font_constants.FaceStyle.from(style.flags.bold, style.flags.italic),
) orelse {
x += 1;
continue;
};
const entry = self.atlas.getOrInsert(result.font, @intCast(result.index)) orelse {
if (result.owned) ct.CFRelease(result.font);
x += 1;
continue;
};
if (result.owned) ct.CFRelease(result.font);
if (entry.w == 0 or entry.h == 0) {
x += 1;
continue;
}