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
|
//! The Lab's bottom strip, in-window chooser and guide, and review card.
//! Nothing here knows what a pass does: the controls invoke the controller's selectors.
const std = @import("std");
const objc = @import("objc.zig");
const msg = objc.msg;
const id = objc.id;
const SEL = objc.SEL;
const NSRect = objc.NSRect;
const NSPoint = objc.NSPoint;
const NSSize = objc.NSSize;
extern const NSViewFrameDidChangeNotification: id;
extern const NSWindowDidResignKeyNotification: id;
extern const NSFontAttributeName: id;
extern const NSForegroundColorAttributeName: id;
/// The trim level on show, as its `labPass:` tag (6…9), or null when nothing is proposed.
pub var pending: ?u8 = null;
const strip_h = 40; // the bar the word count lives in (main's status_h)
const gap = 6; // review-card buttons
const card_h = 80;
const card_max_w = 500;
const card_bottom = strip_h + 12;
var content: id = null;
var ctl: id = null;
var small: id = null;
var ink: id = null;
var me: id = null; // the target of the Lab's own actions
var accent: id = null;
var bright: id = null;
var bar: [4]id = .{null} ** 4; // Save, Open, Overflow, Lab
var tracking: [4]id = .{null} ** 4;
var hovering: id = null;
var saved_dirty = false;
var overflow_open = false;
var card: id = null;
var note_field: id = null;
var hint_field: id = null;
var card_btn: [4]Btn = undefined; // Discard, Next, Keep, Apply
var tools = true;
var review = false;
var has_note = false;
const Btn = struct { v: id, w: f64 = 0, h: f64 = 0 };
// Drop the Next button first on a narrow review card.
const card_drop = [_]u8{ 1, 0, 3, 2 };
const passes = [_]struct { title: []const u8, tag: isize }{
.{ .title = "Fix punctuation and typos", .tag = 0 },
.{ .title = "Mark the weakest sentences", .tag = 1 },
.{ .title = "Mark sentences that run long", .tag = 2 },
.{ .title = "Mark convoluted sentences", .tag = 3 },
.{ .title = "Mark words that don’t fit the tone", .tag = 4 },
.{ .title = "Mark hedges and filler", .tag = 5 },
};
const trims = [_][]const u8{ "Original", "Slight trim", "Tighten more", "Even sharper", "Cut in half" };
const percents = [_][]const u8{ "", "~10%", "~20%", "~30%", "~50%" };
const privacy = "Your draft is sent only when you pick a pass.";
const guide =
\\Each idea asks the AI about your draft and only marks or fades words. It never rewrites.
\\
\\Fix punctuation and typos — marks slips and shows the fix.
\\Mark the weakest sentences — the ones the piece needs least.
\\Mark sentences that run long — where a reader runs out of breath.
\\Mark convoluted sentences — hard to follow on a first read.
\\Mark words that don’t fit the tone — wording that jars with the rest.
\\Mark hedges and filler — “just”, “sort of”, “in order to”.
\\
\\Trims ghost proposed cuts: slight (~10%), tighter (~20%), sharper (~30%), half (~50%). Saving leaves the ghosts out of rendered Markdown. Keep revives a passage; Original revives all remaining proposals. Apply rest deletes them from the draft.
\\
\\Your draft is sent to the model only when you choose a pass.
;
// --- Layout ---------------------------------------------------------------------------------
/// Which of `widths` fit in `avail` (with `gap` between), dropping in `drop` order. Returns
/// the width the shown ones take.
fn plan(widths: []const f64, drop: []const u8, avail: f64, shown: []bool) f64 {
var total: f64 = 0;
var n: usize = 0;
for (widths, shown) |w, *s| {
s.* = true;
total += w;
n += 1;
}
total += gap * @as(f64, @floatFromInt(n -| 1));
for (drop) |i| {
if (total <= avail) break;
shown[i] = false;
total -= widths[i] + (if (n > 1) @as(f64, gap) else 0);
n -= 1;
}
return if (total <= avail and n > 0) total else 0;
}
/// Lay a row of buttons against `right`, vertically centred in `height`; returns its left edge.
fn row(btns: []Btn, drop: []const u8, visible: bool, right: f64, avail: f64, height: f64) f64 {
var widths: [4]f64 = undefined;
var shown: [4]bool = undefined;
for (btns, 0..) |b, i| widths[i] = b.w;
const total = if (visible) plan(widths[0..btns.len], drop, avail, shown[0..btns.len]) else 0;
var x = right;
var i = btns.len;
while (i > 0) {
i -= 1;
const b = btns[i];
const on = visible and total > 0 and shown[i];
msg(void, b.v, "setHidden:", .{!on});
if (!on) continue;
x -= b.w;
msg(void, b.v, "setFrameOrigin:", .{NSPoint{ .x = x, .y = @round((height - b.h) / 2) }});
x -= gap;
}
return if (total > 0) x + gap else right;
}
fn relayout() void {
if (content == null) return;
const w = msg(NSRect, content, "bounds", .{}).size.width;
// Centers measured from the clip. Ink is small; each control has a larger hit area.
const centers = [_]f64{ 31, 65.5, w - 35, w / 2 };
for (bar, centers, 0..) |b, x, i| {
const width: f64 = if (i == 3) 56 else 34;
msg(void, b, "setFrame:", .{NSRect{ .origin = .{ .x = @round(x - width / 2), .y = 15 }, .size = .{ .width = width, .height = 34 } }});
msg(void, b, "setHidden:", .{!tools});
}
const cw = @min(card_max_w, w - 24);
const show = tools and has_note and cw >= 160;
msg(void, card, "setHidden:", .{!show});
if (!show) return;
msg(void, card, "setFrame:", .{NSRect{ .origin = .{ .x = @round((w - cw) / 2), .y = card_bottom }, .size = .{ .width = cw, .height = card_h } }});
msg(void, note_field, "setFrame:", .{NSRect{ .origin = .{ .x = 14, .y = 54 }, .size = .{ .width = cw - 28, .height = 16 } }});
msg(void, hint_field, "setFrame:", .{NSRect{ .origin = .{ .x = 14, .y = 37 }, .size = .{ .width = cw - 28, .height = 14 } }});
if (review) {
_ = row(&card_btn, &card_drop, true, cw - 12, cw - 24, 36);
} else {
for (card_btn[1..]) |b| msg(void, b.v, "setHidden:", .{true});
_ = row(card_btn[0..1], &.{0}, true, cw - 12, cw - 24, 36);
}
}
/// State tint never changes the frame or the click target.
pub fn state(dirty: bool, overflow: bool) void {
saved_dirty = dirty;
overflow_open = overflow;
tint();
}
fn tint() void {
for (bar, tracking, 0..) |b, area, i| {
if (b == null) continue;
const active = (i == 0 and saved_dirty) or (i == 2 and overflow_open) or (i == 3 and (has_note or (chooser_open and writing_at == null)));
msg(void, b, "setContentTintColor:", .{if (hovering != null and hovering == area) bright else if (active) accent else ink});
}
}
fn entered(_: id, _: SEL, event: id) callconv(.c) void {
hovering = msg(id, event, "trackingArea", .{});
tint();
}
fn exited(_: id, _: SEL, event: id) callconv(.c) void {
if (hovering == msg(id, event, "trackingArea", .{})) hovering = null;
tint();
}
// --- State ----------------------------------------------------------------------------------
/// `tools` is main's tool mode (off hides every control but the count). While `review` is on
/// the card shows `note`; `can_apply` says whether anything is left for Apply to do.
pub fn update(tools_on: bool, note: []const u8, review_on: bool, can_apply: bool) void {
if (content == null) return;
tools = tools_on;
review = review_on;
if (!tools) {
closePanel();
hovering = null;
}
has_note = note.len != 0;
tint();
tintPanel();
msg(void, note_field, "setToolTip:", .{objc.str(note)});
msg(void, hint_field, "setStringValue:", .{objc.str(if (!review) "" else if (can_apply) "Keep skips this change · Apply rest edits the draft" else "Next visits a mark · Keep clears it")});
msg(void, note_field, "setStringValue:", .{objc.str(note)});
msg(void, card_btn[3].v, "setEnabled:", .{can_apply});
relayout();
}
// --- The Lab chooser ------------------------------------------------------------------------
const panel_w = 620;
const panel_margin = 10;
const panel_bottom = 50; // just above the trigger, so LAB can also close it
const row_h = 32.5;
const trim_h = 44;
const trim_gap = 4;
const first_trim = 1 + passes.len;
const done_index = first_trim + trims.len;
var chooser_open = false;
var guide_open = false;
var shield: id = null;
var panel: id = null;
var panel_scroll: id = null;
var paper: id = null;
var panel_btn: [done_index + 1]id = .{null} ** (done_index + 1);
var rules: [2]id = .{ null, null };
var privacy_note: id = null;
var guide_text: id = null;
var panel_font: id = null;
var compact_font: id = null;
var surface: id = null;
var edge: id = null;
var highlight: id = null;
var draft_view: id = null;
var return_focus: id = null;
var click_focus: id = null;
var hover_row: id = null;
var trim_cols: usize = trims.len;
const writing_actions = [_][*:0]const u8{ "alternative:", "aiAlternative:", "ghost:", "stash:" };
const writing_keys = [_][]const u8{ "a", "g", "/", "x" };
const writing_shortcuts = [_][]const u8{ "Ctrl+Shift+A", "Ctrl+Shift+G", "Ctrl+/", "Ctrl+Shift+X" };
var writing_btn: [4]id = .{null} ** 4;
var writing_at: ?NSPoint = null;
fn rect(x: f64, y: f64, w: f64, h: f64) NSRect {
return .{ .origin = .{ .x = x, .y = y }, .size = .{ .width = w, .height = h } };
}
fn number(i: usize) f64 {
return @floatFromInt(i);
}
fn panelWindow() id {
return msg(id, content, "window", .{});
}
fn triggerMouseDown(self: id, _: SEL, event: id) callconv(.c) void {
click_focus = msg(id, panelWindow(), "firstResponder", .{});
defer click_focus = null;
objc.msgSuper(void, self, "NSButton", "mouseDown:", .{event});
}
pub fn togglePanel() void {
if (chooser_open) {
if (writing_at == null) return closePanel();
closePanel();
}
if (content == null or !tools) return;
guide_open = false;
openPanel(click_focus);
tint();
}
pub fn canOpenWritingMenu() bool {
return content != null and tools and !chooser_open;
}
pub fn openWritingMenu(point: NSPoint, titles: [4][]const u8) void {
writing_at = msg(NSPoint, content, "convertPoint:fromView:", .{ point, @as(id, null) });
for (writing_btn, titles) |b, title| msg(void, b, "setTitle:", .{objc.str(title)});
openPanel(null);
}
fn openPanel(prior: id) void {
const win = panelWindow();
return_focus = prior orelse msg(id, win, "firstResponder", .{});
if (return_focus == bar[3] or return_focus == win) return_focus = draft_view;
chooser_open = true;
msg(void, panel_scroll, "setHidden:", .{writing_at != null});
for (writing_btn) |b| msg(void, b, "setHidden:", .{writing_at == null});
msg(void, msg(id, panel, "layer", .{}), "setCornerRadius:", .{@as(f64, if (writing_at != null) 12 else 8)});
msg(void, shield, "setHidden:", .{false});
layoutPanel();
focusRow(0);
}
fn closePanel() void {
if (!chooser_open) return;
const win = panelWindow();
const first = msg(id, win, "firstResponder", .{});
const owns_focus = msg(bool, first, "isKindOfClass:", .{objc.class("NSView")}) and msg(bool, first, "isDescendantOf:", .{shield});
const was_writing = writing_at != null;
chooser_open = false;
writing_at = null;
hover_row = null;
msg(void, shield, "setHidden:", .{true});
if (owns_focus) {
const sel = if (was_writing) msg(objc.NSRange, draft_view, "selectedRange", .{}) else objc.NSRange{};
const available = msg(id, return_focus, "window", .{}) == win and !msg(bool, return_focus, "isHiddenOrHasHiddenAncestor", .{});
if (!available or !msg(bool, win, "makeFirstResponder:", .{return_focus})) {
_ = msg(bool, win, "makeFirstResponder:", .{draft_view});
}
if (was_writing and !std.meta.eql(sel, msg(objc.NSRange, draft_view, "selectedRange", .{})))
msg(void, draft_view, "setSelectedRange:", .{sel});
}
return_focus = null;
tint();
}
fn dismiss(_: id, _: SEL, _: id) callconv(.c) void {
closePanel();
}
fn panelIndex(b: id) usize {
return std.mem.indexOfScalar(id, &panel_btn, b).?;
}
fn choose(_: id, _: SEL, sender: id) callconv(.c) void {
if (!chooser_open) return;
if (writing_at != null) {
const i = std.mem.indexOfScalar(id, &writing_btn, sender) orelse return;
closePanel();
return msg(void, ctl, writing_actions[i], .{sender});
}
const i = panelIndex(sender);
if (i == 0) {
guide_open = true;
hover_row = null;
layoutPanel();
focusRow(done_index);
return;
}
closePanel();
if (i == done_index) return;
if (i == first_trim) return msg(void, ctl, "labOriginal:", .{sender});
msg(void, ctl, "labPass:", .{sender});
}
fn focusRow(i: usize) void {
const b = if (writing_at != null) writing_btn[i] else panel_btn[i];
_ = msg(bool, panelWindow(), "makeFirstResponder:", .{b});
_ = msg(bool, b, "scrollRectToVisible:", .{msg(NSRect, b, "bounds", .{})});
tintPanel();
}
fn acceptsFocus(_: id, _: SEL) callconv(.c) bool {
return true;
}
fn panelKeys(self: id, _: SEL, event: id) callconv(.c) void {
const mods = msg(usize, event, "modifierFlags", .{});
const code = msg(u16, event, "keyCode", .{});
if (mods & (0x40000 | 0x80000 | 0x100000) == 0) { // Control, Option, Command
hover_row = null;
switch (code) {
53 => return closePanel(), // Escape
36, 49, 76 => return msg(void, self, "performClick:", .{self}), // Return, Space, keypad Enter
else => {},
}
if (writing_at != null) {
const i = std.mem.indexOfScalar(id, &writing_btn, self).?;
const n = writing_btn.len;
switch (code) {
123, 126 => return focusRow((i + n - 1) % n),
124, 125 => return focusRow((i + 1) % n),
48 => return focusRow((i + if (mods & 0x20000 != 0) n - 1 else @as(usize, 1)) % n),
else => {},
}
} else switch (code) {
48, 123...126 => {
if (guide_open) return focusRow(done_index);
const i = panelIndex(self);
const next = switch (code) {
48 => if (mods & 0x20000 != 0) (i + done_index - 1) % done_index else (i + 1) % done_index, // Tab
123 => if (i == 0) done_index - 1 else i - 1,
124 => (i + 1) % done_index,
125 => if (i < first_trim) i + 1 else if (i + trim_cols < done_index) i + trim_cols else 0,
126 => if (i == 0) done_index - 1 else if (i < first_trim) i - 1 else if (i >= first_trim + trim_cols) i - trim_cols else first_trim - 1,
else => unreachable,
};
return focusRow(next);
},
else => {},
}
}
objc.msgSuper(void, self, "NSButton", "keyDown:", .{event});
}
fn cg(color: id) id {
return msg(id, color, "CGColor", .{});
}
fn activeTrim(i: usize) bool {
if (i < first_trim or i >= done_index) return false;
return if (pending) |p| i == @as(usize, p) + 2 else i == first_trim;
}
fn tintPanel() void {
if (!chooser_open) return;
if (writing_at != null) {
for (writing_btn) |b| msg(void, b, "setNeedsDisplay:", .{true});
return;
}
for (panel_btn, 0..) |b, i| {
msg(void, b, "setNeedsDisplay:", .{true});
if (i >= first_trim and i < done_index) msg(void, b, "setAccessibilityValue:", .{objc.str(if (activeTrim(i)) "Selected" else "Not selected")});
}
}
fn panelEnter(self: id, _: SEL, _: id) callconv(.c) void {
if (writing_at != null) return focusRow(std.mem.indexOfScalar(id, &writing_btn, self) orelse return);
hover_row = self;
tintPanel();
}
fn panelExit(self: id, _: SEL, _: id) callconv(.c) void {
if (hover_row != self) return;
hover_row = null;
tintPanel();
}
const Align = enum { left, center, right };
fn drawString(title: id, font: id, color: id, box: NSRect, alignment: Align) void {
const attrs = msg(id, objc.class("NSDictionary"), "dictionaryWithObjects:forKeys:count:", .{
&[_]id{ font, color }, &[_]id{ NSFontAttributeName, NSForegroundColorAttributeName }, @as(usize, 2),
});
const size = msg(NSSize, title, "sizeWithAttributes:", .{attrs});
const w = @min(size.width, box.size.width);
var frame = box;
frame.size.width = w + 0.5; // leave room for the final glyph's fractional advance
frame.origin.x += switch (alignment) {
.left => 0,
.center => (box.size.width - w) / 2,
.right => box.size.width - w,
};
msg(void, title, "drawInRect:withAttributes:", .{ frame, attrs });
}
fn drawPanelButton(self: id, _: SEL, _: NSRect) callconv(.c) void {
const writing = std.mem.indexOfScalar(id, &writing_btn, self);
const i = writing orelse panelIndex(self);
const trim = writing == null and i >= first_trim and i < done_index;
const active = trim and activeTrim(i);
const focused = msg(id, panelWindow(), "firstResponder", .{}) == self;
const hot = self == hover_row or msg(bool, self, "isHighlighted", .{});
const bounds = msg(NSRect, self, "bounds", .{});
const w = bounds.size.width;
const h = bounds.size.height;
if (w <= 1 or h <= 1) return;
const radius: f64 = if (writing != null) 8 else 5;
const path = msg(id, objc.class("NSBezierPath"), "bezierPathWithRoundedRect:xRadius:yRadius:", .{ rect(0.5, 0.5, w - 1, h - 1), radius, radius });
if (hot or focused) {
msg(void, highlight, "setFill", .{});
msg(void, path, "fill", .{});
}
if (trim or (focused and hover_row != null and !hot)) {
msg(void, if (active or focused) accent else edge, "setStroke", .{});
msg(void, path, "stroke", .{});
}
const title = msg(id, self, "title", .{});
if (writing) |j| {
const y = (h - 20) / 2;
drawString(title, compact_font, bright, rect(10, y, @max(1, w - 130), 20), .left);
drawString(objc.str(writing_shortcuts[j]), compact_font, ink, rect(@max(10, w - 119), y, @min(109, @max(1, w - 20)), 20), .right);
} else if (trim) {
const percent = percents[i - first_trim];
// NSButton drawing coordinates are flipped: smaller y comes first.
drawString(title, panel_font, if (active) accent else bright, rect(3, 6, w - 6, 21), .center);
if (percent.len != 0) drawString(objc.str(percent), small, ink, rect(3, 26, w - 6, 15), .center);
} else if (i == done_index) {
drawString(objc.str("The Lab"), panel_font, bright, rect(10, (h - 20) / 2, w - 20, 20), .left);
drawString(title, panel_font, accent, rect(10, (h - 20) / 2, w - 20, 20), .right);
} else {
const compact = w < 305;
const text_h: f64 = if (w < 288) h else 20;
drawString(title, if (compact) compact_font else panel_font, bright, rect(10, (h - text_h) / 2, w - 20, text_h), .left);
if (i == 0 and w >= 340) drawString(objc.str("what each idea does"), small, ink, rect(10, (h - 15) / 2, w - 20, 15), .right);
}
}
fn fitLabel(f: id, w: f64) f64 {
msg(void, f, "setPreferredMaxLayoutWidth:", .{w});
return @ceil(msg(NSSize, msg(id, f, "cell", .{}), "cellSizeForBounds:", .{rect(0, 0, w, 10000)}).height) + 2;
}
fn layoutPanel() void {
const bounds = msg(NSRect, content, "bounds", .{});
if (writing_at) |p| {
const w = @min(376, bounds.size.width);
const h = @min(136, bounds.size.height);
const rh = @max(1, (h - 12) / 4);
msg(void, shield, "setFrame:", .{bounds});
msg(void, panel, "setFrame:", .{rect(std.math.clamp(p.x, 0, bounds.size.width - w), std.math.clamp(p.y - h, 0, bounds.size.height - h), w, h)});
for (writing_btn, 0..) |b, i| msg(void, b, "setFrame:", .{rect(5, h - 6 - rh * number(i + 1), @max(1, w - 10), rh)});
return tintPanel();
}
const w = @max(1, @min(panel_w, bounds.size.width - 2 * panel_margin));
const trim_w = @max(1, w - 26);
// Keep all trim settings reachable rather than dropping buttons on small windows.
trim_cols = if (trim_w >= 546) 5 else if (trim_w >= 326) 3 else if (trim_w >= 216) 2 else 1;
const trim_rows = (trims.len + trim_cols - 1) / trim_cols;
const note_h = fitLabel(privacy_note, @max(1, w - 32));
const guide_h = fitLabel(guide_text, @max(1, w - 32));
const menu_h = 10 + row_h + 13 + number(passes.len) * row_h + 14 + number(trim_rows) * (trim_h + trim_gap) + note_h + 12;
const doc_h = if (guide_open) 10 + row_h + 12 + guide_h + 12 else menu_h;
const bottom = @min(panel_bottom, @max(panel_margin, bounds.size.height - 100));
const h = @max(1, @min(doc_h, bounds.size.height - bottom - panel_margin));
msg(void, shield, "setFrame:", .{bounds});
msg(void, panel, "setFrame:", .{rect(@round((bounds.size.width - w) / 2), bottom, w, h)});
msg(void, panel_scroll, "setFrame:", .{rect(1, 1, @max(1, w - 2), @max(1, h - 2))});
const paper_w = @max(1, w - 2);
msg(void, paper, "setFrame:", .{rect(0, 0, paper_w, doc_h - 2)});
for (panel_btn, 0..) |b, i| msg(void, b, "setHidden:", .{guide_open != (i == done_index)});
for (rules) |line| msg(void, line, "setHidden:", .{guide_open});
msg(void, privacy_note, "setHidden:", .{guide_open});
msg(void, guide_text, "setHidden:", .{!guide_open});
var y = doc_h - 12 - row_h;
if (guide_open) {
msg(void, panel_btn[done_index], "setFrame:", .{rect(6, y, @max(1, paper_w - 12), row_h)});
msg(void, guide_text, "setFrame:", .{rect(15, y - 9 - guide_h, @max(1, paper_w - 30), guide_h)});
} else {
msg(void, panel_btn[0], "setFrame:", .{rect(6, y, @max(1, paper_w - 12), row_h)});
y -= 7;
msg(void, rules[0], "setFrame:", .{rect(16, y, @max(1, paper_w - 32), 1)});
y -= 6;
for (panel_btn[1..first_trim]) |b| {
y -= row_h;
msg(void, b, "setFrame:", .{rect(6, y, @max(1, paper_w - 12), row_h)});
}
y -= 6;
msg(void, rules[1], "setFrame:", .{rect(16, y, @max(1, paper_w - 32), 1)});
y -= 8 + trim_h;
const cell_w = @max(1, @floor((trim_w - number(trim_cols - 1) * trim_gap) / number(trim_cols)));
for (panel_btn[first_trim..done_index], 0..) |b, i| {
msg(void, b, "setFrame:", .{rect(12 + number(i % trim_cols) * (cell_w + trim_gap), y - number(i / trim_cols) * (trim_h + trim_gap), cell_w, trim_h)});
}
y -= number(trim_rows - 1) * (trim_h + trim_gap);
msg(void, privacy_note, "setFrame:", .{rect(15, y - 6 - note_h, @max(1, paper_w - 30), note_h)});
}
const first = msg(id, panelWindow(), "firstResponder", .{});
for (panel_btn) |b| if (first == b and !msg(bool, b, "isHidden", .{})) {
_ = msg(bool, b, "scrollRectToVisible:", .{msg(NSRect, b, "bounds", .{})});
break;
};
tintPanel();
}
fn colorRGB(rgb: u24) id {
return msg(id, objc.class("NSColor"), "colorWithSRGBRed:green:blue:alpha:", .{
number((rgb >> 16) & 255) / 255, number((rgb >> 8) & 255) / 255, number(rgb & 255) / 255, @as(f64, 1),
});
}
fn view(cls: id, parent: id) id {
const v = msg(id, msg(id, cls, "alloc", .{}), "initWithFrame:", .{NSRect{}});
msg(void, parent, "addSubview:", .{v});
msg(void, v, "release", .{});
return v;
}
fn fillView(v: id, color: id) id {
msg(void, v, "setWantsLayer:", .{true});
const layer = msg(id, v, "layer", .{});
msg(void, layer, "setBackgroundColor:", .{cg(color)});
return layer;
}
fn wrapLabel(parent: id, text: []const u8, font: id, color: id) id {
const f = msg(id, objc.class("NSTextField"), "wrappingLabelWithString:", .{objc.str(text)});
msg(void, f, "setFont:", .{font});
msg(void, f, "setTextColor:", .{color});
msg(void, parent, "addSubview:", .{f});
return f;
}
fn setupPanel() void {
// Write_On frame at 5:00: ink on #121522, two hairlines, one accent outline.
surface = colorRGB(0x121522);
edge = colorRGB(0x272a38);
highlight = colorRGB(0x252532);
panel_font = msg(id, objc.class("NSFont"), "monospacedSystemFontOfSize:weight:", .{ @as(f64, 14), @as(f64, 0) });
compact_font = msg(id, objc.class("NSFont"), "monospacedSystemFontOfSize:weight:", .{ @as(f64, 13), @as(f64, 0) });
const shield_class = objc.subclass("NSView", "ROLabShield", &.{
.{ .name = "mouseDown:", .imp = @ptrCast(&dismiss), .types = "v@:@" },
.{ .name = "rightMouseDown:", .imp = @ptrCast(&dismiss), .types = "v@:@" },
.{ .name = "otherMouseDown:", .imp = @ptrCast(&dismiss), .types = "v@:@" },
});
const btn_class = objc.subclass("NSButton", "ROLabChoice", &.{
.{ .name = "acceptsFirstResponder", .imp = @ptrCast(&acceptsFocus), .types = "B@:" },
.{ .name = "keyDown:", .imp = @ptrCast(&panelKeys), .types = "v@:@" },
.{ .name = "drawRect:", .imp = @ptrCast(&drawPanelButton), .types = "v@:{CGRect={CGPoint=dd}{CGSize=dd}}" },
.{ .name = "mouseEntered:", .imp = @ptrCast(&panelEnter), .types = "v@:@" },
.{ .name = "mouseExited:", .imp = @ptrCast(&panelExit), .types = "v@:@" },
});
const nsview = objc.class("NSView");
shield = view(shield_class, content);
msg(void, shield, "setHidden:", .{true});
panel = view(nsview, shield);
const layer = fillView(panel, surface);
msg(void, layer, "setCornerRadius:", .{@as(f64, 8)});
msg(void, layer, "setBorderWidth:", .{@as(f64, 1)});
msg(void, layer, "setBorderColor:", .{cg(edge)});
msg(void, layer, "setMasksToBounds:", .{true});
panel_scroll = view(objc.class("NSScrollView"), panel);
msg(void, panel_scroll, "setDrawsBackground:", .{false});
msg(void, panel_scroll, "setHasVerticalScroller:", .{true});
msg(void, panel_scroll, "setScrollerStyle:", .{@as(isize, 1)}); // overlay, no reserved width
msg(void, panel_scroll, "setAutohidesScrollers:", .{true});
paper = msg(id, msg(id, nsview, "alloc", .{}), "initWithFrame:", .{NSRect{}});
msg(void, panel_scroll, "setDocumentView:", .{paper});
msg(void, paper, "release", .{});
for (&rules) |*line| {
line.* = view(nsview, paper);
_ = fillView(line.*, edge);
}
for (&panel_btn, 0..) |*b, i| {
const title = if (i == 0) "The Lab guide…" else if (i < first_trim) passes[i - 1].title else if (i < done_index) trims[i - first_trim] else "Done";
b.* = msg(id, btn_class, "buttonWithTitle:target:action:", .{ objc.str(title), me, objc.sel("choose:") });
const tag: isize = if (i == 0 or i == first_trim or i == done_index) -1 else if (i < first_trim) passes[i - 1].tag else @intCast(i - 2);
msg(void, b.*, "setTag:", .{tag});
if (i > first_trim and i < done_index) msg(void, b.*, "setAccessibilityHelp:", .{objc.str(percents[i - first_trim])});
installRow(paper, b.*);
}
for (&writing_btn, writing_keys, writing_shortcuts, 0..) |*b, key, shortcut, i| {
b.* = msg(id, btn_class, "buttonWithTitle:target:action:", .{ objc.str(""), me, objc.sel("choose:") });
msg(void, b.*, "setKeyEquivalent:", .{objc.str(key)});
msg(void, b.*, "setKeyEquivalentModifierMask:", .{@as(usize, if (i == 2) 0x40000 else 0x60000)});
msg(void, b.*, "setAccessibilityHelp:", .{objc.str(shortcut)});
installRow(panel, b.*);
}
privacy_note = wrapLabel(paper, privacy, small, ink);
guide_text = wrapLabel(paper, guide, panel_font, bright);
msg(void, msg(id, objc.class("NSNotificationCenter"), "defaultCenter", .{}), "addObserver:selector:name:object:", .{ me, objc.sel("dismiss:"), NSWindowDidResignKeyNotification, panelWindow() });
}
fn installRow(parent: id, b: id) void {
msg(void, b, "setBordered:", .{false});
msg(void, b, "setFocusRingType:", .{@as(usize, 1)}); // theme draws focus
msg(void, parent, "addSubview:", .{b});
const area = msg(id, msg(id, objc.class("NSTrackingArea"), "alloc", .{}), "initWithRect:options:owner:userInfo:", .{ NSRect{}, @as(usize, 1 | 0x20 | 0x200), b, @as(id, null) });
msg(void, b, "addTrackingArea:", .{area});
msg(void, area, "release", .{});
}
fn relaid(_: id, _: SEL, _: id) callconv(.c) void {
relayout();
if (chooser_open) layoutPanel();
}
// --- Setup ----------------------------------------------------------------------------------
fn button(parent: id, title: []const u8, action: [*:0]const u8, target: id, tip: []const u8) Btn {
const b = msg(id, objc.class("NSButton"), "buttonWithTitle:target:action:", .{ objc.str(title), target, objc.sel(action) });
msg(void, b, "setControlSize:", .{@as(isize, 1)}); // small
msg(void, b, "setFont:", .{msg(id, objc.class("NSFont"), "systemFontOfSize:", .{@as(f64, 11)})});
if (tip.len > 0) msg(void, b, "setToolTip:", .{objc.str(tip)});
msg(void, b, "sizeToFit", .{});
msg(void, parent, "addSubview:", .{b});
const f = msg(NSRect, b, "frame", .{});
return .{ .v = b, .w = f.size.width, .h = f.size.height };
}
fn label(parent: id, font: id, color: id) id {
const f = msg(id, objc.class("NSTextField"), "labelWithString:", .{objc.str("")});
msg(void, f, "setFont:", .{font});
msg(void, f, "setTextColor:", .{color});
msg(void, msg(id, f, "cell", .{}), "setLineBreakMode:", .{@as(isize, 4)}); // truncate the tail
msg(void, parent, "addSubview:", .{f});
return f;
}
/// Call once, after the page, the status bar and the count are in `content_view`. `small` is
/// the 11 pt face and `dim_ink` the quiet color the app already uses.
pub fn setup(content_view: id, controller: id, editor: id, small_font: id, dim_ink: id, accent_ink: id, hot_ink: id) void {
draft_view = editor;
accent = accent_ink;
bright = hot_ink;
content = content_view;
ctl = controller;
small = small_font;
ink = dim_ink;
const cls = objc.subclass("NSObject", "ROLabUI", &.{
.{ .name = "choose:", .imp = @ptrCast(&choose), .types = "v@:@" },
.{ .name = "dismiss:", .imp = @ptrCast(&dismiss), .types = "v@:@" },
.{ .name = "mouseEntered:", .imp = @ptrCast(&entered), .types = "v@:@" },
.{ .name = "mouseExited:", .imp = @ptrCast(&exited), .types = "v@:@" },
.{ .name = "relaid:", .imp = @ptrCast(&relaid), .types = "v@:@" },
});
me = msg(id, msg(id, cls, "alloc", .{}), "init", .{});
// Monochrome vector templates; paths for the tiny lettering keep their spacing
// independent of the installed fonts. Native buttons retain focus, press and AX.
const glyphs = [_][]const u8{
"<svg xmlns='http://www.w3.org/2000/svg' width='18' height='18' viewBox='0 0 18 18'><g fill='none' stroke='black' stroke-width='1.65' stroke-linejoin='round'><path d='M1.4 1.4h11l4.2 4.2v11H1.4z M5 1.4v5.5h7.8V1.9 M4.5 16.3V10h9v6.3'/></g></svg>",
"<svg xmlns='http://www.w3.org/2000/svg' width='18' height='18'><path d='M1.4 2.1h5.7l2.1 2.3h7.4v11.7H1.4z' fill='none' stroke='black' stroke-width='1.65' stroke-linejoin='round'/></svg>",
"<svg xmlns='http://www.w3.org/2000/svg' width='25' height='18'><g fill='none' stroke='black'><rect x='.9' y='.9' width='23.2' height='16.2' rx='3.1' stroke-width='1.65'/><path d='m4.7 5.8 4.1 6.5m0-6.5-4.1 6.5m5.8-6.5 2.1 3.3 2.1-3.3m-2.1 3.3v3.2m3.5-6.2h4.1l-4.1 6h4.2' stroke-width='1.35' stroke-linejoin='round'/></g></svg>",
"<svg xmlns='http://www.w3.org/2000/svg' width='46' height='26'><g fill='none' stroke='black'><rect x='.6' y='.6' width='44.8' height='24.8' rx='4.6' stroke-dasharray='3 2'/><path d='M13.1 9.4v7.2h4.5m2.5 0 2.6-7.2h.6l2.6 7.2m-4.8-2.4h3.9m4-4.8v7.2h2.9c3.2 0 3.1-3.8.2-3.8H29m0-3.4h2.8c2.8 0 2.8 3.4.2 3.4' stroke-width='1.25' stroke-linejoin='round'/></g></svg>",
};
const titles = [_][]const u8{ "Save", "Open", "Overflow", "Lab" };
const tips = [_][]const u8{ "Save (⌘S)", "Open (⌘O)", "Overflow (⌃⇧D)", "Lab — mark or trim the draft" };
const actions = [_][*:0]const u8{ "saveDoc:", "openDoc:", "toggleOverflow:", "labMenu:" };
const trigger_class = objc.subclass("NSButton", "ROLabTrigger", &.{
.{ .name = "mouseDown:", .imp = @ptrCast(&triggerMouseDown), .types = "v@:@" },
});
for (&bar, &tracking, titles, tips, actions, glyphs, 0..) |*b, *area, title, tip, action, svg, i| {
const data = msg(id, objc.class("NSData"), "dataWithBytes:length:", .{ svg.ptr, svg.len });
const image = msg(id, msg(id, objc.class("NSImage"), "alloc", .{}), "initWithData:", .{data});
b.* = msg(id, if (i == 3) trigger_class else objc.class("NSButton"), "buttonWithTitle:target:action:", .{ objc.str(title), ctl, objc.sel(action) });
msg(void, b.*, "setBordered:", .{false});
if (image != null) {
msg(void, image, "setTemplate:", .{true});
msg(void, b.*, "setImage:", .{image});
msg(void, image, "release", .{});
msg(void, b.*, "setImagePosition:", .{@as(isize, 1)}); // NSImageOnly
}
msg(void, b.*, "setAccessibilityLabel:", .{objc.str(title)});
msg(void, b.*, "setToolTip:", .{objc.str(tip)});
msg(void, content, "addSubview:", .{b.*});
area.* = msg(id, msg(id, objc.class("NSTrackingArea"), "alloc", .{}), "initWithRect:options:owner:userInfo:", .{ NSRect{}, @as(usize, 1 | 0x20 | 0x200), me, @as(id, null) }); // entered/exited, in key window, in visible rect
msg(void, b.*, "addTrackingArea:", .{area.*});
msg(void, area.*, "release", .{});
}
tint();
// The review card: a popover-material card, so it follows the system's look.
card = msg(id, msg(id, objc.class("NSVisualEffectView"), "alloc", .{}), "initWithFrame:", .{NSRect{ .size = .{ .width = card_max_w, .height = card_h } }});
msg(void, card, "setMaterial:", .{@as(isize, 6)}); // popover
msg(void, card, "setBlendingMode:", .{@as(isize, 1)}); // within window
msg(void, card, "setState:", .{@as(isize, 1)}); // always active
msg(void, card, "setWantsLayer:", .{true});
const layer = msg(id, card, "layer", .{});
msg(void, layer, "setCornerRadius:", .{@as(f64, 12)});
msg(void, layer, "setMasksToBounds:", .{true});
msg(void, layer, "setBorderWidth:", .{@as(f64, 1)});
msg(void, layer, "setBorderColor:", .{msg(id, msg(id, objc.class("NSColor"), "separatorColor", .{}), "CGColor", .{})});
msg(void, card, "setHidden:", .{true});
note_field = label(card, small, msg(id, objc.class("NSColor"), "labelColor", .{}));
hint_field = label(card, small, ink);
msg(void, hint_field, "setStringValue:", .{objc.str("Keep skips this one · Apply rest takes the others")});
msg(void, card, "setToolTip:", .{objc.str("Sent to the model only when you chose this pass")});
card_btn[0] = button(card, "Discard", "labOriginal:", ctl, "Put it all away; the text stays as it was");
card_btn[1] = button(card, "Next", "labNext:", ctl, "Move on, leaving this one undecided");
card_btn[2] = button(card, "Keep", "labKeep:", ctl, "Keep this one as it is and skip it");
card_btn[3] = button(card, "Apply rest", "labApply:", ctl, "Apply every remaining finding");
msg(void, content, "addSubview:", .{card}); // last, so it is above the page
setupPanel(); // last in the stack, above both the editor and review card
msg(void, content, "setPostsFrameChangedNotifications:", .{true});
msg(void, msg(id, objc.class("NSNotificationCenter"), "defaultCenter", .{}), "addObserver:selector:name:object:", .{ me, objc.sel("relaid:"), NSViewFrameDidChangeNotification, content });
relayout();
}
test "plan drops in order until the rest fit" {
const w = [_]f64{ 50, 50, 50, 50 };
var shown: [4]bool = undefined;
// all four: 200 + 3 gaps
try std.testing.expectEqual(@as(f64, 200 + 3 * gap), plan(&w, &card_drop, 1000, &shown));
try std.testing.expect(shown[0] and shown[1] and shown[2] and shown[3]);
// room for two: Next (1) goes, then Discard (0)
try std.testing.expectEqual(@as(f64, 100 + gap), plan(&w, &card_drop, 110, &shown));
try std.testing.expect(!shown[0] and !shown[1] and shown[2] and shown[3]);
// no room at all: nothing shown
try std.testing.expectEqual(@as(f64, 0), plan(&w, &card_drop, 10, &shown));
try std.testing.expect(!shown[0] and !shown[1] and !shown[2] and !shown[3]);
}
|