diff options
Diffstat (limited to 'src/main.zig')
| -rw-r--r-- | src/main.zig | 509 |
1 files changed, 429 insertions, 80 deletions
diff --git a/src/main.zig b/src/main.zig index e1adb05..e8e4c21 100644 --- a/src/main.zig +++ b/src/main.zig @@ -10,6 +10,7 @@ //! group: see `pull`, `fill` and `settle`. const std = @import("std"); const objc = @import("objc.zig"); +const markdown = @import("markdown.zig"); const doc = @import("doc.zig"); const ai = @import("ai.zig"); const lab = @import("lab.zig"); @@ -28,6 +29,7 @@ const gpa = std.heap.c_allocator; extern const NSFontAttributeName: id; extern const NSForegroundColorAttributeName: id; extern const NSUnderlineStyleAttributeName: id; +extern const NSStrikethroughStyleAttributeName: id; extern const NSUnderlineColorAttributeName: id; extern const NSBackgroundColorAttributeName: id; extern const NSParagraphStyleAttributeName: id; @@ -77,18 +79,31 @@ var tabs: [3]id = undefined; // Word, Sentence, Paragraph var key_group: id = null; var key_ghost: id = null; var key_lab_keep: id = null; +var key_fence: id = null; // on a paragraph that leaves a code fence open: `markdown.fenceLine`'s state after it var yes: id = null; var font: id = null; var bold: id = null; var small: id = null; -var hidden: id = null; // the font of a heading's marker: too small to see +var hidden: id = null; // Markdown punctuation: too small to see +var italic: id = null; +var bold_italic: id = null; +var code_font: id = null; +var markdown_dirty: ?NSRange = null; +var markdown_caret: ?usize = null; +var markdown_rendering = false; +var markdown_units: std.ArrayList(u16) = .empty; +var markdown_parser: markdown.Parser = .{}; +var markdown_strike: id = null; var script: id = null; // the hand the panel's tabs are written in var base_attrs: id = null; -var color: struct { bg: id, panel: id, text: id, near: id, far: id, ghost: id, clear: id, dim: id, word: id, word_line: id, sentence: id, sentence_line: id, paragraph: id, bar: id, ring: id, hover: id, selection: id } = undefined; +var color: struct { bg: id, panel: id, text: id, near: id, far: id, ghost: id, clear: id, dim: id, word: id, word_line: id, sentence: id, sentence_line: id, paragraph: id, bar: id, ring: id, hover: id, selection: id, code: id } = undefined; var groups: std.AutoArrayHashMapUnmanaged(u32, doc.Group) = .empty; var next_id: u32 = 1; var file_path: ?[]u8 = null; +var document_defaults: id = null; +const last_document = "LastDocumentPath"; +var received_open = false; // Finder can send openFile: before didFinishLaunching: var tools = true; // off is read mode: just the text var overflow_open = false; var hover: u32 = 0; // the group under the pointer @@ -97,7 +112,6 @@ var target: u32 = 0; // the group the alternatives panel is on, when it is open var home: std.ArrayList(u8) = .empty; // what the target showed when the page's undo last heard: see `settle` var quiet = false; // the panel is changing the page, and undo is not to be told yet var filling = false; // the panel's text is being set from its group, not typed -var last_caret: usize = 0; var threaded: std.Io.Threaded = undefined; var io: std.Io = undefined; // for libpantograph: the AI's network and the key's file @@ -426,7 +440,7 @@ fn refresh() void { tint(NSForegroundColorAttributeName, color.near, paragraphOf(page, r)); msg(void, layout, "removeTemporaryAttribute:forCharacterRange:", .{ NSForegroundColorAttributeName, r }); }; - headings(); + markdownRefresh(); const um = msg(id, page, "undoManager", .{}); const undoing = msg(bool, um, "isUndoing", .{}) or msg(bool, um, "isRedoing", .{}); @@ -458,32 +472,169 @@ fn scopeColor(scope: doc.Scope) id { }; } -/// The only Markdown rendered so far: a line that opens with "# " is a heading, in bold, -/// and its marker is out of sight. The marker stays in the text, in a font too small to -/// see. A font cannot be a temporary attribute, so these go into the storage, and only -/// where they are wrong. -fn headings() void { +/// Record the post-edit range; don't mutate storage while it is processing an edit. +fn markdownEdited(_: id, _: SEL, _: id, _: usize, changed: NSRange, delta: isize) callconv(.c) void { + if (markdown_rendering) return; + const old_end: usize = @intCast(@as(isize, @intCast(end(changed))) - delta); + if (markdown_caret) |i| markdown_caret = afterEdit(i, changed, old_end); + markdown_dirty = if (markdown_dirty) |r| markdownRange( + @min(changed.location, afterEdit(r.location, changed, old_end)), + @max(end(changed), afterEdit(end(r), changed, old_end)), + ) else changed; +} + +fn afterEdit(i: usize, changed: NSRange, old_end: usize) usize { + if (i < changed.location) return i; + if (i < old_end) return changed.location; + return end(changed) + (i - old_end); +} + +fn markdownRange(start: usize, stop: usize) NSRange { + return .{ .location = start, .length = stop - start }; +} + +/// Fonts must be in storage, not temporary attributes. Style only the edited paragraphs +/// and the ones whose active inline syntax might change. No character edits or undo entries. +fn markdownRefresh() void { + if (markdown_rendering or msg(bool, page, "hasMarkedText", .{})) return; + // The layout manager moves the selection while it is still hearing about an edit, and a + // font changed under it then keeps the old font's glyphs. `textDidChange` comes after. + if (msg(usize, storage, "editedMask", .{}) != 0) return; + const sel = selection(); + const caret = if (sel.length == 0) sel.location else null; + if (markdown_dirty == null and caret == markdown_caret) return; const n = len(); - var i: usize = 0; - while (i < n) { + const previous = markdown_caret; + const changed = markdown_dirty; + markdown_caret = caret; + markdown_dirty = null; + if (n == 0) return; + + const dirty = if (changed) |r| markdownRange( + paragraphOf(page, .{ .location = @min(r.location, n) }).location, + end(paragraphOf(page, .{ .location = @min(end(r), n) })), + ) else NSRange{}; + markdown_rendering = true; + defer markdown_rendering = false; + msg(void, storage, "beginEditing", .{}); + defer msg(void, storage, "endEditing", .{}); + var open = fenceBefore(dirty.location); + var i = dirty.location; + while (i < end(dirty)) { + const para = paragraphOf(page, .{ .location = i }); + markdownParagraph(para, caret, &open); + i = end(para); + } + // A fence that came or went changes the lines after it, up to one it leaves as it found. + while (changed != null and i < n) { const para = paragraphOf(page, .{ .location = i }); - const mark_r: NSRange = .{ .location = para.location, .length = marker(para) }; - setFont(mark_r, hidden); - setFont(.{ .location = end(mark_r), .length = para.length - mark_r.length }, if (mark_r.length > 0) bold else font); - if (mark_r.length > 0) tint(NSForegroundColorAttributeName, color.clear, mark_r); + const was = fenceAt(i); + markdownParagraph(para, caret, &open); i = end(para); + if (open == was) break; + } + var last: ?usize = null; + for ([_]?usize{ previous, caret }) |pos| if (pos) |at| { + const para = paragraphOf(page, .{ .location = @min(at, n) }); + if (para.length == 0 or (para.location >= dirty.location and para.location < i) or last == para.location) continue; + open = fenceBefore(para.location); + markdownParagraph(para, caret, &open); + last = para.location; + }; + markdownFences(caret); + // A change of attributes alone does not get every line it touched drawn again. + msg(void, page, "setNeedsDisplay:", .{true}); +} + +/// The fence state the paragraph at `i` leaves behind it: see `key_fence`. +fn fenceAt(i: usize) u32 { + return idOf(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ key_fence, i, @as(?*NSRange, null) })); +} + +fn fenceBefore(para_start: usize) u32 { + return if (para_start == 0 or para_start > len()) 0 else fenceAt(para_start - 1); +} + +/// A block's fences show only while the caret is in the block, like any other marker. A +/// run of `key_fence` is one block, less the line that closes it. +fn markdownFences(caret: ?usize) void { + const n = len(); + const at = if (caret) |c| paragraphOf(page, .{ .location = c }).location else n + 1; + var it: Runs = .{ .key = key_fence }; + while (it.next()) |run| { + const close = paragraphOf(page, .{ .location = end(run.range) }); + const closed = close.location == end(run.range) and close.length > 0; + const show = at >= run.range.location and at < if (closed) end(close) else n + 1; + for ([_]NSRange{ paragraphOf(page, .{ .location = run.range.location }), if (closed) close else .{} }) |line| { + if (line.length == 0) continue; + setMarkdownAttribute(line, NSFontAttributeName, if (show) code_font else hidden); + setMarkdownAttribute(line, NSForegroundColorAttributeName, if (show) color.dim else color.clear); + setMarkdownAttribute(line, NSStrikethroughStyleAttributeName, null); + } } } -fn setFont(r: NSRange, want: id) void { +/// `open` is the fence state the paragraph starts in, and is left as the next will find it. +fn markdownParagraph(para: NSRange, caret: ?usize, open: *u32) void { + if (para.length == 0) return; + markdown_units.resize(gpa, para.length) catch return; + msg(void, string(page), "getCharacters:range:", .{ markdown_units.items.ptr, para }); + const kind = markdown.fenceLine(markdown_units.items, open); + setMarkdownAttribute(para, key_fence, if (open.* != 0) number(open.*) else null); + switch (kind) { + .fence => return, // `markdownFences` shows or hides it + .code => return markdownPaint(para, .{ .code = true }, false, false), + .text => {}, + } + const prefix = marker(para); + const body = markdownRange(para.location + prefix, end(para)); + if (prefix != 0) { + const active_heading = if (caret) |at| paragraphOf(page, .{ .location = at }).location == para.location else false; + markdownPaint(markdownRange(para.location, body.location), .{}, false, !active_heading); + } + const marks = markdown_parser.parse(gpa, markdown_units.items[prefix..]) catch return markdownPaint(body, .{}, prefix != 0, false); + var active: markdown.Active = .{}; + var at = body.location; + for (marks, 0..) |mark_, idx| { + const partner = mark_.partner orelse continue; + const tag = markdownRange(body.location + mark_.at, body.location + mark_.at + mark_.width); + markdownPaint(markdownRange(at, tag.location), active.style(), prefix != 0, false); + const first = body.location + marks[@min(idx, partner)].at; + const closing = marks[@max(idx, partner)]; + const stop = body.location + closing.at + closing.width; + const reveal = if (caret) |c| c > first and c < stop else false; + markdownPaint(tag, .{}, prefix != 0, !reveal); + active.toggle(mark_); + at = end(tag); + } + markdownPaint(markdownRange(at, end(body)), active.style(), prefix != 0, false); +} + +fn markdownPaint(r: NSRange, style: markdown.Style, heading: bool, hide: bool) void { if (r.length == 0) return; + const strong = heading or style.strong; + const face = if (hide) hidden else if (style.code) code_font else if (style.emphasis) + (if (strong) bold_italic else italic) + else if (strong) bold else font; + setMarkdownAttribute(r, NSFontAttributeName, face); + setMarkdownAttribute(r, NSForegroundColorAttributeName, if (hide) color.clear else color.text); + setMarkdownAttribute(r, NSStrikethroughStyleAttributeName, if (style.strike) markdown_strike else null); +} + +fn setMarkdownAttribute(r: NSRange, key: id, want: id) void { var run: NSRange = .{}; - const have = msg(id, storage, "attribute:atIndex:longestEffectiveRange:inRange:", .{ NSFontAttributeName, r.location, &run, r }); - if (have != want or run.length < r.length) msg(void, storage, "addAttribute:value:range:", .{ NSFontAttributeName, want, r }); + const have = msg(id, storage, "attribute:atIndex:longestEffectiveRange:inRange:", .{ key, r.location, &run, r }); + if (have == want and run.length == r.length) return; + if (want != null) { + msg(void, storage, "addAttribute:value:range:", .{ key, want, r }); + } else { + msg(void, storage, "removeAttribute:range:", .{ key, r }); + } } /// How much of a paragraph is a heading's marker: three characters of "## Title". fn marker(para: NSRange) usize { + if (fenceBefore(para.location) != 0) return 0; // code, not a heading var hashes: usize = 0; while (hashes < para.length and charAt(para.location + hashes) == '#') hashes += 1; if (hashes == 0 or hashes > 6 or hashes == para.length or charAt(para.location + hashes) != ' ') return 0; @@ -1047,8 +1198,26 @@ fn showLab() void { lab_ui.update(tools, line, true, p.isTrim() or p == .typos); } -fn labMenu(_: id, _: SEL, sender: id) callconv(.c) void { - lab_ui.openMenu(sender); +fn labMenu(_: id, _: SEL, _: id) callconv(.c) void { + if (!tools) { + tools = true; + panels(); + refresh(); + } + lab_ui.togglePanel(); +} + +fn validateMenuItem(_: id, _: SEL, menu_item: id) callconv(.c) bool { + const action = msg(SEL, menu_item, "action", .{}); + if (action == objc.sel("labOriginal:")) return tools and reading != null; + if (action == objc.sel("labNext:") or action == objc.sel("labKeep:") or action == objc.sel("labApply:")) { + if (!tools) return false; + const j = reading orelse return false; + const hits = j.hits orelse return false; + if (hits.items.len == 0) return false; + return action != objc.sel("labApply:") or j.pass.?.isTrim() or j.pass.? == .typos; + } + return true; } fn labPass(_: id, _: SEL, sender: id) callconv(.c) void { @@ -1500,7 +1669,6 @@ fn load(bytes: []const u8) void { msg(void, msg(id, page, "undoManager", .{}), "removeAllActions", .{}); select(.{}); - keepOut(); msg(void, page, "scrollPoint:", .{NSPoint{}}); setDirty(false); panels(); @@ -1544,29 +1712,46 @@ fn setPath(path: ?[]const u8) void { file_path = new; if (new) |p| { msg(void, window, "setTitleWithRepresentedFilename:", .{str(p)}); + msg(void, document_defaults, "setObject:forKey:", .{ str(p), str(last_document) }); } else { + msg(void, document_defaults, "removeObjectForKey:", .{str(last_document)}); msg(void, window, "setRepresentedFilename:", .{str("")}); msg(void, window, "setTitle:", .{str("Untitled")}); } } -fn openPath(path: []const u8) bool { - const data = msg(id, objc.class("NSData"), "dataWithContentsOfFile:", .{str(path)}); - if (data == null) { - alert("That file could not be read.", path); - return false; - } +fn readPath(path: []const u8) error{ Unreadable, NotUtf8 }!void { + const data = msg(id, objc.class("NSData"), "dataWithContentsOfFile:", .{str(path)}) orelse return error.Unreadable; const n = msg(usize, data, "length", .{}); const bytes: []const u8 = if (n == 0) "" else msg([*]const u8, data, "bytes", .{})[0..n]; - if (!std.unicode.utf8ValidateSlice(bytes)) { - alert("That file is not UTF-8 text.", path); - return false; - } + if (!std.unicode.utf8ValidateSlice(bytes)) return error.NotUtf8; load(bytes); setPath(path); +} + +fn openPath(path: []const u8) bool { + readPath(path) catch |err| { + alert(switch (err) { + error.Unreadable => "That file could not be read.", + error.NotUtf8 => "That file is not UTF-8 text.", + }, path); + return false; + }; return true; } +fn startDraft() void { + // An explicit Open is authoritative, even if AppKit delivered it during launch. + if (!received_open) { + const path = objc.utf8(msg(id, document_defaults, "stringForKey:", .{str(last_document)})); + if (path.len != 0) { + if (readPath(path)) return else |_| {} // A stale preference isn't an Open error. + } + } else if (file_path != null) return; + load(""); + setPath(null); +} + fn save(ask: bool) bool { var to: []const u8 = file_path orelse ""; if (ask or to.len == 0) { @@ -1646,7 +1831,7 @@ fn selectionDidChange(_: id, _: SEL, note: id) callconv(.c) void { const view = msg(id, note, "object", .{}); if (view == alts) return pull(); if (view != page) return; - keepOut(); + markdownRefresh(); typing(); status(); } @@ -1671,19 +1856,6 @@ fn undoFor(_: id, _: SEL, view: id) callconv(.c) id { return if (view == alts) alts_undo else null; // null: the window's, as ever } -/// A heading's marker is out of sight, and the caret stays out of it. Stepping left from a -/// heading's first letter goes to the end of the line above. -fn keepOut() void { - defer last_caret = selection().location; - const sel = selection(); - if (sel.length > 0) return; - const para = paragraphOf(page, sel); - const first = para.location + marker(para); - if (sel.location >= first) return; - const stepped_left = last_caret == first and sel.location + 1 == first and para.location > 0; - select(.{ .location = if (stepped_left) para.location - 1 else first }); -} - /// Keep the 65-character column centered in whatever width there is. It narrows, and the /// text reflows, only when the window is too small for it, and it steps aside only when /// the alternatives panel would otherwise lie over it. @@ -1716,6 +1888,7 @@ fn quitWithWindow(_: id, _: SEL, _: id) callconv(.c) bool { /// Finder, `open` and a path on the command line all arrive here, the last by AppKit's own /// reading of the arguments. A path with no file yet starts a piece that will save there. fn openFile(_: id, _: SEL, _: id, path: id) callconv(.c) bool { + received_open = true; if (!mayDiscard()) return false; const full = msg(id, msg(id, objc.class("NSURL"), "fileURLWithPath:", .{path}), "path", .{}); if (msg(bool, msg(id, objc.class("NSFileManager"), "defaultManager", .{}), "fileExistsAtPath:", .{full})) return openPath(objc.utf8(full)); @@ -1752,11 +1925,6 @@ fn keyDown(self: id, _: SEL, event: id) callconv(.c) void { armed = false; if (hover != 0) refresh(); } - if (plain and key == Key.backspace and sel.length == 0) { // before a heading's first letter: no longer a heading - const para = paragraphOf(page, sel); - const m = marker(para); - if (m > 0 and sel.location == para.location + m) return insert(page, "", .{ .location = para.location, .length = m }); - } objc.msgSuper(void, self, "NSTextView", "keyDown:", .{event}); } @@ -1770,16 +1938,25 @@ fn mouseDown(self: id, _: SEL, event: id) callconv(.c) void { /// else it puts the caret there and is about the word under it. fn contextMenu(self: id, _: SEL, event: id) callconv(.c) id { if (!tools) return objc.msgSuper(id, self, "NSTextView", "menuForEvent:", .{event}); - const sel = selection(); - if (charUnder(event)) |i| if (i < sel.location or i >= end(sel)) select(.{ .location = i }); - const cs = Mod.ctrl | Mod.shift; - const menu = msg(id, objc.new("NSMenu"), "autorelease", .{}); + if (!lab_ui.canOpenWritingMenu()) return null; + const point = msg(NSPoint, event, "locationInWindow", .{}); + const hit = charUnder(event); + const before = selection(); + if (hit == null or hit.? < before.location or hit.? >= end(before)) { + const local = msg(NSPoint, self, "convertPoint:fromView:", .{ point, @as(id, null) }); + select(.{ .location = hit orelse msg(usize, self, "characterIndexForInsertionAtPoint:", .{local}) }); + } + const subject = selection(); var buf: [2][160]u8 = undefined; - item(menu, menuTitle(&buf[0], "Alternatives"), "alternative:", "a", cs, ctl); - item(menu, menuTitle(&buf[1], "AI alternatives"), "aiAlternative:", "g", cs, ctl); - item(menu, if (ghostIn(ghostable())) "Revive it" else "Ghost it", "ghost:", "/", Mod.ctrl, ctl); - item(menu, "Stash this in Overflow", "stash:", "x", cs, ctl); - return menu; + lab_ui.openWritingMenu(point, .{ + menuTitle(&buf[0], "Alternatives"), + menuTitle(&buf[1], "AI alternatives"), + if (ghostIn(ghostable())) "Revive it" else "Ghost it", + "Stash this in Overflow", + }); + // Leaving an edited alternatives panel can settle it and move the page selection. + if (!std.meta.eql(selection(), subject)) select(subject); + return null; } fn menuTitle(buf: []u8, lead: []const u8) []const u8 { @@ -1825,9 +2002,26 @@ fn paste(self: id, _: SEL, sender: id) callconv(.c) void { /// group, the showing one filled in. fn drawBackground(self: id, _: SEL, dirty: NSRect) callconv(.c) void { objc.msgSuper(void, self, "NSTextView", "drawViewBackgroundInRect:", .{dirty}); - if (!tools) return; const origin = msg(NSPoint, self, "textContainerOrigin", .{}); const container = msg(id, self, "textContainer", .{}); + // Behind each fenced block, from its opening fence to its closing one, a panel as wide + // as the column. The fences' own lines are its padding while they are out of sight. + var fences: Runs = .{ .key = key_fence }; + while (fences.next()) |run| { + const stop = end(paragraphOf(page, .{ .location = end(run.range) })); + const glyphs = msg(NSRange, layout, "glyphRangeForCharacterRange:actualCharacterRange:", .{ markdownRange(run.range.location, stop), @as(?*NSRange, null) }); + if (glyphs.length == 0) continue; + const top = msg(NSRect, layout, "lineFragmentRectForGlyphAtIndex:effectiveRange:", .{ glyphs.location, @as(?*NSRange, null) }); + const bottom = msg(NSRect, layout, "lineFragmentRectForGlyphAtIndex:effectiveRange:", .{ end(glyphs) - 1, @as(?*NSRange, null) }); + const pad = 14; + const box: NSRect = .{ + .origin = .{ .x = origin.x + top.origin.x - pad, .y = origin.y + top.origin.y - line_gap / 2 }, + .size = .{ .width = top.size.width + 2 * pad, .height = bottom.origin.y + bottom.size.height - top.origin.y }, + }; + msg(void, color.code, "setFill", .{}); + msg(void, msg(id, objc.class("NSBezierPath"), "bezierPathWithRoundedRect:xRadius:yRadius:", .{ box, @as(f64, 8), @as(f64, 8) }), "fill", .{}); + } + if (!tools) return; var it: Runs = .{ .key = key_group }; while (it.next()) |run| { const g = groups.getPtr(idOf(run.value)) orelse continue; @@ -1940,6 +2134,10 @@ const status_h = 40; // --- Setup ---------------------------------------------------------------------------------- +fn markdownFont(ns_font: id, name: []const u8, size: f64, fallback: id) id { + return msg(id, msg(id, ns_font, "fontWithName:size:", .{ str(name), size }) orelse fallback, "retain", .{}); +} + fn setup(app: id) void { const NSObject = "NSObject"; const action = "v@:@"; @@ -1961,6 +2159,7 @@ fn setup(app: id) void { .{ .name = "aiAlternative:", .imp = @ptrCast(&aiAlternative), .types = action }, .{ .name = "inference:", .imp = @ptrCast(&inference), .types = action }, .{ .name = "needInference:", .imp = @ptrCast(&needInference), .types = action }, + .{ .name = "validateMenuItem:", .imp = @ptrCast(&validateMenuItem), .types = "B@:@" }, .{ .name = "labMenu:", .imp = @ptrCast(&labMenu), .types = action }, .{ .name = "labPass:", .imp = @ptrCast(&labPass), .types = action }, .{ .name = "labOriginal:", .imp = @ptrCast(&labOriginal), .types = action }, @@ -1969,6 +2168,7 @@ fn setup(app: id) void { .{ .name = "labApply:", .imp = @ptrCast(&labApply), .types = action }, .{ .name = "styleChanged:", .imp = @ptrCast(&styleChanged), .types = action }, .{ .name = "resized:", .imp = @ptrCast(&resized), .types = action }, + .{ .name = "textStorage:didProcessEditing:range:changeInLength:", .imp = @ptrCast(&markdownEdited), .types = "v@:@Q{_NSRange=QQ}q" }, .{ .name = "textDidChange:", .imp = @ptrCast(&textDidChange), .types = action }, .{ .name = "textDidEndEditing:", .imp = @ptrCast(&editingEnded), .types = action }, .{ .name = "textView:doCommandBySelector:", .imp = @ptrCast(&doCommand), .types = "B@:@:" }, @@ -1977,6 +2177,7 @@ fn setup(app: id) void { .{ .name = "windowShouldClose:", .imp = @ptrCast(&windowShouldClose), .types = "B@:@" }, .{ .name = "applicationShouldTerminate:", .imp = @ptrCast(&shouldTerminate), .types = "Q@:@" }, .{ .name = "applicationShouldTerminateAfterLastWindowClosed:", .imp = @ptrCast(&quitWithWindow), .types = "B@:@" }, + .{ .name = "applicationDidFinishLaunching:", .imp = @ptrCast(&didLaunch), .types = action }, .{ .name = "application:openFile:", .imp = @ptrCast(&openFile), .types = "B@:@@" }, }); _ = objc.subclass("NSTextView", "ROPage", &.{ @@ -2013,6 +2214,7 @@ fn setup(app: id) void { .ring = rgb(0x6c6879, 1), .hover = rgb(0x98a8e2, 0.14), .selection = rgb(0x817cd4, 0.28), + .code = rgb(0x121522, 1), }; const regular: f64 = 0; const heavy: f64 = 0.4; @@ -2021,11 +2223,16 @@ fn setup(app: id) void { bold = msg(id, msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 20), heavy }), "retain", .{}); small = msg(id, msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 11), regular }), "retain", .{}); hidden = msg(id, msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 0.1), regular }), "retain", .{}); + italic = markdownFont(NSFont, "Menlo-Italic", 20, font); + bold_italic = markdownFont(NSFont, "Menlo-BoldItalic", 20, bold); + code_font = markdownFont(NSFont, "Monaco", 18, font); + markdown_strike = msg(id, number(1), "retain", .{}); script = msg(id, msg(id, NSFont, "fontWithName:size:", .{ str("BradleyHandITCTT-Bold"), @as(f64, 17) }) orelse small, "retain", .{}); tones = .{ makeTone(1900), makeTone(1500) }; key_group = msg(id, str("WriteAwayGroup"), "retain", .{}); key_ghost = msg(id, str("WriteAwayGhost"), "retain", .{}); key_lab_keep = msg(id, str("WriteAwayLabKeep"), "retain", .{}); + key_fence = msg(id, str("WriteAwayFence"), "retain", .{}); yes = msg(id, msg(id, objc.class("NSNumber"), "numberWithBool:", .{true}), "retain", .{}); const spaced = objc.new("NSMutableParagraphStyle"); msg(void, spaced, "setLineSpacing:", .{@as(f64, line_gap)}); @@ -2068,6 +2275,7 @@ fn setup(app: id) void { msg(void, page, "setDefaultParagraphStyle:", .{spaced}); msg(void, page, "setSelectedTextAttributes:", .{dict(&.{.{ NSBackgroundColorAttributeName, color.selection }})}); storage = msg(id, page, "textStorage", .{}); + msg(void, storage, "setDelegate:", .{ctl}); layout = msg(id, page, "layoutManager", .{}); const strip: NSRect = .{ .size = .{ .width = 280, .height = bounds.size.height } }; over_scroll = textArea("NSTextView", strip, color.panel, &over); @@ -2141,7 +2349,7 @@ fn setup(app: id) void { msg(void, clip, "setPostsFrameChangedNotifications:", .{true}); msg(void, msg(id, objc.class("NSNotificationCenter"), "defaultCenter", .{}), "addObserver:selector:name:object:", .{ ctl, objc.sel("resized:"), NSViewFrameDidChangeNotification, clip }); - lab_ui.setup(content, ctl, small, color.dim, color.word, color.text); + lab_ui.setup(content, ctl, page, small, color.dim, color.word, color.text); menus(app); panels(); resized(null, null, null); @@ -2225,6 +2433,11 @@ fn menus(app: id) void { item(write, "Ghost or Revive", "ghost:", "/", Mod.ctrl, ctl); item(write, "Stash in Overflow", "stash:", "x", cs, ctl); item(write, "Use from Overflow", "useOverflow:", "\r", Mod.ctrl, ctl); + item(write, "Labβ¦", "labMenu:", "l", cs, ctl); + item(write, "Lab: Next", "labNext:", "n", cs, ctl); + item(write, "Lab: Keep", "labKeep:", "k", cs, ctl); + item(write, "Lab: Apply rest", "labApply:", "p", cs, ctl); + item(write, "Lab: Discard / Original", "labOriginal:", "o", cs, ctl); const view = submenu(bar, "View"); item(view, "Tools", "toggleTools:", "r", cs, ctl); @@ -2261,15 +2474,17 @@ pub fn main() void { const process = msg(id, objc.class("NSProcessInfo"), "processInfo", .{}); if (msg(id, msg(id, process, "environment", .{}), "objectForKey:", .{str("WRITE_AWAY_SELFTEST")}) != null) return selftest(); - load(@embedFile("welcome.md")); // until `openFile` is handed something else - setPath(null); - + document_defaults = msg(id, objc.class("NSUserDefaults"), "standardUserDefaults", .{}); const regular: isize = 0; _ = msg(bool, app, "setActivationPolicy:", .{regular}); + msg(void, app, "run", .{}); +} + +fn didLaunch(_: id, _: SEL, note: id) callconv(.c) void { + startDraft(); msg(void, window, "makeKeyAndOrderFront:", .{@as(id, null)}); _ = msg(bool, window, "makeFirstResponder:", .{page}); - msg(void, app, "activateIgnoringOtherApps:", .{true}); - msg(void, app, "run", .{}); + msg(void, msg(id, note, "object", .{}), "activateIgnoringOtherApps:", .{true}); } // --- The check ------------------------------------------------------------------------------ @@ -2286,6 +2501,27 @@ fn selftest() void { }; const um = msg(id, page, "undoManager", .{}); + // Use an isolated defaults suite and temporary draft, never the writer's last file. + const unique = msg(id, msg(id, objc.class("NSUUID"), "UUID", .{}), "UUIDString", .{}); + document_defaults = msg(id, msg(id, objc.class("NSUserDefaults"), "alloc", .{}), "initWithSuiteName:", .{unique}); + startDraft(); + t.expect(len() == 0 and file_path == null and std.mem.eql(u8, objc.utf8(msg(id, window, "title", .{})), "Untitled"), "a first launch is empty and Untitled"); + const fm = msg(id, objc.class("NSFileManager"), "defaultManager", .{}); + const path = msg(id, msg(id, msg(id, fm, "temporaryDirectory", .{}), "URLByAppendingPathComponent:", .{unique}), "path", .{}); + t.expect(openFile(null, null, null, path), "an explicit new path starts a draft"); + startDraft(); + t.expect(file_path != null and std.mem.eql(u8, file_path.?, objc.utf8(path)) and len() == 0, "a launch file takes precedence even when it does not exist yet"); + insert(page, "Remember this.", .{}); + t.expect(save(false), "save the named piece"); + received_open = false; + load(""); + startDraft(); + t.expect(file_path != null and std.mem.eql(u8, file_path.?, objc.utf8(path)) and std.mem.eql(u8, objc.utf8(string(page)), "Remember this."), "the next launch restores the last file from disk"); + t.expect(msg(bool, fm, "removeItemAtPath:error:", .{ path, @as(?*id, null) }), "remove the temporary piece"); + startDraft(); + t.expect(len() == 0 and file_path == null and msg(id, document_defaults, "objectForKey:", .{str(last_document)}) == null and !msg(bool, window, "isDocumentEdited", .{}), "a missing piece leaves a clean unnamed draft and no stale path"); + msg(void, document_defaults, "removePersistentDomainForName:", .{unique}); + load(@embedFile("welcome.md")); t.expect(groups.count() == 3, "the welcome piece has three groups"); @@ -2309,12 +2545,12 @@ fn selftest() void { t.expect(@abs(msg(NSRect, over_scroll, "frame", .{}).size.width - chosen) < 1, "reopening remembers the divider"); toggleOverflow(null, null, null); - // The heading's marker is in the text and out of sight, and the caret keeps out of it. - t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 0), @as(?*NSRange, null) }) == hidden, "a heading's marker is hidden"); - t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 2), @as(?*NSRange, null) }) == bold, "and the heading is bold"); - t.expect(selection().location == 2, "the caret starts after the marker"); + // Moving into the heading reveals its source without changing the styled title. + select(.{ .location = len() }); + t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 0), @as(?*NSRange, null) }) == hidden, "an inactive heading's marker is hidden"); select(.{ .location = 1 }); - t.expect(selection().location == 2, "and cannot be put inside it"); + t.expect(selection().location == 1 and msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 0), @as(?*NSRange, null) }) == font, "the caret can enter and reveal the heading marker"); + t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 2), @as(?*NSRange, null) }) == bold, "the heading title remains bold"); // Flip a group in place, and undo it. const gid = groups.keys()[0]; @@ -2367,12 +2603,42 @@ fn selftest() void { // A right-click on the word: what can be done with it. select(.{}); // undo left the word selected again, and then the menu would be about the selection const right_down: usize = 3; - const menu = contextMenu(page, null, msg(id, NSEvent, "mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:", .{ + _ = msg(bool, window, "makeFirstResponder:", .{page}); + const click = msg(id, NSEvent, "mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:", .{ right_down, msg(NSPoint, page, "convertPoint:toView:", .{ on_word, @as(id, null) }), zero, no_time, no_window, @as(id, null), no_window, no_window, @as(f32, 0), - })); - t.expect(msg(isize, menu, "numberOfItems", .{}) == 4, "the right-click menu has four commands"); - const title = objc.utf8(msg(id, msg(id, menu, "itemAtIndex:", .{@as(isize, 0)}), "title", .{})); - t.expect(std.mem.find(u8, title, first) != null, "and the first names the word under the pointer"); + }); + msg(void, page, "rightMouseDown:", .{click}); + const first_row = msg(id, window, "firstResponder", .{}); + const writing_card = msg(id, first_row, "superview", .{}); + t.expect(msg(usize, msg(id, writing_card, "subviews", .{}), "count", .{}) == 5, "the writing menu has four rows and the hidden Lab scroll view"); + t.expect(std.mem.find(u8, objc.utf8(msg(id, first_row, "title", .{})), first) != null, "the first row names the word under the pointer"); + const menu_key = struct { + fn send(code: u16, mods: usize, chars: []const u8) void { + const event = msg(id, objc.class("NSEvent"), "keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:", .{ + @as(usize, 10), NSPoint{}, mods, @as(f64, 0), msg(isize, window, "windowNumber", .{}), @as(id, null), str(chars), str(chars), false, code, + }); + if (!msg(bool, window, "performKeyEquivalent:", .{event})) + msg(void, msg(id, window, "firstResponder", .{}), "keyDown:", .{event}); + } + }; + menu_key.send(53, 0, ""); + t.expect(msg(id, window, "firstResponder", .{}) == page, "Escape restores editor focus"); + const selected = groupRange(gid).?; + select(selected); + t.expect(contextMenu(page, null, click) == null, "writing mode does not create a system menu"); + t.expect(std.mem.eql(u8, objc.utf8(msg(id, first_row, "title", .{})), "Alternatives for selection"), "a click inside a selection keeps it"); + menu_key.send(125, 0, ""); + t.expect(std.mem.eql(u8, objc.utf8(msg(id, msg(id, window, "firstResponder", .{}), "title", .{})), "AI alternatives for selection"), "the down arrow moves focus to the next action"); + menu_key.send(44, Mod.ctrl, "/"); + t.expect(msg(id, window, "firstResponder", .{}) == page and std.meta.eql(selection(), selected) and ghostIn(selected), "the popup shortcut ghosts the selected text and returns focus"); + msg(void, um, "undo", .{}); + _ = contextMenu(page, null, click); + menu_key.send(36, 0, "\r"); + t.expect(target == gid and msg(id, window, "firstResponder", .{}) == alts, "Return opens alternatives for the clicked group"); + _ = contextMenu(page, null, click); + menu_key.send(53, 0, ""); + t.expect(target == gid and msg(id, window, "firstResponder", .{}) == alts, "dismissing the popup leaves the alternatives panel and its focus alone"); + closePanel(); // Ghost and revive. (Each undo so far has had one command to undo: outside the run // loop nothing closes an undo group but undo itself.) @@ -2476,11 +2742,17 @@ fn selftest() void { reading = j; return j; } + fn key(code: u16, mods: usize) void { + const event = msg(id, objc.class("NSEvent"), "keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:", .{ + @as(usize, 10), NSPoint{}, mods, @as(f64, 0), msg(isize, window, "windowNumber", .{}), @as(id, null), str(""), str(""), false, code, + }); + msg(void, msg(id, window, "firstResponder", .{}), "keyDown:", .{event}); + } fn strength(pass: lab.Pass) void { - const item_ = objc.new("NSMenuItem"); - defer msg(void, item_, "release", .{}); - msg(void, item_, "setTag:", .{@as(isize, @intFromEnum(pass))}); - labPass(null, null, item_); + labMenu(null, null, null); + // Shift-Tab wraps from the guide around the trim buttons, strongest first. + for (0..10 - @intFromEnum(pass)) |_| key(48, Mod.shift); + key(36, 0); } fn ghostValue(at: usize) id { return if (runAt(key_ghost, at)) |run| run.value else null; @@ -2500,6 +2772,25 @@ fn selftest() void { const cut = "[{\"sentence\":1,\"shortened\":\"We need this today.\",\"importance\":5}]"; const trim_draft = "We really need this today. Keep my note."; load(trim_draft); + _ = msg(bool, window, "makeFirstResponder:", .{page}); + const write_menu = msg(id, msg(id, msg(id, msg(id, objc.class("NSApplication"), "sharedApplication", .{}), "mainMenu", .{}), "itemAtIndex:", .{@as(isize, 3)}), "submenu", .{}); + const next_item = msg(id, write_menu, "itemWithTitle:", .{str("Lab: Next")}); + t.expect(next_item != null and !validateMenuItem(null, null, next_item), "Lab review menu is disabled without a review"); + toggleTools(null, null, null); + labMenu(null, null, null); + t.expect(tools and msg(id, window, "firstResponder", .{}) != page, "Lab opens from read mode"); + stub.key(53, 0); + labMenu(null, null, null); + const guide_control = msg(id, window, "firstResponder", .{}); + t.expect(guide_control != page, "Lab focuses the guide first"); + stub.key(36, 0); + t.expect(msg(id, window, "firstResponder", .{}) != guide_control and reading == null, "Return opens the in-window guide without running a pass"); + stub.key(53, 0); + t.expect(msg(id, window, "firstResponder", .{}) == page, "Escape from the guide restores editor focus"); + labMenu(null, null, null); + const shield = msg(id, msg(id, window, "contentView", .{}), "hitTest:", .{NSPoint{ .x = 1, .y = 1 }}); + msg(void, shield, "mouseDown:", .{@as(id, null)}); + t.expect(msg(id, window, "firstResponder", .{}) == page, "An outside click dismisses Lab and restores focus"); // The test has no event loop to close undo groups between commands. msg(void, um, "setGroupsByEvent:", .{false}); select(.{ .location = 10, .length = 4 }); // manual ghost immediately after "really " @@ -2507,6 +2798,7 @@ fn selftest() void { const trim = stub.reply(.slight, cut); landed(trim); t.expect(trim.owner != null and stub.ghostValue(3) == trim.owner and stub.ghostValue(10) == yes, "Lab and adjacent manual ghosts have distinct ownership"); + t.expect(validateMenuItem(null, null, next_item), "Lab review menu is enabled for a review"); const saved_review = doc.parse(arena, snapshot(arena) catch unreachable) catch unreachable; t.expect(saved_review.ghosts.len == 2, "save captures Lab and manual ghosts"); @@ -2612,5 +2904,62 @@ fn selftest() void { removeShown(mixed); t.expect(groups.get(mixed).?.active == 0 and groups.get(mixed).?.variants.items.len == 2 and !msg(bool, alts, "isEditable", .{}), "a mixed ghost cannot be overwritten by flipping, removing, or typing a variant"); t.expect(std.mem.endsWith(u8, snapshot(arena) catch unreachable, "\n\necho eo end"), "a blocked swap leaves the original ghost intact"); + // Markdown changes display attributes without changing the draft or its annotations. + const raw_md = "π€ **bold _and italic_** `*code*` ~~cut~~\n__second__\n\\*literal*"; + const bold_at = doc.utf16Len("π€ **"); + const italic_at = doc.utf16Len("π€ **bold _"); + const code_at = doc.utf16Len("π€ **bold _and italic_** `"); + const cut_at = doc.utf16Len("π€ **bold _and italic_** `*code*` ~~"); + const second_at = doc.utf16Len("π€ **bold _and italic_** `*code*` ~~cut~~\n__"); + const md_style = struct { + fn at(key: id, i: usize) id { + return msg(id, storage, "attribute:atIndex:effectiveRange:", .{ key, i, @as(?*NSRange, null) }); + } + }; + const md_rec = doc.GroupRec{ .at = "π€ **".len, .variants = &.{ "bold", "strong" } }; + load(doc.serialize(arena, .{ .body = raw_md, .groups = &.{md_rec}, .ghosts = &.{.{ .at = "π€ **".len, .text = "bold" }} }) catch unreachable); + t.expect(md_style.at(NSFontAttributeName, bold_at - 1) == hidden and md_style.at(NSFontAttributeName, bold_at) == bold, "strong markup stays in storage while its delimiters hide"); + t.expect(md_style.at(NSFontAttributeName, italic_at) == bold_italic and md_style.at(NSFontAttributeName, code_at) == code_font and md_style.at(NSStrikethroughStyleAttributeName, cut_at) == markdown_strike, "nested emphasis, code and strike have distinct styling"); + t.expect(md_style.at(NSFontAttributeName, second_at) == bold and md_style.at(NSFontAttributeName, len() - 1) == font, "Markdown handles other paragraphs and leaves escaped delimiters literal"); + select(.{ .location = bold_at + 1 }); + t.expect(md_style.at(NSFontAttributeName, bold_at - 1) == font and selection().location == bold_at + 1, "moving inside inline markup reveals its source without moving the caret"); + const typed_attrs = msg(id, page, "typingAttributes", .{}); + t.expect(msg(id, typed_attrs, "objectForKey:", .{NSFontAttributeName}) == font and msg(id, typed_attrs, "objectForKey:", .{key_group}) != null and msg(id, typed_attrs, "objectForKey:", .{key_ghost}) == yes, "Markdown does not replace typing or metadata attributes"); + select(.{ .location = len() }); + t.expect(md_style.at(NSFontAttributeName, bold_at - 1) == hidden and !msg(bool, um, "canUndo", .{}), "leaving a span hides its markers without an Undo step"); + const saved_md = doc.parse(arena, snapshot(arena) catch unreachable) catch unreachable; + t.expect(std.mem.eql(u8, saved_md.body, raw_md) and saved_md.groups.len == 1 and saved_md.ghosts.len == 1, "save retains raw Markdown, group and ghost"); + const close_strong = doc.utf16Len("π€ **bold _and italic_"); + stub.beginEvent(); + insert(page, "", .{ .location = close_strong, .length = 2 }); + stub.endEvent(); + t.expect(md_style.at(NSFontAttributeName, bold_at) == font and md_style.at(NSFontAttributeName, italic_at) == italic and md_style.at(NSFontAttributeName, second_at - 2) == bold, "breaking a pair clears old styling without touching another paragraph"); + msg(void, um, "undo", .{}); + t.expect(std.mem.eql(u8, objc.utf8(string(page)), raw_md) and md_style.at(NSFontAttributeName, bold_at) == bold, "Undo restores both source and rendered formatting"); + msg(void, um, "redo", .{}); + t.expect(md_style.at(NSFontAttributeName, bold_at) == font, "Redo recalculates formatting instead of restoring a style operation"); + load("## Two\n###### Six"); + select(.{ .location = len() }); + t.expect(md_style.at(NSFontAttributeName, 0) == hidden and md_style.at(NSFontAttributeName, 7) == font, "the caret at the end of the last heading reveals just that heading's hashes"); + select(.{ .location = 5 }); + t.expect(md_style.at(NSFontAttributeName, 0) == font and md_style.at(NSFontAttributeName, 7) == hidden, "moving between heading titles switches the visible prefix"); + + // Fenced code: nothing in it is Markdown, and the fences show only with the caret in the block. + load("```zig\n# **raw**\n```\n**after**"); + select(.{ .location = len() }); + t.expect(md_style.at(NSFontAttributeName, 0) == hidden and md_style.at(NSFontAttributeName, 17) == hidden, "a code block's fences are out of sight while the caret is elsewhere"); + t.expect(md_style.at(NSFontAttributeName, 7) == code_font and md_style.at(NSFontAttributeName, 9) == code_font and md_style.at(NSFontAttributeName, 23) == bold, "what is fenced is code, hashes and stars and all, and what follows is not"); + select(.{ .location = 8 }); + t.expect(md_style.at(NSFontAttributeName, 0) == code_font and md_style.at(NSFontAttributeName, 17) == code_font, "the caret in the block shows both fences"); + msg(void, layout, "ensureLayoutForCharacterRange:", .{NSRange{ .length = len() }}); + stub.beginEvent(); + insert(page, "", .{ .length = 1 }); + stub.endEvent(); + t.expect(md_style.at(NSFontAttributeName, 10) == bold and md_style.at(NSFontAttributeName, 16) == hidden and md_style.at(NSFontAttributeName, 22) == code_font, "breaking a fence restyles all that follows: the old closing fence now opens"); + msg(void, layout, "ensureLayoutForCharacterRange:", .{NSRange{ .length = len() }}); + t.expect(msg(u16, layout, "CGGlyphAtIndex:", .{@as(usize, 22)}) == msg(u32, code_font, "glyphWithName:", .{str("a")}), "in the code font's own glyphs, not the ones laid out before"); + msg(void, um, "undo", .{}); + t.expect(md_style.at(NSFontAttributeName, 9) == code_font and md_style.at(NSFontAttributeName, 23) == bold, "and Undo puts the block back"); + t.expect(std.mem.eql(u8, snapshot(arena) catch unreachable, "```zig\n# **raw**\n```\n**after**"), "none of which is in the file"); std.debug.print("selftest ok\n", .{}); } |
