From 3792bf1bfac9dac4340aedacf1fea0b3a4aa33fb Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 14:05:35 +0100 Subject: [PATCH 01/27] fix: ordered lists count up from their first number (#61) An ordered item showed the number typed in the source, so `1.` `1.` `1.` read 1. 1. 1. and `5.` `8.` read 5. 8. The run walk that already found each list for the marker alignment is now the one place that decides the list, the displayed number (first item's number + position) and the hang (the widest displayed marker, so twelve `1.` items hang under "12. "). Two run rules join the existing ones, as on GitHub: the other delimiter (`.` vs `)`) starts a new list, and a line an item owns (after a hard break, at the margin) no longer ends the item's list. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/MarkdownBlockParser.swift | 40 +++- QuickMD/QuickMD/MarkdownRenderer.swift | 131 +++++++----- QuickMD/QuickMDTests/ListContentTests.swift | 194 ++++++++++++++++++ QuickMD/QuickMDTests/ParserTests.swift | 4 +- .../QuickMDTests/VerticalRhythmTests.swift | 5 +- 5 files changed, 314 insertions(+), 60 deletions(-) diff --git a/QuickMD/QuickMD/MarkdownBlockParser.swift b/QuickMD/QuickMD/MarkdownBlockParser.swift index 6c5a376..492e881 100644 --- a/QuickMD/QuickMD/MarkdownBlockParser.swift +++ b/QuickMD/QuickMD/MarkdownBlockParser.swift @@ -2086,19 +2086,25 @@ struct MarkdownBlockParser: Sendable { let blocks: [Int: Int] } - /// Stands in for a non-text block when the ordered-list hangs are worked + /// Stands in for a non-text block when the ordered lists are worked /// out: not blank, not a list item — so it continues a list exactly when /// its first line is indented under the list's items (a step's code /// block, a picture under an item), as a nested paragraph would. private static let blockStandIn = "\u{FFFC}" - /// Renders the text rows, every ordered item hanging under the widest - /// marker of ITS list (`MarkdownRenderer.widestOrderedPrefixes`), worked - /// out over the whole document: the rows' lines in order, each other - /// block standing in as one line with its indentation. Until 1.14.4 the - /// widest marker was each row's own, so a list cut into rows had two text - /// edges, and the steps of a list whose items hold code blocks each hung - /// under their own number ("1. " is narrower than "10. "). + /// Renders the text rows, every ordered item numbered within ITS list + /// and hanging under that list's widest marker + /// (`MarkdownRenderer.orderedMarkers`), worked out over the whole + /// document: the rows' lines in order, each other block standing in as + /// one line with its indentation. Until 1.14.4 the widest marker was each + /// row's own, so a list cut into rows had two text edges, and the steps + /// of a list whose items hold code blocks each hung under their own + /// number ("1. " is narrower than "10. "); until 1.16 each item showed + /// its source number (#61). + /// + /// A line an item owns (`owners.paragraphs`) tells the walk its owner's + /// level: a line after a hard break in an item sits at the margin and + /// must not end (and so restart) the item's list. /// /// The same pass lines a list item's own blocks up with the item's text /// (`owners`, from `ListNesting`): a paragraph of the item hangs where the @@ -2129,11 +2135,23 @@ struct MarkdownBlockParser: Sendable { lines.append(String(first.prefix(while: { $0 == " " || $0 == "\t" })) + Self.blockStandIn) } } - let hangs = renderer.widestOrderedPrefixes(lines) + // The level of the item that owns each line (by its place in `lines`). + var ownerLevels: [Int?] = [] + if !owners.paragraphs.isEmpty { + ownerLevels = [Int?](repeating: nil, count: lines.count) + for (row, start) in zip(pending, starts) { + for (offset, source) in row.sources.enumerated() { + guard let owner = owners.paragraphs[source], let k = itemLines[owner] else { continue } + ownerLevels[start + offset] = MarkdownRenderer.listLevel( + for: lines[k].prefix(while: { $0 == " " || $0 == "\t" })) + } + } + } + let markers = renderer.orderedMarkers(lines, ownerLevels: ownerLevels) /// The text column of the item on original line `itemLine`. func column(ofItem itemLine: Int) -> MarkdownRenderer.ListItemColumn? { guard let k = itemLines[itemLine] else { return nil } - return renderer.listItemColumn(itemLine: lines[k], hang: hangs[k]) + return renderer.listItemColumn(itemLine: lines[k], hang: markers[k]?.hang) } for (row, start) in zip(pending, starts) { let columns = owners.paragraphs.isEmpty ? [] : row.sources.map { source in @@ -2141,7 +2159,7 @@ struct MarkdownBlockParser: Sendable { } blocks[row.position] = .text(index: row.index, renderer.render(joined: row.lines, - hangs: Array(hangs[start..<(start + row.lines.count)]), + markers: Array(markers[start..<(start + row.lines.count)]), itemColumns: columns), sourceLine: row.sourceLine, joinsPrevious: row.joinsPrevious) } diff --git a/QuickMD/QuickMD/MarkdownRenderer.swift b/QuickMD/QuickMD/MarkdownRenderer.swift index 2234744..f220305 100644 --- a/QuickMD/QuickMD/MarkdownRenderer.swift +++ b/QuickMD/QuickMD/MarkdownRenderer.swift @@ -183,48 +183,67 @@ struct MarkdownRenderer: Sendable { func render(_ markdown: String) -> AttributedString { let lines = Self.joinSoftBreaks(markdown.components(separatedBy: "\n")) - // Ordered items of one list line up on the WIDEST marker of that list: - // the body font is not monospaced, so "1. " and "10. " have different - // widths and each item's text would otherwise start at a different x. - // The run is known before any rendering, so the widest prefix is too. - return render(joined: lines, hangs: widestOrderedPrefixes(lines)) + // Which ordered list each item is in decides its number (the list + // counts up from its first item) and its hang (ordered items of one + // list line up on the WIDEST displayed marker: the body font is not + // monospaced, so "9. " and "10. " differ). The runs are known before + // any rendering, so both are too. + return render(joined: lines, markers: orderedMarkers(lines)) } /// Renders lines that are ALREADY soft-break joined (`joinSoftBreaks`), - /// each ordered item hanging under `hangs[i]` (`widestOrderedPrefixes`). + /// each ordered item drawn with `markers[i]` (`orderedMarkers`). /// - /// The parser's entry point: it joins and computes the hangs over a whole - /// text run, then renders the run one block at a time — so the items of a - /// loose list, one row each, still share their list's widest marker. + /// The parser's entry point: it joins and computes the markers over a + /// whole text run, then renders the run one block at a time — so the + /// items of a loose list, one row each, still count on and share their + /// list's widest marker. /// /// `itemColumns[i]` (when given) is the list item that owns line `i` — a /// paragraph of the item after its first (`ListNesting`): that line is /// drawn at the item's text column (`renderItemParagraph`). - func render(joined lines: [String], hangs: [String?], itemColumns: [ListItemColumn?] = []) -> AttributedString { + func render(joined lines: [String], markers: [OrderedMarker?], itemColumns: [ListItemColumn?] = []) -> AttributedString { var result = AttributedString() for (index, line) in lines.enumerated() { if index < itemColumns.count, let column = itemColumns[index] { result.append(renderItemParagraph(line, column: column)) } else { - result.append(renderLine(line, hangingPrefix: index < hangs.count ? hangs[index] : nil)) + result.append(renderLine(line, marker: index < markers.count ? markers[index] : nil)) } result.append(AttributedString("\n")) } return result } - /// For every line, the widest marker prefix (indent spaces + "N. ") of the - /// ordered list the line belongs to — `nil` for lines that are not ordered - /// items. "Widest" is measured in the body font, not counted in characters: - /// "9. " is wider than "1. " although both are three characters. + /// What an ordered item shows: its marker as drawn (indent spaces + "N. ") + /// and the widest drawn marker of its list (what its text hangs under). + struct OrderedMarker: Equatable { + let prefix: String + let hang: String + } + + /// For every line, the marker it is drawn with when it is an ordered + /// item — `nil` for every other line. This walk is the ONE place that + /// decides which list an ordered item is in, and from that its number and + /// its hang (#61; until 1.16 the number was the source's and only the + /// hang came from here). /// - /// A list is a run of ordered items at one indent level. Blank lines and - /// deeper-indented lines between its items (a loose list, a nested list, a - /// continuation paragraph) do not end it; any other line does. Nested - /// ordered lists form their own runs. - func widestOrderedPrefixes(_ lines: [String]) -> [String?] { + /// A list is a run of ordered items at one level with one delimiter + /// (`.` or `)`; the other one starts a new list, as on GitHub). It + /// counts up from its first item's number. Blank lines, deeper-indented + /// lines (a loose list, a nested list, an item's own blocks) and lines an + /// item at the run's level or deeper owns (`ownerLevels[i]`: the + /// `listLevel` of the item that owns line `i` — a line after a hard break + /// sits at the margin but is still that item's) do not end it; a + /// shallower item or any other line does. Nested ordered lists form + /// their own runs. + /// + /// The hang is the widest DISPLAYED marker, measured in the body font, + /// not counted in characters: "9. " is wider than "1. " although both + /// are three characters, and twelve `1.` items end in "12. ". + func orderedMarkers(_ lines: [String], ownerLevels: [Int?] = []) -> [OrderedMarker?] { let items = lines.map(Self.orderedItem) - var out = [String?](repeating: nil, count: lines.count) + var out = [OrderedMarker?](repeating: nil, count: lines.count) var widths: [String: CGFloat] = [:] func measured(_ prefix: String) -> CGFloat { if let w = widths[prefix] { return w } @@ -235,33 +254,51 @@ struct MarkdownRenderer: Sendable { for start in lines.indices { guard out[start] == nil, let first = items[start] else { continue } var members = [start] - var widest = first.prefix var i = start + 1 while i < lines.count { if let item = items[i] { if item.level < first.level { break } if item.level == first.level { + if item.delimiter != first.delimiter { break } members.append(i) - if measured(item.prefix) > measured(widest) { widest = item.prefix } } - } else if !Self.lineContinuesList(lines[i], atLevel: first.level) { + } else if !Self.lineContinuesList(lines[i], atLevel: first.level), + (i < ownerLevels.count ? ownerLevels[i] ?? -1 : -1) < first.level { break } i += 1 } - for m in members { out[m] = widest } + let indent = Self.indentSpaces(first.level) + let prefixes = members.indices.map { indent + "\(first.number + $0). " } + var widest = prefixes[0] + for prefix in prefixes.dropFirst() where measured(prefix) > measured(widest) { widest = prefix } + for (m, prefix) in zip(members, prefixes) { out[m] = OrderedMarker(prefix: prefix, hang: widest) } } return out } - /// `(prefix, level)` of an ordered list item, prefix exactly as - /// `renderListItem` will emit it (indent spaces + normalised number). - private static func orderedItem(_ line: String) -> (prefix: String, level: Int)? { + /// An ordered list item line as the source has it: its level, its number + /// (leading zeros dropped), its delimiter and how many characters of the + /// trimmed line its marker takes (digits, delimiter, one white space). + /// The ONE place a source number is read. + private struct OrderedItem { + let level: Int + let number: Int + let delimiter: Character + let markerLength: Int + + /// The marker the item draws without list context: its own number. + var ownPrefix: String { MarkdownRenderer.indentSpaces(level) + "\(number). " } + } + + private static func orderedItem(_ line: String) -> OrderedItem? { let trimmed = markerLine(line) - guard trimmed.range(of: Self.orderedMarkerPattern, options: .regularExpression) != nil else { return nil } - let level = listLevel(for: line.prefix(while: { $0 == " " || $0 == "\t" })) - let number = Int(trimmed.prefix(while: { $0.isNumber })) ?? 1 - return (indentSpaces(level) + "\(number). ", level) + guard let match = trimmed.range(of: Self.orderedMarkerPattern, options: .regularExpression) else { return nil } + let digits = trimmed.prefix(while: { $0.isNumber }) + return OrderedItem(level: listLevel(for: line.prefix(while: { $0 == " " || $0 == "\t" })), + number: Int(digits) ?? 1, + delimiter: trimmed[digits.endIndex], + markerLength: trimmed.distance(from: trimmed.startIndex, to: match.upperBound)) } /// A blank line or a line indented deeper than the list's own items keeps @@ -440,7 +477,10 @@ struct MarkdownRenderer: Sendable { // MARK: - Line Rendering - private func renderLine(_ line: String, hangingPrefix: String? = nil) -> AttributedString { + /// `marker`: what an ordered item line draws (`orderedMarkers`); nil + /// for a line rendered without list context, which draws its own + /// number and hangs under itself. + private func renderLine(_ line: String, marker: OrderedMarker? = nil) -> AttributedString { let trimmed = Self.markerLine(line) // Header - extract hash count from regex group, not space position @@ -467,16 +507,13 @@ struct MarkdownRenderer: Sendable { if let bullet = ["- ", "* ", "+ "].first(where: { trimmed.hasPrefix($0) }) { let level = Self.listLevel(for: line.prefix(while: { $0 == " " || $0 == "\t" })) let content = String(trimmed.dropFirst(bullet.count)) - return renderListItem(content, level: level, ordered: false, number: 0) + return renderListItem(content, prefix: Self.indentSpaces(level) + "• ") } // Ordered list - if let match = trimmed.range(of: Self.orderedMarkerPattern, options: .regularExpression) { - let level = Self.listLevel(for: line.prefix(while: { $0 == " " || $0 == "\t" })) - let number = Int(trimmed.prefix(while: { $0.isNumber })) ?? 1 - let content = String(trimmed[match.upperBound...]) - return renderListItem(content, level: level, ordered: true, number: number, - hangingPrefix: hangingPrefix) + if let item = Self.orderedItem(line) { + let content = String(trimmed.dropFirst(item.markerLength)) + return renderListItem(content, prefix: marker?.prefix ?? item.ownPrefix, hangingUnder: marker?.hang) } // Empty line @@ -732,9 +769,9 @@ struct MarkdownRenderer: Sendable { return min(columns / 2, 8) } - private func renderListItem(_ text: String, level: Int, ordered: Bool, number: Int, - hangingPrefix: String? = nil) -> AttributedString { - let prefix = Self.indentSpaces(level) + (ordered ? "\(number). " : "• ") + /// `prefix`: the indent spaces + marker the item draws; `hang`: the + /// widest marker of its ordered list (nil: it hangs under itself). + private func renderListItem(_ text: String, prefix: String, hangingUnder hang: String? = nil) -> AttributedString { var attr = AttributedString(prefix) attr.setDualFont(size: scaled(14), fonts: theme.fonts) attr.setDualForeground(theme.textColor) @@ -743,7 +780,7 @@ struct MarkdownRenderer: Sendable { // push their own, narrower marker right by the difference, so the markers // are right-aligned and every item's text starts at the same x — on the // first line and on wrapped lines alike. - let hangWidth = width(of: hangingPrefix ?? prefix) + let hangWidth = width(of: hang ?? prefix) applyHangingIndent(&attr, indent: scaled(Self.listGutter), firstLineLead: max(0, hangWidth - width(of: prefix)), hangWidth: hangWidth) return attr @@ -759,7 +796,9 @@ struct MarkdownRenderer: Sendable { } /// The text column of the item `itemLine` renders (`renderLine`), hanging - /// under `hang` when it is an ordered item (`widestOrderedPrefixes`). + /// under `hang` when it is an ordered item (`OrderedMarker.hang` from + /// `orderedMarkers`; nil: under its own source marker, as `renderLine` + /// draws it without list context). /// Nil for a line that is not an item. func listItemColumn(itemLine: String, hang: String?) -> ListItemColumn? { let indent = itemLine.prefix(while: { $0 == " " || $0 == "\t" }) @@ -768,7 +807,7 @@ struct MarkdownRenderer: Sendable { if let task = parseTaskList(itemLine) { prefix = Self.indentSpaces(task.level) + (task.checked ? "☑ " : "☐ ") } else if let ordered = Self.orderedItem(itemLine) { - prefix = hang ?? ordered.prefix + prefix = hang ?? ordered.ownPrefix } else if Self.isListItem(itemLine) { prefix = Self.indentSpaces(level) + "• " } else { diff --git a/QuickMD/QuickMDTests/ListContentTests.swift b/QuickMD/QuickMDTests/ListContentTests.swift index ded2ec0..2d2e1b5 100644 --- a/QuickMD/QuickMDTests/ListContentTests.swift +++ b/QuickMD/QuickMDTests/ListContentTests.swift @@ -436,6 +436,200 @@ final class ListContentTests: XCTestCase { XCTAssertEqual(MarkdownRenderer.printedListIndent(0), 0) } + // MARK: - Numbering (#61): the first item's number starts the list + + /// Every list item's displayed marker, in document order, read from the + /// rendered strings: the number of an ordered item, `•` for a bullet, + /// `☐`/`☑` for a task. A deeper level opens `[`, a shallower one closes + /// `]` — `1 [1 2] 2` is two items with two nested under the first. + /// Brackets count distinct levels as seen (a stack), so a 4-space nest + /// that the 2-column model draws two levels deeper is still one `[`. + /// Lists that follow each other ("‖" in the spec) simply read on. + private func markers(_ markdown: String) throws -> String { + var out: [String] = [] + var levels: [Int] = [] + for block in parse(markdown) { + for paragraph in try paragraphs(block) where paragraph.style != nil { + let text = paragraph.text + let spaces = text.prefix(while: { $0 == " " }) + let rest = text.dropFirst(spaces.count) + let marker: String + if let first = rest.first, "•☐☑".contains(first) { + marker = String(first) + } else if let dot = rest.firstIndex(of: "."), !rest[.. level, levels.count > 1 { out.append("]"); levels.removeLast() } + if let top = levels.last, level > top { out.append("["); levels.append(level) } + if levels.isEmpty { levels.append(level) } + out.append(marker) + } + } + out.append(contentsOf: repeatElement("]", count: max(0, levels.count - 1))) + return out.joined(separator: " ") + .replacingOccurrences(of: "[ ", with: "[").replacingOccurrences(of: " ]", with: "]") + } + + /// The text x (`headIndent`) of every ordered item paragraph, in order. + private func orderedHangs(_ markdown: String) throws -> [CGFloat] { + try parse(markdown).flatMap { try paragraphs($0) } + .filter { $0.style != nil && $0.text.drop(while: { $0 == " " }).first?.isNumber == true } + .map { try XCTUnwrap($0.style?.headIndent) } + } + + /// GitHub (`gh api markdown -f mode=gfm`, 2026-11-17): `
    ` with + /// `start` = the first item's number and every later `
  1. ` one more. + func testOrderedItemsCountUpFromTheFirstNumber() throws { + //
    1. One
    2. Two
    3. Three
    + XCTAssertEqual(try markers("1. One\n1. Two\n1. Three"), "1 2 3") + //
    1. new list
    2. starts here
    (the #61 report) + XCTAssertEqual(try markers(" 5. new list\n 8. starts here"), "5 6") + //
    1. zero
    2. again
    3. x
    + XCTAssertEqual(try markers("0. zero\n0. again\n5. x"), "0 1 2") + //
    1. c
    2. b
    3. a
    + XCTAssertEqual(try markers("3. c\n2. b\n1. a"), "3 4 5") + //
    1. a
    2. b
    3. c
    + XCTAssertEqual(try markers("10. a\n1. b\n1. c"), "10 11 12") + //
    1. a
    2. b
    — leading zeros drop + XCTAssertEqual(try markers("007. a\n1. b"), "7 8") + //
    1. a
    2. b
    + XCTAssertEqual(try markers("999999999. a\n1. b"), "999999999 1000000000") + //
    1. a
    2. b
    3. c
    — `)` is drawn as `.` + XCTAssertEqual(try markers("1) a\n1) b\n1) c"), "1 2 3") + XCTAssertEqual(try parse("1) a\n1) b").flatMap { try paragraphs($0) }.map(\.text), ["1. a", "2. b"]) + //
    1. Intro
    2. The year
    + XCTAssertEqual(try markers("1. Intro\n1986. The year"), "1 2") + } + + /// D3 (a): the other delimiter starts a new list. + /// GitHub: `
    1. a
    2. b
    1. c
    2. d
    ` + /// and `
    1. a
    2. b
    1. c
    2. d
    `. + func testTheOtherDelimiterStartsANewList() throws { + XCTAssertEqual(try markers("1. a\n2. b\n3) c\n4) d"), "1 2 3 4") + XCTAssertEqual(try markers("1. a\n1. b\n1) c\n1) d"), "1 2 1 2") + // Its own hang too: "8. 9. 10." hang under "10. ", the new "1." under itself. + let hangs = try orderedHangs("8. a\n8. b\n8. c\n1) d") + XCTAssertEqual(hangs.count, 4) + XCTAssertEqual(Set(hangs[0..<3]).count, 1, "\(hangs)") + XCTAssertLessThan(hangs[3], hangs[0], "a new list: \(hangs)") + } + + /// Nested lists count on their own. + func testNestedListsCountOnTheirOwn() throws { + //
    1. a
      1. a1
      2. a2
    2. b
      1. b1
    + XCTAssertEqual(try markers("1. a\n 1. a1\n 1. a2\n1. b\n 1. b1"), "1 [1 2] 2 [1]") + //
    1. a
      1. x
      2. y
    2. b
    + XCTAssertEqual(try markers("1. a\n 1. x\n 1. y\n1. b"), "1 [1 2] 2") + //
    1. a
      1. x
        1. p
        2. q
      2. y
    2. b
    + XCTAssertEqual(try markers("1. a\n 1. x\n 1. p\n 1. q\n 1. y\n1. b"), "1 [1 [1 2] 2] 2") + } + + /// What ends a list restarts the count; what an item holds does not. + func testWhatEndsAListAndWhatKeepsItGoing() throws { + //
    1. a
    2. b

    para

    1. c
    2. d
    + XCTAssertEqual(try markers("1. a\n1. b\n\npara\n\n1. c\n1. d"), "1 2 1 2") + //
      …

    para

      …
    + XCTAssertEqual(try markers("8. a\n8. b\n\npara\n\n8. c\n8. d"), "8 9 8 9") + //
    1. a
    • x
    1. b
    + XCTAssertEqual(try markers("1. a\n- x\n1. b"), "1 • 1") + //
    1. a

    2. b

    3. c

    + XCTAssertEqual(try markers("1. a\n\n1. b\n\n1. c"), "1 2 3") + //
    1. a

    2. b

    + XCTAssertEqual(try markers("1. a\n\n\n1. b"), "1 2") + //
    1. Step one

      code
    2. Step two

      …
    3. Step three

    + XCTAssertEqual(try markers("1. Step one\n\n code\n\n1. Step two\n\n more\n\n1. Step three"), "1 2 3") + //
    1. a

      code
    2. b

    + XCTAssertEqual(try markers("1. a\n\n ```\n code\n ```\n\n1. b"), "1 2") + //
    1. a
    code
    1. b
    + XCTAssertEqual(try markers("1. a\n\n```\ncode\n```\n\n1. b"), "1 1") + // heading / rule / table / image / quote at the margin: `
    1. a
    …
    1. b
    ` + for between in ["# H", "---", "| h |\n|---|\n| c |", "![x](y.png)", "> q"] { + XCTAssertEqual(try markers("1. a\n\n\(between)\n\n1. b"), "1 1", between) + } + //
    1. a

      q

    2. b

    + XCTAssertEqual(try markers("1. a\n\n > q\n\n1. b"), "1 2") + //
    1. a

      para

      • x
    2. b

    + XCTAssertEqual(try markers("1. a\n\n para\n\n - x\n\n1. b"), "1 [•] 2") + //
    1. a
      lazy
    2. b
    + XCTAssertEqual(try markers("1. a\nlazy\n1. b"), "1 2") + // ParserTests' picture case: `10. ten` after an item-owned picture is item 3. + XCTAssertEqual(try markers("1. one\n2. two\n\n ![b](b.png)\n\n10. ten"), "1 2 3") + } + + /// D3 (b): a line after a hard break in an item is the item's even at + /// the margin, so the list goes on — number and hang. + /// GitHub: `
    1. a
      more
    2. b
    `. + func testALineAfterAHardBreakKeepsTheListGoing() throws { + XCTAssertEqual(try markers("1. a \nmore\n1. b"), "1 2") + XCTAssertEqual(try markers("1. a\\\nmore\n1. b"), "1 2") + let hangs = try orderedHangs("9. a \nmore\n9. b") + XCTAssertEqual(try markers("9. a \nmore\n9. b"), "9 10") + XCTAssertEqual(hangs.count, 2) + XCTAssertEqual(hangs[0], hangs[1], accuracy: 0.01, "one list hangs under \"10. \"") + // Nested: the line is the nested item's, both levels go on. + XCTAssertEqual(try markers("1. a\n 1. x \nmore\n 1. y\n1. b"), "1 [1 2] 2") + } + + /// A numbered line after paragraph text is still text unless it is 1. + /// GitHub: `

    text
    2. b
    3. c

    ` and `

    text

    1. a
    2. b
    `. + func testParagraphTextBeforeANumberedLine() throws { + XCTAssertEqual(shape(parse("text\n2. b\n3. c")), ["T:text 2. b 3. c"]) + XCTAssertEqual(try markers("text\n1. a\n1. b"), "1 2") + XCTAssertEqual(shape(parse("text\n1. a\n1. b")), ["T:text", "T:1. a\n2. b"]) + } + + /// D4: the hang is the widest DISPLAYED marker. Twelve `1.` items show + /// 1 … 12 and all hang under "12. ". + func testTwelveOnesShareOneTextEdge() throws { + let markdown = (1...12).map { "1. item \($0)" }.joined(separator: "\n") + XCTAssertEqual(try markers(markdown), (1...12).map(String.init).joined(separator: " ")) + let hangs = try orderedHangs(markdown) + XCTAssertEqual(hangs.count, 12) + XCTAssertEqual(Set(hangs).count, 1, "\(hangs)") + // The text edge is the gutter plus the widest of the DRAWN markers + // "1. " … "12. " (digits are proportional: not always "12. "). + func width(_ s: String) -> CGFloat { + (s as NSString).size(withAttributes: [.font: theme.fonts.appKit(size: 14)]).width + } + let widest = (1...12).map { width("\($0). ") }.max()! + let single = try orderedHangs("1. a")[0] // gutter + "1. " + XCTAssertEqual(hangs[0] - single, widest - width("1. "), accuracy: 0.01) + } + + /// A loose list longer than a text row (`textChunkLineLimit`): the count + /// goes on across the rows. And 5 000 items: the numbers, not the clock. + func testALongListCountsAcrossRows() throws { + let loose = (1...40).map { "1. item \($0)" }.joined(separator: "\n\n") + XCTAssertEqual(try markers(loose), (1...40).map(String.init).joined(separator: " ")) + let long = String(repeating: "1. item\n", count: 5_000) + XCTAssertEqual(try markers(long), (1...5_000).map(String.init).joined(separator: " ")) + } + + /// Kept deviations from GitHub (the pre-existing nesting model: a level + /// is 2 columns; quotes, alerts and footnotes draw list lines literally). + func testKnownDeviationsFromGitHub() throws { + // GitHub 1 2 3 (`
    1. a
    2. b
    3. c
    `); QuickMD nests at 2 columns. + XCTAssertEqual(try markers("1. a\n 1. b\n 1. c"), "1 2 [1]") + // GitHub 1 2 3 4; QuickMD draws 2 columns under `1.` nested, as their own list. + XCTAssertEqual(try markers("1. a\n 1. b\n 1. c\n1. d"), "1 [1 2] 2") + // GitHub `
    1. a
      5. x
      5. y
    2. b
    `; QuickMD nests them. + XCTAssertEqual(try markers("2. a\n 5. x\n 5. y\n3. b"), "2 [5 6] 3") + // GitHub draws checkboxes (`
  2. a
  3. …
  4. c
  5. `); + // QuickMD's task items are bullets only, so these stay ordered items with literal text. + let task = try parse("1. [ ] a\n1. [x] b\n1. c").flatMap { try paragraphs($0) }.map(\.text) + XCTAssertEqual(task, ["1. [ ] a", "2. [x] b", "3. c"]) + // GitHub `
      …`; QuickMD keeps a quote's lines literal. + guard case .blockquote(let quote, _) = try XCTUnwrap(parse("> 7. a\n> 7. b").first).content + else { return XCTFail("quote") } + let shown = String(MarkdownRenderer(theme: theme).renderQuotedBody(quote).characters) + XCTAssertEqual(shown.components(separatedBy: "7. ").count - 1, 2, shown) + XCTAssertFalse(shown.contains("8."), shown) + } + // MARK: - Content column func testContentColumnOfAnItem() { diff --git a/QuickMD/QuickMDTests/ParserTests.swift b/QuickMD/QuickMDTests/ParserTests.swift index 9b6f37e..6dfdd82 100644 --- a/QuickMD/QuickMDTests/ParserTests.swift +++ b/QuickMD/QuickMDTests/ParserTests.swift @@ -498,7 +498,9 @@ final class ParserTests: XCTestCase { let linkedHangs = hangs(linked) XCTAssertEqual(linkedHangs.count, 2) XCTAssertEqual(linkedHangs, hangs(plain), "a linked image stands in like a plain image") - XCTAssertEqual(linkedHangs[0], linkedHangs[1], accuracy: 0.01, "one list: 1. and 10. share the widest hang") + XCTAssertEqual(linkedHangs[0], linkedHangs[1], accuracy: 0.01, "one list: its items share the widest hang") + // One list, so `10. ten` is its item 3 (#61). GitHub: `
      1. one

      2. two

      3. ten

      `. + XCTAssertEqual(parse(linked).compactMap(plainText).last, "3. ten") let split = hangs("1. one\n2. two\n\n[![b](b.png)](https://x)\n\n10. ten") XCTAssertNotEqual(split[0], split[1], "control: an unindented picture ends the list") diff --git a/QuickMD/QuickMDTests/VerticalRhythmTests.swift b/QuickMD/QuickMDTests/VerticalRhythmTests.swift index 6d2b8d5..ae8b317 100644 --- a/QuickMD/QuickMDTests/VerticalRhythmTests.swift +++ b/QuickMD/QuickMDTests/VerticalRhythmTests.swift @@ -168,8 +168,9 @@ final class VerticalRhythmTests: XCTestCase { // delimiter (drawn `n.`, as GitHub draws both). XCTAssertEqual(parse("Text.\n\n3. third\n4. fourth").count, 2) XCTAssertTrue(plain(parse("1984) A year")[0]).hasPrefix("1984. A year"), plain(parse("1984) A year")[0])) - // Inside a list, an item of any number is the next item. - XCTAssertTrue(plain(parse("1. one\n1984. two")[0]).contains("\n1984. two")) + // Inside a list, an item of any number is the next item — numbered + // as the next one (#61). GitHub: `
      1. one
      2. two
      `. + XCTAssertTrue(plain(parse("1. one\n1984. two")[0]).contains("\n2. two"), plain(parse("1. one\n1984. two")[0])) } // MARK: - Headings From e5ae6426b3f34c46b7742b66ae1972179db03612 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 14:07:01 +0100 Subject: [PATCH 02/27] feat: folder listing, folder store and the chooser's folder grant (#62) FolderListing scans a folder for Markdown files (md, markdown, mdown, mkd, any case): recursive to depth 8, at most 2 000 files, skipping hidden items, packages and node_modules, never following symbolic links; grouped by folder in Finder order. MarkdownFileKind is the one Markdown predicate. FolderBrowserStore holds the one open folder: persisted under openFolderPath, restored at launch (forgotten silently when gone or not restorable), watched by one FSEventStream and re-scanned on change. In the sandbox the folder chosen in Open Folder is a grant recorded by FolderAccessBroker.registerUserChosenFolder (bookmark, access, coverage, folderAccessGranted); unsandboxed nothing is registered. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD.xcodeproj/project.pbxproj | 20 ++ QuickMD/QuickMD/FolderAccessBroker.swift | 17 ++ QuickMD/QuickMD/FolderBrowserStore.swift | 176 +++++++++++++++ QuickMD/QuickMD/FolderListing.swift | 145 ++++++++++++ QuickMD/QuickMD/SandboxAccessManager.swift | 10 + .../FolderAccessBrokerTests.swift | 41 +++- .../FolderBrowserStoreTests.swift | 210 ++++++++++++++++++ QuickMD/QuickMDTests/FolderListingTests.swift | 130 +++++++++++ 8 files changed, 748 insertions(+), 1 deletion(-) create mode 100644 QuickMD/QuickMD/FolderBrowserStore.swift create mode 100644 QuickMD/QuickMD/FolderListing.swift create mode 100644 QuickMD/QuickMDTests/FolderBrowserStoreTests.swift create mode 100644 QuickMD/QuickMDTests/FolderListingTests.swift diff --git a/QuickMD/QuickMD.xcodeproj/project.pbxproj b/QuickMD/QuickMD.xcodeproj/project.pbxproj index 1803afd..fbe491a 100644 --- a/QuickMD/QuickMD.xcodeproj/project.pbxproj +++ b/QuickMD/QuickMD.xcodeproj/project.pbxproj @@ -156,6 +156,12 @@ A1B2C3D401000466 /* FolderAccessBroker.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000466 /* FolderAccessBroker.swift */; }; A1B2C3D401000467 /* FolderAccessBroker.swift in Sources (Tests) */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000466 /* FolderAccessBroker.swift */; }; A1B2C3D401000468 /* FolderAccessBrokerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000468 /* FolderAccessBrokerTests.swift */; }; + F62A000001000001 /* FolderListing.swift in Sources */ = {isa = PBXBuildFile; fileRef = F62A000000000001 /* FolderListing.swift */; }; + F62A000001000002 /* FolderListing.swift in Sources (Tests) */ = {isa = PBXBuildFile; fileRef = F62A000000000001 /* FolderListing.swift */; }; + F62A000001000003 /* FolderBrowserStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = F62A000000000003 /* FolderBrowserStore.swift */; }; + F62A000001000004 /* FolderBrowserStore.swift in Sources (Tests) */ = {isa = PBXBuildFile; fileRef = F62A000000000003 /* FolderBrowserStore.swift */; }; + F62A000001000005 /* FolderListingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F62A000000000005 /* FolderListingTests.swift */; }; + F62A000001000006 /* FolderBrowserStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F62A000000000006 /* FolderBrowserStoreTests.swift */; }; A1B2C3D401000400 /* TableRulesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000400 /* TableRulesTests.swift */; }; A1B2C3D4010004A1 /* FootnoteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000004A0 /* FootnoteTests.swift */; }; A1B2C3D40100006B /* BlockHeightMeasurer.swift in Sources (Tests) */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000069 /* BlockHeightMeasurer.swift */; }; @@ -249,6 +255,10 @@ A1B2C3D400000465 /* LocalLinkSafetyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalLinkSafetyTests.swift; sourceTree = ""; }; A1B2C3D400000466 /* FolderAccessBroker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderAccessBroker.swift; sourceTree = ""; }; A1B2C3D400000468 /* FolderAccessBrokerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderAccessBrokerTests.swift; sourceTree = ""; }; + F62A000000000001 /* FolderListing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderListing.swift; sourceTree = ""; }; + F62A000000000003 /* FolderBrowserStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderBrowserStore.swift; sourceTree = ""; }; + F62A000000000005 /* FolderListingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderListingTests.swift; sourceTree = ""; }; + F62A000000000006 /* FolderBrowserStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderBrowserStoreTests.swift; sourceTree = ""; }; A1B2C3D400000400 /* TableRulesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRulesTests.swift; sourceTree = ""; }; A1B2C3D4000004A0 /* FootnoteTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FootnoteTests.swift; sourceTree = ""; }; A1B2C3D40000006C /* VirtualBlockList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VirtualBlockList.swift; sourceTree = ""; }; @@ -436,6 +446,8 @@ A1B2C3D400000462 /* ImageRowTests.swift */, A1B2C3D400000465 /* LocalLinkSafetyTests.swift */, A1B2C3D400000468 /* FolderAccessBrokerTests.swift */, + F62A000000000005 /* FolderListingTests.swift */, + F62A000000000006 /* FolderBrowserStoreTests.swift */, A1B2C3D400000400 /* TableRulesTests.swift */, A1B2C3D4000004E1 /* SideBySideTests.swift */, A1B2C3D400000421 /* ListContentTests.swift */, @@ -490,6 +502,8 @@ A1B2C3D400000460 /* ImageRowLayout.swift */, A1B2C3D400000463 /* LocalLinkSafety.swift */, A1B2C3D400000466 /* FolderAccessBroker.swift */, + F62A000000000001 /* FolderListing.swift */, + F62A000000000003 /* FolderBrowserStore.swift */, A1B2C3D4000004E0 /* SideBySide.swift */, A1B2C3D400000420 /* ListNesting.swift */, A1B2C3D400000301 /* ReferenceLinks.swift */, @@ -801,6 +815,8 @@ A1B2C3D401000460 /* ImageRowLayout.swift in Sources */, A1B2C3D401000463 /* LocalLinkSafety.swift in Sources */, A1B2C3D401000466 /* FolderAccessBroker.swift in Sources */, + F62A000001000001 /* FolderListing.swift in Sources */, + F62A000001000003 /* FolderBrowserStore.swift in Sources */, A1B2C3D4010004E0 /* SideBySide.swift in Sources */, A1B2C3D401000420 /* ListNesting.swift in Sources */, A1B2C3D401000301 /* ReferenceLinks.swift in Sources */, @@ -886,6 +902,8 @@ A1B2C3D401000462 /* ImageRowTests.swift in Sources */, A1B2C3D401000465 /* LocalLinkSafetyTests.swift in Sources */, A1B2C3D401000468 /* FolderAccessBrokerTests.swift in Sources */, + F62A000001000005 /* FolderListingTests.swift in Sources */, + F62A000001000006 /* FolderBrowserStoreTests.swift in Sources */, A1B2C3D401000400 /* TableRulesTests.swift in Sources */, A1B2C3D4010004E2 /* SideBySideTests.swift in Sources */, A1B2C3D401000422 /* ListContentTests.swift in Sources */, @@ -905,6 +923,8 @@ A1B2C3D401000461 /* ImageRowLayout.swift in Sources (Tests) */, A1B2C3D401000464 /* LocalLinkSafety.swift in Sources (Tests) */, A1B2C3D401000467 /* FolderAccessBroker.swift in Sources (Tests) */, + F62A000001000002 /* FolderListing.swift in Sources (Tests) */, + F62A000001000004 /* FolderBrowserStore.swift in Sources (Tests) */, A1B2C3D4010004E1 /* SideBySide.swift in Sources (Tests) */, A1B2C3D401000421 /* ListNesting.swift in Sources (Tests) */, A1B2C3D401000302 /* ReferenceLinks.swift in Sources (Tests) */, diff --git a/QuickMD/QuickMD/FolderAccessBroker.swift b/QuickMD/QuickMD/FolderAccessBroker.swift index fa3df20..8934fef 100644 --- a/QuickMD/QuickMD/FolderAccessBroker.swift +++ b/QuickMD/QuickMD/FolderAccessBroker.swift @@ -132,6 +132,23 @@ final class FolderAccessBroker { return .ask(folder: Self.folderToAsk(forFileAt: file, documentURL: documentURL)) } + /// The reader chose `folder` in File ▸ Open Folder's chooser. In the + /// sandbox that answer IS a grant (the powerbox gave the process the + /// folder): it is saved like a panel's grant, covers everything below it + /// (pictures and links of documents in the folder never ask), clears the + /// declines it covers and tells waiting pictures. Not a question — this + /// broker still decides every ask. Unsandboxed: nothing to record + /// (false). True when the grant was recorded. + @discardableResult + func registerUserChosenFolder(_ folder: URL) -> Bool { + guard environment.isSandboxed, environment.save(folder) else { return false } + let granted = Self.canonicalPath(folder) + if !grantedFolders.contains(granted) { grantedFolders.append(granted) } + declinedFolders = declinedFolders.filter { !Self.covers(granted, $0) } + environment.didGrant(folder) + return true + } + /// Restores a saved grant covering `file`, never asks (print/PDF). func restoreWithoutAsking(forFileAt file: URL) -> Bool { if case .granted = decision(forFileAt: file, documentURL: nil, explicit: false) { return true } diff --git a/QuickMD/QuickMD/FolderBrowserStore.swift b/QuickMD/QuickMD/FolderBrowserStore.swift new file mode 100644 index 0000000..7308390 --- /dev/null +++ b/QuickMD/QuickMD/FolderBrowserStore.swift @@ -0,0 +1,176 @@ +import Foundation +import CoreServices + +// MARK: - Folder browser store (File ▸ Open Folder, #62) + +/// The ONE folder the Documents sidebar lists (app-wide: Open Folder replaces +/// it, Close Folder forgets it), with its listing (`FolderListing`). +/// +/// - Remembered by path under `openFolderPath` until it is closed; `restore()` +/// brings it back at launch — a folder that is gone, or whose sandbox +/// bookmark cannot be restored, is forgotten without a word (the sidebar +/// simply shows no folder). +/// - Watched with ONE `FSEventStream` over the whole tree (the listing is +/// recursive; a vnode source per folder would not be), and re-scanned on +/// every change. A re-scan that finds the folder gone forgets it too. +/// - Scans run off the main thread; a newer scan (or a close) supersedes an +/// older one, whose result is dropped. +/// +/// Access is NOT decided here: in the sandbox the chooser's answer is a +/// folder grant recorded by `SandboxAccessManager.registerUserChosenFolder` +/// before `open` is called, and a restore goes through +/// `Environment.restoreAccess`. Every effect (defaults, access, watcher, +/// scan) is injected, so `FolderBrowserStoreTests` needs neither real file +/// events nor `UserDefaults.standard`. +@MainActor +final class FolderBrowserStore: ObservableObject { + struct Environment { + var defaults: UserDefaults + /// Starts access to a remembered folder (sandbox: its bookmark). + /// False = it cannot be read this launch. + var restoreAccess: @MainActor (URL) -> Bool + /// Watches the tree under the folder; the token stops it when + /// released. The closure is called on the main actor. + var watch: @MainActor (URL, @escaping @MainActor () -> Void) -> AnyObject? + var scan: @Sendable (URL) -> FolderListing.Result? = { FolderListing.scan($0) } + } + + static let defaultsKey = "openFolderPath" + + @Published private(set) var folder: URL? + @Published private(set) var groups: [FolderListing.Group] = [] + @Published private(set) var isTruncated = false + @Published private(set) var isLoading = false + + private let environment: Environment + private var watcher: AnyObject? + /// Bumped by every scan start and every close: a scan whose number is no + /// longer current publishes nothing. + private var generation = 0 + /// The latest scan (tests and Open Folder wait for it). + private(set) var scanTask: Task? + + init(environment: Environment) { + self.environment = environment + } + + /// Lists `url` instead of any folder listed before, remembers it, and + /// returns once its first listing is published. + func open(_ url: URL) async { + let url = url.standardizedFileURL + environment.defaults.set(url.path, forKey: Self.defaultsKey) + await start(url).value + } + + /// Forgets the folder: no list, no watcher, nothing remembered. + func close() { + generation += 1 + scanTask = nil + watcher = nil + folder = nil + groups = [] + isTruncated = false + isLoading = false + environment.defaults.removeObject(forKey: Self.defaultsKey) + } + + /// The remembered folder, if it still exists and can be read; otherwise + /// it is forgotten silently. + @discardableResult + func restore() -> Task? { + guard folder == nil, let path = environment.defaults.string(forKey: Self.defaultsKey) else { return nil } + let url = URL(fileURLWithPath: path, isDirectory: true).standardizedFileURL + var isDirectory: ObjCBool = false + // Existence first (metadata, allowed in the sandbox everywhere): a + // folder that is gone needs no bookmark. + guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), isDirectory.boolValue, + environment.restoreAccess(url) else { + environment.defaults.removeObject(forKey: Self.defaultsKey) + return nil + } + return start(url) + } + + /// Lists the folder again (the watcher calls it). + @discardableResult + func refresh() -> Task { + guard let root = folder else { return Task {} } + generation += 1 + let current = generation + isLoading = true + let scan = environment.scan + let task = Task { @MainActor [weak self] in + let result = await Task.detached(priority: .userInitiated) { scan(root) }.value + guard let self, self.generation == current else { return } + guard let result else { + // The folder went away (or can no longer be read). + self.close() + return + } + self.isLoading = false + self.groups = result.groups + self.isTruncated = result.isTruncated + } + scanTask = task + return task + } + + private func start(_ url: URL) -> Task { + watcher = nil + folder = url + groups = [] + isTruncated = false + watcher = environment.watch(url) { [weak self] in + self?.refresh() + } + return refresh() + } +} + +// MARK: - Tree watcher + +/// One `FSEventStream` over a folder tree: directory-level events (no +/// per-file flags), 0.5 s latency (a save that touches several files is one +/// re-scan), on the main queue. `kFSEventStreamCreateFlagWatchRoot` also +/// reports the root itself being moved or deleted, so the re-scan can forget +/// it. Stops when released. +final class FolderTreeWatcher { + private final class Handler { + let fire: () -> Void + init(_ fire: @escaping () -> Void) { self.fire = fire } + } + + private let handler: Handler + private var stream: FSEventStreamRef? + + init?(root: URL, latency: TimeInterval = 0.5, onChange: @escaping () -> Void) { + handler = Handler(onChange) + // The stream holds the handler unretained: it is invalidated in + // deinit, before the handler goes away. + var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(handler).toOpaque(), + retain: nil, release: nil, copyDescription: nil) + let callback: FSEventStreamCallback = { _, info, _, _, _, _ in + guard let info else { return } + Unmanaged.fromOpaque(info).takeUnretainedValue().fire() + } + guard let stream = FSEventStreamCreate(kCFAllocatorDefault, callback, &context, [root.path] as CFArray, + FSEventStreamEventId(kFSEventStreamEventIdSinceNow), latency, + FSEventStreamCreateFlags(kFSEventStreamCreateFlagWatchRoot)) else { + return nil + } + FSEventStreamSetDispatchQueue(stream, DispatchQueue.main) + guard FSEventStreamStart(stream) else { + FSEventStreamInvalidate(stream) + FSEventStreamRelease(stream) + return nil + } + self.stream = stream + } + + deinit { + guard let stream else { return } + FSEventStreamStop(stream) + FSEventStreamInvalidate(stream) + FSEventStreamRelease(stream) + } +} diff --git a/QuickMD/QuickMD/FolderListing.swift b/QuickMD/QuickMD/FolderListing.swift new file mode 100644 index 0000000..7888c36 --- /dev/null +++ b/QuickMD/QuickMD/FolderListing.swift @@ -0,0 +1,145 @@ +import Foundation + +// MARK: - Markdown file kind + +/// THE test for "is this a Markdown file", by extension, any case. Shared by +/// the folder listing (which files the Documents sidebar lists) and the link +/// handler (which local links open in QuickMD rather than in their default +/// app), so the two can never disagree about a file. The list matches the +/// document types QuickMD declares in Info.plist. +enum MarkdownFileKind { + static let extensions: Set = ["md", "markdown", "mdown", "mkd"] + + static func isMarkdown(_ url: URL) -> Bool { + extensions.contains(url.pathExtension.lowercased()) + } +} + +// MARK: - Folder listing (File ▸ Open Folder, #62) + +/// The Markdown files under a folder, grouped by the folder they sit in — +/// what the Documents sidebar lists after File ▸ Open Folder. A list to read +/// from, never a file manager. +/// +/// Rules (and why): +/// - Recursive, but bounded: at most `Limits.maxDepth` folders deep and +/// `Limits.maxFiles` files (`isTruncated` beyond) — someone WILL open their +/// home folder, and the sidebar must stay a list, not a crawl. +/// - Skipped: hidden files and folders (`.git`, dot files, the Finder hidden +/// flag), packages (an `.app`, a `.textbundle` — one document to Finder), +/// `node_modules` (thousands of vendored READMEs nobody wants to read). +/// - Symbolic links are never followed, to folders or files: a link back up +/// the tree would loop, and a link out of the folder would list (and in the +/// sandbox fail to open) files that are not in it. +/// - Order is Finder's (`localizedStandardCompare`: `file2` before `file10`), +/// per path component: the root's files first, then every subfolder in +/// path order, each before its own subfolders. The walk visits folders in +/// exactly that order, so the files kept under the limit are the first ones +/// shown. +/// +/// Pure (no app state), runs off the main thread; tested on temporary trees +/// (`FolderListingTests`). +enum FolderListing { + struct Limits: Equatable, Sendable { + /// Folders below the root that are still read (the root is 0). + var maxDepth = 8 + /// Files listed at most; more makes the result truncated. + var maxFiles = 2_000 + } + + /// The Markdown files directly inside one folder. + struct Group: Equatable, Identifiable, Sendable { + /// Path relative to the root, components joined by "/"; "" for the root. + let relativePath: String + let files: [URL] + var id: String { relativePath } + } + + struct Result: Equatable, Sendable { + /// Folders that hold Markdown files, in display order (root first). + let groups: [Group] + /// More files exist than `Limits.maxFiles`. + let isTruncated: Bool + + var files: [URL] { groups.flatMap(\.files) } + + /// What Open Folder opens when no document window is open: the root's + /// README.md (any case), else the first listed file. + var preferredFile: URL? { + if let root = groups.first(where: { $0.relativePath.isEmpty }), + let readme = root.files.first(where: { $0.lastPathComponent.lowercased() == "readme.md" }) { + return readme + } + return groups.first?.files.first + } + } + + static let skippedFolderNames: Set = ["node_modules"] + + private static let keys: [URLResourceKey] = [.isDirectoryKey, .isSymbolicLinkKey, .isPackageKey, + .isHiddenKey, .isRegularFileKey] + + /// The listing of `root`, or nil when `root` is not a folder that can be + /// read (gone, a file, no access). + static func scan(_ root: URL, limits: Limits = Limits()) -> Result? { + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: root.path, isDirectory: &isDirectory), isDirectory.boolValue, + let rootEntries = entries(of: root) else { return nil } + var groups: [Group] = [] + var count = 0 + var truncated = false + + /// Depth-first, children in Finder order: a folder's files, then its + /// subfolders — the display order (see the type). + func visit(_ folder: URL, entries: [Entry], relativePath: String, depth: Int) { + var files: [URL] = [] + for entry in entries where entry.kind == .markdown { + guard count < limits.maxFiles else { + truncated = true + break + } + files.append(entry.url) + count += 1 + } + if !files.isEmpty { groups.append(Group(relativePath: relativePath, files: files)) } + guard depth < limits.maxDepth else { return } + for entry in entries where entry.kind == .folder { + guard !truncated else { return } + guard let children = Self.entries(of: entry.url) else { continue } + let name = entry.url.lastPathComponent + visit(entry.url, entries: children, + relativePath: relativePath.isEmpty ? name : relativePath + "/" + name, + depth: depth + 1) + } + } + visit(root, entries: rootEntries, relativePath: "", depth: 0) + return Result(groups: groups, isTruncated: truncated) + } + + private struct Entry { + enum Kind { case markdown, folder } + let url: URL + let kind: Kind + } + + /// The listable children of `folder` in Finder order; nil when it cannot + /// be read. + private static func entries(of folder: URL) -> [Entry]? { + guard let urls = try? FileManager.default.contentsOfDirectory( + at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles]) else { return nil } + var entries: [Entry] = [] + for url in urls { + let name = url.lastPathComponent + guard !name.hasPrefix("."), let values = try? url.resourceValues(forKeys: Set(keys)) else { continue } + if values.isHidden == true || values.isSymbolicLink == true { continue } + if values.isDirectory == true { + if values.isPackage == true || skippedFolderNames.contains(name) { continue } + entries.append(Entry(url: url, kind: .folder)) + } else if values.isRegularFile == true, MarkdownFileKind.isMarkdown(url) { + entries.append(Entry(url: url, kind: .markdown)) + } + } + entries.sort { $0.url.lastPathComponent.localizedStandardCompare($1.url.lastPathComponent) == .orderedAscending } + return entries + } +} diff --git a/QuickMD/QuickMD/SandboxAccessManager.swift b/QuickMD/QuickMD/SandboxAccessManager.swift index 73cf00a..df9dced 100644 --- a/QuickMD/QuickMD/SandboxAccessManager.swift +++ b/QuickMD/QuickMD/SandboxAccessManager.swift @@ -107,6 +107,16 @@ final class SandboxAccessManager { mayAsk: explicit || !isEditing(documentURL)) } + /// File ▸ Open Folder: the folder the reader picked in the chooser is + /// also a folder grant — bookmark saved, access started, the broker's + /// bookkeeping told, `folderAccessGranted` posted — so pictures and links + /// of the documents in it never ask. Unsandboxed: nothing (no bookmark; + /// the folder store keeps only the path). + @discardableResult + func registerUserChosenFolder(_ folder: URL) -> Bool { + broker.registerUserChosenFolder(folder) + } + // MARK: - Source Edit /// Documents with an active Source Edit session, by the windows editing diff --git a/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift b/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift index d9319b2..74246a0 100644 --- a/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift +++ b/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift @@ -15,6 +15,7 @@ final class FolderAccessBrokerTests: XCTestCase { var prompts: [String] = [] var granted: [URL] = [] var restored: [URL] = [] + var saves: [URL] = [] /// Panels held back until the test releases them (all of them: a /// broken coalescing must FAIL by its prompt count, never hang). var gates: [CheckedContinuation] = [] @@ -34,7 +35,7 @@ final class FolderAccessBrokerTests: XCTestCase { world.prompts.append(FolderAccessBroker.canonicalPath(folder)) return world.answer(folder) }, - save: { _ in true }, + save: { folder in world.saves.append(folder); return true }, didGrant: { world.granted.append($0) })) } @@ -235,6 +236,44 @@ final class FolderAccessBrokerTests: XCTestCase { } } + /// File ▸ Open Folder (#62): the folder chosen in the chooser is a + /// grant in the sandbox — saved once, its files (and subfolders') are + /// covered without a panel, a decline below it is cleared, waiting + /// pictures are told. + func testAUserChosenFolderCoversItsFilesWithoutAPanel() async { + let world = World() + let access = broker(world) + let declined = await access.requestAccess(forFileAt: file("docs/badges/a.svg"), documentURL: document, + explicit: false) + XCTAssertFalse(declined) + XCTAssertEqual(world.prompts.count, 1) + XCTAssertTrue(access.registerUserChosenFolder(file("docs"))) + XCTAssertEqual(world.saves.map(FolderAccessBroker.canonicalPath), [FolderAccessBroker.canonicalPath(file("docs"))]) + XCTAssertEqual(world.granted.map(FolderAccessBroker.canonicalPath), [FolderAccessBroker.canonicalPath(file("docs"))]) + XCTAssertTrue(access.declinedFolders.isEmpty, "the earlier decline below it is cleared") + for picture in ["docs/badges/a.svg", "docs/images/b.png", "docs/badges/deep/c.svg", "docs/other.md"] { + let granted = await access.requestAccess(forFileAt: file(picture), documentURL: document, explicit: false) + XCTAssertTrue(granted, picture) + } + let link = await access.requestAccess(forFileAt: file("docs/other.md"), documentURL: document, explicit: true) + XCTAssertTrue(link, "a link click in the folder does not ask either") + XCTAssertEqual(world.prompts.count, 1, "no panel after the chooser") + XCTAssertNotEqual(access.decision(forFileAt: file("elsewhere/x.png"), documentURL: document, explicit: false), + .granted, "outside the chosen folder nothing changed") + } + + /// Unsandboxed (GitHub/Homebrew) the chooser's folder is only a path: + /// nothing is saved, granted or announced. + func testAUserChosenFolderIsNeverRegisteredUnsandboxed() { + let world = World() + let access = broker(world, sandboxed: false) + XCTAssertFalse(access.registerUserChosenFolder(file("docs"))) + XCTAssertTrue(world.saves.isEmpty) + XCTAssertTrue(world.granted.isEmpty) + XCTAssertTrue(access.grantedFolders.isEmpty) + XCTAssertEqual(access.decision(forFileAt: file("docs/a.png"), documentURL: document, explicit: false), .declined) + } + /// Final review N1: the editing mark is ended by the window's token, not /// by the URL it reports at the end (a renamed/moved document). func testSourceEditRegistryEndsByToken() { diff --git a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift new file mode 100644 index 0000000..699e155 --- /dev/null +++ b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift @@ -0,0 +1,210 @@ +import XCTest + +/// `FolderBrowserStore` (File ▸ Open Folder, #62): open / close / persist / +/// restore, a vanished folder forgotten, and a watcher event re-scans. The +/// defaults are a `TemporaryDefaults` suite, the watcher a fake whose trigger +/// the test pulls (no real FSEvents), the access a recording closure; the +/// scan is the real `FolderListing` on a temporary tree. +@MainActor +final class FolderBrowserStoreTests: XCTestCase { + + /// A watcher token; the world sees whether it is still alive. + private final class Token {} + + private final class World { + var restoreAnswer = true + var restored: [String] = [] + var watched: [String] = [] + var trigger: (@MainActor () -> Void)? + weak var token: Token? + weak var earlierToken: Token? + } + + private var root: URL! + private var suite: TemporaryDefaults! + + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory + .appendingPathComponent("FolderBrowserStoreTests-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + suite = try TemporaryDefaults("FolderBrowserStore") + } + + override func tearDownWithError() throws { + suite.remove() + try? FileManager.default.removeItem(at: root) + } + + private func store(_ world: World) -> FolderBrowserStore { + FolderBrowserStore(environment: .init( + defaults: suite.defaults, + restoreAccess: { folder in + world.restored.append(folder.path) + return world.restoreAnswer + }, + watch: { folder, onChange in + world.watched.append(folder.path) + world.trigger = onChange + let token = Token() + world.token = token + return token + })) + } + + private func folder(_ name: String, files: [String]) throws -> URL { + let url = root.appendingPathComponent(name, isDirectory: true) + for file in files { + let path = url.appendingPathComponent(file) + try FileManager.default.createDirectory(at: path.deletingLastPathComponent(), + withIntermediateDirectories: true) + try Data("# x\n".utf8).write(to: path) + } + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } + + private func names(_ store: FolderBrowserStore) -> [String] { + store.groups.flatMap(\.files).map(\.lastPathComponent) + } + + func testOpenListsPersistsAndWatches() async throws { + let world = World() + let notes = try folder("Notes", files: ["b.md", "a.md", "sub/c.md", "x.txt"]) + let browser = store(world) + await browser.open(notes) + XCTAssertEqual(browser.folder?.path, notes.standardizedFileURL.path) + XCTAssertEqual(names(browser), ["a.md", "b.md", "c.md"]) + XCTAssertFalse(browser.isLoading) + XCTAssertFalse(browser.isTruncated) + XCTAssertEqual(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey), notes.standardizedFileURL.path) + XCTAssertEqual(world.watched, [notes.standardizedFileURL.path], "one watcher, on the root") + XCTAssertNotNil(world.token) + XCTAssertTrue(world.restored.isEmpty, "a chosen folder is not restored: the chooser granted it") + } + + func testOpenReplacesTheFolderAndItsWatcher() async throws { + let world = World() + let first = try folder("One", files: ["one.md"]) + let second = try folder("Two", files: ["two.md"]) + let browser = store(world) + await browser.open(first) + world.earlierToken = world.token + XCTAssertNotNil(world.earlierToken) + await browser.open(second) + XCTAssertNil(world.earlierToken, "the first folder's watcher stopped") + XCTAssertNotNil(world.token) + XCTAssertEqual(names(browser), ["two.md"]) + XCTAssertEqual(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey), second.standardizedFileURL.path) + } + + func testCloseForgetsEverything() async throws { + let world = World() + let browser = store(world) + await browser.open(try folder("Notes", files: ["a.md"])) + browser.close() + XCTAssertNil(browser.folder) + XCTAssertTrue(browser.groups.isEmpty) + XCTAssertNil(world.token, "the watcher stopped") + XCTAssertNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + XCTAssertNil(store(World()).restore(), "nothing to restore after a close") + } + + func testRestoreBringsTheRememberedFolderBack() async throws { + let notes = try folder("Notes", files: ["a.md"]) + await store(World()).open(notes) + // Next launch: a new store over the same defaults. + let world = World() + let browser = store(world) + let task = browser.restore() + XCTAssertNotNil(task) + await task?.value + XCTAssertEqual(world.restored, [notes.standardizedFileURL.path], "access restored (sandbox: its bookmark)") + XCTAssertEqual(browser.folder?.path, notes.standardizedFileURL.path) + XCTAssertEqual(names(browser), ["a.md"]) + XCTAssertEqual(world.watched.count, 1) + } + + func testAVanishedFolderIsForgottenSilently() async throws { + let notes = try folder("Notes", files: ["a.md"]) + await store(World()).open(notes) + try FileManager.default.removeItem(at: notes) + let world = World() + let browser = store(world) + XCTAssertNil(browser.restore()) + XCTAssertNil(browser.folder) + XCTAssertTrue(world.restored.isEmpty, "existence first: no bookmark for a folder that is gone") + XCTAssertTrue(world.watched.isEmpty) + XCTAssertNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + } + + func testAFolderThatCannotBeRestoredIsForgottenSilently() async throws { + let notes = try folder("Notes", files: ["a.md"]) + await store(World()).open(notes) + let world = World() + world.restoreAnswer = false + let browser = store(world) + XCTAssertNil(browser.restore()) + XCTAssertNil(browser.folder) + XCTAssertEqual(world.restored.count, 1) + XCTAssertNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + } + + func testAWatcherEventRescans() async throws { + let world = World() + let notes = try folder("Notes", files: ["a.md", "b.md"]) + let browser = store(world) + await browser.open(notes) + try Data("# new\n".utf8).write(to: notes.appendingPathComponent("sub/new.md").creatingParent()) + try FileManager.default.removeItem(at: notes.appendingPathComponent("a.md")) + XCTAssertEqual(names(browser), ["a.md", "b.md"], "nothing changes before the event") + world.trigger?() + await browser.scanTask?.value + XCTAssertEqual(names(browser), ["b.md", "new.md"]) + XCTAssertEqual(browser.groups.map(\.relativePath), ["", "sub"]) + } + + func testAWatcherEventAfterTheFolderWentAwayForgetsIt() async throws { + let world = World() + let notes = try folder("Notes", files: ["a.md"]) + let browser = store(world) + await browser.open(notes) + try FileManager.default.removeItem(at: notes) + world.trigger?() + await browser.scanTask?.value + XCTAssertNil(browser.folder) + XCTAssertTrue(browser.groups.isEmpty) + XCTAssertNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + } + + /// The real watcher starts on a folder and stops when released (no event + /// is waited for: delivery timing is the system's). + func testTheTreeWatcherStartsAndStops() { + weak var released: FolderTreeWatcher? + do { + let watcher = FolderTreeWatcher(root: root) {} + XCTAssertNotNil(watcher) + released = watcher + } + XCTAssertNil(released) + } + + func testALateScanOfAClosedFolderPublishesNothing() async throws { + let world = World() + let notes = try folder("Notes", files: ["a.md"]) + let browser = store(world) + await browser.open(notes) + let pending = browser.refresh() + browser.close() + await pending.value + XCTAssertNil(browser.folder) + XCTAssertTrue(browser.groups.isEmpty, "the superseded scan dropped its result") + } +} + +private extension URL { + /// Creates the parent folder and returns self (test trees). + func creatingParent() throws -> URL { + try FileManager.default.createDirectory(at: deletingLastPathComponent(), withIntermediateDirectories: true) + return self + } +} diff --git a/QuickMD/QuickMDTests/FolderListingTests.swift b/QuickMD/QuickMDTests/FolderListingTests.swift new file mode 100644 index 0000000..49cf66d --- /dev/null +++ b/QuickMD/QuickMDTests/FolderListingTests.swift @@ -0,0 +1,130 @@ +import XCTest + +/// `FolderListing` (File ▸ Open Folder, #62) on temporary trees: which +/// files are listed, in which order and groups, what is skipped, and the +/// depth and count limits. Plus the shared Markdown predicate. +final class FolderListingTests: XCTestCase { + private var root: URL! + + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory + .appendingPathComponent("FolderListingTests-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + + override func tearDownWithError() throws { + try? FileManager.default.removeItem(at: root) + } + + private func make(_ paths: String...) throws { + for path in paths { + let url = root.appendingPathComponent(path) + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), + withIntermediateDirectories: true) + try Data("# x\n".utf8).write(to: url) + } + } + + /// The listing as "group: name name" lines, root group as "/". + private func shape(_ result: FolderListing.Result?) -> [String] { + (result?.groups ?? []).map { group in + (group.relativePath.isEmpty ? "/" : group.relativePath) + ": " + + group.files.map(\.lastPathComponent).joined(separator: " ") + } + } + + func testMarkdownPredicateTakesTheFourExtensionsInAnyCase() { + for name in ["a.md", "b.MD", "c.markdown", "d.MarkDown", "e.mdown", "f.MDOWN", "g.mkd", "h.Mkd"] { + XCTAssertTrue(MarkdownFileKind.isMarkdown(URL(fileURLWithPath: "/x/" + name)), name) + } + for name in ["a.txt", "b.mdx", "c.md.txt", "md", "d.rmd", "e.", "f"] { + XCTAssertFalse(MarkdownFileKind.isMarkdown(URL(fileURLWithPath: "/x/" + name)), name) + } + } + + func testListsMarkdownFilesInAnyCaseAndNothingElse() throws { + try make("a.md", "B.MARKDOWN", "c.Mdown", "d.mkd", "e.txt", "f.mdx", "g.html") + try FileManager.default.createDirectory(at: root.appendingPathComponent("folder.md"), + withIntermediateDirectories: true) + XCTAssertEqual(shape(FolderListing.scan(root)), ["/: a.md B.MARKDOWN c.Mdown d.mkd"], + "a FOLDER named .md is no file") + } + + func testFinderOrderAndGroupingByFolder() throws { + try make("file10.md", "file2.md", "File1.md", + "docs/b.md", "docs/a.md", "docs/sub/z.md", + "Zeta/x.md", "alpha/y.md", "empty/notes.txt", "docs 2/q.md") + XCTAssertEqual(shape(FolderListing.scan(root)), [ + "/: File1.md file2.md file10.md", + "alpha: y.md", + "docs: a.md b.md", + "docs/sub: z.md", + "docs 2: q.md", + "Zeta: x.md", + ], "root first; folders in Finder order, each before its own subfolders; no group without files") + } + + func testSkipsHiddenFilesFoldersPackagesAndNodeModules() throws { + try make("keep.md", ".hidden.md", ".git/HEAD.md", "flagged.md", "Tool.app/Contents/README.md", + "node_modules/pkg/README.md", "lib/node_modules/dep/README.md", "lib/real.md") + var flagged = root.appendingPathComponent("flagged.md") + var values = URLResourceValues() + values.isHidden = true + try flagged.setResourceValues(values) + XCTAssertEqual(shape(FolderListing.scan(root)), ["/: keep.md", "lib: real.md"]) + } + + func testSymbolicLinksAreNeverFollowedSoALoopEnds() throws { + try make("a.md", "sub/b.md") + let fm = FileManager.default + try fm.createSymbolicLink(at: root.appendingPathComponent("sub/loop"), withDestinationURL: root) + try fm.createSymbolicLink(at: root.appendingPathComponent("link.md"), + withDestinationURL: root.appendingPathComponent("a.md")) + XCTAssertEqual(shape(FolderListing.scan(root)), ["/: a.md", "sub: b.md"]) + } + + func testDepthLimit() throws { + var path = "" + for level in 0...10 { + try make(path + "f\(level).md") + path += "d\(level + 1)/" + } + let listed = FolderListing.scan(root)?.files.map(\.lastPathComponent) + XCTAssertEqual(listed, (0...8).map { "f\($0).md" }, "the root and 8 folders below it") + let shallow = FolderListing.scan(root, limits: .init(maxDepth: 2, maxFiles: 2_000)) + XCTAssertEqual(shallow?.files.map(\.lastPathComponent), ["f0.md", "f1.md", "f2.md"]) + XCTAssertEqual(shallow?.isTruncated, false, "depth is a limit of the walk, not truncation") + } + + func testCountLimitTruncatesInDisplayOrder() throws { + try make("a.md", "b.md", "c.md", "sub/d.md", "sub/e.md", "sub/deeper/f.md", "z/g.md") + let limited = FolderListing.scan(root, limits: .init(maxDepth: 8, maxFiles: 4)) + XCTAssertEqual(shape(limited), ["/: a.md b.md c.md", "sub: d.md"]) + XCTAssertEqual(limited?.isTruncated, true) + let exact = FolderListing.scan(root, limits: .init(maxDepth: 8, maxFiles: 7)) + XCTAssertEqual(exact?.files.count, 7) + XCTAssertEqual(exact?.isTruncated, false, "exactly the limit is the whole folder") + XCTAssertEqual(FolderListing.Limits().maxFiles, 2_000) + XCTAssertEqual(FolderListing.Limits().maxDepth, 8) + } + + func testPreferredFileIsTheRootReadmeElseTheFirstListed() throws { + try make("guide.md", "ReadMe.md", "sub/README.md") + XCTAssertEqual(FolderListing.scan(root)?.preferredFile?.lastPathComponent, "ReadMe.md") + try FileManager.default.removeItem(at: root.appendingPathComponent("ReadMe.md")) + XCTAssertEqual(FolderListing.scan(root)?.preferredFile?.lastPathComponent, "guide.md", + "a README in a subfolder does not count") + try FileManager.default.removeItem(at: root.appendingPathComponent("guide.md")) + XCTAssertEqual(FolderListing.scan(root)?.preferredFile?.lastPathComponent, "README.md", + "no root files: the first listed one") + try FileManager.default.removeItem(at: root.appendingPathComponent("sub")) + XCTAssertNil(FolderListing.scan(root)?.preferredFile) + XCTAssertEqual(FolderListing.scan(root)?.groups, [], "an empty folder lists, with nothing in it") + } + + func testAFolderThatIsGoneOrAFileListsNothing() throws { + try make("a.md") + XCTAssertNil(FolderListing.scan(root.appendingPathComponent("missing"))) + XCTAssertNil(FolderListing.scan(root.appendingPathComponent("a.md"))) + } +} From 18c8a0b6ae0e04b8bcee240abf56e351c3712e49 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 14:07:02 +0100 Subject: [PATCH 03/27] feat: File > Open Folder lists a folder's Markdown files in the Documents sidebar (#62) Open Folder... (Shift-Cmd-O, after the system Open items, app-level) runs one folder chooser, shows the Documents sidebar and, with no document window open, opens the root README.md or the first listed file. The sidebar lists the folder above a "Recent" header; with no folder open it is unchanged. Folder rows and recent rows open through one function, and a failed open is a toast in the window instead of a debug assertion. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/MarkdownView.swift | 9 +- QuickMD/QuickMD/QuickMDApp.swift | 95 +++++++++ .../Views/RecentDocumentsSidebar.swift | 200 +++++++++++++++++- 3 files changed, 292 insertions(+), 12 deletions(-) diff --git a/QuickMD/QuickMD/MarkdownView.swift b/QuickMD/QuickMD/MarkdownView.swift index 022ed75..fd4230f 100644 --- a/QuickMD/QuickMD/MarkdownView.swift +++ b/QuickMD/QuickMD/MarkdownView.swift @@ -57,7 +57,7 @@ struct MarkdownView: View { /// monitor uses it to ignore events addressed to other tabs' windows. @State private var hostWindow: NSWindow? @AppStorage("isToCVisible") private var isToCVisible: Bool = false - @AppStorage("isDocumentListVisible") private var isDocumentListVisible: Bool = false + @AppStorage(RecentDocumentsSidebar.visibilityDefaultsKey) private var isDocumentListVisible: Bool = false @AppStorage("documentListWidth") private var documentListWidth: Double = 220 @State private var headings: [ToCEntry] = [] /// Transient bottom toast ("Copied 12 characters", "Opened in …"). Nil = hidden. @@ -272,9 +272,9 @@ struct MarkdownView: View { // sidebars at the USE SITE — their @AppStorage flags keep whatever the // reader chose, so leaving reading mode brings back exactly that. if isDocumentListVisible && !isReadingMode { - RecentDocumentsSidebar(theme: theme, currentURL: documentURL) { + RecentDocumentsSidebar(theme: theme, currentURL: documentURL, onCollapse: { withAnimation(.easeInOut(duration: 0.2)) { isDocumentListVisible = false } - } + }, onOpenFailed: { showToast($0) }) .frame(width: documentListWidth) .transition(.move(edge: .leading).combined(with: .opacity)) SidebarResizeHandle(width: $documentListWidth, minWidth: 160, maxWidth: 500) @@ -1960,8 +1960,7 @@ struct MarkdownView: View { DispatchQueue.main.async { showToast(LocalLinkOpening.message(for: .openFailed, name: name)) } } - let ext = finalURL.pathExtension.lowercased() - if ext == "md" || ext == "markdown" || ext == "mdown" || ext == "mkd" { + if MarkdownFileKind.isMarkdown(finalURL) { // `other.md#section`: the window that shows other.md scrolls there. if let fragment = CrossDocumentAnchors.fragment(of: url) { CrossDocumentAnchors.shared.request(fragment, for: finalURL) diff --git a/QuickMD/QuickMD/QuickMDApp.swift b/QuickMD/QuickMD/QuickMDApp.swift index 1f65039..2d5edcd 100644 --- a/QuickMD/QuickMD/QuickMDApp.swift +++ b/QuickMD/QuickMD/QuickMDApp.swift @@ -34,6 +34,11 @@ struct QuickMDApp: App { MarkdownView(document: file.document, documentURL: file.fileURL) } .commands { + // Right after the system's Open… / Open Recent; app-level, so it + // works with no window. The .saveItem group below is not touched. + CommandGroup(after: .newItem) { + OpenFolderCommand() + } CommandGroup(replacing: .saveItem) { Button("Close") { EditCloseGuard.requestClose(NSApp.keyWindow) @@ -102,6 +107,96 @@ struct QuickMDApp: App { } } +// MARK: - Open Folder (#62) + +/// File ▸ Open Folder… (⇧⌘O): choose a folder; the Documents sidebar lists +/// its Markdown files above the recent documents. App-level, enabled with no +/// window open. +struct OpenFolderCommand: View { + var body: some View { + Button("Open Folder\u{2026}") { + OpenFolderFlow.run() + } + .keyboardShortcut("o", modifiers: [.command, .shift]) + } +} + +extension FolderBrowserStore { + /// The app's folder (one at a time), restored when first used — the + /// Documents sidebar or the command, whichever comes first. + static let shared: FolderBrowserStore = { + let store = FolderBrowserStore(environment: .init( + defaults: .standard, + restoreAccess: { folder in + // Unsandboxed the path is enough; in the sandbox the + // chooser's grant comes back through its bookmark. + !SandboxAccessManager.isSandboxed || SandboxAccessManager.shared.restoreAccess(for: folder) + }, + watch: { root, onChange in + FolderTreeWatcher(root: root) { + Task { @MainActor in onChange() } + } + })) + store.restore() + return store + }() +} + +/// What File ▸ Open Folder does, start to end (F2, F7 of the 1.16 spec). +@MainActor +enum OpenFolderFlow { + static func run() { + let store = FolderBrowserStore.shared + guard let folder = chooseFolder(startingAt: store.folder) else { return } + // In the sandbox the chooser's answer is also a folder grant: the + // documents' pictures and links in it never ask. + SandboxAccessManager.shared.registerUserChosenFolder(folder) + UserDefaults.standard.set(true, forKey: RecentDocumentsSidebar.visibilityDefaultsKey) + Task { @MainActor in + await store.open(folder) + // With a document window open the list is all that changes. + guard !hasDocumentWindow else { return } + let name = folder.lastPathComponent + guard store.folder != nil else { + alert(LocalLinkOpening.message(for: .openFailed, name: name)) + return + } + guard let file = FolderListing.Result(groups: store.groups, isTruncated: store.isTruncated) + .preferredFile else { + alert("No Markdown files in \u{201C}\(LocalLinkSafety.displayName(name))\u{201D}") + return + } + DocumentOpener.open(file) { alert($0) } + } + } + + /// The chooser: ONE panel, folders only, no message — a list to read + /// from, not an access request (the sandbox grant comes with it). + private static func chooseFolder(startingAt current: URL?) -> URL? { + let panel = NSOpenPanel() + panel.canChooseDirectories = true + panel.canChooseFiles = false + panel.allowsMultipleSelection = false + panel.canCreateDirectories = false + panel.prompt = "Open" + if let current { panel.directoryURL = current.deletingLastPathComponent() } + guard panel.runModal() == .OK else { return nil } + return panel.url + } + + /// A visible (or minimised) document window exists. + private static var hasDocumentWindow: Bool { + WindowTabbing.documentWindows.contains { $0.isVisible || $0.isMiniaturized } + } + + private static func alert(_ message: String) { + let alert = NSAlert() + alert.messageText = message + alert.addButton(withTitle: "OK") + alert.runModal() + } +} + /// View ▸ Bigger / Smaller / Actual Size — scales the rendered text of the /// frontmost document only, via @FocusedValue (same routing as ⌘F and ⌘⇧T), /// so zooming one tab leaves the others alone. diff --git a/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift b/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift index ca8fe2f..a96f1e1 100644 --- a/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift +++ b/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift @@ -3,15 +3,28 @@ import AppKit // MARK: - Recent Documents Sidebar -/// Left sidebar listing documents opened in this session. -/// Clicking a row re-opens the file in QuickMD. +/// Left sidebar listing documents opened in this session — and, after +/// File ▸ Open Folder (#62), the Markdown files of that folder above them. +/// Clicking a row opens the file in QuickMD (`DocumentOpener`). +/// +/// With no folder open the sidebar is exactly the 1.15 one: that branch of +/// `body` is kept as it was. Rows are plain `Text` inside the `LazyVStack`, +/// never `.textSelection` (constraints, first section); `.onHover` is right +/// here — window chrome, not a document row. /// /// Originally contributed by COSMAX-JYP (https://github.com/COSMAX-JYP/quickmd). struct RecentDocumentsSidebar: View { + /// The `@AppStorage` key of "the Documents sidebar is shown" (all + /// windows): Open Folder sets it from outside any window. + static let visibilityDefaultsKey = "isDocumentListVisible" + @ObservedObject var store: RecentDocumentsStore = .shared + @ObservedObject var folders: FolderBrowserStore = .shared let theme: MarkdownTheme let currentURL: URL? let onCollapse: () -> Void + /// A row's file could not be opened: the message, for this window's toast. + let onOpenFailed: (String) -> Void var body: some View { VStack(alignment: .leading, spacing: 0) { @@ -59,7 +72,24 @@ struct RecentDocumentsSidebar: View { Divider() - if store.documents.isEmpty { + if let folder = folders.folder { + ScrollView { + LazyVStack(alignment: .leading, spacing: 0) { + folderSection(folder) + if !store.documents.isEmpty { + Text("Recent") + .font(.system(size: 10)) + .foregroundColor(.secondary) + .lineLimit(1) + .padding(.horizontal, 12) + .padding(.top, 10) + .padding(.bottom, 2) + recentRows + } + } + .padding(.vertical, 4) + } + } else if store.documents.isEmpty { Spacer(minLength: 0) Text("No documents opened yet") .font(.system(size: 11)) @@ -89,7 +119,79 @@ struct RecentDocumentsSidebar: View { .background(theme.backgroundColor.opacity(0.5)) } + /// The recent rows, as in the no-folder branch. + private var recentRows: some View { + ForEach(store.documents, id: \.absoluteString) { url in + DocumentRow( + url: url, + isCurrent: isCurrent(url), + theme: theme, + onOpen: { openDocument(url) }, + onRemove: { store.remove(url) } + ) + } + } + + /// The open folder: its header, then every folder that holds Markdown + /// files (the root's without a header of its own). + @ViewBuilder + private func folderSection(_ folder: URL) -> some View { + FolderHeaderRow(folder: folder, onClose: { folders.close() }) + if folders.groups.isEmpty { + if !folders.isLoading { + folderNote("No Markdown files") + } + } else { + ForEach(folders.groups) { group in + if !group.relativePath.isEmpty { + Text(group.relativePath) + .font(.system(size: 10)) + .foregroundColor(.secondary) + .lineLimit(1) + .truncationMode(.head) + .padding(.horizontal, 12) + .padding(.top, 8) + .padding(.bottom, 2) + } + ForEach(group.files, id: \.absoluteString) { url in + FolderFileRow(url: url, isCurrent: isCurrent(url), theme: theme, + onOpen: { openDocument(url) }) + } + } + if folders.isTruncated { + folderNote("Showing the first \(FolderListing.Limits().maxFiles.formatted()) files") + } + } + } + + private func folderNote(_ text: String) -> some View { + Text(text) + .font(.system(size: 11)) + .foregroundColor(.secondary) + .padding(.horizontal, 12) + .padding(.vertical, 6) + } + + private func isCurrent(_ url: URL) -> Bool { + currentURL?.standardizedFileURL == url.standardizedFileURL + } + private func openDocument(_ url: URL) { + DocumentOpener.open(url, onFailure: onOpenFailed) + } +} + +// MARK: - Opening + +/// The ONE way a sidebar row (folder file or recent document) or Open Folder +/// opens a file: in QuickMD itself, as Finder would — a tab, or a window with +/// "Open documents in separate windows" on; an already open document gets +/// its tab selected. A failure is reported (`onFailure`, on the main queue, +/// with the Local links wording) instead of the pre-1.16 debug-only +/// assertion: the sandbox may have dropped a recent file's access, a listed +/// file may have been removed a moment ago. +enum DocumentOpener { + static func open(_ url: URL, onFailure: @escaping (String) -> Void) { let config = NSWorkspace.OpenConfiguration() config.activates = true NSWorkspace.shared.open( @@ -97,13 +199,97 @@ struct RecentDocumentsSidebar: View { withApplicationAt: Bundle.main.bundleURL, configuration: config, completionHandler: { _, error in - if let error = error { - // Sandbox may deny access if the system has dropped its bookmark - // for this URL (rare). Surface via assertion in debug only. - assertionFailure("Recent document open failed: \(error.localizedDescription)") + guard error != nil else { return } + let message = LocalLinkOpening.message(for: .openFailed, name: url.lastPathComponent) + DispatchQueue.main.async { onFailure(message) } + } + ) + } +} + +// MARK: - Folder rows + +/// The open folder's name, its path as help, and Close Folder on hover. +private struct FolderHeaderRow: View { + let folder: URL + let onClose: () -> Void + @State private var isHovered = false + + var body: some View { + HStack(spacing: 6) { + Image(systemName: "folder") + .font(.system(size: 12)) + .foregroundColor(.secondary) + Text(folder.lastPathComponent) + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(.secondary) + .lineLimit(1) + .truncationMode(.middle) + .frame(maxWidth: .infinity, alignment: .leading) + if isHovered { + Button { + onClose() + } label: { + Image(systemName: "xmark.circle.fill") + .font(.system(size: 11)) + .foregroundColor(.secondary) + .padding(2) + .contentShape(Rectangle()) } + .buttonStyle(.plain) + .help("Close Folder") + .accessibilityLabel("Close Folder") + .transition(.opacity) } + } + .padding(.horizontal, 12) + .padding(.vertical, 6) + .contentShape(Rectangle()) + .onHover { hovering in + isHovered = hovering + } + .help(folder.path) + } +} + +/// A file of the open folder: the recent row's look on one line (name only), +/// no remove button — the folder decides what is listed. +private struct FolderFileRow: View { + let url: URL + let isCurrent: Bool + let theme: MarkdownTheme + let onOpen: () -> Void + @State private var isHovered = false + + var body: some View { + HStack(spacing: 6) { + Image(systemName: "doc.plaintext") + .font(.system(size: 11)) + .foregroundColor(isCurrent ? .accentColor : .secondary) + Text(url.lastPathComponent) + .font(.system(size: 12, weight: isCurrent ? .semibold : .regular)) + .foregroundColor(theme.textColor) + .lineLimit(1) + .truncationMode(.middle) + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(.horizontal, 8) + .padding(.vertical, 6) + .background( + RoundedRectangle(cornerRadius: 4) + .fill(isCurrent + ? Color.accentColor.opacity(0.18) + : (isHovered ? Color.gray.opacity(0.12) : Color.clear)) + .padding(.horizontal, 4) ) + .contentShape(Rectangle()) + .onTapGesture { + onOpen() + } + .onHover { hovering in + isHovered = hovering + } + .help(url.path) } } From cecabc2c966999733365ac64233a0d189b82435a Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 14:22:23 +0100 Subject: [PATCH 04/27] fix: an ordered list goes on only past what its items own; ASCII digits only (#61) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A paragraph or fence indented short of the item's content column is not the item's: GitHub ends the list there, but the run walk looked only at the indentation, so the count carried on (`1. a`, ` para`, `1. b` showed 1 and 2). Every non-item line now continues a run only when an item at the run's level or deeper owns it (ListNesting): paragraph lines, rules kept in a text row, and every kind of block under an item. Indentation still decides for list-item lines and for direct callers of render(_:). An ordered marker takes ASCII digits only (`١. a` is paragraph text on GitHub; ListNesting.contentColumn already read ASCII only). Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/MarkdownBlockParser.swift | 85 ++++++++++++------- QuickMD/QuickMD/MarkdownRenderer.swift | 39 +++++---- QuickMD/QuickMDTests/ListContentTests.swift | 46 ++++++++++ .../QuickMDTests/VerticalRhythmTests.swift | 17 +++- 4 files changed, 140 insertions(+), 47 deletions(-) diff --git a/QuickMD/QuickMD/MarkdownBlockParser.swift b/QuickMD/QuickMD/MarkdownBlockParser.swift index 492e881..42bc4c5 100644 --- a/QuickMD/QuickMD/MarkdownBlockParser.swift +++ b/QuickMD/QuickMD/MarkdownBlockParser.swift @@ -300,14 +300,25 @@ struct MarkdownBlockParser: Sendable { var nesting = ListNesting() var paragraphOwners: [Int: Int] = [:] var blockOwners: [Int: Int] = [:] + // For the ordered-list runs (`ListOwners.rules` / `.everyBlock`): the + // item that owns a thematic break kept as text, and EVERY block an + // item owns (code, diagrams, pictures, tables, quotes, math, headings). + var ruleOwners: [Int: Int] = [:] + var everyBlockOwner: [Int: Int] = [:] while i < lines.count { + // The item that owns the block(s) this turn appends, and where in + // `blocks` they start (after the text the branch flushed first). + var turnOwner: (owner: Int?, from: Int)? // Every turn consumes at least one line. A branch that decides on a // line its own loop then refuses would otherwise re-enter it for // ever (a quote marker after a no-break space did, 9bbf6ae): DEBUG // stops there, Release keeps the line as text and goes on. let turnStart = i defer { + if let turnOwner, let owner = turnOwner.owner, turnOwner.from < blocks.count { + for position in turnOwner.from..` is decoded by `HTMLImageSyntax`). @@ -540,7 +552,7 @@ struct MarkdownBlockParser: Sendable { } else { flushTextBuffer(&textBuffer, to: &blocks, index: &blockIndex, pending: &pendingRows) // Inline HTML in a paragraph for CommonMark: as an image line. - _ = nesting.text(line, sourceLine: sourceLine) + turnOwner = (nesting.text(line, sourceLine: sourceLine), blocks.count) for tag in html.images { // `` on one line: the picture is the link. blocks.append(.image(index: blockIndex, url: tag.url, alt: tag.alt, width: tag.width, @@ -583,7 +595,7 @@ struct MarkdownBlockParser: Sendable { var preceding = Array(textBuffer[..= 2 && !trimmed.isEmpty { if !isTableSeparator(trimmed) && i + 1 < lines.count && isTableSeparator(lines[i + 1]) { flushTextBuffer(&textBuffer, to: &blocks, index: &blockIndex, pending: &pendingRows) - nesting.block(startingAt: line) + turnOwner = (nesting.block(startingAt: line), blocks.count) var alignments = parseTableAlignments(lines[i + 1]) // The separator row is authoritative for column count: a header row @@ -637,7 +649,7 @@ struct MarkdownBlockParser: Sendable { // Blockquote detection - group consecutive > lines by nesting level if trimmed.hasPrefix(">") { flushTextBuffer(&textBuffer, to: &blocks, index: &blockIndex, pending: &pendingRows) - nesting.block(startingAt: line) + turnOwner = (nesting.block(startingAt: line), blocks.count) // A later nesting group of this run continues the quote row // before it (`MarkdownBlock.joinsPrevious`): `> a` then `>> b` // is one quote on the page, drawn as two rows. @@ -790,7 +802,7 @@ struct MarkdownBlockParser: Sendable { // "para line\n: def" as term + definition). var preceding = Array(textBuffer[..= 0 && block.sourceLine < allLines.count ? allLines[block.sourceLine] : "" lines.append(String(first.prefix(while: { $0 == " " || $0 == "\t" })) + Self.blockStandIn) + lineOwners.append(owners.everyBlock[position]) } } - // The level of the item that owns each line (by its place in `lines`). - var ownerLevels: [Int?] = [] - if !owners.paragraphs.isEmpty { - ownerLevels = [Int?](repeating: nil, count: lines.count) - for (row, start) in zip(pending, starts) { - for (offset, source) in row.sources.enumerated() { - guard let owner = owners.paragraphs[source], let k = itemLines[owner] else { continue } - ownerLevels[start + offset] = MarkdownRenderer.listLevel( - for: lines[k].prefix(while: { $0 == " " || $0 == "\t" })) - } - } + // What keeps an ordered list going past a line that is not a list + // item is OWNERSHIP (`ListNesting`), never its indentation alone: a + // paragraph indented two columns under `1.` is not the item's and + // ends the list on GitHub, so it must restart the count here too. + let ownerLevels: [Int?] = lineOwners.map { owner in + guard let owner, let k = itemLines[owner] else { return nil } + return MarkdownRenderer.listLevel(for: lines[k].prefix(while: { $0 == " " || $0 == "\t" })) } let markers = renderer.orderedMarkers(lines, ownerLevels: ownerLevels) /// The text column of the item on original line `itemLine`. diff --git a/QuickMD/QuickMD/MarkdownRenderer.swift b/QuickMD/QuickMD/MarkdownRenderer.swift index f220305..dac86a7 100644 --- a/QuickMD/QuickMD/MarkdownRenderer.swift +++ b/QuickMD/QuickMD/MarkdownRenderer.swift @@ -230,18 +230,22 @@ struct MarkdownRenderer: Sendable { /// /// A list is a run of ordered items at one level with one delimiter /// (`.` or `)`; the other one starts a new list, as on GitHub). It - /// counts up from its first item's number. Blank lines, deeper-indented - /// lines (a loose list, a nested list, an item's own blocks) and lines an - /// item at the run's level or deeper owns (`ownerLevels[i]`: the - /// `listLevel` of the item that owns line `i` — a line after a hard break - /// sits at the margin but is still that item's) do not end it; a - /// shallower item or any other line does. Nested ordered lists form - /// their own runs. + /// counts up from its first item's number. A shallower item ends it; + /// deeper ordered items form their own runs. Any other line: + /// - a list item (bullet, task) continues it when indented deeper than + /// the run's items (`lineContinuesList`), a blank line always does; + /// - with `ownerLevels` (the parser: one entry per line, the `listLevel` + /// of the item that OWNS line `i`, nil when none does) any other line + /// continues it only when an item at the run's level or deeper owns it. + /// Ownership (`ListNesting`), not indentation: a line after a hard + /// break sits at the margin and is still the item's, a paragraph + /// indented two columns under `1.` is not and ends the list; + /// - without them (direct callers) by its indentation alone. /// /// The hang is the widest DISPLAYED marker, measured in the body font, /// not counted in characters: "9. " is wider than "1. " although both /// are three characters, and twelve `1.` items end in "12. ". - func orderedMarkers(_ lines: [String], ownerLevels: [Int?] = []) -> [OrderedMarker?] { + func orderedMarkers(_ lines: [String], ownerLevels: [Int?]? = nil) -> [OrderedMarker?] { let items = lines.map(Self.orderedItem) var out = [OrderedMarker?](repeating: nil, count: lines.count) var widths: [String: CGFloat] = [:] @@ -262,8 +266,10 @@ struct MarkdownRenderer: Sendable { if item.delimiter != first.delimiter { break } members.append(i) } - } else if !Self.lineContinuesList(lines[i], atLevel: first.level), - (i < ownerLevels.count ? ownerLevels[i] ?? -1 : -1) < first.level { + } else if let ownerLevels, !Self.isListItem(lines[i]) { + let owned = i < ownerLevels.count && (ownerLevels[i] ?? -1) >= first.level + if !owned && !Self.isBlankLine(lines[i]) { break } + } else if !Self.lineContinuesList(lines[i], atLevel: first.level) { break } i += 1 @@ -294,7 +300,7 @@ struct MarkdownRenderer: Sendable { private static func orderedItem(_ line: String) -> OrderedItem? { let trimmed = markerLine(line) guard let match = trimmed.range(of: Self.orderedMarkerPattern, options: .regularExpression) else { return nil } - let digits = trimmed.prefix(while: { $0.isNumber }) + let digits = trimmed.prefix(while: { $0.isASCII && $0.isNumber }) return OrderedItem(level: listLevel(for: line.prefix(while: { $0 == " " || $0 == "\t" })), number: Int(digits) ?? 1, delimiter: trimmed[digits.endIndex], @@ -421,16 +427,17 @@ struct MarkdownRenderer: Sendable { String(text.drop(while: { $0 == " " || $0 == "\t" })) } - /// An ordered item's marker (CommonMark): one to nine digits, then `.` or - /// `)`, then white space. Drawn as `n.` whichever delimiter it had, as + /// An ordered item's marker (CommonMark): one to nine ASCII digits (`\d` + /// would take `١.` too; GitHub keeps that text), then `.` or `)`, then + /// white space. Drawn as `n.` whichever delimiter it had, as /// GitHub draws both (an HTML list). - static let orderedMarkerPattern = #"^(\d{1,9})[.)][ \t]"# + static let orderedMarkerPattern = #"^([0-9]{1,9})[.)][ \t]"# /// `line` (an ordered item line that may not interrupt a paragraph) as /// paragraph text: its delimiter backslash-escaped, so `renderLine` draws /// `1984. A year` as the words it is and never as an item. static func asParagraphText(_ line: String) -> String { - line.replacingOccurrences(of: #"^([ \t]*\d{1,9})([.)])"#, with: "$1\\\\$2", options: .regularExpression) + line.replacingOccurrences(of: #"^([ \t]*[0-9]{1,9})([.)])"#, with: "$1\\\\$2", options: .regularExpression) } /// Whether this item line may interrupt a paragraph (CommonMark): a @@ -441,7 +448,7 @@ struct MarkdownRenderer: Sendable { static func canInterruptParagraph(_ line: String) -> Bool { guard isListItem(line) else { return false } let trimmed = markerLine(line) - if let marker = trimmed.range(of: #"^\d{1,9}[.)]"#, options: .regularExpression) { + if let marker = trimmed.range(of: #"^[0-9]{1,9}[.)]"#, options: .regularExpression) { guard Int(trimmed[marker].dropLast()) == 1 else { return false } return !isBlankLine(trimmed[marker.upperBound...]) } diff --git a/QuickMD/QuickMDTests/ListContentTests.swift b/QuickMD/QuickMDTests/ListContentTests.swift index 2d2e1b5..144bf98 100644 --- a/QuickMD/QuickMDTests/ListContentTests.swift +++ b/QuickMD/QuickMDTests/ListContentTests.swift @@ -574,6 +574,48 @@ final class ListContentTests: XCTestCase { XCTAssertEqual(try markers("1. a\n 1. x \nmore\n 1. y\n1. b"), "1 [1 2] 2") } + /// Ownership, not indentation, keeps a list going past a line that is not + /// an item: a paragraph or fence indented short of the item's content + /// column is not the item's, so the list ends there and the next item + /// starts a new one — number and hang. GitHub (`gh api markdown`, 2026-11-17): + func testOnlyWhatAnItemOwnsKeepsTheListGoing() throws { + //
      1. a

      para

      1. b
      + XCTAssertEqual(try markers("1. a\n\n para\n\n1. b"), "1 1") + //
      1. a

      para

      1. b
      + XCTAssertEqual(try markers("8. a\n\n para\n\n8. b"), "8 8") + //
      1. a

      para

      1. b
      + XCTAssertEqual(try markers("10. a\n\n para\n\n1. b"), "10 1") + let hangs = try orderedHangs("10. a\n\n para\n\n1. b") + XCTAssertEqual(hangs.count, 2) + XCTAssertGreaterThan(hangs[0], hangs[1], "two lists, two hangs") + //
      1. a
      2. b

      para

      1. c
      + XCTAssertEqual(try markers("1. a\n1. b\n\n para\n1. c"), "1 2 1") + // A fence at 2 columns is not the item's: + //
      1. a
      code
      1. b
      + XCTAssertEqual(try markers("1. a\n\n ```\n code\n ```\n\n1. b"), "1 1") + // … at the content column it is:
      1. a

        code
      2. b

      + XCTAssertEqual(try markers("1. a\n\n ```\n code\n ```\n\n1. b"), "1 2") + // A paragraph at the content column after a blank line is the item's: + //
      1. a

        para

      2. b

      + XCTAssertEqual(try markers("1. a\n\n para\n\n1. b"), "1 2") + // The same under a nested bullet, at the ordered item's content column: + //
      • x
        1. a

          para

        2. b

      + XCTAssertEqual(try markers("- x\n 1. a\n\n para\n\n 1. b"), "• [1 2]") + // … and short of it, the bullet's paragraph: + //
      • x

        1. a

        para

        1. b
      + XCTAssertEqual(try markers("- x\n 1. a\n\n para\n\n 1. b"), "• [1 1]") + // A rule inside an item (a text-row line, not a paragraph) is the item's: + //
      1. a


      2. b

      + XCTAssertEqual(try markers("1. a\n\n ---\n\n1. b"), "1 2") + } + + /// Only ASCII digits make an ordered marker. GitHub: `

      ١. a
      ١. b

      `. + func testNonASCIIDigitsAreNoMarker() { + XCTAssertEqual(shape(parse("١. a\n١. b")), ["T:١. a ١. b"]) + XCTAssertFalse(MarkdownRenderer.isListItem("١. a")) + XCTAssertFalse(MarkdownRenderer.canInterruptParagraph("١. a")) + } + /// A numbered line after paragraph text is still text unless it is 1. /// GitHub: `

      text
      2. b
      3. c

      ` and `

      text

      1. a
      2. b
      `. func testParagraphTextBeforeANumberedLine() throws { @@ -622,6 +664,10 @@ final class ListContentTests: XCTestCase { // QuickMD's task items are bullets only, so these stay ordered items with literal text. let task = try parse("1. [ ] a\n1. [x] b\n1. c").flatMap { try paragraphs($0) }.map(\.text) XCTAssertEqual(task, ["1. [ ] a", "2. [x] b", "3. c"]) + // GitHub `
      • a
        3. x
        3. y
      • b
        3. z
      ` (a nested + // list may interrupt the item's paragraph only when it starts at 1); + // QuickMD draws nested ordered items counting from 3. + XCTAssertEqual(try markers("- a\n 3. x\n 3. y\n- b\n 3. z"), "• [3 4] • [3]") // GitHub `
        …`; QuickMD keeps a quote's lines literal. guard case .blockquote(let quote, _) = try XCTUnwrap(parse("> 7. a\n> 7. b").first).content else { return XCTFail("quote") } diff --git a/QuickMD/QuickMDTests/VerticalRhythmTests.swift b/QuickMD/QuickMDTests/VerticalRhythmTests.swift index ae8b317..a335b44 100644 --- a/QuickMD/QuickMDTests/VerticalRhythmTests.swift +++ b/QuickMD/QuickMDTests/VerticalRhythmTests.swift @@ -460,13 +460,28 @@ final class VerticalRhythmTests: XCTestCase { /// its OWN number — the digits are proportional, so "1. " to "9. " each /// started the text at a different x and "10. " further right still. func testOrderedStepsWithCodeBlocksKeepOneTextEdge() throws { - let steps = (1...11).map { "\($0). Step \($0)\n ```sh\n run \($0)\n ```" } + // Each fence at its item's content column ("10. " is 4 wide): GitHub + // keeps one list, `
        1. Step 8
          …
        2. …
        3. Step 11
          …
        `. + let steps = (1...11).map { n -> String in + let pad = String(repeating: " ", count: "\(n). ".count) + return "\(n). Step \(n)\n\(pad)```sh\n\(pad)run \(n)\n\(pad)```" + } let blocks = parse(steps.joined(separator: "\n")) XCTAssertEqual(blocks.filter { if case .codeBlock = $0.content { return true }; return false }.count, 11) let indents = try orderedItemIndents(blocks) XCTAssertEqual(indents.count, 11) XCTAssertEqual(Set(indents).count, 1, "\(indents)") + // A fence at 3 columns under "10. " (content column 4) is NOT the + // item's (#61 review): GitHub ends the list there, + // `…
      1. Step 10
      run 10
      1. Step 11
      `, + // so "11." is a list of its own and hangs under itself. + let short = (8...11).map { "\($0). Step \($0)\n ```sh\n run \($0)\n ```" } + let shortIndents = try orderedItemIndents(parse(short.joined(separator: "\n"))) + XCTAssertEqual(shortIndents.count, 4) + XCTAssertEqual(Set(shortIndents[0..<3]).count, 1, "\(shortIndents)") + XCTAssertNotEqual(shortIndents[2], shortIndents[3], "\(shortIndents)") + // A block NOT under the list (not indented) ends it: the list after // it hangs on its own. let separate = try orderedItemIndents(parse("1. a\n2. b\n\n```\ncode\n```\n\n10. c")) From 3c15cb8a6069f97887e424e920eae929d139aabf Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 14:29:08 +0100 Subject: [PATCH 05/27] fix: Open Folder scans one at a time, at a bounded cost, and only for relevant changes (#62) - One scan in flight per folder; events during it cause exactly one follow-up, no sooner than 1 s after it ended. Close and a new Open cancel the running scan between folders. - A scan looks at no more than 20 000 entries (the root's own excepted) and never enters another volume or a volume root; a folder the budget does not cover lists nothing. Either cap reads "Showing the first N files" with N listed. - The watcher drops event batches under .git, dot folders and node_modules (one name rule shared with the scan); an equal listing publishes nothing. - open() returns only with a listing for its own folder, or when it was superseded; the flow then does nothing. A chosen folder that cannot be read is an alert, window or not. - Restoring does no I/O on the main thread: the existence check runs off it, started once from the sidebar's first appearance. - Gone forgets the folder, unreadable keeps it and its last listing. - Listing URLs keep the canonical root's spelling and the sidebar compares them with the current document's canonical path. - Finder order gets a deterministic tie-break. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderBrowserStore.swift | 305 +++++++++++---- QuickMD/QuickMD/FolderListing.swift | 158 ++++++-- QuickMD/QuickMD/QuickMDApp.swift | 28 +- .../Views/RecentDocumentsSidebar.swift | 26 +- .../FolderBrowserStoreTests.swift | 353 +++++++++++++++--- QuickMD/QuickMDTests/FolderListingTests.swift | 121 +++++- 6 files changed, 795 insertions(+), 196 deletions(-) diff --git a/QuickMD/QuickMD/FolderBrowserStore.swift b/QuickMD/QuickMD/FolderBrowserStore.swift index 7308390..da16442 100644 --- a/QuickMD/QuickMD/FolderBrowserStore.swift +++ b/QuickMD/QuickMD/FolderBrowserStore.swift @@ -6,22 +6,39 @@ import CoreServices /// The ONE folder the Documents sidebar lists (app-wide: Open Folder replaces /// it, Close Folder forgets it), with its listing (`FolderListing`). /// -/// - Remembered by path under `openFolderPath` until it is closed; `restore()` -/// brings it back at launch — a folder that is gone, or whose sandbox -/// bookmark cannot be restored, is forgotten without a word (the sidebar -/// simply shows no folder). +/// - Remembered by path under `openFolderPath` until it is closed. Creating +/// the store does no I/O; `restore()` (started once, from a task) checks +/// the folder's existence OFF the main thread — a remembered folder on a +/// disconnected share must not stall launch — and only then restores +/// access and publishes it. A folder that is gone, or whose sandbox +/// bookmark cannot be restored, is forgotten without a word. /// - Watched with ONE `FSEventStream` over the whole tree (the listing is -/// recursive; a vnode source per folder would not be), and re-scanned on -/// every change. A re-scan that finds the folder gone forgets it too. -/// - Scans run off the main thread; a newer scan (or a close) supersedes an -/// older one, whose result is dropped. +/// recursive; a vnode source per folder would not be). An event batch +/// whose paths all lie under skipped names (`.git`, `node_modules`; +/// `FolderListing.isRelevantChange`, the scan's own rule) is dropped. +/// - ONE scan at a time (measured in review: ten events 100 ms apart had +/// started ten scans at once on the pool the document parse uses). Events +/// during a scan only mark the listing dirty; exactly one more scan +/// follows, no sooner than `followUpDelay` (1 s) after the previous one +/// ended. Close and a new Open cancel the running scan (it stops between +/// folders). +/// - A scan that finds the same listing publishes nothing (no +/// `objectWillChange`: the sidebar does not re-render on every save of an +/// unrelated file). +/// - Gone vs unreadable: a scan that finds no folder forgets it; one that +/// cannot read it keeps the folder and the last listing and tries again on +/// the next event (or launch). +/// - Listing URLs are built on the CANONICAL root (the disk spelling, +/// `FolderAccessBroker.canonicalPath`), so the sidebar can recognise the +/// current document however its path was spelled; `folder` stays as +/// chosen (the persisted path is the sandbox bookmark's key). /// /// Access is NOT decided here: in the sandbox the chooser's answer is a /// folder grant recorded by `SandboxAccessManager.registerUserChosenFolder` /// before `open` is called, and a restore goes through /// `Environment.restoreAccess`. Every effect (defaults, access, watcher, -/// scan) is injected, so `FolderBrowserStoreTests` needs neither real file -/// events nor `UserDefaults.standard`. +/// scan, follow-up delay) is injected, so `FolderBrowserStoreTests` needs +/// neither real file events, nor the clock, nor `UserDefaults.standard`. @MainActor final class FolderBrowserStore: ObservableObject { struct Environment { @@ -29,133 +46,269 @@ final class FolderBrowserStore: ObservableObject { /// Starts access to a remembered folder (sandbox: its bookmark). /// False = it cannot be read this launch. var restoreAccess: @MainActor (URL) -> Bool - /// Watches the tree under the folder; the token stops it when - /// released. The closure is called on the main actor. - var watch: @MainActor (URL, @escaping @MainActor () -> Void) -> AnyObject? - var scan: @Sendable (URL) -> FolderListing.Result? = { FolderListing.scan($0) } + /// Watches the tree under the (canonical) root; the token stops it + /// when released. The closure gets the changed paths, on the main + /// actor (empty = unknown, treated as relevant). + var watch: @MainActor (URL, @escaping @MainActor ([String]) -> Void) -> AnyObject? + /// Lists the root off the main thread; the closure says the scan + /// was cancelled. + var scan: @Sendable (URL, @escaping @Sendable () -> Bool) async -> FolderListing.Outcome = { root, cancelled in + await Task.detached(priority: .utility) { FolderListing.scan(root, isCancelled: cancelled) }.value + } + /// The pause between a scan and the follow-up that events during it + /// asked for. + var followUpDelay: @MainActor () async -> Void = { + try? await Task.sleep(nanoseconds: 1_000_000_000) + } + } + + /// How an `open` ended. + enum OpenResult: Equatable { + /// The folder's listing is published. + case listed + /// The chosen folder does not exist (forgotten). + case missing + /// It exists but cannot be read (kept; empty list). + case unreadable + /// Another Open or a Close came first. + case superseded } static let defaultsKey = "openFolderPath" + /// The folder as chosen (standardized) — shown, persisted. @Published private(set) var folder: URL? @Published private(set) var groups: [FolderListing.Group] = [] @Published private(set) var isTruncated = false + /// No listing yet for this folder. @Published private(set) var isLoading = false + /// The last scan could not read the folder. + @Published private(set) var isUnreadable = false + + /// The canonical root the listing is built on. + private(set) var listingRoot: URL? + /// The root as FSEvents spells it (`realpath`), for the event filter. + private var eventRootPath: String? + var fileCount: Int { groups.reduce(0) { $0 + $1.files.count } } private let environment: Environment private var watcher: AnyObject? - /// Bumped by every scan start and every close: a scan whose number is no - /// longer current publishes nothing. - private var generation = 0 - /// The latest scan (tests and Open Folder wait for it). - private(set) var scanTask: Task? + + /// One open folder's scans; cancelled when it is closed or replaced. + private final class Session: @unchecked Sendable { + private let lock = NSLock() + private var cancelled = false + var isCancelled: Bool { + lock.lock(); defer { lock.unlock() } + return cancelled + } + func cancel() { + lock.lock(); cancelled = true; lock.unlock() + } + } + + private var session: Session? + /// The scan loop of `session` (at most one). + private(set) var scanLoop: Task? + /// An event arrived since the running scan started. + private var dirty = false + /// `open` calls waiting for their folder's first listing. + private var waiters: [(session: Session, continuation: CheckedContinuation)] = [] + private var didRestore = false init(environment: Environment) { self.environment = environment } - /// Lists `url` instead of any folder listed before, remembers it, and - /// returns once its first listing is published. - func open(_ url: URL) async { - let url = url.standardizedFileURL - environment.defaults.set(url.path, forKey: Self.defaultsKey) - await start(url).value + /// Lists `url` instead of any folder listed before and remembers it. + /// Returns once a listing FOR THIS FOLDER is published (or it turned out + /// missing / unreadable), or when another Open or a Close replaced it. + func open(_ url: URL) async -> OpenResult { + didRestore = true + let chosen = url.standardizedFileURL + environment.defaults.set(chosen.path, forKey: Self.defaultsKey) + let root = URL(fileURLWithPath: FolderAccessBroker.canonicalPath(chosen), isDirectory: true) + let opened = begin(folder: chosen, root: root) + return await withCheckedContinuation { continuation in + waiters.append((opened, continuation)) + } } /// Forgets the folder: no list, no watcher, nothing remembered. func close() { - generation += 1 - scanTask = nil - watcher = nil + endSession() folder = nil + listingRoot = nil + eventRootPath = nil groups = [] isTruncated = false isLoading = false + isUnreadable = false environment.defaults.removeObject(forKey: Self.defaultsKey) } - /// The remembered folder, if it still exists and can be read; otherwise - /// it is forgotten silently. - @discardableResult - func restore() -> Task? { - guard folder == nil, let path = environment.defaults.string(forKey: Self.defaultsKey) else { return nil } - let url = URL(fileURLWithPath: path, isDirectory: true).standardizedFileURL - var isDirectory: ObjCBool = false - // Existence first (metadata, allowed in the sandbox everywhere): a - // folder that is gone needs no bookmark. - guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), isDirectory.boolValue, - environment.restoreAccess(url) else { + /// The remembered folder, once per process (later calls, and calls after + /// an Open, do nothing). See the type for the order of the checks. + func restore() async { + guard !didRestore else { return } + didRestore = true + guard folder == nil, let path = environment.defaults.string(forKey: Self.defaultsKey) else { return } + let canonical = await Task.detached(priority: .utility) { Self.existingCanonicalPath(path) }.value + // Opened, closed or replaced while the check ran: the reader acted. + guard folder == nil, environment.defaults.string(forKey: Self.defaultsKey) == path else { return } + let chosen = URL(fileURLWithPath: path, isDirectory: true).standardizedFileURL + guard let canonical, environment.restoreAccess(chosen) else { environment.defaults.removeObject(forKey: Self.defaultsKey) + return + } + begin(folder: chosen, root: URL(fileURLWithPath: canonical, isDirectory: true)) + } + + /// Lists the folder again — at once, or after the running scan. + func refresh() { + guard session != nil else { return } + dirty = true + startScanLoopIfNeeded() + } + + // MARK: Private + + /// The disk spelling of `path` when it is an existing folder (I/O: call + /// off the main thread). + nonisolated private static func existingCanonicalPath(_ path: String) -> String? { + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue else { return nil } - return start(url) + return FolderAccessBroker.canonicalPath(URL(fileURLWithPath: path, isDirectory: true)) } - /// Lists the folder again (the watcher calls it). @discardableResult - func refresh() -> Task { - guard let root = folder else { return Task {} } - generation += 1 - let current = generation + private func begin(folder chosen: URL, root: URL) -> Session { + endSession() + let opened = Session() + session = opened + folder = chosen + listingRoot = root + eventRootPath = FolderListing.realPath(root.path) + groups = [] + isTruncated = false + isUnreadable = false isLoading = true - let scan = environment.scan - let task = Task { @MainActor [weak self] in - let result = await Task.detached(priority: .userInitiated) { scan(root) }.value - guard let self, self.generation == current else { return } - guard let result else { - // The folder went away (or can no longer be read). - self.close() - return - } - self.isLoading = false - self.groups = result.groups - self.isTruncated = result.isTruncated + watcher = environment.watch(root) { [weak self] paths in + self?.filesChanged(atPaths: paths) } - scanTask = task - return task + dirty = true + startScanLoopIfNeeded() + return opened } - private func start(_ url: URL) -> Task { + /// Ends the open folder's session: the scan stops early, the watcher + /// goes, waiting `open`s learn they were superseded. + private func endSession() { + session?.cancel() + scanLoop?.cancel() + scanLoop = nil + session = nil + dirty = false watcher = nil - folder = url - groups = [] - isTruncated = false - watcher = environment.watch(url) { [weak self] in - self?.refresh() + resumeWaiters(.superseded) { _ in true } + } + + private func filesChanged(atPaths paths: [String]) { + guard let root = listingRoot?.path else { return } + let real = eventRootPath ?? root + // A path outside a root counts as relevant, so a path is dropped + // when it lies under a skipped name in either spelling of the root. + guard paths.isEmpty || paths.contains(where: { + FolderListing.isRelevantChange(atPath: $0, root: root) + && FolderListing.isRelevantChange(atPath: $0, root: real) + }) else { return } + refresh() + } + + private func startScanLoopIfNeeded() { + guard scanLoop == nil, let current = session else { return } + scanLoop = Task { [weak self] in + await self?.runScans(for: current) } - return refresh() + } + + /// Scans while events keep the listing dirty; one at a time. + private func runScans(for current: Session) async { + while dirty, session === current, let root = listingRoot { + dirty = false + let outcome = await environment.scan(root) { current.isCancelled } + guard session === current else { return } + apply(outcome, for: current) + guard session === current else { return } + if dirty { + await environment.followUpDelay() + } + } + if session === current { scanLoop = nil } + } + + private func apply(_ outcome: FolderListing.Outcome, for current: Session) { + switch outcome { + case .cancelled: + return + case .missing: + resumeWaiters(.missing) { $0 === current } + close() + case .unreadable: + if !isUnreadable { isUnreadable = true } + if isLoading { isLoading = false } + resumeWaiters(.unreadable) { $0 === current } + case .listed(let result): + // Only what changed is assigned: equal listings publish nothing. + if isUnreadable { isUnreadable = false } + if isLoading { isLoading = false } + if groups != result.groups { groups = result.groups } + if isTruncated != result.isTruncated { isTruncated = result.isTruncated } + resumeWaiters(.listed) { $0 === current } + } + } + + private func resumeWaiters(_ result: OpenResult, where matches: (Session) -> Bool) { + let ready = waiters.filter { matches($0.session) } + waiters.removeAll { matches($0.session) } + ready.forEach { $0.continuation.resume(returning: result) } } } // MARK: - Tree watcher /// One `FSEventStream` over a folder tree: directory-level events (no -/// per-file flags), 0.5 s latency (a save that touches several files is one -/// re-scan), on the main queue. `kFSEventStreamCreateFlagWatchRoot` also -/// reports the root itself being moved or deleted, so the re-scan can forget -/// it. Stops when released. +/// per-file flags) with their paths (`UseCFTypes`), 0.5 s latency (a save +/// that touches several files is one batch), on the main queue. +/// `kFSEventStreamCreateFlagWatchRoot` also reports the root itself being +/// moved or deleted, so the re-scan can forget it. Stops when released. final class FolderTreeWatcher { private final class Handler { - let fire: () -> Void - init(_ fire: @escaping () -> Void) { self.fire = fire } + let fire: ([String]) -> Void + init(_ fire: @escaping ([String]) -> Void) { self.fire = fire } } private let handler: Handler private var stream: FSEventStreamRef? - init?(root: URL, latency: TimeInterval = 0.5, onChange: @escaping () -> Void) { + init?(root: URL, latency: TimeInterval = 0.5, onChange: @escaping ([String]) -> Void) { handler = Handler(onChange) // The stream holds the handler unretained: it is invalidated in // deinit, before the handler goes away. var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(handler).toOpaque(), retain: nil, release: nil, copyDescription: nil) - let callback: FSEventStreamCallback = { _, info, _, _, _, _ in + let callback: FSEventStreamCallback = { _, info, _, eventPaths, _, _ in guard let info else { return } - Unmanaged.fromOpaque(info).takeUnretainedValue().fire() + // UseCFTypes: the paths are a CFArray of CFString. + let paths = (Unmanaged.fromOpaque(eventPaths).takeUnretainedValue() as NSArray) as? [String] ?? [] + Unmanaged.fromOpaque(info).takeUnretainedValue().fire(paths) } + let flags = FSEventStreamCreateFlags(kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagUseCFTypes) guard let stream = FSEventStreamCreate(kCFAllocatorDefault, callback, &context, [root.path] as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), latency, - FSEventStreamCreateFlags(kFSEventStreamCreateFlagWatchRoot)) else { + flags) else { return nil } FSEventStreamSetDispatchQueue(stream, DispatchQueue.main) diff --git a/QuickMD/QuickMD/FolderListing.swift b/QuickMD/QuickMD/FolderListing.swift index 7888c36..6001fc0 100644 --- a/QuickMD/QuickMD/FolderListing.swift +++ b/QuickMD/QuickMD/FolderListing.swift @@ -22,20 +22,35 @@ enum MarkdownFileKind { /// from, never a file manager. /// /// Rules (and why): -/// - Recursive, but bounded: at most `Limits.maxDepth` folders deep and -/// `Limits.maxFiles` files (`isTruncated` beyond) — someone WILL open their -/// home folder, and the sidebar must stay a list, not a crawl. +/// - Recursive, but bounded in COST, not only in what is shown: at most +/// `Limits.maxDepth` folders deep, `Limits.maxFiles` files listed and +/// `Limits.maxEntries` entries looked at (files and folders, Markdown or +/// not) — someone WILL open their home folder or "/", and the scan runs +/// again on every change in the tree. Either count limit makes the result +/// `isTruncated`. The root's own entries are always read in full before +/// anything is descended into, so its files survive any cap. +/// - Never onto another volume: a subfolder that is a volume's root, or +/// whose volume differs from the root's, is skipped ("/" must not walk +/// /Volumes or /System/Volumes/Data). Both tests are needed: measured on +/// macOS 27, `/System/Volumes/Data` reports the SAME `volumeIdentifier` +/// (and `st_dev`) as `/` — the APFS firmlink group — and only `isVolume` +/// tells it apart; a mounted disk under /Volumes differs in both. /// - Skipped: hidden files and folders (`.git`, dot files, the Finder hidden /// flag), packages (an `.app`, a `.textbundle` — one document to Finder), -/// `node_modules` (thousands of vendored READMEs nobody wants to read). +/// `node_modules` (thousands of vendored READMEs nobody wants to read). The +/// name part of that rule is `isSkippedName`, shared with the watcher's +/// event filter (`isRelevantChange`) so the two never disagree. /// - Symbolic links are never followed, to folders or files: a link back up /// the tree would loop, and a link out of the folder would list (and in the /// sandbox fail to open) files that are not in it. -/// - Order is Finder's (`localizedStandardCompare`: `file2` before `file10`), -/// per path component: the root's files first, then every subfolder in -/// path order, each before its own subfolders. The walk visits folders in -/// exactly that order, so the files kept under the limit are the first ones -/// shown. +/// - Order is Finder's (`localizedStandardCompare`: `file2` before `file10`; +/// ties such as `a.md` / `A.md` on a case-sensitive volume broken by the +/// code points, so two scans of one tree always agree), per path +/// component: the root's files first, then every subfolder in path order, +/// each before its own subfolders. The walk visits folders in exactly that +/// order, so the files kept under a limit are the first ones shown. +/// - Cancellable between folders (`isCancelled`): a closed or replaced +/// folder stops its scan early. /// /// Pure (no app state), runs off the main thread; tested on temporary trees /// (`FolderListingTests`). @@ -45,6 +60,9 @@ enum FolderListing { var maxDepth = 8 /// Files listed at most; more makes the result truncated. var maxFiles = 2_000 + /// Entries (files + folders) looked at at most, the root's own + /// excepted; more makes the result truncated. + var maxEntries = 20_000 } /// The Markdown files directly inside one folder. @@ -58,7 +76,7 @@ enum FolderListing { struct Result: Equatable, Sendable { /// Folders that hold Markdown files, in display order (root first). let groups: [Group] - /// More files exist than `Limits.maxFiles`. + /// A limit stopped the walk: more files may exist than are listed. let isTruncated: Bool var files: [URL] { groups.flatMap(\.files) } @@ -74,24 +92,69 @@ enum FolderListing { } } + /// What a scan found: the listing, no such folder (gone — forget it), or + /// a folder that exists but cannot be read now (keep it, try again). + enum Outcome: Equatable, Sendable { + case listed(Result) + case missing + case unreadable + /// Stopped by `isCancelled`; nothing to publish. + case cancelled + } + static let skippedFolderNames: Set = ["node_modules"] + /// The NAME part of the skip rule: hidden by a leading dot, or a folder + /// nobody reads (`node_modules`). Shared by the scan and the watcher. + static func isSkippedName(_ name: String) -> Bool { + name.hasPrefix(".") || skippedFolderNames.contains(name) + } + + /// A change at `path` (as FSEvents reports it) can change the listing of + /// `root` (both canonical paths): false only when some component of the + /// path below the root is a skipped name (`.git/objects/ab`, + /// `node_modules/x`). Paths outside the root (the root itself moved) + /// count as relevant. + static func isRelevantChange(atPath path: String, root: String) -> Bool { + let base = root.hasSuffix("/") ? root : root + "/" + let trimmed = path.hasSuffix("/") ? String(path.dropLast()) : path + guard trimmed.hasPrefix(base) else { return true } + return !trimmed.dropFirst(base.count).split(separator: "/").contains { isSkippedName(String($0)) } + } + + /// `realpath(3)`: the spelling FSEvents reports (`/private/var/…`, where + /// `canonicalPath` — Foundation's `resolvingSymlinksInPath` — gives + /// `/var/…`). `path` itself when it cannot be resolved. + static func realPath(_ path: String) -> String { + guard let resolved = realpath(path, nil) else { return path } + defer { free(resolved) } + return String(cString: resolved) + } + private static let keys: [URLResourceKey] = [.isDirectoryKey, .isSymbolicLinkKey, .isPackageKey, - .isHiddenKey, .isRegularFileKey] + .isHiddenKey, .isRegularFileKey, .volumeIdentifierKey, + .isVolumeKey] - /// The listing of `root`, or nil when `root` is not a folder that can be - /// read (gone, a file, no access). - static func scan(_ root: URL, limits: Limits = Limits()) -> Result? { + /// The listing of `root` (see the type and `Outcome`). + /// `didVisit` (tests) hears the relative path of every subfolder read. + static func scan(_ root: URL, limits: Limits = Limits(), + isCancelled: () -> Bool = { false }, + didVisit: ((String) -> Void)? = nil) -> Outcome { var isDirectory: ObjCBool = false - guard FileManager.default.fileExists(atPath: root.path, isDirectory: &isDirectory), isDirectory.boolValue, - let rootEntries = entries(of: root) else { return nil } + guard FileManager.default.fileExists(atPath: root.path, isDirectory: &isDirectory), + isDirectory.boolValue else { return .missing } + var budget = Int.max + guard let rootEntries = entries(of: root, budget: &budget) else { return .unreadable } + let volume = try? root.resourceValues(forKeys: [.volumeIdentifierKey]).volumeIdentifier var groups: [Group] = [] var count = 0 var truncated = false + var cancelled = false + budget = limits.maxEntries /// Depth-first, children in Finder order: a folder's files, then its /// subfolders — the display order (see the type). - func visit(_ folder: URL, entries: [Entry], relativePath: String, depth: Int) { + func visit(_ entries: [Entry], relativePath: String, depth: Int) { var files: [URL] = [] for entry in entries where entry.kind == .markdown { guard count < limits.maxFiles else { @@ -104,42 +167,77 @@ enum FolderListing { if !files.isEmpty { groups.append(Group(relativePath: relativePath, files: files)) } guard depth < limits.maxDepth else { return } for entry in entries where entry.kind == .folder { - guard !truncated else { return } - guard let children = Self.entries(of: entry.url) else { continue } + guard !truncated, !cancelled else { return } + if isCancelled() { + cancelled = true + return + } + if entry.isVolume { continue } + if let volume, let own = entry.volume, !own.isEqual(volume) { continue } + guard budget > 0 else { + truncated = true + return + } + guard let children = Self.entries(of: entry.url, budget: &budget) else { continue } + if budget < 0 { truncated = true } let name = entry.url.lastPathComponent - visit(entry.url, entries: children, - relativePath: relativePath.isEmpty ? name : relativePath + "/" + name, - depth: depth + 1) + let path = relativePath.isEmpty ? name : relativePath + "/" + name + didVisit?(path) + visit(children, relativePath: path, depth: depth + 1) } } - visit(root, entries: rootEntries, relativePath: "", depth: 0) - return Result(groups: groups, isTruncated: truncated) + visit(rootEntries, relativePath: "", depth: 0) + return cancelled ? .cancelled : .listed(Result(groups: groups, isTruncated: truncated)) } private struct Entry { enum Kind { case markdown, folder } let url: URL let kind: Kind + let volume: (NSCopying & NSSecureCoding & NSObjectProtocol)? + var isVolume = false } /// The listable children of `folder` in Finder order; nil when it cannot - /// be read. - private static func entries(of folder: URL) -> [Entry]? { + /// be read. Each entry looked at costs one unit of `budget`. A folder + /// the budget does not cover lists NOTHING (`budget` ends at -1): the + /// directory's own order is not Finder's, and a partial folder would + /// break "the files kept are the first ones shown". + private static func entries(of folder: URL, budget: inout Int) -> [Entry]? { guard let urls = try? FileManager.default.contentsOfDirectory( at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles]) else { return nil } var entries: [Entry] = [] for url in urls { + guard budget > 0 else { + budget = -1 + return [] + } + budget -= 1 let name = url.lastPathComponent guard !name.hasPrefix("."), let values = try? url.resourceValues(forKeys: Set(keys)) else { continue } if values.isHidden == true || values.isSymbolicLink == true { continue } + // Built on `folder`, not taken from the enumeration: Foundation + // hands back `/private/var/…` for a root spelled `/var/…`, and + // the listing must keep the root's (canonical) spelling. if values.isDirectory == true { - if values.isPackage == true || skippedFolderNames.contains(name) { continue } - entries.append(Entry(url: url, kind: .folder)) + if values.isPackage == true || isSkippedName(name) { continue } + entries.append(Entry(url: folder.appendingPathComponent(name, isDirectory: true), kind: .folder, + volume: values.volumeIdentifier, isVolume: values.isVolume == true)) } else if values.isRegularFile == true, MarkdownFileKind.isMarkdown(url) { - entries.append(Entry(url: url, kind: .markdown)) + entries.append(Entry(url: folder.appendingPathComponent(name, isDirectory: false), kind: .markdown, + volume: nil)) } } - entries.sort { $0.url.lastPathComponent.localizedStandardCompare($1.url.lastPathComponent) == .orderedAscending } + entries.sort { finderOrder($0.url.lastPathComponent, $1.url.lastPathComponent) } return entries } + + /// Finder order with a deterministic tie-break (code points). + static func finderOrder(_ a: String, _ b: String) -> Bool { + switch a.localizedStandardCompare(b) { + case .orderedAscending: return true + case .orderedDescending: return false + case .orderedSame: return Array(a.unicodeScalars.map(\.value)).lexicographicallyPrecedes(b.unicodeScalars.map(\.value)) + } + } } diff --git a/QuickMD/QuickMD/QuickMDApp.swift b/QuickMD/QuickMD/QuickMDApp.swift index 2d5edcd..15552bf 100644 --- a/QuickMD/QuickMD/QuickMDApp.swift +++ b/QuickMD/QuickMD/QuickMDApp.swift @@ -122,10 +122,11 @@ struct OpenFolderCommand: View { } extension FolderBrowserStore { - /// The app's folder (one at a time), restored when first used — the - /// Documents sidebar or the command, whichever comes first. + /// The app's folder (one at a time). Creating it does no I/O; the + /// Documents sidebar starts `restore()` from a task when it first + /// appears (an Open Folder before that makes the restore a no-op). static let shared: FolderBrowserStore = { - let store = FolderBrowserStore(environment: .init( + FolderBrowserStore(environment: .init( defaults: .standard, restoreAccess: { folder in // Unsandboxed the path is enough; in the sandbox the @@ -133,12 +134,10 @@ extension FolderBrowserStore { !SandboxAccessManager.isSandboxed || SandboxAccessManager.shared.restoreAccess(for: folder) }, watch: { root, onChange in - FolderTreeWatcher(root: root) { - Task { @MainActor in onChange() } + FolderTreeWatcher(root: root) { paths in + Task { @MainActor in onChange(paths) } } })) - store.restore() - return store }() } @@ -153,14 +152,21 @@ enum OpenFolderFlow { SandboxAccessManager.shared.registerUserChosenFolder(folder) UserDefaults.standard.set(true, forKey: RecentDocumentsSidebar.visibilityDefaultsKey) Task { @MainActor in - await store.open(folder) - // With a document window open the list is all that changes. - guard !hasDocumentWindow else { return } let name = folder.lastPathComponent - guard store.folder != nil else { + switch await store.open(folder) { + case .superseded: + // The reader chose again (or closed it): that answer stands. + return + case .missing, .unreadable: + // An explicit command: say so, window or not. alert(LocalLinkOpening.message(for: .openFailed, name: name)) return + case .listed: + break } + // With a document window open the list is all that changes. + guard !hasDocumentWindow, + store.folder == folder.standardizedFileURL else { return } guard let file = FolderListing.Result(groups: store.groups, isTruncated: store.isTruncated) .preferredFile else { alert("No Markdown files in \u{201C}\(LocalLinkSafety.displayName(name))\u{201D}") diff --git a/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift b/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift index a96f1e1..01f3a7c 100644 --- a/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift +++ b/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift @@ -25,6 +25,11 @@ struct RecentDocumentsSidebar: View { let onCollapse: () -> Void /// A row's file could not be opened: the message, for this window's toast. let onOpenFailed: (String) -> Void + /// The current document's path as the disk spells it (symlinks, case), + /// computed once per document off the main thread — the folder's + /// listing is built on the canonical root, so a document opened as + /// `/tmp/x.md` still finds its `/private/tmp/x.md` row. No I/O in rows. + @State private var canonicalCurrentPath: String? var body: some View { VStack(alignment: .leading, spacing: 0) { @@ -117,6 +122,15 @@ struct RecentDocumentsSidebar: View { } .frame(maxHeight: .infinity) .background(theme.backgroundColor.opacity(0.5)) + // The remembered folder comes back on the first appearance (once per + // process; the store does the I/O off the main thread). + .task { await folders.restore() } + .task(id: currentURL) { + let url = currentURL + canonicalCurrentPath = await Task.detached(priority: .utility) { + url.map { FolderAccessBroker.canonicalPath($0) } + }.value + } } /// The recent rows, as in the no-folder branch. @@ -138,7 +152,8 @@ struct RecentDocumentsSidebar: View { private func folderSection(_ folder: URL) -> some View { FolderHeaderRow(folder: folder, onClose: { folders.close() }) if folders.groups.isEmpty { - if !folders.isLoading { + // Unreadable: the header alone — "no files" would not be true. + if !folders.isLoading && !folders.isUnreadable { folderNote("No Markdown files") } } else { @@ -154,12 +169,12 @@ struct RecentDocumentsSidebar: View { .padding(.bottom, 2) } ForEach(group.files, id: \.absoluteString) { url in - FolderFileRow(url: url, isCurrent: isCurrent(url), theme: theme, + FolderFileRow(url: url, isCurrent: isCurrentInFolder(url), theme: theme, onOpen: { openDocument(url) }) } } if folders.isTruncated { - folderNote("Showing the first \(FolderListing.Limits().maxFiles.formatted()) files") + folderNote("Showing the first \(folders.fileCount.formatted()) files") } } } @@ -176,6 +191,11 @@ struct RecentDocumentsSidebar: View { currentURL?.standardizedFileURL == url.standardizedFileURL } + /// Listing URLs are canonical (see `canonicalCurrentPath`). + private func isCurrentInFolder(_ url: URL) -> Bool { + (canonicalCurrentPath != nil && canonicalCurrentPath == url.path) || isCurrent(url) + } + private func openDocument(_ url: URL) { DocumentOpener.open(url, onFailure: onOpenFailed) } diff --git a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift index 699e155..653563f 100644 --- a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift +++ b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift @@ -1,23 +1,55 @@ import XCTest +import Combine /// `FolderBrowserStore` (File ▸ Open Folder, #62): open / close / persist / -/// restore, a vanished folder forgotten, and a watcher event re-scans. The -/// defaults are a `TemporaryDefaults` suite, the watcher a fake whose trigger -/// the test pulls (no real FSEvents), the access a recording closure; the -/// scan is the real `FolderListing` on a temporary tree. +/// restore, gone vs unreadable, one scan at a time with one follow-up, +/// irrelevant events dropped, equal listings unpublished, and `open` +/// waiting for ITS folder's listing. The defaults are a `TemporaryDefaults` +/// suite, the watcher a fake whose trigger the test pulls (no FSEvents), the +/// follow-up delay a recorded no-op (no clock), the scan the real +/// `FolderListing` on a temporary tree behind a probe that counts scans and +/// can hold them (work counters, never time). @MainActor final class FolderBrowserStoreTests: XCTestCase { /// A watcher token; the world sees whether it is still alive. private final class Token {} + @MainActor private final class World { var restoreAnswer = true var restored: [String] = [] var watched: [String] = [] - var trigger: (@MainActor () -> Void)? + var trigger: (@MainActor ([String]) -> Void)? weak var token: Token? weak var earlierToken: Token? + // Scan probe. + var started = 0 + var running = 0 + var peak = 0 + var hold = false + var gates: [CheckedContinuation] = [] + var events: [String] = [] + /// Answers instead of the real scan when set. + var forced: FolderListing.Outcome? + var cancelChecks: [@Sendable () -> Bool] = [] + + func begin(_ isCancelled: @escaping @Sendable () -> Bool) async { + started += 1 + running += 1 + peak = max(peak, running) + events.append("scan") + cancelChecks.append(isCancelled) + if hold { await withCheckedContinuation { gates.append($0) } } + } + + func end() { running -= 1 } + + func release() { + hold = false + gates.forEach { $0.resume() } + gates.removeAll() + } } private var root: URL! @@ -48,18 +80,26 @@ final class FolderBrowserStoreTests: XCTestCase { let token = Token() world.token = token return token - })) + }, + scan: { folder, isCancelled in + await world.begin(isCancelled) + let forced = await MainActor.run { world.forced } + let outcome = forced ?? FolderListing.scan(folder, isCancelled: isCancelled) + await world.end() + return outcome + }, + followUpDelay: { world.events.append("delay") })) } private func folder(_ name: String, files: [String]) throws -> URL { let url = root.appendingPathComponent(name, isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) for file in files { let path = url.appendingPathComponent(file) try FileManager.default.createDirectory(at: path.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("# x\n".utf8).write(to: path) } - try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) return url } @@ -67,19 +107,52 @@ final class FolderBrowserStoreTests: XCTestCase { store.groups.flatMap(\.files).map(\.lastPathComponent) } + /// Spins until `condition` holds (bounded by a generous deadline, which a + /// passing run never reaches). + private func until(_ condition: () -> Bool, file: StaticString = #filePath, line: UInt = #line) async { + let deadline = Date().addingTimeInterval(15) + while !condition() && Date() < deadline { await Task.yield() } + XCTAssertTrue(condition(), "condition never held", file: file, line: line) + } + + /// The scans the store has left to run, finished. + private func settle(_ store: FolderBrowserStore) async { + while let loop = store.scanLoop { await loop.value; await Task.yield() } + } + + private func path(_ url: URL) -> String { url.standardizedFileURL.path } + + // MARK: Open, close, persist + func testOpenListsPersistsAndWatches() async throws { let world = World() let notes = try folder("Notes", files: ["b.md", "a.md", "sub/c.md", "x.txt"]) let browser = store(world) - await browser.open(notes) - XCTAssertEqual(browser.folder?.path, notes.standardizedFileURL.path) + let result = await browser.open(notes) + XCTAssertEqual(result, .listed) + XCTAssertEqual(browser.folder?.path, path(notes)) XCTAssertEqual(names(browser), ["a.md", "b.md", "c.md"]) + XCTAssertEqual(browser.fileCount, 3) XCTAssertFalse(browser.isLoading) XCTAssertFalse(browser.isTruncated) - XCTAssertEqual(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey), notes.standardizedFileURL.path) - XCTAssertEqual(world.watched, [notes.standardizedFileURL.path], "one watcher, on the root") + XCTAssertEqual(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey), path(notes)) + XCTAssertEqual(world.watched, [FolderAccessBroker.canonicalPath(notes)], "one watcher, on the canonical root") XCTAssertNotNil(world.token) XCTAssertTrue(world.restored.isEmpty, "a chosen folder is not restored: the chooser granted it") + XCTAssertEqual(world.started, 1) + } + + /// The listing is built on the disk spelling of the root (the temporary + /// directory lives under the `/var` → `/private/var` symlink), while the + /// folder stays as chosen. + func testListingURLsAreCanonicalAndTheFolderAsChosen() async throws { + let notes = try folder("Notes", files: ["a.md"]) + let browser = store(World()) + _ = await browser.open(notes) + let canonical = FolderAccessBroker.canonicalPath(notes) + XCTAssertEqual(browser.listingRoot?.path, canonical) + XCTAssertEqual(browser.groups.first?.files.first?.path, canonical + "/a.md") + XCTAssertEqual(browser.folder?.path, path(notes)) } func testOpenReplacesTheFolderAndItsWatcher() async throws { @@ -87,50 +160,77 @@ final class FolderBrowserStoreTests: XCTestCase { let first = try folder("One", files: ["one.md"]) let second = try folder("Two", files: ["two.md"]) let browser = store(world) - await browser.open(first) + _ = await browser.open(first) world.earlierToken = world.token XCTAssertNotNil(world.earlierToken) - await browser.open(second) + _ = await browser.open(second) XCTAssertNil(world.earlierToken, "the first folder's watcher stopped") XCTAssertNotNil(world.token) XCTAssertEqual(names(browser), ["two.md"]) - XCTAssertEqual(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey), second.standardizedFileURL.path) + XCTAssertEqual(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey), path(second)) } func testCloseForgetsEverything() async throws { let world = World() let browser = store(world) - await browser.open(try folder("Notes", files: ["a.md"])) + _ = await browser.open(try folder("Notes", files: ["a.md"])) browser.close() XCTAssertNil(browser.folder) + XCTAssertNil(browser.listingRoot) XCTAssertTrue(browser.groups.isEmpty) XCTAssertNil(world.token, "the watcher stopped") XCTAssertNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) - XCTAssertNil(store(World()).restore(), "nothing to restore after a close") + let next = store(World()) + await next.restore() + XCTAssertNil(next.folder, "nothing to restore after a close") + } + + // MARK: Restore + + func testCreatingTheStoreDoesNothingUntilRestore() async throws { + _ = await store(World()).open(try folder("Notes", files: ["a.md"])) + let world = World() + let browser = store(world) + XCTAssertNil(browser.folder, "no I/O and no publishing at creation") + XCTAssertTrue(world.restored.isEmpty) + XCTAssertEqual(world.started, 0) + await browser.restore() + await settle(browser) + XCTAssertEqual(names(browser), ["a.md"]) + await browser.restore() + XCTAssertEqual(world.restored.count, 1, "once per process") } func testRestoreBringsTheRememberedFolderBack() async throws { let notes = try folder("Notes", files: ["a.md"]) - await store(World()).open(notes) + _ = await store(World()).open(notes) // Next launch: a new store over the same defaults. let world = World() let browser = store(world) - let task = browser.restore() - XCTAssertNotNil(task) - await task?.value - XCTAssertEqual(world.restored, [notes.standardizedFileURL.path], "access restored (sandbox: its bookmark)") - XCTAssertEqual(browser.folder?.path, notes.standardizedFileURL.path) + await browser.restore() + await settle(browser) + XCTAssertEqual(world.restored, [path(notes)], "access restored (sandbox: its bookmark) for the chosen path") + XCTAssertEqual(browser.folder?.path, path(notes)) XCTAssertEqual(names(browser), ["a.md"]) - XCTAssertEqual(world.watched.count, 1) + XCTAssertEqual(world.watched, [FolderAccessBroker.canonicalPath(notes)]) + } + + func testAnOpenBeforeTheRestoreWins() async throws { + let old = try folder("Old", files: ["old.md"]) + _ = await store(World()).open(old) + let browser = store(World()) + _ = await browser.open(try folder("New", files: ["new.md"])) + await browser.restore() + XCTAssertEqual(names(browser), ["new.md"]) } func testAVanishedFolderIsForgottenSilently() async throws { let notes = try folder("Notes", files: ["a.md"]) - await store(World()).open(notes) + _ = await store(World()).open(notes) try FileManager.default.removeItem(at: notes) let world = World() let browser = store(world) - XCTAssertNil(browser.restore()) + await browser.restore() XCTAssertNil(browser.folder) XCTAssertTrue(world.restored.isEmpty, "existence first: no bookmark for a folder that is gone") XCTAssertTrue(world.watched.isEmpty) @@ -139,72 +239,207 @@ final class FolderBrowserStoreTests: XCTestCase { func testAFolderThatCannotBeRestoredIsForgottenSilently() async throws { let notes = try folder("Notes", files: ["a.md"]) - await store(World()).open(notes) + _ = await store(World()).open(notes) let world = World() world.restoreAnswer = false let browser = store(world) - XCTAssertNil(browser.restore()) + await browser.restore() XCTAssertNil(browser.folder) XCTAssertEqual(world.restored.count, 1) XCTAssertNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) } + // MARK: Gone vs unreadable + + func testAnUnreadableFolderIsKeptWithItsLastListing() async throws { + let world = World() + let notes = try folder("Notes", files: ["a.md"]) + let browser = store(world) + _ = await browser.open(notes) + world.forced = .unreadable + world.trigger?([]) + await settle(browser) + XCTAssertEqual(browser.folder?.path, path(notes), "kept") + XCTAssertTrue(browser.isUnreadable) + XCTAssertEqual(names(browser), ["a.md"], "the last listing stays") + XCTAssertNotNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + world.forced = nil + world.trigger?([]) + await settle(browser) + XCTAssertFalse(browser.isUnreadable, "tried again on the next event") + } + + func testAnUnreadableFolderAtOpenIsReportedAndKept() async throws { + let world = World() + world.forced = .unreadable + let notes = try folder("Notes", files: ["a.md"]) + let browser = store(world) + let result = await browser.open(notes) + XCTAssertEqual(result, .unreadable) + XCTAssertNotNil(browser.folder, "at launch too: the header with an empty list") + XCTAssertTrue(browser.groups.isEmpty) + XCTAssertFalse(browser.isLoading) + // Restored at launch while unreadable: kept as well. + let next = store(world) + await next.restore() + await settle(next) + XCTAssertNotNil(next.folder) + XCTAssertTrue(next.isUnreadable) + } + + func testAMissingFolderIsForgotten() async throws { + let world = World() + let notes = try folder("Notes", files: ["a.md"]) + let browser = store(world) + _ = await browser.open(notes) + try FileManager.default.removeItem(at: notes) + world.trigger?([]) + await settle(browser) + XCTAssertNil(browser.folder) + XCTAssertTrue(browser.groups.isEmpty) + XCTAssertNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + } + + // MARK: One scan at a time + func testAWatcherEventRescans() async throws { let world = World() let notes = try folder("Notes", files: ["a.md", "b.md"]) let browser = store(world) - await browser.open(notes) - try Data("# new\n".utf8).write(to: notes.appendingPathComponent("sub/new.md").creatingParent()) + _ = await browser.open(notes) + try FileManager.default.createDirectory(at: notes.appendingPathComponent("sub"), withIntermediateDirectories: true) + try Data("# new\n".utf8).write(to: notes.appendingPathComponent("sub/new.md")) try FileManager.default.removeItem(at: notes.appendingPathComponent("a.md")) XCTAssertEqual(names(browser), ["a.md", "b.md"], "nothing changes before the event") - world.trigger?() - await browser.scanTask?.value + world.trigger?([FolderAccessBroker.canonicalPath(notes) + "/sub"]) + await settle(browser) XCTAssertEqual(names(browser), ["b.md", "new.md"]) XCTAssertEqual(browser.groups.map(\.relativePath), ["", "sub"]) + XCTAssertEqual(world.events, ["scan", "scan"], "no delay before a scan nothing was waiting for") } - func testAWatcherEventAfterTheFolderWentAwayForgetsIt() async throws { + /// Ten events during one scan: still one scan in flight, then exactly + /// ONE follow-up, after the delay. + func testEventsDuringAScanCauseExactlyOneFollowUp() async throws { let world = World() let notes = try folder("Notes", files: ["a.md"]) let browser = store(world) - await browser.open(notes) - try FileManager.default.removeItem(at: notes) - world.trigger?() - await browser.scanTask?.value + world.hold = true + let opening = Task { await browser.open(notes) } + await until { world.started == 1 && !world.gates.isEmpty } + for _ in 0..<10 { world.trigger?([FolderAccessBroker.canonicalPath(notes)]) } + for _ in 0..<50 { await Task.yield() } + XCTAssertEqual(world.started, 1, "events while a scan runs start nothing") + world.release() + let result = await opening.value + XCTAssertEqual(result, .listed) + await settle(browser) + XCTAssertEqual(world.started, 2) + XCTAssertEqual(world.peak, 1, "never two scans at once") + XCTAssertEqual(world.events, ["scan", "delay", "scan"]) + } + + func testIrrelevantEventsStartNoScan() async throws { + let world = World() + let notes = try folder("Notes", files: ["a.md"]) + let browser = store(world) + _ = await browser.open(notes) + let canonical = FolderAccessBroker.canonicalPath(notes) + world.trigger?([canonical + "/.git/objects/ab", canonical + "/node_modules/pkg"]) + await settle(browser) + XCTAssertEqual(world.started, 1, "a batch only under skipped names is dropped") + // FSEvents spells the temporary folder `/private/var/…`. + let real = FolderListing.realPath(canonical) + world.trigger?([real + "/.git/index", real + "/docs/node_modules"]) + await settle(browser) + XCTAssertEqual(world.started, 1, "in the realpath spelling too") + world.trigger?([canonical + "/.git", canonical + "/docs"]) + await settle(browser) + XCTAssertEqual(world.started, 2, "one relevant path is enough") + } + + func testAnEqualListingPublishesNothing() async throws { + let world = World() + let notes = try folder("Notes", files: ["a.md"]) + let browser = store(world) + _ = await browser.open(notes) + var changes = 0 + let subscription = browser.objectWillChange.sink { changes += 1 } + world.trigger?([]) + await settle(browser) + XCTAssertEqual(world.started, 2) + XCTAssertEqual(changes, 0) + try Data("# b\n".utf8).write(to: notes.appendingPathComponent("b.md")) + world.trigger?([]) + await settle(browser) + XCTAssertGreaterThan(changes, 0, "a changed listing does publish") + subscription.cancel() + } + + func testCloseCancelsTheRunningScan() async throws { + let world = World() + let notes = try folder("Notes", files: ["a.md"]) + let browser = store(world) + world.hold = true + let opening = Task { await browser.open(notes) } + await until { world.started == 1 && !world.gates.isEmpty } + XCTAssertEqual(world.cancelChecks.first?(), false) + browser.close() + XCTAssertEqual(world.cancelChecks.first?(), true, "the scan sees it was cancelled") + let result = await opening.value + XCTAssertEqual(result, .superseded) + world.release() + for _ in 0..<50 { await Task.yield() } XCTAssertNil(browser.folder) - XCTAssertTrue(browser.groups.isEmpty) - XCTAssertNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + XCTAssertTrue(browser.groups.isEmpty, "the cancelled scan published nothing") + } + + // MARK: open waits for its own listing + + func testASecondOpenSupersedesTheFirst() async throws { + let world = World() + let first = try folder("One", files: ["one.md"]) + let second = try folder("Two", files: ["two.md"]) + let browser = store(world) + world.hold = true + let firstOpen = Task { await browser.open(first) } + await until { world.started == 1 && !world.gates.isEmpty } + XCTAssertEqual(world.cancelChecks.first?(), false) + let secondOpen = Task { await browser.open(second) } + await until { world.started == 2 } + world.release() + let results = await [firstOpen.value, secondOpen.value] + XCTAssertEqual(results, [.superseded, .listed]) + XCTAssertEqual(world.cancelChecks.first?(), true, "the first folder's scan was cancelled") + XCTAssertEqual(names(browser), ["two.md"]) + } + + func testOpenReturnsWithItsOwnListingWhenAnEventArrivesDuringTheScan() async throws { + let world = World() + let notes = try folder("Notes", files: ["a.md"]) + let browser = store(world) + world.hold = true + let opening = Task { await browser.open(notes) } + await until { world.started == 1 && !world.gates.isEmpty } + world.trigger?([]) + world.release() + let result = await opening.value + XCTAssertEqual(result, .listed) + XCTAssertEqual(names(browser), ["a.md"], "published before open returned") + await settle(browser) } + // MARK: Real watcher + /// The real watcher starts on a folder and stops when released (no event /// is waited for: delivery timing is the system's). func testTheTreeWatcherStartsAndStops() { weak var released: FolderTreeWatcher? do { - let watcher = FolderTreeWatcher(root: root) {} + let watcher = FolderTreeWatcher(root: root) { _ in } XCTAssertNotNil(watcher) released = watcher } XCTAssertNil(released) } - - func testALateScanOfAClosedFolderPublishesNothing() async throws { - let world = World() - let notes = try folder("Notes", files: ["a.md"]) - let browser = store(world) - await browser.open(notes) - let pending = browser.refresh() - browser.close() - await pending.value - XCTAssertNil(browser.folder) - XCTAssertTrue(browser.groups.isEmpty, "the superseded scan dropped its result") - } -} - -private extension URL { - /// Creates the parent folder and returns self (test trees). - func creatingParent() throws -> URL { - try FileManager.default.createDirectory(at: deletingLastPathComponent(), withIntermediateDirectories: true) - return self - } } diff --git a/QuickMD/QuickMDTests/FolderListingTests.swift b/QuickMD/QuickMDTests/FolderListingTests.swift index 49cf66d..d64835a 100644 --- a/QuickMD/QuickMDTests/FolderListingTests.swift +++ b/QuickMD/QuickMDTests/FolderListingTests.swift @@ -25,6 +25,16 @@ final class FolderListingTests: XCTestCase { } } + /// The listing of a scan, nil when it did not list. + private func listed(_ outcome: FolderListing.Outcome) -> FolderListing.Result? { + if case .listed(let result) = outcome { return result } + return nil + } + + private func scan(_ limits: FolderListing.Limits = .init()) -> FolderListing.Result? { + listed(FolderListing.scan(root, limits: limits)) + } + /// The listing as "group: name name" lines, root group as "/". private func shape(_ result: FolderListing.Result?) -> [String] { (result?.groups ?? []).map { group in @@ -46,7 +56,7 @@ final class FolderListingTests: XCTestCase { try make("a.md", "B.MARKDOWN", "c.Mdown", "d.mkd", "e.txt", "f.mdx", "g.html") try FileManager.default.createDirectory(at: root.appendingPathComponent("folder.md"), withIntermediateDirectories: true) - XCTAssertEqual(shape(FolderListing.scan(root)), ["/: a.md B.MARKDOWN c.Mdown d.mkd"], + XCTAssertEqual(shape(scan()), ["/: a.md B.MARKDOWN c.Mdown d.mkd"], "a FOLDER named .md is no file") } @@ -54,7 +64,7 @@ final class FolderListingTests: XCTestCase { try make("file10.md", "file2.md", "File1.md", "docs/b.md", "docs/a.md", "docs/sub/z.md", "Zeta/x.md", "alpha/y.md", "empty/notes.txt", "docs 2/q.md") - XCTAssertEqual(shape(FolderListing.scan(root)), [ + XCTAssertEqual(shape(scan()), [ "/: File1.md file2.md file10.md", "alpha: y.md", "docs: a.md b.md", @@ -71,7 +81,7 @@ final class FolderListingTests: XCTestCase { var values = URLResourceValues() values.isHidden = true try flagged.setResourceValues(values) - XCTAssertEqual(shape(FolderListing.scan(root)), ["/: keep.md", "lib: real.md"]) + XCTAssertEqual(shape(scan()), ["/: keep.md", "lib: real.md"]) } func testSymbolicLinksAreNeverFollowedSoALoopEnds() throws { @@ -80,7 +90,7 @@ final class FolderListingTests: XCTestCase { try fm.createSymbolicLink(at: root.appendingPathComponent("sub/loop"), withDestinationURL: root) try fm.createSymbolicLink(at: root.appendingPathComponent("link.md"), withDestinationURL: root.appendingPathComponent("a.md")) - XCTAssertEqual(shape(FolderListing.scan(root)), ["/: a.md", "sub: b.md"]) + XCTAssertEqual(shape(scan()), ["/: a.md", "sub: b.md"]) } func testDepthLimit() throws { @@ -89,19 +99,19 @@ final class FolderListingTests: XCTestCase { try make(path + "f\(level).md") path += "d\(level + 1)/" } - let listed = FolderListing.scan(root)?.files.map(\.lastPathComponent) + let listed = scan()?.files.map(\.lastPathComponent) XCTAssertEqual(listed, (0...8).map { "f\($0).md" }, "the root and 8 folders below it") - let shallow = FolderListing.scan(root, limits: .init(maxDepth: 2, maxFiles: 2_000)) + let shallow = scan(.init(maxDepth: 2, maxFiles: 2_000)) XCTAssertEqual(shallow?.files.map(\.lastPathComponent), ["f0.md", "f1.md", "f2.md"]) XCTAssertEqual(shallow?.isTruncated, false, "depth is a limit of the walk, not truncation") } func testCountLimitTruncatesInDisplayOrder() throws { try make("a.md", "b.md", "c.md", "sub/d.md", "sub/e.md", "sub/deeper/f.md", "z/g.md") - let limited = FolderListing.scan(root, limits: .init(maxDepth: 8, maxFiles: 4)) + let limited = scan(.init(maxDepth: 8, maxFiles: 4)) XCTAssertEqual(shape(limited), ["/: a.md b.md c.md", "sub: d.md"]) XCTAssertEqual(limited?.isTruncated, true) - let exact = FolderListing.scan(root, limits: .init(maxDepth: 8, maxFiles: 7)) + let exact = scan(.init(maxDepth: 8, maxFiles: 7)) XCTAssertEqual(exact?.files.count, 7) XCTAssertEqual(exact?.isTruncated, false, "exactly the limit is the whole folder") XCTAssertEqual(FolderListing.Limits().maxFiles, 2_000) @@ -110,21 +120,98 @@ final class FolderListingTests: XCTestCase { func testPreferredFileIsTheRootReadmeElseTheFirstListed() throws { try make("guide.md", "ReadMe.md", "sub/README.md") - XCTAssertEqual(FolderListing.scan(root)?.preferredFile?.lastPathComponent, "ReadMe.md") + XCTAssertEqual(scan()?.preferredFile?.lastPathComponent, "ReadMe.md") try FileManager.default.removeItem(at: root.appendingPathComponent("ReadMe.md")) - XCTAssertEqual(FolderListing.scan(root)?.preferredFile?.lastPathComponent, "guide.md", + XCTAssertEqual(scan()?.preferredFile?.lastPathComponent, "guide.md", "a README in a subfolder does not count") try FileManager.default.removeItem(at: root.appendingPathComponent("guide.md")) - XCTAssertEqual(FolderListing.scan(root)?.preferredFile?.lastPathComponent, "README.md", + XCTAssertEqual(scan()?.preferredFile?.lastPathComponent, "README.md", "no root files: the first listed one") try FileManager.default.removeItem(at: root.appendingPathComponent("sub")) - XCTAssertNil(FolderListing.scan(root)?.preferredFile) - XCTAssertEqual(FolderListing.scan(root)?.groups, [], "an empty folder lists, with nothing in it") + XCTAssertNil(scan()?.preferredFile) + XCTAssertEqual(scan()?.groups, [], "an empty folder lists, with nothing in it") } - func testAFolderThatIsGoneOrAFileListsNothing() throws { - try make("a.md") - XCTAssertNil(FolderListing.scan(root.appendingPathComponent("missing"))) - XCTAssertNil(FolderListing.scan(root.appendingPathComponent("a.md"))) + func testGoneIsMissingAndAFolderThatCannotBeReadIsUnreadable() throws { + try make("a.md", "locked/b.md") + XCTAssertEqual(FolderListing.scan(root.appendingPathComponent("missing")), .missing) + XCTAssertEqual(FolderListing.scan(root.appendingPathComponent("a.md")), .missing, "a file is no folder") + let locked = root.appendingPathComponent("locked") + try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: locked.path) + defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: locked.path) } + XCTAssertEqual(FolderListing.scan(locked), .unreadable) + XCTAssertEqual(shape(scan()), ["/: a.md"], "an unreadable subfolder is left out of the parent's listing") + } + + func testTheEntryCapCountsEveryEntryButKeepsTheRootsFiles() throws { + try make("r1.md", "r2.md", "r3.md", "r.txt", "a/x1.txt", "a/x2.txt", "a/m.md", "b/n.md") + // The root's own entries are read whatever the cap; a/ (3 entries) + // does not fit in 2, so it lists nothing and the walk stops. + let capped = scan(.init(maxDepth: 8, maxFiles: 2_000, maxEntries: 2)) + XCTAssertEqual(shape(capped), ["/: r1.md r2.md r3.md"]) + XCTAssertEqual(capped?.isTruncated, true) + let exact = scan(.init(maxDepth: 8, maxFiles: 2_000, maxEntries: 4)) + XCTAssertEqual(shape(exact), ["/: r1.md r2.md r3.md", "a: m.md", "b: n.md"]) + XCTAssertEqual(exact?.isTruncated, false, "3 entries in a/, 1 in b/: exactly the cap") + let short = scan(.init(maxDepth: 8, maxFiles: 2_000, maxEntries: 3)) + XCTAssertEqual(shape(short), ["/: r1.md r2.md r3.md", "a: m.md"]) + XCTAssertEqual(short?.isTruncated, true) + XCTAssertEqual(FolderListing.Limits().maxEntries, 20_000) + } + + func testAScanStopsWhenCancelled() throws { + try make("a/1.md", "b/2.md", "c/3.md", "d/4.md") + var asked = 0 + let outcome = FolderListing.scan(root, isCancelled: { + asked += 1 + return asked >= 2 + }) + XCTAssertEqual(outcome, .cancelled) + XCTAssertEqual(asked, 2, "asked between folders, stopped at the first yes") + } + + /// Volume roots are never entered. `/System/Volumes` holds only volume + /// roots (Data, Preboot, VM…); `Data` has the same volumeIdentifier as + /// `/` (firmlinks), so only the `isVolume` test keeps the walk out. + func testVolumeRootsAreNeverEntered() throws { + let volumes = URL(fileURLWithPath: "/System/Volumes", isDirectory: true) + try XCTSkipUnless(FileManager.default.fileExists(atPath: volumes.appendingPathComponent("Data").path)) + var visited: [String] = [] + _ = FolderListing.scan(volumes, limits: .init(maxDepth: 1, maxFiles: 10, maxEntries: 100), + didVisit: { visited.append($0) }) + XCTAssertFalse(visited.contains("Data"), "\(visited)") + XCTAssertFalse(visited.contains("Preboot"), "\(visited)") + } + + /// Finder order is a STRICT total order on distinct names (exactly one + /// of a Date: Tue, 17 Nov 2026 14:33:29 +0100 Subject: [PATCH 06/27] fix: a formula used as link text is drawn in the link colour and underlined `See [$x$](u)` drew the formula in the text colour with no underline: the attachment carried `.link` and `.underlineStyle`, but its image was typeset in the theme's text colour and TextKit 1 never underlines an attachment's run. - MathRendering.inlineImageInColor: the formula is typeset in the link's colour (an input of the image; the engine is untouched). nil falls back to inlineImage, so stubs keep working. - FittingMathAttachment.linkUnderline + drawLinkUnderline, called after the glyphs by DocumentSelectionLayoutManager.drawGlyphs: AppKit's own text underline (a kerned no-break space in the link's font) so it meets the link text's underline exactly; at the bottom of the line when the formula reaches below the text's descenders or the line holds no text descent. The source box keeps its own underlined link text. - Drawing only: bounds, the fit rule and every measured height unchanged; an unlinked formula is pixel-identical. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/BlockHeightMeasurer.swift | 195 ++++++++++++- QuickMD/QuickMD/DocumentSelection.swift | 9 + QuickMD/QuickMD/Views/MathBlockView.swift | 28 +- .../QuickMDTests/MathInTextKindsTests.swift | 268 ++++++++++++++++++ 4 files changed, 481 insertions(+), 19 deletions(-) diff --git a/QuickMD/QuickMD/BlockHeightMeasurer.swift b/QuickMD/QuickMD/BlockHeightMeasurer.swift index dd34c6c..2f843c9 100644 --- a/QuickMD/QuickMD/BlockHeightMeasurer.swift +++ b/QuickMD/QuickMD/BlockHeightMeasurer.swift @@ -742,6 +742,19 @@ struct MathRendering { /// when it does not typeset. nil = `inlineImage` stands in (stubs, the /// search placeholder: only the attachment character matters there). var displayImage: ((_ latex: String, _ theme: MarkdownTheme, _ fontSize: CGFloat) -> NSImage?)? + /// Renders one inline formula as `inlineImage` does, in `color` instead of + /// the theme's text colour: a formula that is link text (`[$x$](u)`) takes + /// the link's colour (v1.16). The colour is an INPUT of the image, so the + /// engine is not touched. nil = `inlineImage` stands in (stubs, the search + /// placeholder: only the attachment character matters there). + var inlineImageInColor: ((_ latex: String, _ fontSize: CGFloat, _ color: NSColor) -> NSImage?)? + + /// The image an inline formula is drawn with: in `color` when it is link + /// text (`inlineImageInColor`), else in the theme's text colour. + func formulaImage(_ latex: String, theme: MarkdownTheme, fontSize: CGFloat, color: NSColor?) -> NSImage? { + if let color, let inColor = inlineImageInColor { return inColor(latex, fontSize, color) } + return inlineImage(latex, theme, fontSize) + } /// No math engine: inline math degrades to the italic-literal fallback and /// display math to zero intrinsic height. Only for tests and previews. @@ -800,9 +813,24 @@ final class FittingMathAttachment: NSTextAttachment { private let capHeight: CGFloat private let source: NSAttributedString - init(image: NSImage, capHeight: CGFloat, source: NSAttributedString) { + /// The underline of the link text a formula is part of (`[$x$](u)`): + /// the link's colour and underline style, and the font of the text + /// around it, which decides where AppKit puts that text's underline. + struct LinkUnderline { + let font: NSFont + let color: NSColor + let style: Int + } + + /// nil = not link text. An unlinked formula draws exactly as before 1.16. + let linkUnderline: LinkUnderline? + + /// `linkUnderline`: the formula is underlined link text (v1.16) — see + /// `drawLinkUnderline`. Its image already comes in the link's colour. + init(image: NSImage, capHeight: CGFloat, source: NSAttributedString, linkUnderline: LinkUnderline? = nil) { self.capHeight = capHeight self.source = source + self.linkUnderline = linkUnderline super.init(data: nil, ofType: nil) self.image = image bounds = Self.bounds(for: image.size, capHeight: capHeight, availableWidth: .greatestFiniteMagnitude) @@ -811,6 +839,7 @@ final class FittingMathAttachment: NSTextAttachment { required init?(coder: NSCoder) { capHeight = 0 source = NSAttributedString() + linkUnderline = nil super.init(coder: coder) } @@ -871,9 +900,7 @@ final class FittingMathAttachment: NSTextAttachment { override func image(forBounds imageBounds: CGRect, textContainer: NSTextContainer?, characterIndex charIndex: Int) -> NSImage? { guard let image, image.size.width > 0, image.size.height > 0 else { return image } - let sameAspect = abs(imageBounds.width * image.size.height - imageBounds.height * image.size.width) - <= max(imageBounds.width, imageBounds.height) * 0.01 - guard !sameAspect else { return image } + guard showsSource(laidOutAs: imageBounds.size) else { return image } let source = self.source return NSImage(size: imageBounds.size, flipped: true) { rect in // Cut at the box (`maximumSourceLines`), the last line with "…". @@ -881,6 +908,143 @@ final class FittingMathAttachment: NSTextAttachment { return true } } + + /// Whether a box laid out `size` big is the source box: its aspect is + /// not the image's (a scaled formula keeps it). + private func showsSource(laidOutAs size: CGSize) -> Bool { + guard let image, image.size.width > 0, image.size.height > 0 else { return false } + return abs(size.width * image.size.height - size.height * image.size.width) + > max(size.width, size.height) * 0.01 + } + + // MARK: Link underline (v1.16) + + /// Draws the underline of a formula that is link text, as the link text + /// beside it is underlined. TextKit 1 underlines the text runs of a link + /// but skips an attachment's run (`underlineGlyphRange` is never called + /// for it), so the formula carried `.underlineStyle` and showed none. + /// Called after the glyphs by the layout manager of every view that shows + /// these strings (`DocumentSelectionLayoutManager.drawGlyphs`): TextKit + /// draws an image attachment only inside its own box (`image(forBounds:)`; + /// an `attachmentCell` is never asked to draw while the attachment has an + /// image), and the text's underline lies below that box. + /// + /// Drawing only, inside the line the formula sits on: the attachment's + /// bounds, the fit rule and every measured height stay as they were. + /// - The line is AppKit's own: a layout manager underlines one + /// no-break space in the link's font, kerned to the formula's width + /// (`drawTextUnderline`). AppKit's position is not the font's + /// `underlinePosition` (measured: Menlo 13 says 0.8 pt, AppKit draws + /// 1.1–1.75 pt), so only AppKit's own drawing meets the text's + /// underline on either side exactly, at every scale. + /// - Where AppKit's line would not lie inside the formula's line, the + /// underline lies at the bottom of that line instead, as thick as the + /// text's: a formula that reaches deeper than the text's descenders (a + /// fraction, a sum with limits — it would be struck through), or a line + /// with no text below the baseline (a formula alone on its line or in + /// a table cell: the line ends at the baseline). A shallower formula in + /// a line of text is crossed as the text's own descenders are. + /// - The source box (a formula too wide even at half size) draws none + /// here: its text is link text with its own underline + /// (`inlineFallback(link:)`). + /// + /// - Parameters: + /// - frame: the formula's laid-out box in the drawing coordinates + /// (flipped, as a text view draws). + /// - baseline: the line's baseline, same coordinates. + /// - lineBottom: the bottom of the line's used rect, same coordinates. + func drawLinkUnderline(frame: CGRect, baseline: CGFloat, lineBottom: CGFloat) { + guard let linkUnderline, frame.width > 0, !showsSource(laidOutAs: frame.size) else { return } + let descender = -linkUnderline.font.descender // `descender` is negative + // A line of text ends its descent in whole points (TextKit rounds: + // a 26 pt heading's line keeps 5 of 5.48), so `floor` is "the line + // holds the text's descent"; a formula alone on its line keeps none. + let lineHoldsDescent = lineBottom - baseline >= floor(descender) + if frame.maxY <= baseline + descender && lineHoldsDescent { + Self.drawTextUnderline(linkUnderline, x: frame.minX, width: frame.width, baseline: baseline) + } else { + Self.drawLineBottomUnderline(linkUnderline, x: frame.minX, width: frame.width, lineBottom: lineBottom) + } + } + + /// A line `underline.font.underlineThickness` thick (whole device + /// pixels, rounded up, as AppKit's) whose bottom is the line's bottom. + private static func drawLineBottomUnderline(_ underline: LinkUnderline, x: CGFloat, width: CGFloat, + lineBottom: CGFloat) { + guard let context = NSGraphicsContext.current?.cgContext else { return } + let thickness = underline.font.underlineThickness + // Orientation-agnostic: snap the bottom edge to a device pixel and + // grow whole pixels towards the line's inside. + let bottom = context.convertToDeviceSpace(CGPoint(x: x, y: lineBottom)) + let top = context.convertToDeviceSpace(CGPoint(x: x, y: lineBottom - thickness)) + let right = context.convertToDeviceSpace(CGPoint(x: x + width, y: lineBottom)) + let pixels = max(1, ceil(abs(top.y - bottom.y) - 0.001)) + let edge = bottom.y.rounded() + let inner = edge + (top.y < bottom.y ? -pixels : pixels) + let device = CGRect(x: bottom.x.rounded(), y: min(edge, inner), + width: max(1, right.x.rounded() - bottom.x.rounded()), height: pixels) + context.saveGState() + context.setFillColor(underline.color.cgColor) + context.fill(context.convertToUserSpace(device).standardized) + context.restoreGState() + } + + /// AppKit's underline of `width` points of text in `underline.font`, + /// starting at `x` on `baseline` (flipped drawing coordinates): one + /// no-break space in a scratch TextKit 1 stack, kerned to `width`. The + /// space draws nothing; its underline is drawn by the same layout + /// manager code as the link text's. + private static func drawTextUnderline(_ underline: LinkUnderline, x: CGFloat, width: CGFloat, + baseline: CGFloat) { + let space = "\u{00A0}" + let advance = (space as NSString).size(withAttributes: [.font: underline.font]).width + let storage = NSTextStorage(string: space, attributes: [ + .font: underline.font, .foregroundColor: underline.color, .underlineStyle: underline.style, + .kern: width - advance, + ]) + let layoutManager = NSLayoutManager() + let container = NSTextContainer(size: NSSize(width: CGFloat.greatestFiniteMagnitude, + height: CGFloat.greatestFiniteMagnitude)) + container.lineFragmentPadding = 0 + layoutManager.addTextContainer(container) + storage.addLayoutManager(layoutManager) + layoutManager.ensureLayout(for: container) + let glyphs = NSRange(location: 0, length: layoutManager.numberOfGlyphs) + guard glyphs.length > 0 else { return } + let ownBaseline = layoutManager.lineFragmentRect(forGlyphAt: 0, effectiveRange: nil).minY + + layoutManager.location(forGlyphAt: 0).y + layoutManager.drawGlyphs(forGlyphRange: glyphs, at: NSPoint(x: x, y: baseline - ownBaseline)) + } + + /// Every linked formula's underline among `glyphRange`, drawn by a + /// layout manager after its glyphs (`DocumentSelectionLayoutManager`): + /// `origin` is the text container's origin, as `drawGlyphs` gets it. + static func drawLinkUnderlines(of layoutManager: NSLayoutManager, forGlyphRange glyphRange: NSRange, + at origin: NSPoint) { + guard let storage = layoutManager.textStorage, glyphRange.length > 0 else { return } + let characters = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil) + storage.enumerateAttribute(.attachment, in: characters) { value, range, _ in + guard let formula = value as? FittingMathAttachment, formula.linkUnderline != nil else { return } + for index in range.location.. FittingMathAttachment.LinkUnderline? { + guard let underline, underline != 0 else { return nil } + return FittingMathAttachment.LinkUnderline(font: font ?? theme.fonts.appKit(size: fontSize), + color: color ?? NSColor(theme.linkColor), style: underline) } /// `colors`: also the link's colour (text, the fallback) — an diff --git a/QuickMD/QuickMD/DocumentSelection.swift b/QuickMD/QuickMD/DocumentSelection.swift index 652ce16..a951f96 100644 --- a/QuickMD/QuickMD/DocumentSelection.swift +++ b/QuickMD/QuickMD/DocumentSelection.swift @@ -223,6 +223,15 @@ final class DocumentSelectionLayoutManager: NSLayoutManager { for rect in rects { rect.fill(using: .sourceOver) } } + /// The glyphs, then the underline of every formula that is link text + /// (`FittingMathAttachment.drawLinkUnderlines`, v1.16): TextKit skips an + /// attachment when it underlines a link. Drawing only, like everything + /// here. + override func drawGlyphs(forGlyphRange glyphsToShow: NSRange, at origin: NSPoint) { + super.drawGlyphs(forGlyphRange: glyphsToShow, at: origin) + FittingMathAttachment.drawLinkUnderlines(of: self, forGlyphRange: glyphsToShow, at: origin) + } + override func fillBackgroundRectArray(_ rectArray: UnsafePointer, count rectCount: Int, forCharacterRange charRange: NSRange, color: NSColor) { guard let covered = selectionCoveredRange, diff --git a/QuickMD/QuickMD/Views/MathBlockView.swift b/QuickMD/QuickMD/Views/MathBlockView.swift index eb11d09..467c076 100644 --- a/QuickMD/QuickMD/Views/MathBlockView.swift +++ b/QuickMD/QuickMD/Views/MathBlockView.swift @@ -34,18 +34,7 @@ extension MathRendering { /// additionally rounds up, which is the safe direction for a row height). static let swiftMath = MathRendering( inlineImage: { latex, theme, fontSize in - var mathImage = MathImage( - latex: latex, - fontSize: fontSize, - textColor: NSColor(theme.textColor), - labelMode: .text, - textAlignment: .left - ) - let (error, image, _) = mathImage.asImage() - // Nothing drawn (an empty or spacing-only `$…$`, an accent over - // nothing): the italic literal, like a formula that fails. - guard error == nil, let image, MathInk.drawsSomething(latex, image: image) else { return nil } - return image + inlineFormula(latex, fontSize: fontSize, color: NSColor(theme.textColor)) }, displayHeight: { latex, theme, fontScale in var mathImage = MathImage( @@ -71,8 +60,23 @@ extension MathRendering { let (error, image, _) = mathImage.asImage() guard error == nil, let image, MathInk.drawsSomething(latex, image: image) else { return nil } return image + }, + // A formula that is link text, in the link's colour (v1.16). + inlineImageInColor: { latex, fontSize, color in + inlineFormula(latex, fontSize: fontSize, color: color) } ) + + /// One inline formula, text style, in `color`; nil when nothing is drawn + /// (an empty or spacing-only `$…$`, an accent over nothing: the italic + /// literal, like a formula that fails). + private static func inlineFormula(_ latex: String, fontSize: CGFloat, color: NSColor) -> NSImage? { + var mathImage = MathImage(latex: latex, fontSize: fontSize, textColor: color, + labelMode: .text, textAlignment: .left) + let (error, image, _) = mathImage.asImage() + guard error == nil, let image, MathInk.drawsSomething(latex, image: image) else { return nil } + return image + } } // MARK: - Formulas that typeset to nothing diff --git a/QuickMD/QuickMDTests/MathInTextKindsTests.swift b/QuickMD/QuickMDTests/MathInTextKindsTests.swift index 904251a..cc488ab 100644 --- a/QuickMD/QuickMDTests/MathInTextKindsTests.swift +++ b/QuickMD/QuickMDTests/MathInTextKindsTests.swift @@ -1049,6 +1049,274 @@ final class MathInTextKindsTests: XCTestCase { } } + // MARK: - A formula in link text looks like the link (v1.16) + + /// The theme role a colour equals (`text`, `link`), resolved in the + /// light appearance — never an sRGB value (constraints "Tests (v1.15)"). + private func role(_ color: NSColor?) -> String { + guard let color else { return "-" } + var name = "other" + NSAppearance(named: .aqua)!.performAsCurrentDrawingAppearance { + guard let value = color.usingColorSpace(.sRGB) else { return } + for (role, themeColor) in [("text", theme.textColor), ("link", theme.linkColor)] { + guard let expected = NSColor(themeColor).usingColorSpace(.sRGB) else { continue } + if abs(value.redComponent - expected.redComponent) < 0.02, + abs(value.greenComponent - expected.greenComponent) < 0.02, + abs(value.blueComponent - expected.blueComponent) < 0.02, + abs(value.alphaComponent - expected.alphaComponent) < 0.02 { name = role } + } + } + return name + } + + /// The stub engine with the colour entry: a box of `size` filled with the + /// colour the formula was asked in (the theme's text colour through + /// `inlineImage`), only its top `filled` part — so a line drawn under + /// the box is told apart from the box itself. + private func paintingEngine(_ asked: ((String, String) -> Void)? = nil, filled: CGFloat = 1) -> MathRendering { + func box(_ latex: String, _ color: NSColor) -> NSImage { + let tall = latex.contains("\\frac") + let size = tall ? NSSize(width: 20, height: 30) : NSSize(width: 20, height: 6) + return NSImage(size: size, flipped: true) { rect in + color.setFill() + NSRect(x: 0, y: 0, width: rect.width, height: rect.height * filled).fill() + return true + } + } + return MathRendering(inlineImage: { latex, theme, _ in + asked?(latex, "theme.text") + return box(latex, NSColor(theme.textColor)) + }, displayHeight: { _, _, _ in 40 }, inlineImageInColor: { latex, _, color in + asked?(latex, self.role(color)) + return box(latex, color) + }) + } + + /// Every formula attachment of `string`, in order. + private func formulas(in string: NSAttributedString) -> [FittingMathAttachment] { + var found: [FittingMathAttachment] = [] + string.enumerateAttribute(.attachment, in: NSRange(location: 0, length: string.length)) { value, _, _ in + if let formula = value as? FittingMathAttachment { found.append(formula) } + } + return found + } + + /// `[$x$](u)` in every text kind is typeset in the LINK's colour and + /// carries the link's underline; `$x$` beside it in the same block stays + /// in the text colour with none — two images, never one shared (M1, M3). + @MainActor + func testFormulaInLinkTextIsTypesetInTheLinkColour() { + let markdown = """ + See $x$ and [$x$](https://e.com) here + + # See $x$ and [$x$](https://e.com) here + + > See $x$ and [$x$](https://e.com) here + + - See $x$ and [$x$](https://e.com) here + + > [!NOTE] + > See $x$ and [$x$](https://e.com) here + + | A | + |---| + | See $x$ and [$x$](https://e.com) here | + """ + var asked: [String] = [] + let blocks = parse(markdown) + let measured = measure(blocks, math: paintingEngine { _, role in asked.append(role) }) + XCTAssertEqual(blocks.count, 6) + // Every formula asked in its own colour: the text's or the link's. + XCTAssertEqual(Set(asked), ["theme.text", "link"]) + XCTAssertEqual(asked.filter { $0 == "link" }.count, asked.filter { $0 == "theme.text" }.count) + for block in blocks { + guard let string = measured.converted[block.id] ?? measured.tables[block.id]?.string else { + XCTFail("\(block.content)"); continue + } + let found = formulas(in: string) + XCTAssertEqual(found.count, 2, "\(block.content)") + guard found.count == 2 else { continue } + XCTAssertNil(found[0].linkUnderline, "\(block.content): an unlinked formula draws no underline") + XCTAssertEqual(role(found[1].linkUnderline?.color), "link", "\(block.content)") + XCTAssertFalse(found[0].image === found[1].image, "\(block.content): one image per colour") + } + } + + /// A linked formula's measured height is the unlinked one's in every + /// kind and every fit state — natural, tall, scaled down to fit, shown as + /// its source (M2: drawing only, no layout change). + @MainActor + func testLinkedFormulaKeepsTheMeasuredHeight() { + for (formula, width) in [("x", 600.0), ("\\frac{a}{b}", 600), ("long", 400), ("matrix", 300)] { + func document(_ linked: Bool) -> String { + let atom = linked ? "[$\(formula)$](https://e.com)" : "$\(formula)$" + return "See \(atom) here\n\n# See \(atom) here\n\n> See \(atom) here\n\n" + + "| A |\n|---|\n| See \(atom) here |\n\n\(atom)" + } + let plainBlocks = parse(document(false)), linkedBlocks = parse(document(true)) + // The sizes `engine()` gives, through the colour entry too. + let base = engine() + let math = MathRendering(inlineImage: base.inlineImage, displayHeight: base.displayHeight, + inlineImageInColor: { latex, size, _ in base.inlineImage(latex, self.theme, size) }) + let plain = measure(plainBlocks, math: math, width: width) + let linked = measure(linkedBlocks, math: math, width: width) + XCTAssertEqual(plainBlocks.count, linkedBlocks.count, formula) + XCTAssertEqual(plain.table.heights, linked.table.heights, "\(formula) at \(width)") + } + } + + /// The drawn result (M1, M2, M4): a linked formula is underlined at the + /// rows AppKit underlines the link text beside it, in the link colour, at + /// 1× and 2×; a formula deeper than the text is underlined at the bottom + /// of its line, inside it; a formula scaled down to fit keeps both; an + /// unlinked formula has nothing under it. + @MainActor + func testLinkedFormulaIsDrawnUnderlinedLikeTheLinkText() { + let theme = self.theme + let cases: [(markdown: String, width: CGFloat, atTextRows: Bool)] = [ + ("See [$x$](https://e.com) and [a text link](https://e.com).", 600, true), + ("See [$\\frac{a}{b}$](https://e.com) and [a text link](https://e.com).", 600, false), + ("# See [$x$](https://e.com) and [a text link](https://e.com)", 600, true), + ] + for scale in [1, 2] { + for (markdown, width, atTextRows) in cases { + let blocks = parse(markdown) + let measured = measure(blocks, math: paintingEngine(filled: 0.5), width: width) + guard let string = measured.converted[blocks[0].id] else { XCTFail(markdown); continue } + let drawn = DrawnText(string, width: width, scale: CGFloat(scale), theme: theme) + let label = "\(markdown) @\(scale)x" + let link = drawn.rect(of: "a text link") + let underline = drawn.rows(in: link.minX...link.maxX, below: link.midY) { self.role($0) == "link" } + XCTAssertFalse(underline.isEmpty, "\(label): the text link is underlined") + let formula = drawn.formulaRects()[0] + let columns = (formula.minX + 1)...(formula.maxX - 1) + let under = drawn.rows(in: columns, below: formula.midY) { self.role($0) == "link" } + if atTextRows { + XCTAssertEqual(under, underline, "\(label): the formula's underline is the text's") + } else { + XCTAssertFalse(under.isEmpty, "\(label): underlined") + XCTAssertEqual(under.max(), drawn.lineBottomRow(of: formula), "\(label): at the line's bottom") + } + } + } + // Unlinked: nothing under the formula; scaled down to fit: still + // link-coloured and underlined, inside its row. + for (markdown, width, expectsLine) in [("See $x$ here and $x$.", CGFloat(600), false), + ("See [$long$](https://e.com) here", 400, true)] { + let blocks = parse(markdown) + let measured = measure(blocks, math: MathRendering( + inlineImage: { latex, theme, _ in + NSImage(size: latex == "long" ? NSSize(width: 500, height: 6) : NSSize(width: 20, height: 6), + flipped: true) { NSColor(theme.textColor).setFill(); $0.fill(); return true } + }, displayHeight: { _, _, _ in 40 }, + inlineImageInColor: { _, _, color in + NSImage(size: NSSize(width: 500, height: 6), flipped: true) { color.setFill(); $0.fill(); return true } + }), width: width) + guard let string = measured.converted[blocks[0].id] else { XCTFail(markdown); continue } + let drawn = DrawnText(string, width: width, scale: 2, theme: theme) + for formula in drawn.formulaRects() { + XCTAssertLessThanOrEqual(formula.width, width, markdown) + let below = drawn.rows(in: (formula.minX + 1)...(formula.maxX - 1), below: formula.maxY - 0.5) { + self.role($0) == "link" + } + XCTAssertEqual(!below.isEmpty, expectsLine, markdown) + XCTAssertTrue(below.allSatisfy { $0 <= drawn.lineBottomRow(of: formula) }, "\(markdown): inside its line") + if expectsLine { + XCTAssertEqual(role(drawn.color(atPoint: NSPoint(x: formula.midX, y: formula.minY + 1))), "link", + "\(markdown): the scaled formula keeps the link colour") + } + } + } + } + + /// `string` laid out and drawn as a document row draws it: a text view + /// with `DocumentSelectionLayoutManager`, the light appearance, into a + /// bitmap at `scale` pixels per point. + @MainActor + private struct DrawnText { + let string: NSAttributedString + let textView: NSTextView + let bitmap: NSBitmapImageRep + let scale: CGFloat + let height: CGFloat + + init(_ string: NSAttributedString, width: CGFloat, scale: CGFloat, theme: MarkdownTheme) { + self.string = string + self.scale = scale + textView = NSTextView(frame: NSRect(x: 0, y: 0, width: width, height: 10)) + textView.configureForSelfSizing() + textView.installDocumentSelectionLayoutManager() + // As `TextBlockView`: the renderer's link look, not NSTextView's. + textView.linkTextAttributes = [.cursor: NSCursor.pointingHand] + textView.appearance = NSAppearance(named: .aqua) + textView.drawsBackground = true + textView.backgroundColor = NSColor(theme.backgroundColor) + textView.textStorage?.setAttributedString(string) + let layoutManager = textView.layoutManager!, container = textView.textContainer! + layoutManager.ensureLayout(for: container) + height = ceil(layoutManager.usedRect(for: container).height) + textView.frame = NSRect(x: 0, y: 0, width: width, height: height) + bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(width * scale), + pixelsHigh: Int(height * scale), bitsPerSample: 8, samplesPerPixel: 4, + hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, + bytesPerRow: 0, bitsPerPixel: 0)! + bitmap.size = NSSize(width: width, height: height) + let (view, target) = (textView, bitmap) + NSAppearance(named: .aqua)!.performAsCurrentDrawingAppearance { + view.cacheDisplay(in: view.bounds, to: target) + } + } + + func rect(of text: String) -> NSRect { + let range = (string.string as NSString).range(of: text) + let layoutManager = textView.layoutManager! + return layoutManager.boundingRect(forGlyphRange: layoutManager.glyphRange(forCharacterRange: range, + actualCharacterRange: nil), + in: textView.textContainer!) + } + + /// The laid-out box of every formula (an attachment glyph's location + /// is its box's bottom-left corner). + func formulaRects() -> [NSRect] { + let layoutManager = textView.layoutManager! + var rects: [NSRect] = [] + string.enumerateAttribute(.attachment, in: NSRange(location: 0, length: string.length)) { value, range, _ in + guard value != nil else { return } + let glyph = layoutManager.glyphIndexForCharacter(at: range.location) + let fragment = layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil) + let location = layoutManager.location(forGlyphAt: glyph) + let size = layoutManager.attachmentSize(forGlyphAt: glyph) + rects.append(NSRect(x: fragment.minX + location.x, y: fragment.minY + location.y - size.height, + width: size.width, height: size.height)) + } + return rects + } + + /// The last pixel row of the used line `formula` sits on. + func lineBottomRow(of formula: NSRect) -> Int { + let layoutManager = textView.layoutManager! + let glyph = layoutManager.glyphIndex(for: NSPoint(x: formula.midX, y: formula.midY), + in: textView.textContainer!) + let used = layoutManager.lineFragmentUsedRect(forGlyphAt: glyph, effectiveRange: nil) + return Int((used.maxY * scale).rounded()) - 1 + } + + func color(atPoint point: NSPoint) -> NSColor? { + bitmap.colorAt(x: Int(point.x * scale), y: Int(point.y * scale)) + } + + /// Pixel rows below `y` (points) where at least 80 % of the pixels + /// in `columns` (points) pass `test`. + func rows(in columns: ClosedRange, below y: CGFloat, where test: (NSColor?) -> Bool) -> [Int] { + let x0 = Int((columns.lowerBound * scale).rounded(.up)), x1 = Int((columns.upperBound * scale).rounded(.down)) + guard x1 > x0 else { return [] } + return (Int(y * scale)..= 0.8 * Double(x1 - x0) + } + } + } + // MARK: - Heading baseline with a tall formula (seam review N1) /// `# $\frac{a}{b}$ Title`: the formula is taller than the heading's From 99f821abdeb8c2433e7d49b0a88e257c48983c9e Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 14:33:29 +0100 Subject: [PATCH 07/27] fix: print a formula used as link text in the link colour PrintableMath typesets a formula inside a link in the link's colour, and its italic source fallback is link-coloured and underlined, as on screen. SwiftUI Text draws no underline under an image, so the printed typeset formula has none. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/MarkdownExport.swift | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/QuickMD/QuickMD/MarkdownExport.swift b/QuickMD/QuickMD/MarkdownExport.swift index 21c8924..c435894 100644 --- a/QuickMD/QuickMD/MarkdownExport.swift +++ b/QuickMD/QuickMD/MarkdownExport.swift @@ -968,8 +968,11 @@ enum PrintableMath { return error == nil ? image : nil } - static func inlineImage(_ latex: String, fontSize: CGFloat = 14) -> (image: NSImage, descent: CGFloat)? { - var mathImage = MathImage(latex: latex, fontSize: fontSize, textColor: .black, + /// `color`: a formula that is link text prints in the link's colour + /// (v1.16, as on screen); black otherwise. + static func inlineImage(_ latex: String, fontSize: CGFloat = 14, + color: NSColor = .black) -> (image: NSImage, descent: CGFloat)? { + var mathImage = MathImage(latex: latex, fontSize: fontSize, textColor: color, labelMode: .text, textAlignment: .left) let (error, image, info) = mathImage.asImage() // Nothing drawn: the italic literal, as on screen (`MathInk`). @@ -1014,15 +1017,27 @@ enum PrintableMath { index = end } case .math(let latex): + // A formula in link text takes the link's colour, as on + // screen (v1.16). The underline stays the screen's: SwiftUI + // `Text` draws none under an image. + var linkColor: Color? if let end = attributed.characters.index(index, offsetBy: piece.length, limitedBy: attributed.endIndex) { + if let run = attributed[index.. Date: Tue, 17 Nov 2026 14:35:19 +0100 Subject: [PATCH 08/27] fix: a thematic break may have spaces between its characters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `* * *`, `- - -`, `_ _ _` and `** **` are rules on GitHub (CommonMark), but the rule pattern wanted the characters touching, so `* * *` and `- - -` were drawn as the bullets "• * *" / "• - -" and `_ _ _` as text, and a list went on across them. The one pattern now takes three or more of one character with spaces or tabs between; every reader of a rule uses it and checks it before list items. Front matter and the setext underline keep their exact `---`. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/MarkdownRenderer.swift | 3 +- QuickMD/QuickMD/MarkdownTheme.swift | 10 +++- QuickMD/QuickMDTests/ListContentTests.swift | 52 +++++++++++++++++++++ 3 files changed, 62 insertions(+), 3 deletions(-) diff --git a/QuickMD/QuickMD/MarkdownRenderer.swift b/QuickMD/QuickMD/MarkdownRenderer.swift index dac86a7..e8bd5a7 100644 --- a/QuickMD/QuickMD/MarkdownRenderer.swift +++ b/QuickMD/QuickMD/MarkdownRenderer.swift @@ -455,7 +455,8 @@ struct MarkdownRenderer: Sendable { return !isBlankLine(trimmed.dropFirst(2)) } - /// A thematic break (`---`, `***`, `___`) — `renderLine` draws it as a rule. + /// A thematic break (`---`, `***`, `___`, also spaced: `* * *`) — + /// `renderLine` draws it as a rule. static func isThematicBreak(_ line: String) -> Bool { markerLine(line) .range(of: MarkdownTheme.horizontalRulePattern, options: .regularExpression) != nil diff --git a/QuickMD/QuickMD/MarkdownTheme.swift b/QuickMD/QuickMD/MarkdownTheme.swift index 2b88853..c0e5305 100644 --- a/QuickMD/QuickMD/MarkdownTheme.swift +++ b/QuickMD/QuickMD/MarkdownTheme.swift @@ -297,8 +297,14 @@ struct MarkdownTheme: Sendable, Identifiable { /// Captures: (1) hash marks, (2) header text static let headerPattern = #"^(#{1,6})[ \t]+(.*)$"# - /// Matches horizontal rules: ***, ---, ___ (3 or more) - static let horizontalRulePattern = #"^(\*{3,}|-{3,}|_{3,})[ \t]*$"# + /// Matches horizontal rules (CommonMark thematic breaks) on a TRIMMED + /// line: three or more of ONE of `*`, `-`, `_`, with any spaces or tabs + /// between them (`* * *`, `- - -`, `** **`). Before 1.16 the characters + /// had to touch, and `* * *` was drawn as the bullet "• * *". Every + /// reader of a rule goes through this one pattern (`isThematicBreak`), + /// and each checks it before list items. The front-matter fence and the + /// setext underline keep their own exact `---` patterns. + static let horizontalRulePattern = #"^(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$"# /// Matches task list items: - [ ] or - [x] with optional indentation /// Captures: (1) indent whitespace, (2) check state (space or x), (3) content diff --git a/QuickMD/QuickMDTests/ListContentTests.swift b/QuickMD/QuickMDTests/ListContentTests.swift index 144bf98..64f89fa 100644 --- a/QuickMD/QuickMDTests/ListContentTests.swift +++ b/QuickMD/QuickMDTests/ListContentTests.swift @@ -668,6 +668,12 @@ final class ListContentTests: XCTestCase { // list may interrupt the item's paragraph only when it starts at 1); // QuickMD draws nested ordered items counting from 3. XCTAssertEqual(try markers("- a\n 3. x\n 3. y\n- b\n 3. z"), "• [3 4] • [3]") + // A bullet short of the ordered item's content column is drawn + // nested (a level is 2 columns), so it counts as nested and the + // list goes on. GitHub: `
      1. a
      • x
      1. b
      ` + // and `
      1. a
      • x
      1. b
      `. + XCTAssertEqual(try markers("1. a\n - x\n1. b"), "1 [•] 2") + XCTAssertEqual(try markers("10. a\n - x\n10. b"), "10 [•] 11") // GitHub `
        …`; QuickMD keeps a quote's lines literal. guard case .blockquote(let quote, _) = try XCTUnwrap(parse("> 7. a\n> 7. b").first).content else { return XCTFail("quote") } @@ -676,6 +682,52 @@ final class ListContentTests: XCTestCase { XCTAssertFalse(shown.contains("8."), shown) } + // MARK: - Thematic breaks with spaces + + /// The block list with every drawn rule as `HR`. + private func ruleShape(_ markdown: String) -> [String] { + shape(parse(markdown)).map { $0.replacingOccurrences(of: String(repeating: "─", count: 32), with: "HR") } + } + + /// Three or more of ONE of `*`, `-`, `_`, with spaces or tabs between + /// them, are a rule — before any list reading. GitHub (`gh api markdown`, + /// 2026-11-17): `
        ` for each of these. + func testARuleMayHaveSpacesBetweenItsCharacters() { + for rule in ["* * *", "- - -", "_ _ _", " ***", "** **", "- - - -", "_\t_\t_"] { + XCTAssertEqual(ruleShape(rule), ["T:HR"], rule.debugDescription) + XCTAssertTrue(MarkdownRenderer.isThematicBreak(rule), rule.debugDescription) + XCTAssertFalse(MarkdownRenderer.isListItem(rule), rule.debugDescription) + } + //

        -

        and

        ***a

        : no rule. + XCTAssertFalse(MarkdownRenderer.isThematicBreak("*-*")) + XCTAssertFalse(MarkdownRenderer.isThematicBreak("***a")) + XCTAssertFalse(ruleShape("*-*").contains("T:HR")) + XCTAssertEqual(ruleShape("***a"), ["T:***a"]) + // GitHub draws `- - x` / `* *` as nested empty bullets; QuickMD keeps + // its one-line reading of them (a bullet), and never a rule. + XCTAssertEqual(ruleShape("- - x"), ["T:• - x"]) + XCTAssertEqual(ruleShape("* *"), ["T:• *"]) + } + + /// A spaced rule ends a paragraph or a list like `---` does, and is the + /// item's when indented to its content column. + func testASpacedRuleBetweenBlocks() throws { + //

        text


        (not a setext heading: that is `---` only) + XCTAssertEqual(ruleShape("text\n- - -"), ["T:text", "T:HR"]) + //

        text

        + XCTAssertEqual(parse("text\n---").map(\.id).count, 1) + guard case .heading(2, _, _) = try XCTUnwrap(parse("text\n---").first).content else { return XCTFail("setext") } + //
        1. a

        1. b
        + XCTAssertEqual(ruleShape("1. a\n* * *\n2. b"), ["T:1. a", "T:HR", "T:2. b"]) + //
        • a

        • b
        + XCTAssertEqual(ruleShape("- a\n- - -\n- b"), ["T:• a", "T:HR", "T:• b"]) + //
        1. a


        2. b

        : one list + XCTAssertEqual(try markers("1. a\n\n * * *\n\n1. b"), "1 2") + //
        1. a

        1. b
        : two lists + XCTAssertEqual(try markers("1. a\n\n* * *\n\n1. b"), "1 1") + XCTAssertTrue(ruleShape("1. a\n\n* * *\n\n1. b").contains("T:HR")) + } + // MARK: - Content column func testContentColumnOfAnItem() { From 4873396524d27a0b7da0dd1eff890300106782cd Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 14:38:10 +0100 Subject: [PATCH 09/27] fix: Open Folder caps folders read, says when a listing is incomplete, never keeps a folder it could not open (#62) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The cost cap counts folders read (2 000, root included) instead of entries, so one huge sibling no longer hides another; a folder read is listed whole. A truncated result never reads "No Markdown files": the sidebar says "This folder is too large to list" with no files listed, the no-window flow alerts "“name” is too large to list". - An explicit Open of a missing or unreadable folder alerts and leaves no folder and no remembered path; only a folder listed this session or restored at launch is kept when it cannot be read. - Missing vs unreadable comes from stat's error (LocalLinkOpening .existence): EACCES/EPERM is unreadable, so a remembered folder is not forgotten at launch over a permission. - A kept unreadable folder shows "Can’t read this folder" under its header. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderBrowserStore.swift | 46 ++++++++++---- QuickMD/QuickMD/FolderListing.swift | 58 +++++++++-------- QuickMD/QuickMD/QuickMDApp.swift | 4 +- .../Views/RecentDocumentsSidebar.swift | 14 ++++- .../FolderBrowserStoreTests.swift | 63 ++++++++++++++++--- QuickMD/QuickMDTests/FolderListingTests.swift | 62 +++++++++++++----- 6 files changed, 184 insertions(+), 63 deletions(-) diff --git a/QuickMD/QuickMD/FolderBrowserStore.swift b/QuickMD/QuickMD/FolderBrowserStore.swift index da16442..d2cefec 100644 --- a/QuickMD/QuickMD/FolderBrowserStore.swift +++ b/QuickMD/QuickMD/FolderBrowserStore.swift @@ -96,6 +96,12 @@ final class FolderBrowserStore: ObservableObject { /// One open folder's scans; cancelled when it is closed or replaced. private final class Session: @unchecked Sendable { + /// Restored at launch, or listed once in this session: such a + /// folder is KEPT when a scan cannot read it. An explicit Open that + /// cannot read its folder leaves nothing behind. Main actor only. + var keepsWhenUnreadable: Bool + init(keepsWhenUnreadable: Bool) { self.keepsWhenUnreadable = keepsWhenUnreadable } + private let lock = NSLock() private var cancelled = false var isCancelled: Bool { @@ -128,7 +134,7 @@ final class FolderBrowserStore: ObservableObject { let chosen = url.standardizedFileURL environment.defaults.set(chosen.path, forKey: Self.defaultsKey) let root = URL(fileURLWithPath: FolderAccessBroker.canonicalPath(chosen), isDirectory: true) - let opened = begin(folder: chosen, root: root) + let opened = begin(folder: chosen, root: root, restored: false) return await withCheckedContinuation { continuation in waiters.append((opened, continuation)) } @@ -153,7 +159,7 @@ final class FolderBrowserStore: ObservableObject { guard !didRestore else { return } didRestore = true guard folder == nil, let path = environment.defaults.string(forKey: Self.defaultsKey) else { return } - let canonical = await Task.detached(priority: .utility) { Self.existingCanonicalPath(path) }.value + let canonical = await Task.detached(priority: .utility) { Self.restorableCanonicalPath(path) }.value // Opened, closed or replaced while the check ran: the reader acted. guard folder == nil, environment.defaults.string(forKey: Self.defaultsKey) == path else { return } let chosen = URL(fileURLWithPath: path, isDirectory: true).standardizedFileURL @@ -161,7 +167,7 @@ final class FolderBrowserStore: ObservableObject { environment.defaults.removeObject(forKey: Self.defaultsKey) return } - begin(folder: chosen, root: URL(fileURLWithPath: canonical, isDirectory: true)) + begin(folder: chosen, root: URL(fileURLWithPath: canonical, isDirectory: true), restored: true) } /// Lists the folder again — at once, or after the running scan. @@ -173,20 +179,30 @@ final class FolderBrowserStore: ObservableObject { // MARK: Private - /// The disk spelling of `path` when it is an existing folder (I/O: call - /// off the main thread). - nonisolated private static func existingCanonicalPath(_ path: String) -> String? { - var isDirectory: ObjCBool = false - guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue else { + /// The disk spelling of a remembered `path`, or nil when it is gone + /// (ENOENT / ENOTDIR) or not a folder. A path `stat` may not see + /// (EACCES / EPERM) is kept — the scan will report it unreadable — so a + /// permission never forgets a folder. I/O: call off the main thread. + nonisolated static func restorableCanonicalPath(_ path: String) -> String? { + switch LocalLinkOpening.existence(atPath: path) { + case .missing: return nil + case .unknown: + return FolderAccessBroker.canonicalPath(URL(fileURLWithPath: path, isDirectory: true)) + case .exists: + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) else { + return FolderAccessBroker.canonicalPath(URL(fileURLWithPath: path, isDirectory: true)) + } + return isDirectory.boolValue + ? FolderAccessBroker.canonicalPath(URL(fileURLWithPath: path, isDirectory: true)) : nil } - return FolderAccessBroker.canonicalPath(URL(fileURLWithPath: path, isDirectory: true)) } @discardableResult - private func begin(folder chosen: URL, root: URL) -> Session { + private func begin(folder chosen: URL, root: URL, restored: Bool) -> Session { endSession() - let opened = Session() + let opened = Session(keepsWhenUnreadable: restored) session = opened folder = chosen listingRoot = root @@ -257,10 +273,18 @@ final class FolderBrowserStore: ObservableObject { resumeWaiters(.missing) { $0 === current } close() case .unreadable: + guard current.keepsWhenUnreadable else { + // An explicit Open of a folder that cannot be read: the + // reader is told (alert); nothing stays behind. + resumeWaiters(.unreadable) { $0 === current } + close() + return + } if !isUnreadable { isUnreadable = true } if isLoading { isLoading = false } resumeWaiters(.unreadable) { $0 === current } case .listed(let result): + current.keepsWhenUnreadable = true // Only what changed is assigned: equal listings publish nothing. if isUnreadable { isUnreadable = false } if isLoading { isLoading = false } diff --git a/QuickMD/QuickMD/FolderListing.swift b/QuickMD/QuickMD/FolderListing.swift index 6001fc0..bbfed12 100644 --- a/QuickMD/QuickMD/FolderListing.swift +++ b/QuickMD/QuickMD/FolderListing.swift @@ -24,11 +24,14 @@ enum MarkdownFileKind { /// Rules (and why): /// - Recursive, but bounded in COST, not only in what is shown: at most /// `Limits.maxDepth` folders deep, `Limits.maxFiles` files listed and -/// `Limits.maxEntries` entries looked at (files and folders, Markdown or -/// not) — someone WILL open their home folder or "/", and the scan runs -/// again on every change in the tree. Either count limit makes the result -/// `isTruncated`. The root's own entries are always read in full before -/// anything is descended into, so its files survive any cap. +/// `Limits.maxFolders` folders read (the root is one) — someone WILL open +/// their home folder or "/", and the scan runs again on every change in +/// the tree. Either count limit makes the result `isTruncated`. Folders, +/// not entries: an entry budget let one huge `Attachments/` (20 000 +/// pictures) starve its sibling `Notes/` and the vault read as "No +/// Markdown files". A folder that is read is read whole (one directory +/// read, not interruptible — accepted) and listed in Finder order; the +/// file cap cuts in display order. /// - Never onto another volume: a subfolder that is a volume's root, or /// whose volume differs from the root's, is skipped ("/" must not walk /// /Volumes or /System/Volumes/Data). Both tests are needed: measured on @@ -60,9 +63,9 @@ enum FolderListing { var maxDepth = 8 /// Files listed at most; more makes the result truncated. var maxFiles = 2_000 - /// Entries (files + folders) looked at at most, the root's own - /// excepted; more makes the result truncated. - var maxEntries = 20_000 + /// Folders read at most, the root included; more makes the result + /// truncated. + var maxFolders = 2_000 } /// The Markdown files directly inside one folder. @@ -140,17 +143,27 @@ enum FolderListing { static func scan(_ root: URL, limits: Limits = Limits(), isCancelled: () -> Bool = { false }, didVisit: ((String) -> Void)? = nil) -> Outcome { + // Missing vs unreadable by `stat`'s error (the Local links rule): + // only ENOENT / ENOTDIR is "missing"; EACCES / EPERM (a parent we + // may not search) is "unreadable" — a remembered folder must not be + // forgotten over a permission. + switch LocalLinkOpening.existence(atPath: root.path) { + case .missing: return .missing + case .unknown: return .unreadable + case .exists: break + } var isDirectory: ObjCBool = false - guard FileManager.default.fileExists(atPath: root.path, isDirectory: &isDirectory), - isDirectory.boolValue else { return .missing } - var budget = Int.max - guard let rootEntries = entries(of: root, budget: &budget) else { return .unreadable } + guard FileManager.default.fileExists(atPath: root.path, isDirectory: &isDirectory) else { + return .unreadable + } + guard isDirectory.boolValue else { return .missing } + guard let rootEntries = entries(of: root) else { return .unreadable } let volume = try? root.resourceValues(forKeys: [.volumeIdentifierKey]).volumeIdentifier var groups: [Group] = [] var count = 0 + var foldersRead = 1 var truncated = false var cancelled = false - budget = limits.maxEntries /// Depth-first, children in Finder order: a folder's files, then its /// subfolders — the display order (see the type). @@ -174,12 +187,12 @@ enum FolderListing { } if entry.isVolume { continue } if let volume, let own = entry.volume, !own.isEqual(volume) { continue } - guard budget > 0 else { + guard foldersRead < limits.maxFolders else { truncated = true return } - guard let children = Self.entries(of: entry.url, budget: &budget) else { continue } - if budget < 0 { truncated = true } + foldersRead += 1 + guard let children = Self.entries(of: entry.url) else { continue } let name = entry.url.lastPathComponent let path = relativePath.isEmpty ? name : relativePath + "/" + name didVisit?(path) @@ -199,20 +212,13 @@ enum FolderListing { } /// The listable children of `folder` in Finder order; nil when it cannot - /// be read. Each entry looked at costs one unit of `budget`. A folder - /// the budget does not cover lists NOTHING (`budget` ends at -1): the - /// directory's own order is not Finder's, and a partial folder would - /// break "the files kept are the first ones shown". - private static func entries(of folder: URL, budget: inout Int) -> [Entry]? { + /// be read. The directory read prefetches exactly the keys the rules + /// above read (kind, link, hidden, package, volume). + private static func entries(of folder: URL) -> [Entry]? { guard let urls = try? FileManager.default.contentsOfDirectory( at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles]) else { return nil } var entries: [Entry] = [] for url in urls { - guard budget > 0 else { - budget = -1 - return [] - } - budget -= 1 let name = url.lastPathComponent guard !name.hasPrefix("."), let values = try? url.resourceValues(forKeys: Set(keys)) else { continue } if values.isHidden == true || values.isSymbolicLink == true { continue } diff --git a/QuickMD/QuickMD/QuickMDApp.swift b/QuickMD/QuickMD/QuickMDApp.swift index 15552bf..5371eac 100644 --- a/QuickMD/QuickMD/QuickMDApp.swift +++ b/QuickMD/QuickMD/QuickMDApp.swift @@ -169,7 +169,9 @@ enum OpenFolderFlow { store.folder == folder.standardizedFileURL else { return } guard let file = FolderListing.Result(groups: store.groups, isTruncated: store.isTruncated) .preferredFile else { - alert("No Markdown files in \u{201C}\(LocalLinkSafety.displayName(name))\u{201D}") + let shown = "\u{201C}\(LocalLinkSafety.displayName(name))\u{201D}" + // Truncated with nothing listed: there may well be files. + alert(store.isTruncated ? "\(shown) is too large to list" : "No Markdown files in \(shown)") return } DocumentOpener.open(file) { alert($0) } diff --git a/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift b/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift index 01f3a7c..20ae9fc 100644 --- a/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift +++ b/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift @@ -127,9 +127,12 @@ struct RecentDocumentsSidebar: View { .task { await folders.restore() } .task(id: currentURL) { let url = currentURL - canonicalCurrentPath = await Task.detached(priority: .utility) { + let canonical = await Task.detached(priority: .utility) { url.map { FolderAccessBroker.canonicalPath($0) } }.value + // A newer document's task replaced this one: its answer stands. + guard !Task.isCancelled else { return } + canonicalCurrentPath = canonical } } @@ -151,10 +154,15 @@ struct RecentDocumentsSidebar: View { @ViewBuilder private func folderSection(_ folder: URL) -> some View { FolderHeaderRow(folder: folder, onClose: { folders.close() }) + if folders.isUnreadable { + // Kept (restored, or listed before): the last listing, if any, + // stays below. + folderNote("Can\u{2019}t read this folder") + } if folders.groups.isEmpty { - // Unreadable: the header alone — "no files" would not be true. + // Only a COMPLETE scan may say there are none. if !folders.isLoading && !folders.isUnreadable { - folderNote("No Markdown files") + folderNote(folders.isTruncated ? "This folder is too large to list" : "No Markdown files") } } else { ForEach(folders.groups) { group in diff --git a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift index 653563f..a045725 100644 --- a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift +++ b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift @@ -269,22 +269,69 @@ final class FolderBrowserStoreTests: XCTestCase { XCTAssertFalse(browser.isUnreadable, "tried again on the next event") } - func testAnUnreadableFolderAtOpenIsReportedAndKept() async throws { + /// An explicit Open of a folder that cannot be read leaves nothing + /// behind (it would come back, unreadable, at every launch). + func testAnExplicitOpenOfAnUnreadableFolderLeavesNothingBehind() async throws { let world = World() world.forced = .unreadable let notes = try folder("Notes", files: ["a.md"]) let browser = store(world) let result = await browser.open(notes) XCTAssertEqual(result, .unreadable) - XCTAssertNotNil(browser.folder, "at launch too: the header with an empty list") + XCTAssertNil(browser.folder) + XCTAssertFalse(browser.isUnreadable) + XCTAssertNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + XCTAssertNil(world.token, "no watcher left") + } + + func testAnExplicitOpenOfAMissingFolderLeavesNothingBehind() async throws { + let world = World() + let browser = store(world) + let result = await browser.open(root.appendingPathComponent("Nowhere", isDirectory: true)) + XCTAssertEqual(result, .missing) + XCTAssertNil(browser.folder) + XCTAssertNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + } + + /// Restored at launch while it cannot be read: kept, header + the + /// "Can't read" line (isUnreadable), tried again on the next event. + func testARestoredUnreadableFolderIsKept() async throws { + let notes = try folder("Notes", files: ["a.md"]) + _ = await store(World()).open(notes) + let world = World() + world.forced = .unreadable + let browser = store(world) + await browser.restore() + await settle(browser) + XCTAssertNotNil(browser.folder) + XCTAssertTrue(browser.isUnreadable) XCTAssertTrue(browser.groups.isEmpty) XCTAssertFalse(browser.isLoading) - // Restored at launch while unreadable: kept as well. - let next = store(world) - await next.restore() - await settle(next) - XCTAssertNotNil(next.folder) - XCTAssertTrue(next.isUnreadable) + XCTAssertNotNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + world.forced = nil + world.trigger?([]) + await settle(browser) + XCTAssertFalse(browser.isUnreadable) + XCTAssertEqual(names(browser), ["a.md"]) + } + + /// A remembered folder behind a parent without search permission (stat: + /// EACCES) is not forgotten at launch: the REAL scan reports it + /// unreadable and it stays. + func testAPermissionErrorAtLaunchDoesNotForgetTheFolder() async throws { + let parent = try folder("Locked", files: ["Notes/a.md"]) + let notes = parent.appendingPathComponent("Notes", isDirectory: true) + _ = await store(World()).open(notes) + try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: parent.path) + defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: parent.path) } + let world = World() + let browser = store(world) + await browser.restore() + await settle(browser) + XCTAssertEqual(world.restored.count, 1) + XCTAssertEqual(browser.folder?.path, path(notes)) + XCTAssertTrue(browser.isUnreadable) + XCTAssertNotNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) } func testAMissingFolderIsForgotten() async throws { diff --git a/QuickMD/QuickMDTests/FolderListingTests.swift b/QuickMD/QuickMDTests/FolderListingTests.swift index d64835a..4840dde 100644 --- a/QuickMD/QuickMDTests/FolderListingTests.swift +++ b/QuickMD/QuickMDTests/FolderListingTests.swift @@ -143,20 +143,54 @@ final class FolderListingTests: XCTestCase { XCTAssertEqual(shape(scan()), ["/: a.md"], "an unreadable subfolder is left out of the parent's listing") } - func testTheEntryCapCountsEveryEntryButKeepsTheRootsFiles() throws { - try make("r1.md", "r2.md", "r3.md", "r.txt", "a/x1.txt", "a/x2.txt", "a/m.md", "b/n.md") - // The root's own entries are read whatever the cap; a/ (3 entries) - // does not fit in 2, so it lists nothing and the walk stops. - let capped = scan(.init(maxDepth: 8, maxFiles: 2_000, maxEntries: 2)) - XCTAssertEqual(shape(capped), ["/: r1.md r2.md r3.md"]) + /// The cost cap counts FOLDERS READ (the root is one). A huge sibling + /// never starves another: a vault whose `Attachments/` holds many + /// pictures and whose `Notes/` holds the Markdown lists `Notes/` (under + /// the 1.16 review's entry budget it read as "No Markdown files"). + func testTheFolderCapCountsFoldersReadAndAHugeSiblingStarvesNothing() throws { + let fm = FileManager.default + let attachments = root.appendingPathComponent("Attachments", isDirectory: true) + try fm.createDirectory(at: attachments, withIntermediateDirectories: true) + for index in 0..<300 { fm.createFile(atPath: attachments.appendingPathComponent("p\(index).png").path, contents: nil) } + try make("Notes/a.md", "Notes/b.md", "Zettel/c.md") + let whole = scan(.init(maxDepth: 8, maxFiles: 2_000, maxFolders: 4)) + XCTAssertEqual(shape(whole), ["Notes: a.md b.md", "Zettel: c.md"]) + XCTAssertEqual(whole?.isTruncated, false, "root + three folders: exactly the cap") + let capped = scan(.init(maxDepth: 8, maxFiles: 2_000, maxFolders: 3)) + XCTAssertEqual(shape(capped), ["Notes: a.md b.md"], "the folders read are listed whole") XCTAssertEqual(capped?.isTruncated, true) - let exact = scan(.init(maxDepth: 8, maxFiles: 2_000, maxEntries: 4)) - XCTAssertEqual(shape(exact), ["/: r1.md r2.md r3.md", "a: m.md", "b: n.md"]) - XCTAssertEqual(exact?.isTruncated, false, "3 entries in a/, 1 in b/: exactly the cap") - let short = scan(.init(maxDepth: 8, maxFiles: 2_000, maxEntries: 3)) - XCTAssertEqual(shape(short), ["/: r1.md r2.md r3.md", "a: m.md"]) - XCTAssertEqual(short?.isTruncated, true) - XCTAssertEqual(FolderListing.Limits().maxEntries, 20_000) + let starved = scan(.init(maxDepth: 8, maxFiles: 2_000, maxFolders: 2)) + XCTAssertEqual(starved?.groups, [], "only Attachments/ was read…") + XCTAssertEqual(starved?.isTruncated, true, "…and the result says it is incomplete, never \"no files\"") + XCTAssertEqual(FolderListing.Limits().maxFolders, 2_000) + } + + /// The file cap still cuts in display order. + func testTheFileCapCutsInDisplayOrder() throws { + try make("r1.md", "r2.md", "a/m1.md", "a/m2.md", "b/n.md") + let capped = scan(.init(maxDepth: 8, maxFiles: 3, maxFolders: 2_000)) + XCTAssertEqual(shape(capped), ["/: r1.md r2.md", "a: m1.md"]) + XCTAssertEqual(capped?.isTruncated, true) + } + + /// A parent without search permission: `stat` fails with EACCES — the + /// folder is unreadable, not missing (it must not be forgotten). + func testAFolderBehindAParentWithoutSearchPermissionIsUnreadableNotMissing() throws { + try make("locked/inner/a.md") + let locked = root.appendingPathComponent("locked") + let inner = locked.appendingPathComponent("inner") + try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: locked.path) + defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: locked.path) } + XCTAssertEqual(LocalLinkOpening.existence(atPath: inner.path), .unknown, "the probe: stat says EACCES") + XCTAssertEqual(FolderListing.scan(inner), .unreadable) + XCTAssertEqual(FolderListing.scan(locked.appendingPathComponent("gone")), .unreadable, + "behind the locked parent even a missing name cannot be told missing") + XCTAssertEqual(FolderListing.scan(root.appendingPathComponent("gone/inner")), .missing, "ENOENT") + XCTAssertNotNil(FolderBrowserStore.restorableCanonicalPath(inner.path), "restore keeps it") + XCTAssertNil(FolderBrowserStore.restorableCanonicalPath(root.appendingPathComponent("gone").path)) + try make("plain.md") + XCTAssertNil(FolderBrowserStore.restorableCanonicalPath(root.appendingPathComponent("plain.md").path), + "a file is no folder") } func testAScanStopsWhenCancelled() throws { @@ -177,7 +211,7 @@ final class FolderListingTests: XCTestCase { let volumes = URL(fileURLWithPath: "/System/Volumes", isDirectory: true) try XCTSkipUnless(FileManager.default.fileExists(atPath: volumes.appendingPathComponent("Data").path)) var visited: [String] = [] - _ = FolderListing.scan(volumes, limits: .init(maxDepth: 1, maxFiles: 10, maxEntries: 100), + _ = FolderListing.scan(volumes, limits: .init(maxDepth: 1, maxFiles: 10, maxFolders: 100), didVisit: { visited.append($0) }) XCTAssertFalse(visited.contains("Data"), "\(visited)") XCTAssertFalse(visited.contains("Preboot"), "\(visited)") From cf5ded2f3418ba02301df9a4c1e30cfc5a27fd9f Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 14:42:31 +0100 Subject: [PATCH 10/27] fix: linked formula underline costs one layout per font, not one per draw - drawTextUnderline reuses a scratch TextKit stack laid out once per (font, underline style, colour), bounded at 64 entries; per draw it is one clip and one glyph's underline. Rows are unchanged (probe: same pixel rows at 1x/2x, zoom 100/200, body and heading fonts). - drawLinkUnderlines skips a formula shown as its source before any geometry and reads the laid-out size from the layout manager instead of calling attachmentBounds (two text layouts per draw for a source box). - Test: 40 linked formulas drawn twice build at most one scratch stack. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/BlockHeightMeasurer.swift | 122 +++++++++++++----- .../QuickMDTests/MathInTextKindsTests.swift | 27 ++++ 2 files changed, 116 insertions(+), 33 deletions(-) diff --git a/QuickMD/QuickMD/BlockHeightMeasurer.swift b/QuickMD/QuickMD/BlockHeightMeasurer.swift index 2f843c9..66cdcc7 100644 --- a/QuickMD/QuickMD/BlockHeightMeasurer.swift +++ b/QuickMD/QuickMD/BlockHeightMeasurer.swift @@ -931,9 +931,9 @@ final class FittingMathAttachment: NSTextAttachment { /// /// Drawing only, inside the line the formula sits on: the attachment's /// bounds, the fit rule and every measured height stay as they were. - /// - The line is AppKit's own: a layout manager underlines one - /// no-break space in the link's font, kerned to the formula's width - /// (`drawTextUnderline`). AppKit's position is not the font's + /// - The line is AppKit's own: a layout manager underlines one long + /// no-break space in the link's font, clipped to the formula's width + /// (`drawTextUnderline`, laid out once per font). AppKit's position is not the font's /// `underlinePosition` (measured: Menlo 13 says 0.8 pt, AppKit draws /// 1.1–1.75 pt), so only AppKit's own drawing meets the text's /// underline on either side exactly, at every scale. @@ -990,32 +990,87 @@ final class FittingMathAttachment: NSTextAttachment { } /// AppKit's underline of `width` points of text in `underline.font`, - /// starting at `x` on `baseline` (flipped drawing coordinates): one - /// no-break space in a scratch TextKit 1 stack, kerned to `width`. The - /// space draws nothing; its underline is drawn by the same layout - /// manager code as the link text's. + /// starting at `x` on `baseline` (flipped drawing coordinates), drawn by + /// the same layout manager code as the link text's: a scratch stack + /// (`UnderlineScratch`) laid out once per font, style and colour, its + /// long underline clipped to the formula's width. Per draw this is one + /// clip and one glyph's underline — no layout, no allocation. private static func drawTextUnderline(_ underline: LinkUnderline, x: CGFloat, width: CGFloat, baseline: CGFloat) { - let space = "\u{00A0}" - let advance = (space as NSString).size(withAttributes: [.font: underline.font]).width - let storage = NSTextStorage(string: space, attributes: [ - .font: underline.font, .foregroundColor: underline.color, .underlineStyle: underline.style, - .kern: width - advance, - ]) - let layoutManager = NSLayoutManager() - let container = NSTextContainer(size: NSSize(width: CGFloat.greatestFiniteMagnitude, - height: CGFloat.greatestFiniteMagnitude)) - container.lineFragmentPadding = 0 - layoutManager.addTextContainer(container) - storage.addLayoutManager(layoutManager) - layoutManager.ensureLayout(for: container) - let glyphs = NSRange(location: 0, length: layoutManager.numberOfGlyphs) - guard glyphs.length > 0 else { return } - let ownBaseline = layoutManager.lineFragmentRect(forGlyphAt: 0, effectiveRange: nil).minY - + layoutManager.location(forGlyphAt: 0).y - layoutManager.drawGlyphs(forGlyphRange: glyphs, at: NSPoint(x: x, y: baseline - ownBaseline)) + guard let context = NSGraphicsContext.current?.cgContext else { return } + let scratch = UnderlineScratch.scratch(for: underline) + context.saveGState() + context.clip(to: CGRect(x: x, y: baseline - 10_000, width: width, height: 20_000)) + scratch.layoutManager.drawGlyphs(forGlyphRange: NSRange(location: 0, length: 1), + at: NSPoint(x: x, y: baseline - scratch.baseline)) + context.restoreGState() + } + + /// One no-break space in `LinkUnderline`'s font, colour and underline + /// style, kerned to `width` points, laid out once in its own TextKit 1 + /// stack: the space draws nothing, its underline is AppKit's. Kept per + /// (font, style, colour) — a handful in a session (body and heading + /// sizes × zoom × theme) — and dropped wholesale past `limit`. Drawing + /// runs on the main thread only, so is this cache. + private final class UnderlineScratch { + let layoutManager: NSLayoutManager + /// The space's baseline in its own container. + let baseline: CGFloat + private let storage: NSTextStorage + + /// Wider than any line a formula can sit on. + static let width: CGFloat = 100_000 + static let limit = 64 + private static var cache: [Key: UnderlineScratch] = [:] + + #if DEBUG + /// Stacks built so far (tests: one per distinct key, never one per + /// formula or per draw). + static var builtForTesting = 0 + #endif + + private struct Key: Hashable { + let font: NSFont + let style: Int + let color: NSColor + } + + static func scratch(for underline: LinkUnderline) -> UnderlineScratch { + let key = Key(font: underline.font, style: underline.style, color: underline.color) + if let hit = cache[key] { return hit } + if cache.count >= limit { cache.removeAll() } + let made = UnderlineScratch(underline) + cache[key] = made + return made + } + + private init(_ underline: LinkUnderline) { + let space = "\u{00A0}" + let advance = (space as NSString).size(withAttributes: [.font: underline.font]).width + storage = NSTextStorage(string: space, attributes: [ + .font: underline.font, .foregroundColor: underline.color, .underlineStyle: underline.style, + .kern: Self.width - advance, + ]) + layoutManager = NSLayoutManager() + let container = NSTextContainer(size: NSSize(width: CGFloat.greatestFiniteMagnitude, + height: CGFloat.greatestFiniteMagnitude)) + container.lineFragmentPadding = 0 + layoutManager.addTextContainer(container) + storage.addLayoutManager(layoutManager) + layoutManager.ensureLayout(for: container) + baseline = layoutManager.lineFragmentRect(forGlyphAt: 0, effectiveRange: nil).minY + + layoutManager.location(forGlyphAt: 0).y + #if DEBUG + Self.builtForTesting += 1 + #endif + } } + #if DEBUG + /// Tests: how many underline scratch stacks were built (`UnderlineScratch`). + static var underlineScratchesBuiltForTesting: Int { UnderlineScratch.builtForTesting } + #endif + /// Every linked formula's underline among `glyphRange`, drawn by a /// layout manager after its glyphs (`DocumentSelectionLayoutManager`): /// `origin` is the text container's origin, as `drawGlyphs` gets it. @@ -1028,19 +1083,20 @@ final class FittingMathAttachment: NSTextAttachment { for index in range.location.. 0, !formula.showsSource(laidOutAs: size) else { continue } let fragment = layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil) let used = layoutManager.lineFragmentUsedRect(forGlyphAt: glyph, effectiveRange: nil) // An attachment glyph's location is its box's bottom-left - // corner (not the baseline, as for a character). + // corner (not the baseline, as for a character); a typeset + // box is centred on the cap height (`bounds(for:)`). let location = layoutManager.location(forGlyphAt: glyph) - // The bounds layout gave it on this line: the same call. - let bounds = formula.attachmentBounds( - for: layoutManager.textContainer(forGlyphAt: glyph, effectiveRange: nil), - proposedLineFragment: fragment, glyphPosition: location, characterIndex: index) let bottom = origin.y + fragment.minY + location.y - let frame = CGRect(x: origin.x + fragment.minX + location.x, y: bottom - bounds.height, - width: bounds.width, height: bounds.height) - formula.drawLinkUnderline(frame: frame, baseline: bottom + bounds.minY, + let frame = CGRect(x: origin.x + fragment.minX + location.x, y: bottom - size.height, + width: size.width, height: size.height) + formula.drawLinkUnderline(frame: frame, baseline: bottom + (formula.capHeight - size.height) / 2, lineBottom: origin.y + used.maxY) } } diff --git a/QuickMD/QuickMDTests/MathInTextKindsTests.swift b/QuickMD/QuickMDTests/MathInTextKindsTests.swift index cc488ab..345e850 100644 --- a/QuickMD/QuickMDTests/MathInTextKindsTests.swift +++ b/QuickMD/QuickMDTests/MathInTextKindsTests.swift @@ -1229,6 +1229,33 @@ final class MathInTextKindsTests: XCTestCase { } } + /// The underline's cost does not grow with the formulas drawn: a + /// 40-row table with a linked formula in every cell, drawn twice, builds + /// at most ONE scratch stack (one font, style and colour) — never one + /// per formula or per draw. And every formula is still underlined. + @MainActor + func testLinkedFormulaUnderlinesCostOneMeasurementPerFont() { + // Text beside each formula: its underline is AppKit's (the scratch). + let rows = (1...40).map { _ in "| see [$x$](https://e.com) here |" }.joined(separator: "\n") + let blocks = parse("| A |\n|---|\n" + rows) + let measured = measure(blocks, math: paintingEngine(filled: 0.5)) + guard let string = measured.tables[blocks[0].id]?.string else { return XCTFail("no table") } + let before = FittingMathAttachment.underlineScratchesBuiltForTesting + let first = DrawnText(string, width: 600, scale: 2, theme: theme) + _ = DrawnText(string, width: 600, scale: 1, theme: theme) + XCTAssertLessThanOrEqual(FittingMathAttachment.underlineScratchesBuiltForTesting - before, 1) + XCTAssertGreaterThanOrEqual(FittingMathAttachment.underlineScratchesBuiltForTesting, 1, + "the text underline path was taken") + let formulas = first.formulaRects() + XCTAssertEqual(formulas.count, 40) + for formula in formulas { + let under = first.rows(in: (formula.minX + 1)...(formula.maxX - 1), below: formula.midY) { + self.role($0) == "link" + } + XCTAssertFalse(under.isEmpty, "every formula is underlined") + } + } + /// `string` laid out and drawn as a document row draws it: a text view /// with `DocumentSelectionLayoutManager`, the light appearance, into a /// bitmap at `scale` pixels per point. From 6cad9d44b374aa89b84ed03d8fe1d0477a69397e Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 14:43:20 +0100 Subject: [PATCH 11/27] fix: Open Folder bounds the total entries a scan reads (#62) Every directory read adds the number of entries it returned to a running total (the root's included); once it passes Limits.maxEntriesRead (200 000) no further subfolder is read and the result is truncated. The folders already read stay listed whole, so a scan costs at most that total plus one folder. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderListing.swift | 24 ++++++++++++---- QuickMD/QuickMDTests/FolderListingTests.swift | 28 +++++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/QuickMD/QuickMD/FolderListing.swift b/QuickMD/QuickMD/FolderListing.swift index bbfed12..78e6434 100644 --- a/QuickMD/QuickMD/FolderListing.swift +++ b/QuickMD/QuickMD/FolderListing.swift @@ -31,7 +31,13 @@ enum MarkdownFileKind { /// pictures) starve its sibling `Notes/` and the vault read as "No /// Markdown files". A folder that is read is read whole (one directory /// read, not interruptible — accepted) and listed in Finder order; the -/// file cap cuts in display order. +/// file cap cuts in display order. A TOTAL bounds the reads as well: +/// once the entries returned by all directory reads so far (the root's +/// included) pass `Limits.maxEntriesRead`, no further subfolder is read +/// and the result is truncated — without it the worst case was 2 000 +/// folders × their size (photo exports, build outputs of 50–100k files), +/// re-read on every relevant event. A scan costs at most that total plus +/// one folder. /// - Never onto another volume: a subfolder that is a volume's root, or /// whose volume differs from the root's, is skipped ("/" must not walk /// /Volumes or /System/Volumes/Data). Both tests are needed: measured on @@ -66,6 +72,9 @@ enum FolderListing { /// Folders read at most, the root included; more makes the result /// truncated. var maxFolders = 2_000 + /// Entries returned by all directory reads together (the root's + /// included); past it no further folder is read (truncated). + var maxEntriesRead = 200_000 } /// The Markdown files directly inside one folder. @@ -157,7 +166,8 @@ enum FolderListing { return .unreadable } guard isDirectory.boolValue else { return .missing } - guard let rootEntries = entries(of: root) else { return .unreadable } + var entriesRead = 0 + guard let rootEntries = entries(of: root, read: &entriesRead) else { return .unreadable } let volume = try? root.resourceValues(forKeys: [.volumeIdentifierKey]).volumeIdentifier var groups: [Group] = [] var count = 0 @@ -187,12 +197,12 @@ enum FolderListing { } if entry.isVolume { continue } if let volume, let own = entry.volume, !own.isEqual(volume) { continue } - guard foldersRead < limits.maxFolders else { + guard foldersRead < limits.maxFolders, entriesRead <= limits.maxEntriesRead else { truncated = true return } foldersRead += 1 - guard let children = Self.entries(of: entry.url) else { continue } + guard let children = Self.entries(of: entry.url, read: &entriesRead) else { continue } let name = entry.url.lastPathComponent let path = relativePath.isEmpty ? name : relativePath + "/" + name didVisit?(path) @@ -213,10 +223,12 @@ enum FolderListing { /// The listable children of `folder` in Finder order; nil when it cannot /// be read. The directory read prefetches exactly the keys the rules - /// above read (kind, link, hidden, package, volume). - private static func entries(of folder: URL) -> [Entry]? { + /// above read (kind, link, hidden, package, volume). `read` grows by the + /// number of entries the read returned (the cost, listable or not). + private static func entries(of folder: URL, read: inout Int) -> [Entry]? { guard let urls = try? FileManager.default.contentsOfDirectory( at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles]) else { return nil } + read += urls.count var entries: [Entry] = [] for url in urls { let name = url.lastPathComponent diff --git a/QuickMD/QuickMDTests/FolderListingTests.swift b/QuickMD/QuickMDTests/FolderListingTests.swift index 4840dde..37cb07e 100644 --- a/QuickMD/QuickMDTests/FolderListingTests.swift +++ b/QuickMD/QuickMDTests/FolderListingTests.swift @@ -165,6 +165,34 @@ final class FolderListingTests: XCTestCase { XCTAssertEqual(FolderListing.Limits().maxFolders, 2_000) } + /// The total of entries read bounds the walk: root (4 entries) + a/ (3) + /// + b/ (3) = 10 passes a limit of 9 after the SECOND folder, so c/ is + /// never read — the folders already read stay listed whole, truncated. + /// The visit counter proves what was read. + func testTheTotalOfEntriesReadStopsFurtherReads() throws { + try make("r.md", "a/a.md", "a/x.txt", "a/y.txt", "b/b.md", "b/x.txt", "b/y.txt", "c/c.md") + var visited: [String] = [] + let outcome = FolderListing.scan(root, limits: .init(maxDepth: 8, maxFiles: 2_000, maxFolders: 2_000, + maxEntriesRead: 9), + didVisit: { visited.append($0) }) + XCTAssertEqual(visited, ["a", "b"], "c/ is not read") + XCTAssertEqual(shape(listed(outcome)), ["/: r.md", "a: a.md", "b: b.md"]) + XCTAssertEqual(listed(outcome)?.isTruncated, true) + // At exactly the limit after b/ the total has not passed it: c/ is read. + visited = [] + let whole = FolderListing.scan(root, limits: .init(maxDepth: 8, maxFiles: 2_000, maxFolders: 2_000, + maxEntriesRead: 10), + didVisit: { visited.append($0) }) + XCTAssertEqual(visited, ["a", "b", "c"]) + XCTAssertEqual(listed(whole)?.isTruncated, false, "nothing was left unread") + // The root alone passing the limit: only the root is listed. + let rootOnly = FolderListing.scan(root, limits: .init(maxDepth: 8, maxFiles: 2_000, maxFolders: 2_000, + maxEntriesRead: 3)) + XCTAssertEqual(shape(listed(rootOnly)), ["/: r.md"]) + XCTAssertEqual(listed(rootOnly)?.isTruncated, true) + XCTAssertEqual(FolderListing.Limits().maxEntriesRead, 200_000) + } + /// The file cap still cuts in display order. func testTheFileCapCutsInDisplayOrder() throws { try make("r1.md", "r2.md", "a/m1.md", "a/m2.md", "b/n.md") From 48f6d591caf57a0d2d133a7595a5b62b5e0b5153 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 14:53:54 +0100 Subject: [PATCH 12/27] fix: sidebar rows of a file listed in the folder and in Recent no longer go blank (#62) The folder list and the recent rows shared one LazyVStack and used the same explicit id (the URL string) for a file in both sections; after an insert the recent row kept its space but drew nothing. Every row of that stack now takes its id from SidebarRowID (folder group, folder file, recent), disjoint by construction. The no-folder branch is unchanged. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderListing.swift | 34 +++++++++++++++++++ .../Views/RecentDocumentsSidebar.swift | 11 +++--- QuickMD/QuickMDTests/FolderListingTests.swift | 27 +++++++++++++++ 3 files changed, 68 insertions(+), 4 deletions(-) diff --git a/QuickMD/QuickMD/FolderListing.swift b/QuickMD/QuickMD/FolderListing.swift index 78e6434..7db8f7d 100644 --- a/QuickMD/QuickMD/FolderListing.swift +++ b/QuickMD/QuickMD/FolderListing.swift @@ -15,6 +15,38 @@ enum MarkdownFileKind { } } +// MARK: - Sidebar row identity + +/// The identity of every row of the Documents sidebar's lazy stack while a +/// folder is open. A file may be listed in BOTH sections (a folder file the +/// reader opened is also a recent document), and two `ForEach`es in one +/// `LazyVStack` with the same explicit id for it left the recent row blank +/// after an insert or move (1.16 GUI E2E: space reserved, nothing drawn, not +/// in the accessibility tree). Each section has its own case, so the ids are +/// disjoint by construction: +/// - `folderGroup`: a subfolder header, by its relative path; +/// - `folderFile`: a listed file, by its path — unique within a listing, +/// because the walk reads every folder once (it reaches a folder only +/// through its parent: symbolic links are never followed, volume roots +/// are skipped, and APFS has no directory hard links), so no path is +/// listed twice; two hard links to one file are two paths, two rows; +/// - `recent`: a recent document, by its URL string. +enum SidebarRowID: Hashable { + case folderGroup(String) + case folderFile(String) + case recent(String) + + static func folderFile(_ url: URL) -> SidebarRowID { .folderFile(url.path) } + static func recent(_ url: URL) -> SidebarRowID { .recent(url.absoluteString) } +} + +extension URL { + /// This URL as a row of the open folder's list (`SidebarRowID`). + var sidebarFolderRowID: SidebarRowID { .folderFile(self) } + /// This URL as a recent-document row (`SidebarRowID`). + var sidebarRecentRowID: SidebarRowID { .recent(self) } +} + // MARK: - Folder listing (File ▸ Open Folder, #62) /// The Markdown files under a folder, grouped by the folder they sit in — @@ -83,6 +115,8 @@ enum FolderListing { let relativePath: String let files: [URL] var id: String { relativePath } + /// The subfolder header's sidebar row (`SidebarRowID`). + var rowID: SidebarRowID { .folderGroup(relativePath) } } struct Result: Equatable, Sendable { diff --git a/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift b/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift index 20ae9fc..5f30396 100644 --- a/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift +++ b/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift @@ -79,6 +79,8 @@ struct RecentDocumentsSidebar: View { if let folder = folders.folder { ScrollView { + // Every row id in this stack comes from `SidebarRowID`; + // a file may be in both sections. LazyVStack(alignment: .leading, spacing: 0) { folderSection(folder) if !store.documents.isEmpty { @@ -136,9 +138,10 @@ struct RecentDocumentsSidebar: View { } } - /// The recent rows, as in the no-folder branch. + /// The recent rows, as in the no-folder branch, under the folder's + /// list — with ids of their own (`SidebarRowID.recent`). private var recentRows: some View { - ForEach(store.documents, id: \.absoluteString) { url in + ForEach(store.documents, id: \.sidebarRecentRowID) { url in DocumentRow( url: url, isCurrent: isCurrent(url), @@ -165,7 +168,7 @@ struct RecentDocumentsSidebar: View { folderNote(folders.isTruncated ? "This folder is too large to list" : "No Markdown files") } } else { - ForEach(folders.groups) { group in + ForEach(folders.groups, id: \.rowID) { group in if !group.relativePath.isEmpty { Text(group.relativePath) .font(.system(size: 10)) @@ -176,7 +179,7 @@ struct RecentDocumentsSidebar: View { .padding(.top, 8) .padding(.bottom, 2) } - ForEach(group.files, id: \.absoluteString) { url in + ForEach(group.files, id: \.sidebarFolderRowID) { url in FolderFileRow(url: url, isCurrent: isCurrentInFolder(url), theme: theme, onOpen: { openDocument(url) }) } diff --git a/QuickMD/QuickMDTests/FolderListingTests.swift b/QuickMD/QuickMDTests/FolderListingTests.swift index 37cb07e..b4510b1 100644 --- a/QuickMD/QuickMDTests/FolderListingTests.swift +++ b/QuickMD/QuickMDTests/FolderListingTests.swift @@ -193,6 +193,33 @@ final class FolderListingTests: XCTestCase { XCTAssertEqual(FolderListing.Limits().maxEntriesRead, 200_000) } + /// The sidebar's lazy stack shows a file in both sections: its folder + /// row and its recent row must never share an id, and the ids of one + /// listing (headers and files) are unique. + func testSidebarRowIdsAreDisjointBetweenSectionsAndUniqueInAListing() throws { + try make("README.md", "notes.md", "docs/guide.md", "docs/a/notes.md", "docs a/guide.md", + "notes.md.d/x.md") + let fm = FileManager.default + try fm.linkItem(at: root.appendingPathComponent("notes.md"), + to: root.appendingPathComponent("docs/hard-link.md")) + let listing = try XCTUnwrap(scan()) + var ids: [SidebarRowID] = [] + for group in listing.groups { + if !group.relativePath.isEmpty { ids.append(group.rowID) } + ids.append(contentsOf: group.files.map(\.sidebarFolderRowID)) + } + XCTAssertEqual(Set(ids).count, ids.count, "no id twice in one listing") + XCTAssertEqual(Set(listing.files.map(\.path)).count, listing.files.count, "no path listed twice") + for url in listing.files { + XCTAssertNotEqual(url.sidebarFolderRowID, url.sidebarRecentRowID, url.path) + // A recent row's URL is the same file however it is spelled. + XCTAssertNotEqual(url.sidebarFolderRowID, url.standardizedFileURL.sidebarRecentRowID) + } + // A group named like a file path is still a different case. + XCTAssertNotEqual(SidebarRowID.folderGroup("docs"), SidebarRowID.folderFile("docs")) + XCTAssertNotEqual(SidebarRowID.folderGroup("docs"), SidebarRowID.recent("docs")) + } + /// The file cap still cuts in display order. func testTheFileCapCutsInDisplayOrder() throws { try make("r1.md", "r2.md", "a/m1.md", "a/m2.md", "b/n.md") From be58fd38245b2202609e45062b1b810a8703e86f Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 15:54:41 +0100 Subject: [PATCH 13/27] perf: the thematic-break test is a byte scan, not a regular expression The spaced-rule pattern (28a947e) is tried on every line that starts with `-`, `*` or `_` - every bullet - and no longer failed at the second character, so opening an 11 400-bullet document cost ~40 ms more. One hand-written scan (`MarkdownRenderer.isRuleRun`, on the trimmed line's UTF-8, no allocation) now answers for every reader of a rule; the pattern constant is gone. A test checks it against the old pattern for every string of up to seven characters over the rule alphabet. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/MarkdownBlockParser.swift | 2 +- QuickMD/QuickMD/MarkdownRenderer.swift | 36 ++++++++++++++++++--- QuickMD/QuickMD/MarkdownTheme.swift | 9 ------ QuickMD/QuickMDTests/ListContentTests.swift | 33 +++++++++++++++++++ 4 files changed, 66 insertions(+), 14 deletions(-) diff --git a/QuickMD/QuickMD/MarkdownBlockParser.swift b/QuickMD/QuickMD/MarkdownBlockParser.swift index 42bc4c5..02a8a0a 100644 --- a/QuickMD/QuickMD/MarkdownBlockParser.swift +++ b/QuickMD/QuickMD/MarkdownBlockParser.swift @@ -1215,7 +1215,7 @@ struct MarkdownBlockParser: Sendable { if isTableSeparator(trimmed) { return false } // Rules and setext underlines - if trimmed.range(of: MarkdownTheme.horizontalRulePattern, options: .regularExpression) != nil { return false } + if MarkdownRenderer.isRuleRun(trimmed) { return false } if trimmed.range(of: MarkdownTheme.setextH1Pattern, options: .regularExpression) != nil { return false } // ATX headings and standalone image lines — the SAME predicate the diff --git a/QuickMD/QuickMD/MarkdownRenderer.swift b/QuickMD/QuickMD/MarkdownRenderer.swift index e8bd5a7..f33758f 100644 --- a/QuickMD/QuickMD/MarkdownRenderer.swift +++ b/QuickMD/QuickMD/MarkdownRenderer.swift @@ -458,8 +458,36 @@ struct MarkdownRenderer: Sendable { /// A thematic break (`---`, `***`, `___`, also spaced: `* * *`) — /// `renderLine` draws it as a rule. static func isThematicBreak(_ line: String) -> Bool { - markerLine(line) - .range(of: MarkdownTheme.horizontalRulePattern, options: .regularExpression) != nil + isRuleRun(markerLine(line)) + } + + /// Whether an ALREADY TRIMMED line (`markerLine`: spaces and tabs off + /// both ends) is a thematic break: three or more of ONE of `*`, `-`, + /// `_`, with any spaces or tabs between them (`* * *`, `- - -`, + /// `** **`). The one rule test: every reader of a rule calls it, before + /// any list-item test. The front-matter fence and the setext underline + /// keep their own exact `---` checks. + /// + /// A hand-written scan over the UTF-8 bytes, not a regular expression: + /// it is asked about every line that starts with `-` or `*` (every + /// bullet) and fails at the first other byte, without allocating. The + /// equivalent regex cost ~40 ms more to open an 11 400-bullet document. + /// `ListContentTests.testTheRuleScanAnswersAsThePatternDid` pins the + /// equivalence with that regex. + static func isRuleRun(_ trimmed: String) -> Bool { + var bytes = trimmed.utf8.makeIterator() + guard let marker = bytes.next(), + marker == UInt8(ascii: "*") || marker == UInt8(ascii: "-") || marker == UInt8(ascii: "_") + else { return false } + var count = 1 + while let byte = bytes.next() { + if byte == marker { + count += 1 + } else if byte != UInt8(ascii: " ") && byte != UInt8(ascii: "\t") { + return false + } + } + return count >= 3 } /// Must mirror the dispatch in `renderLine`, or a structural line could @@ -469,7 +497,7 @@ struct MarkdownRenderer: Sendable { let trimmed = markerLine(line) let nsRange = NSRange(line.startIndex..., in: line) if headerRegex.firstMatch(in: line, range: nsRange) != nil { return .structural } - if trimmed.range(of: MarkdownTheme.horizontalRulePattern, options: .regularExpression) != nil { return .structural } + if isRuleRun(trimmed) { return .structural } if taskListRegex.firstMatch(in: line, range: nsRange) != nil { return .listItem } if ["- ", "* ", "+ "].contains(where: { trimmed.hasPrefix($0) }) { return .listItem } if trimmed.range(of: orderedMarkerPattern, options: .regularExpression) != nil { return .listItem } @@ -502,7 +530,7 @@ struct MarkdownRenderer: Sendable { } // Horizontal rule - if trimmed.range(of: MarkdownTheme.horizontalRulePattern, options: .regularExpression) != nil { + if Self.isRuleRun(trimmed) { return renderHorizontalRule() } diff --git a/QuickMD/QuickMD/MarkdownTheme.swift b/QuickMD/QuickMD/MarkdownTheme.swift index c0e5305..aabeb42 100644 --- a/QuickMD/QuickMD/MarkdownTheme.swift +++ b/QuickMD/QuickMD/MarkdownTheme.swift @@ -297,15 +297,6 @@ struct MarkdownTheme: Sendable, Identifiable { /// Captures: (1) hash marks, (2) header text static let headerPattern = #"^(#{1,6})[ \t]+(.*)$"# - /// Matches horizontal rules (CommonMark thematic breaks) on a TRIMMED - /// line: three or more of ONE of `*`, `-`, `_`, with any spaces or tabs - /// between them (`* * *`, `- - -`, `** **`). Before 1.16 the characters - /// had to touch, and `* * *` was drawn as the bullet "• * *". Every - /// reader of a rule goes through this one pattern (`isThematicBreak`), - /// and each checks it before list items. The front-matter fence and the - /// setext underline keep their own exact `---` patterns. - static let horizontalRulePattern = #"^(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$"# - /// Matches task list items: - [ ] or - [x] with optional indentation /// Captures: (1) indent whitespace, (2) check state (space or x), (3) content static let taskListPattern = #"^([ \t]*)[-*+][ \t]+\[([ xX])\][ \t]+(.*)$"# diff --git a/QuickMD/QuickMDTests/ListContentTests.swift b/QuickMD/QuickMDTests/ListContentTests.swift index 64f89fa..0e52a18 100644 --- a/QuickMD/QuickMDTests/ListContentTests.swift +++ b/QuickMD/QuickMDTests/ListContentTests.swift @@ -709,6 +709,39 @@ final class ListContentTests: XCTestCase { XCTAssertEqual(ruleShape("* *"), ["T:• *"]) } + /// The hand-written rule scan answers exactly as the regular expression + /// it replaced (kept here as the oracle) for EVERY string of up to seven + /// characters over `*`, `-`, `_`, space, tab and `a` (335 922 strings), + /// trimmed as every caller trims (`isThematicBreak`) and untrimmed. + func testTheRuleScanAnswersAsThePatternDid() { + // The old callers' exact call: `String.range(of:options: .regularExpression)`. + // (`NSRegularExpression.firstMatch` differs: its `$` also matches + // before a final `\r` or U+2028, which the old callers never did.) + let oracle = #"^(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$"# + func pattern(_ s: String) -> Bool { + s.range(of: oracle, options: .regularExpression) != nil + } + let alphabet: [Character] = ["*", "-", "_", " ", "\t", "a"] + var level = [""] + var checked = 0, rules = 0 + for _ in 1...7 { + level = level.flatMap { prefix in alphabet.map { prefix + String($0) } } + for s in level { + let trimmed = s.trimmingCharacters(in: MarkdownRenderer.markerWhitespace) + XCTAssertEqual(MarkdownRenderer.isRuleRun(s), pattern(s), s.debugDescription) + XCTAssertEqual(MarkdownRenderer.isThematicBreak(s), pattern(trimmed), s.debugDescription) + checked += 1 + if pattern(trimmed) { rules += 1 } + } + } + XCTAssertEqual(checked, 335_922) + XCTAssertGreaterThan(rules, 0) + // Outside the alphabet: other characters and other white space. + for s in ["***\u{2028}", "*\u{00A0}*\u{00A0}*", "***", "—————", "\u{0B}***", "***\r", "-–-"] { + XCTAssertEqual(MarkdownRenderer.isRuleRun(s), pattern(s), s.debugDescription) + } + } + /// A spaced rule ends a paragraph or a list like `---` does, and is the /// item's when indented to its content column. func testASpacedRuleBetweenBlocks() throws { From 1512bade7690cec123e13a21dd4deb92541951e1 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 16:12:29 +0100 Subject: [PATCH 14/27] docs(code): the block stand-in continues a list by ownership, not indentation Co-Authored-By: Claude Fable 5.2 --- QuickMD/QuickMD/MarkdownBlockParser.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/QuickMD/QuickMD/MarkdownBlockParser.swift b/QuickMD/QuickMD/MarkdownBlockParser.swift index 02a8a0a..9cdaf06 100644 --- a/QuickMD/QuickMD/MarkdownBlockParser.swift +++ b/QuickMD/QuickMD/MarkdownBlockParser.swift @@ -2111,8 +2111,10 @@ struct MarkdownBlockParser: Sendable { /// Stands in for a non-text block when the ordered lists are worked /// out: not blank, not a list item — so it continues a list exactly when - /// its first line is indented under the list's items (a step's code - /// block, a picture under an item), as a nested paragraph would. + /// an item of that list's level or deeper OWNS the block + /// (`ListOwners.everyBlock`: a step's code block, a picture under an + /// item), as an owned nested paragraph would. Its indentation alone + /// decides nothing since 1.16 (see `renderPendingRows`). private static let blockStandIn = "\u{FFFC}" /// Renders the text rows, every ordered item numbered within ITS list From bf7c9599b830dc1dc8576c03fc358863f32099ac Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 16:16:19 +0100 Subject: [PATCH 15/27] fix: a folder's permission change re-lists the open folder (#62) The watcher now takes item events (FileEvents) and judges each by path and flags: an item created, removed or renamed, a folder's permissions or owner (ItemChangeOwner with ItemIsDir, which chmod of a directory delivers, the root included), or a "look again" flag re-scans. A content write, a file's chmod, xattrs and a folder's mtime do not. A listed folder made unreadable now shows "Can't read this folder", and a kept unreadable folder made readable lists again, without waiting for an unrelated change. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderBrowserStore.swift | 50 +++++++------- QuickMD/QuickMD/FolderListing.swift | 43 ++++++++++++ QuickMD/QuickMD/QuickMDApp.swift | 4 +- .../FolderBrowserStoreTests.swift | 66 +++++++++++++++---- QuickMD/QuickMDTests/FolderListingTests.swift | 42 ++++++++++++ 5 files changed, 167 insertions(+), 38 deletions(-) diff --git a/QuickMD/QuickMD/FolderBrowserStore.swift b/QuickMD/QuickMD/FolderBrowserStore.swift index d2cefec..bb40adc 100644 --- a/QuickMD/QuickMD/FolderBrowserStore.swift +++ b/QuickMD/QuickMD/FolderBrowserStore.swift @@ -13,9 +13,11 @@ import CoreServices /// access and publishes it. A folder that is gone, or whose sandbox /// bookmark cannot be restored, is forgotten without a word. /// - Watched with ONE `FSEventStream` over the whole tree (the listing is -/// recursive; a vnode source per folder would not be). An event batch -/// whose paths all lie under skipped names (`.git`, `node_modules`; -/// `FolderListing.isRelevantChange`, the scan's own rule) is dropped. +/// recursive; a vnode source per folder would not be), with item events. +/// A batch is dropped unless one change can alter the listing +/// (`FolderListing.isRelevantChange`: not under a skipped name such as +/// `.git` / `node_modules`, the scan's own rule; and an item created, +/// removed, renamed, or a FOLDER's permissions changed). /// - ONE scan at a time (measured in review: ten events 100 ms apart had /// started ten scans at once on the pool the document parse uses). Events /// during a scan only mark the listing dirty; exactly one more scan @@ -47,9 +49,9 @@ final class FolderBrowserStore: ObservableObject { /// False = it cannot be read this launch. var restoreAccess: @MainActor (URL) -> Bool /// Watches the tree under the (canonical) root; the token stops it - /// when released. The closure gets the changed paths, on the main + /// when released. The closure gets the batch's changes, on the main /// actor (empty = unknown, treated as relevant). - var watch: @MainActor (URL, @escaping @MainActor ([String]) -> Void) -> AnyObject? + var watch: @MainActor (URL, @escaping @MainActor ([FolderListing.Change]) -> Void) -> AnyObject? /// Lists the root off the main thread; the closure says the scan /// was cancelled. var scan: @Sendable (URL, @escaping @Sendable () -> Bool) async -> FolderListing.Outcome = { root, cancelled in @@ -211,8 +213,8 @@ final class FolderBrowserStore: ObservableObject { isTruncated = false isUnreadable = false isLoading = true - watcher = environment.watch(root) { [weak self] paths in - self?.filesChanged(atPaths: paths) + watcher = environment.watch(root) { [weak self] changes in + self?.filesChanged(changes) } dirty = true startScanLoopIfNeeded() @@ -231,15 +233,13 @@ final class FolderBrowserStore: ObservableObject { resumeWaiters(.superseded) { _ in true } } - private func filesChanged(atPaths paths: [String]) { + private func filesChanged(_ changes: [FolderListing.Change]) { guard let root = listingRoot?.path else { return } - let real = eventRootPath ?? root // A path outside a root counts as relevant, so a path is dropped // when it lies under a skipped name in either spelling of the root. - guard paths.isEmpty || paths.contains(where: { - FolderListing.isRelevantChange(atPath: $0, root: root) - && FolderListing.isRelevantChange(atPath: $0, root: real) - }) else { return } + let roots = [root, eventRootPath ?? root] + guard changes.isEmpty || changes.contains(where: { FolderListing.isRelevantChange($0, roots: roots) }) + else { return } refresh() } @@ -303,33 +303,39 @@ final class FolderBrowserStore: ObservableObject { // MARK: - Tree watcher -/// One `FSEventStream` over a folder tree: directory-level events (no -/// per-file flags) with their paths (`UseCFTypes`), 0.5 s latency (a save -/// that touches several files is one batch), on the main queue. +/// One `FSEventStream` over a folder tree: ITEM events (`FileEvents`: a +/// directory-level stream carries no flags, so a folder's `chmod` could not +/// be told from a content write) with their paths (`UseCFTypes`), 0.5 s +/// latency (a save that touches several files is one batch), on the main +/// queue. /// `kFSEventStreamCreateFlagWatchRoot` also reports the root itself being /// moved or deleted, so the re-scan can forget it. Stops when released. final class FolderTreeWatcher { private final class Handler { - let fire: ([String]) -> Void - init(_ fire: @escaping ([String]) -> Void) { self.fire = fire } + let fire: ([FolderListing.Change]) -> Void + init(_ fire: @escaping ([FolderListing.Change]) -> Void) { self.fire = fire } } private let handler: Handler private var stream: FSEventStreamRef? - init?(root: URL, latency: TimeInterval = 0.5, onChange: @escaping ([String]) -> Void) { + init?(root: URL, latency: TimeInterval = 0.5, onChange: @escaping ([FolderListing.Change]) -> Void) { handler = Handler(onChange) // The stream holds the handler unretained: it is invalidated in // deinit, before the handler goes away. var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(handler).toOpaque(), retain: nil, release: nil, copyDescription: nil) - let callback: FSEventStreamCallback = { _, info, _, eventPaths, _, _ in + let callback: FSEventStreamCallback = { _, info, count, eventPaths, eventFlags, _ in guard let info else { return } // UseCFTypes: the paths are a CFArray of CFString. let paths = (Unmanaged.fromOpaque(eventPaths).takeUnretainedValue() as NSArray) as? [String] ?? [] - Unmanaged.fromOpaque(info).takeUnretainedValue().fire(paths) + let changes = (0...fromOpaque(info).takeUnretainedValue().fire(changes) } - let flags = FSEventStreamCreateFlags(kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagUseCFTypes) + let flags = FSEventStreamCreateFlags(kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagUseCFTypes + | kFSEventStreamCreateFlagFileEvents) guard let stream = FSEventStreamCreate(kCFAllocatorDefault, callback, &context, [root.path] as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), latency, flags) else { diff --git a/QuickMD/QuickMD/FolderListing.swift b/QuickMD/QuickMD/FolderListing.swift index 7db8f7d..230a82b 100644 --- a/QuickMD/QuickMD/FolderListing.swift +++ b/QuickMD/QuickMD/FolderListing.swift @@ -1,4 +1,5 @@ import Foundation +import CoreServices // MARK: - Markdown file kind @@ -168,6 +169,48 @@ enum FolderListing { return !trimmed.dropFirst(base.count).split(separator: "/").contains { isSkippedName(String($0)) } } + /// One FSEvents item event: where, and what happened (the stream's + /// `kFSEventStreamEventFlag…` bits). + struct Change: Equatable, Sendable { + let path: String + let flags: UInt32 + } + + /// The flags that can change the listing: + /// - an item created, removed or renamed (files appear / vanish); + /// - a DIRECTORY's permissions or owner (`ItemChangeOwner` + `ItemIsDir` + /// — what `chmod` / `chown` of a folder delivers, probed on macOS 27: + /// `chmod 000 sub` → `…|ChangeOwner|IsDir` on `sub`, the root + /// included): a folder becomes unreadable or readable again; + /// - anything that says "events were lost / look again" (must scan, + /// root changed, dropped, ids wrapped, mount, unmount), and an event + /// with no item flags at all (unknown). + /// Not: a content write (`ItemModified`), a FILE's permissions + /// (`ChangeOwner` + `IsFile`), xattrs, inode metadata (mtime) or Finder + /// info — a busy tree writes those all the time and the listing (names + /// only) cannot change. + static func isRelevantEventFlags(_ flags: UInt32) -> Bool { + let structural = UInt32(kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemRemoved + | kFSEventStreamEventFlagItemRenamed) + let lookAgain = UInt32(kFSEventStreamEventFlagMustScanSubDirs | kFSEventStreamEventFlagRootChanged + | kFSEventStreamEventFlagUserDropped | kFSEventStreamEventFlagKernelDropped + | kFSEventStreamEventFlagEventIdsWrapped | kFSEventStreamEventFlagMount + | kFSEventStreamEventFlagUnmount) + if flags & (structural | lookAgain) != 0 { return true } + if flags & UInt32(kFSEventStreamEventFlagItemChangeOwner) != 0, + flags & UInt32(kFSEventStreamEventFlagItemIsDir) != 0 { return true } + return flags == 0 + } + + /// `change` can change the listing of `root` (both spellings of the + /// root must agree that it is not under a skipped name; see + /// `isRelevantChange(atPath:root:)`). The root's own event (its path IS + /// the root) is judged by its flags alone. + static func isRelevantChange(_ change: Change, roots: [String]) -> Bool { + isRelevantEventFlags(change.flags) + && roots.allSatisfy { isRelevantChange(atPath: change.path, root: $0) } + } + /// `realpath(3)`: the spelling FSEvents reports (`/private/var/…`, where /// `canonicalPath` — Foundation's `resolvingSymlinksInPath` — gives /// `/var/…`). `path` itself when it cannot be resolved. diff --git a/QuickMD/QuickMD/QuickMDApp.swift b/QuickMD/QuickMD/QuickMDApp.swift index 5371eac..34d0e23 100644 --- a/QuickMD/QuickMD/QuickMDApp.swift +++ b/QuickMD/QuickMD/QuickMDApp.swift @@ -134,8 +134,8 @@ extension FolderBrowserStore { !SandboxAccessManager.isSandboxed || SandboxAccessManager.shared.restoreAccess(for: folder) }, watch: { root, onChange in - FolderTreeWatcher(root: root) { paths in - Task { @MainActor in onChange(paths) } + FolderTreeWatcher(root: root) { changes in + Task { @MainActor in onChange(changes) } } })) }() diff --git a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift index a045725..869e231 100644 --- a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift +++ b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift @@ -1,5 +1,6 @@ import XCTest import Combine +import CoreServices /// `FolderBrowserStore` (File ▸ Open Folder, #62): open / close / persist / /// restore, gone vs unreadable, one scan at a time with one follow-up, @@ -20,7 +21,13 @@ final class FolderBrowserStoreTests: XCTestCase { var restoreAnswer = true var restored: [String] = [] var watched: [String] = [] - var trigger: (@MainActor ([String]) -> Void)? + var trigger: (@MainActor ([FolderListing.Change]) -> Void)? + + /// An event batch: these paths, each with `flags` (default: an item + /// created — a change that can alter the listing). + func fire(_ paths: [String], flags: UInt32 = UInt32(kFSEventStreamEventFlagItemCreated)) { + trigger?(paths.map { FolderListing.Change(path: $0, flags: flags) }) + } weak var token: Token? weak var earlierToken: Token? // Scan probe. @@ -257,14 +264,14 @@ final class FolderBrowserStoreTests: XCTestCase { let browser = store(world) _ = await browser.open(notes) world.forced = .unreadable - world.trigger?([]) + world.fire([]) await settle(browser) XCTAssertEqual(browser.folder?.path, path(notes), "kept") XCTAssertTrue(browser.isUnreadable) XCTAssertEqual(names(browser), ["a.md"], "the last listing stays") XCTAssertNotNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) world.forced = nil - world.trigger?([]) + world.fire([]) await settle(browser) XCTAssertFalse(browser.isUnreadable, "tried again on the next event") } @@ -309,7 +316,7 @@ final class FolderBrowserStoreTests: XCTestCase { XCTAssertFalse(browser.isLoading) XCTAssertNotNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) world.forced = nil - world.trigger?([]) + world.fire([]) await settle(browser) XCTAssertFalse(browser.isUnreadable) XCTAssertEqual(names(browser), ["a.md"]) @@ -340,7 +347,7 @@ final class FolderBrowserStoreTests: XCTestCase { let browser = store(world) _ = await browser.open(notes) try FileManager.default.removeItem(at: notes) - world.trigger?([]) + world.fire([]) await settle(browser) XCTAssertNil(browser.folder) XCTAssertTrue(browser.groups.isEmpty) @@ -358,7 +365,7 @@ final class FolderBrowserStoreTests: XCTestCase { try Data("# new\n".utf8).write(to: notes.appendingPathComponent("sub/new.md")) try FileManager.default.removeItem(at: notes.appendingPathComponent("a.md")) XCTAssertEqual(names(browser), ["a.md", "b.md"], "nothing changes before the event") - world.trigger?([FolderAccessBroker.canonicalPath(notes) + "/sub"]) + world.fire([FolderAccessBroker.canonicalPath(notes) + "/sub"]) await settle(browser) XCTAssertEqual(names(browser), ["b.md", "new.md"]) XCTAssertEqual(browser.groups.map(\.relativePath), ["", "sub"]) @@ -374,7 +381,7 @@ final class FolderBrowserStoreTests: XCTestCase { world.hold = true let opening = Task { await browser.open(notes) } await until { world.started == 1 && !world.gates.isEmpty } - for _ in 0..<10 { world.trigger?([FolderAccessBroker.canonicalPath(notes)]) } + for _ in 0..<10 { world.fire([FolderAccessBroker.canonicalPath(notes)]) } for _ in 0..<50 { await Task.yield() } XCTAssertEqual(world.started, 1, "events while a scan runs start nothing") world.release() @@ -392,15 +399,15 @@ final class FolderBrowserStoreTests: XCTestCase { let browser = store(world) _ = await browser.open(notes) let canonical = FolderAccessBroker.canonicalPath(notes) - world.trigger?([canonical + "/.git/objects/ab", canonical + "/node_modules/pkg"]) + world.fire([canonical + "/.git/objects/ab", canonical + "/node_modules/pkg"]) await settle(browser) XCTAssertEqual(world.started, 1, "a batch only under skipped names is dropped") // FSEvents spells the temporary folder `/private/var/…`. let real = FolderListing.realPath(canonical) - world.trigger?([real + "/.git/index", real + "/docs/node_modules"]) + world.fire([real + "/.git/index", real + "/docs/node_modules"]) await settle(browser) XCTAssertEqual(world.started, 1, "in the realpath spelling too") - world.trigger?([canonical + "/.git", canonical + "/docs"]) + world.fire([canonical + "/.git", canonical + "/docs"]) await settle(browser) XCTAssertEqual(world.started, 2, "one relevant path is enough") } @@ -412,12 +419,12 @@ final class FolderBrowserStoreTests: XCTestCase { _ = await browser.open(notes) var changes = 0 let subscription = browser.objectWillChange.sink { changes += 1 } - world.trigger?([]) + world.fire([]) await settle(browser) XCTAssertEqual(world.started, 2) XCTAssertEqual(changes, 0) try Data("# b\n".utf8).write(to: notes.appendingPathComponent("b.md")) - world.trigger?([]) + world.fire([]) await settle(browser) XCTAssertGreaterThan(changes, 0, "a changed listing does publish") subscription.cancel() @@ -468,7 +475,7 @@ final class FolderBrowserStoreTests: XCTestCase { world.hold = true let opening = Task { await browser.open(notes) } await until { world.started == 1 && !world.gates.isEmpty } - world.trigger?([]) + world.fire([]) world.release() let result = await opening.value XCTAssertEqual(result, .listed) @@ -476,6 +483,37 @@ final class FolderBrowserStoreTests: XCTestCase { await settle(browser) } + /// Restored while unreadable, then the folder's permission is fixed: + /// the `chmod` event of the ROOT (ChangeOwner + IsDir) lists it again. + /// A file's chmod, an xattr or a content write would not have. + func testAPermissionChangeOfTheRootListsARestoredUnreadableFolderAgain() async throws { + let notes = try folder("Notes", files: ["a.md"]) + _ = await store(World()).open(notes) + let world = World() + world.forced = .unreadable + let browser = store(world) + await browser.restore() + await settle(browser) + XCTAssertTrue(browser.isUnreadable) + world.forced = nil + let real = FolderListing.realPath(FolderAccessBroker.canonicalPath(notes)) + let started = world.started + for flags in [kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemIsFile, + kFSEventStreamEventFlagItemXattrMod | kFSEventStreamEventFlagItemIsDir, + kFSEventStreamEventFlagItemInodeMetaMod | kFSEventStreamEventFlagItemIsDir, + kFSEventStreamEventFlagItemModified | kFSEventStreamEventFlagItemIsFile] { + world.fire([real + "/a.md", real], flags: UInt32(flags)) + await settle(browser) + } + XCTAssertEqual(world.started, started, "file chmod, xattr, mtime, content write: no scan") + XCTAssertTrue(browser.isUnreadable) + world.fire([real], flags: UInt32(kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemIsDir)) + await settle(browser) + XCTAssertEqual(world.started, started + 1) + XCTAssertFalse(browser.isUnreadable) + XCTAssertEqual(names(browser), ["a.md"]) + } + // MARK: Real watcher /// The real watcher starts on a folder and stops when released (no event @@ -483,7 +521,7 @@ final class FolderBrowserStoreTests: XCTestCase { func testTheTreeWatcherStartsAndStops() { weak var released: FolderTreeWatcher? do { - let watcher = FolderTreeWatcher(root: root) { _ in } + let watcher = FolderTreeWatcher(root: root) { (_: [FolderListing.Change]) in } XCTAssertNotNil(watcher) released = watcher } diff --git a/QuickMD/QuickMDTests/FolderListingTests.swift b/QuickMD/QuickMDTests/FolderListingTests.swift index b4510b1..aa7567b 100644 --- a/QuickMD/QuickMDTests/FolderListingTests.swift +++ b/QuickMD/QuickMDTests/FolderListingTests.swift @@ -1,4 +1,5 @@ import XCTest +import CoreServices /// `FolderListing` (File ▸ Open Folder, #62) on temporary trees: which /// files are listed, in which order and groups, what is skipped, and the @@ -220,6 +221,47 @@ final class FolderListingTests: XCTestCase { XCTAssertNotEqual(SidebarRowID.folderGroup("docs"), SidebarRowID.recent("docs")) } + /// What an FSEvents item event may trigger, with the flag combinations + /// probed on macOS 27 (`chmod 000 dir` → ChangeOwner|IsDir; a content + /// write → Modified|IsFile; `xattr -w` → XattrMod; `touch dir` → + /// InodeMetaMod|IsDir). + func testOnlyStructuralChangesAndFolderPermissionsAreRelevant() { + func flags(_ bits: Int...) -> UInt32 { UInt32(bits.reduce(0, |)) } + let dir = kFSEventStreamEventFlagItemIsDir, file = kFSEventStreamEventFlagItemIsFile + let relevant = [ + flags(kFSEventStreamEventFlagItemChangeOwner, dir), // chmod / chown of a folder + flags(kFSEventStreamEventFlagItemCreated, file), + flags(kFSEventStreamEventFlagItemRemoved, file), + flags(kFSEventStreamEventFlagItemRenamed, dir), + flags(kFSEventStreamEventFlagItemCreated, kFSEventStreamEventFlagItemModified, file), + flags(kFSEventStreamEventFlagMustScanSubDirs), + flags(kFSEventStreamEventFlagRootChanged), + flags(kFSEventStreamEventFlagKernelDropped), + 0, // no item flags: unknown + ] + let irrelevant = [ + flags(kFSEventStreamEventFlagItemChangeOwner, file), // chmod of a file + flags(kFSEventStreamEventFlagItemXattrMod, dir), // xattr on a folder + flags(kFSEventStreamEventFlagItemXattrMod, file), + flags(kFSEventStreamEventFlagItemInodeMetaMod, dir), // a folder's mtime + flags(kFSEventStreamEventFlagItemModified, file), // a content write + flags(kFSEventStreamEventFlagItemFinderInfoMod, file), + ] + for value in relevant { XCTAssertTrue(FolderListing.isRelevantEventFlags(value), String(value, radix: 16)) } + for value in irrelevant { XCTAssertFalse(FolderListing.isRelevantEventFlags(value), String(value, radix: 16)) } + + // The root's own event is judged by its flags only; a skipped name + // still drops a folder's chmod below it. + let root = "/r/Notes", real = "/private/r/Notes" + let chmodDir = flags(kFSEventStreamEventFlagItemChangeOwner, dir) + for path in [root, real, root + "/", real + "/docs"] { + XCTAssertTrue(FolderListing.isRelevantChange(.init(path: path, flags: chmodDir), roots: [root, real]), path) + } + XCTAssertFalse(FolderListing.isRelevantChange(.init(path: real + "/.git", flags: chmodDir), roots: [root, real])) + XCTAssertFalse(FolderListing.isRelevantChange(.init(path: root, flags: flags(kFSEventStreamEventFlagItemChangeOwner, file)), + roots: [root, real])) + } + /// The file cap still cuts in display order. func testTheFileCapCutsInDisplayOrder() throws { try make("r1.md", "r2.md", "a/m1.md", "a/m2.md", "b/n.md") From 1b724ce75745bad2329d6c1d12e294175615779b Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 16:24:41 +0100 Subject: [PATCH 16/27] fix: Open Folder judges file events off the main thread (#62) The FSEventStream is delivered on a private serial utility queue, where FolderEventBatchFilter tests each event's flags first and then its path as UTF-8 bytes against both spellings of the root, without bridging or allocating per component, and stops at the first relevant change. Only a batch with a relevant change hops to the main actor, once; an npm install or git checkout under node_modules/ or .git/ never reaches it. The stream is released in a block on its own queue that holds the filter, so the filter outlives every callback. The name rule is decided on bytes in both the scan and the watcher. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderBrowserStore.swift | 144 +++++++++++++----- QuickMD/QuickMD/FolderListing.swift | 66 +++++++- QuickMD/QuickMD/QuickMDApp.swift | 7 +- .../FolderBrowserStoreTests.swift | 108 ++++++++++++- QuickMD/QuickMDTests/FolderListingTests.swift | 43 ++++++ 5 files changed, 319 insertions(+), 49 deletions(-) diff --git a/QuickMD/QuickMD/FolderBrowserStore.swift b/QuickMD/QuickMD/FolderBrowserStore.swift index bb40adc..cd03522 100644 --- a/QuickMD/QuickMD/FolderBrowserStore.swift +++ b/QuickMD/QuickMD/FolderBrowserStore.swift @@ -48,10 +48,11 @@ final class FolderBrowserStore: ObservableObject { /// Starts access to a remembered folder (sandbox: its bookmark). /// False = it cannot be read this launch. var restoreAccess: @MainActor (URL) -> Bool - /// Watches the tree under the (canonical) root; the token stops it - /// when released. The closure gets the batch's changes, on the main - /// actor (empty = unknown, treated as relevant). - var watch: @MainActor (URL, @escaping @MainActor ([FolderListing.Change]) -> Void) -> AnyObject? + /// Watches the tree under the (canonical) root, judging every event + /// OFF the main thread against `roots` (both spellings); the closure + /// runs on the main actor once per batch that holds a relevant + /// change. The token stops it when released. + var watch: @MainActor (URL, [String], @escaping @MainActor () -> Void) -> AnyObject? /// Lists the root off the main thread; the closure says the scan /// was cancelled. var scan: @Sendable (URL, @escaping @Sendable () -> Bool) async -> FolderListing.Outcome = { root, cancelled in @@ -213,8 +214,11 @@ final class FolderBrowserStore: ObservableObject { isTruncated = false isUnreadable = false isLoading = true - watcher = environment.watch(root) { [weak self] changes in - self?.filesChanged(changes) + // A path outside a root counts as relevant, so a path is dropped + // when it lies under a skipped name in either spelling of the root. + let roots = [root.path, eventRootPath ?? root.path] + watcher = environment.watch(root, roots) { [weak self] in + self?.refresh() } dirty = true startScanLoopIfNeeded() @@ -233,16 +237,6 @@ final class FolderBrowserStore: ObservableObject { resumeWaiters(.superseded) { _ in true } } - private func filesChanged(_ changes: [FolderListing.Change]) { - guard let root = listingRoot?.path else { return } - // A path outside a root counts as relevant, so a path is dropped - // when it lies under a skipped name in either spelling of the root. - let roots = [root, eventRootPath ?? root] - guard changes.isEmpty || changes.contains(where: { FolderListing.isRelevantChange($0, roots: roots) }) - else { return } - refresh() - } - private func startScanLoopIfNeeded() { guard scanLoop == nil, let current = session else { return } scanLoop = Task { [weak self] in @@ -303,36 +297,107 @@ final class FolderBrowserStore: ObservableObject { // MARK: - Tree watcher +/// Judges one FSEvents batch on the stream's own queue (`FolderTreeWatcher`) +/// and calls `onRelevant` ONCE when the batch holds a change that can alter +/// the listing (`FolderListing.ChangeFilter`), stopping at the first one. +/// +/// Why off the main thread: item events arrive per FILE — an `npm install`, +/// `cargo build` or `git checkout` inside the open folder is tens of +/// thousands of `Created|IsFile` events under `node_modules/` or `target/` +/// every 0.5 s. Bridging and splitting those on main hitched scrolling and +/// Source Edit typing (review of bf7c959). Here a batch with nothing +/// relevant never reaches the main thread; nothing is bridged to Swift +/// (paths are read as UTF-8 into one reused buffer); flags are tested +/// before any path is looked at. +/// +/// Serial-queue only (the buffer); `stop()` may be called from any thread. +final class FolderEventBatchFilter: @unchecked Sendable { + private let filter: FolderListing.ChangeFilter + private let onRelevant: @Sendable () -> Void + private var buffer = [CChar](repeating: 0, count: 1_024) + private let lock = NSLock() + private var stopped = false + + init(roots: [String], onRelevant: @escaping @Sendable () -> Void) { + filter = FolderListing.ChangeFilter(roots: roots) + self.onRelevant = onRelevant + } + + /// After this no batch calls `onRelevant` (a batch already past the + /// check may still finish: the store's `refresh` tolerates a late one). + func stop() { + lock.lock(); stopped = true; lock.unlock() + } + + private var isStopped: Bool { + lock.lock(); defer { lock.unlock() } + return stopped + } + + /// One batch: `count` events, `paths` a CFArray of CFString + /// (`UseCFTypes`), `flags` their flags. True when `onRelevant` was called. + @discardableResult + func handle(count: Int, paths: CFArray, flags: UnsafePointer) -> Bool { + guard !isStopped else { return false } + let available = min(count, CFArrayGetCount(paths)) + for index in 0.. Bool { + let utf8 = CFStringBuiltInEncodings.UTF8.rawValue + let needed = CFStringGetMaximumSizeForEncoding(CFStringGetLength(path), utf8) + 1 + if buffer.count < needed { buffer = [CChar](repeating: 0, count: needed) } + // An unconvertible path: look again rather than miss a change. + guard CFStringGetCString(path, &buffer, buffer.count, utf8) else { return true } + return buffer.withUnsafeBufferPointer { chars in + guard let start = chars.baseAddress else { return true } + let length = strlen(start) + return start.withMemoryRebound(to: UInt8.self, capacity: length) { + filter.isRelevant(flags: flags, path: UnsafeBufferPointer(start: $0, count: length)) + } + } + } +} + /// One `FSEventStream` over a folder tree: ITEM events (`FileEvents`: a /// directory-level stream carries no flags, so a folder's `chmod` could not /// be told from a content write) with their paths (`UseCFTypes`), 0.5 s -/// latency (a save that touches several files is one batch), on the main -/// queue. +/// latency (a save that touches several files is one batch), delivered on +/// a PRIVATE serial utility queue where `FolderEventBatchFilter` judges +/// them; only a relevant batch hops to the main actor (once). /// `kFSEventStreamCreateFlagWatchRoot` also reports the root itself being /// moved or deleted, so the re-scan can forget it. Stops when released. +/// +/// Lifetime: the stream holds the filter UNRETAINED. On release the filter +/// is stopped, the stream stopped and invalidated (no new callbacks), and +/// the stream is RELEASED in a block queued on the stream's own serial +/// queue that also holds the filter: any callback in flight or already +/// queued runs before that block, so the filter outlives every callback. +/// Nothing waits on that queue synchronously (no `sync`), so a release from +/// the main actor never blocks on a busy queue. final class FolderTreeWatcher { - private final class Handler { - let fire: ([FolderListing.Change]) -> Void - init(_ fire: @escaping ([FolderListing.Change]) -> Void) { self.fire = fire } - } - - private let handler: Handler + private let filter: FolderEventBatchFilter + private let queue = DispatchQueue(label: "pl.falami.studio.QuickMD.folder-watch", qos: .utility) private var stream: FSEventStreamRef? - init?(root: URL, latency: TimeInterval = 0.5, onChange: @escaping ([FolderListing.Change]) -> Void) { - handler = Handler(onChange) - // The stream holds the handler unretained: it is invalidated in - // deinit, before the handler goes away. - var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(handler).toOpaque(), + init?(root: URL, roots: [String], latency: TimeInterval = 0.5, onRelevant: @escaping @Sendable () -> Void) { + filter = FolderEventBatchFilter(roots: roots, onRelevant: onRelevant) + var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(filter).toOpaque(), retain: nil, release: nil, copyDescription: nil) let callback: FSEventStreamCallback = { _, info, count, eventPaths, eventFlags, _ in guard let info else { return } - // UseCFTypes: the paths are a CFArray of CFString. - let paths = (Unmanaged.fromOpaque(eventPaths).takeUnretainedValue() as NSArray) as? [String] ?? [] - let changes = (0...fromOpaque(info).takeUnretainedValue().fire(changes) + let paths = Unmanaged.fromOpaque(eventPaths).takeUnretainedValue() + Unmanaged.fromOpaque(info).takeUnretainedValue() + .handle(count: count, paths: paths, flags: eventFlags) } let flags = FSEventStreamCreateFlags(kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents) @@ -341,7 +406,7 @@ final class FolderTreeWatcher { flags) else { return nil } - FSEventStreamSetDispatchQueue(stream, DispatchQueue.main) + FSEventStreamSetDispatchQueue(stream, queue) guard FSEventStreamStart(stream) else { FSEventStreamInvalidate(stream) FSEventStreamRelease(stream) @@ -351,9 +416,14 @@ final class FolderTreeWatcher { } deinit { + filter.stop() guard let stream else { return } FSEventStreamStop(stream) FSEventStreamInvalidate(stream) - FSEventStreamRelease(stream) + let filter = self.filter + queue.async { + FSEventStreamRelease(stream) + withExtendedLifetime(filter) {} + } } } diff --git a/QuickMD/QuickMD/FolderListing.swift b/QuickMD/QuickMD/FolderListing.swift index 230a82b..8b6360a 100644 --- a/QuickMD/QuickMD/FolderListing.swift +++ b/QuickMD/QuickMD/FolderListing.swift @@ -153,8 +153,21 @@ enum FolderListing { /// The NAME part of the skip rule: hidden by a leading dot, or a folder /// nobody reads (`node_modules`). Shared by the scan and the watcher. + /// Decided on the UTF-8 BYTES (a leading 0x2E; byte equality with + /// `node_modules`), so the watcher's allocation-free byte rule + /// (`ChangeFilter`) is exactly this rule — `String.hasPrefix` would + /// compare graphemes (".\u{301}x" does not start with "."). static func isSkippedName(_ name: String) -> Bool { - name.hasPrefix(".") || skippedFolderNames.contains(name) + isSkippedName(utf8: name.utf8) + } + + private static let nodeModulesUTF8 = Array("node_modules".utf8) + private static let dotByte = UInt8(ascii: ".") + private static let slashByte = UInt8(ascii: "/") + + static func isSkippedName(utf8 name: Bytes) -> Bool where Bytes.Element == UInt8 { + guard let first = name.first else { return false } + return first == dotByte || name.elementsEqual(nodeModulesUTF8) } /// A change at `path` (as FSEvents reports it) can change the listing of @@ -162,11 +175,56 @@ enum FolderListing { /// path below the root is a skipped name (`.git/objects/ab`, /// `node_modules/x`). Paths outside the root (the root itself moved) /// count as relevant. + /// The reference form of the watcher's path rule (Strings; the watcher + /// itself runs `ChangeFilter`, its allocation-free twin — a test proves + /// they agree). Byte-wise prefix, like the twin. static func isRelevantChange(atPath path: String, root: String) -> Bool { let base = root.hasSuffix("/") ? root : root + "/" - let trimmed = path.hasSuffix("/") ? String(path.dropLast()) : path - guard trimmed.hasPrefix(base) else { return true } - return !trimmed.dropFirst(base.count).split(separator: "/").contains { isSkippedName(String($0)) } + var trimmed = Array(path.utf8) + if trimmed.last == slashByte { trimmed.removeLast() } + guard trimmed.starts(with: base.utf8) else { return true } + return !trimmed.dropFirst(base.utf8.count).split(separator: slashByte).contains { isSkippedName(utf8: $0) } + } + + /// The watcher's rule for one event, on the stream's own queue and + /// without allocating: flags first (an integer test), then the path's + /// UTF-8 bytes after each spelling of the root, component by component + /// (a leading "." or `node_modules` → not relevant). Exactly + /// `isRelevantChange(_:roots:)` (tested over generated paths). + struct ChangeFilter: Sendable { + /// Each root spelling with one trailing "/". + let bases: [[UInt8]] + + init(roots: [String]) { + bases = roots.map { Array(($0.hasSuffix("/") ? $0 : $0 + "/").utf8) } + } + + func isRelevant(flags: UInt32, path: UnsafeBufferPointer) -> Bool { + guard FolderListing.isRelevantEventFlags(flags) else { return false } + return bases.allSatisfy { Self.isRelevant(path: path, base: $0) } + } + + static func isRelevant(path: UnsafeBufferPointer, base: [UInt8]) -> Bool { + var end = path.count + if end > 0, path[end - 1] == FolderListing.slashByte { end -= 1 } + guard end >= base.count else { return true } + for index in 0.. 0 { + if path[start] == FolderListing.dotByte { return false } + if length == FolderListing.nodeModulesUTF8.count, + FolderListing.nodeModulesUTF8.indices.allSatisfy({ path[start + $0] == FolderListing.nodeModulesUTF8[$0] }) { + return false + } + } + index += 1 + } + return true + } } /// One FSEvents item event: where, and what happened (the stream's diff --git a/QuickMD/QuickMD/QuickMDApp.swift b/QuickMD/QuickMD/QuickMDApp.swift index 34d0e23..2997846 100644 --- a/QuickMD/QuickMD/QuickMDApp.swift +++ b/QuickMD/QuickMD/QuickMDApp.swift @@ -133,9 +133,10 @@ extension FolderBrowserStore { // chooser's grant comes back through its bookmark. !SandboxAccessManager.isSandboxed || SandboxAccessManager.shared.restoreAccess(for: folder) }, - watch: { root, onChange in - FolderTreeWatcher(root: root) { changes in - Task { @MainActor in onChange(changes) } + watch: { root, roots, onChange in + // Called on the watcher's queue, once per relevant batch. + FolderTreeWatcher(root: root, roots: roots) { + Task { @MainActor in onChange() } } })) }() diff --git a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift index 869e231..edb1cfe 100644 --- a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift +++ b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift @@ -21,12 +21,31 @@ final class FolderBrowserStoreTests: XCTestCase { var restoreAnswer = true var restored: [String] = [] var watched: [String] = [] - var trigger: (@MainActor ([FolderListing.Change]) -> Void)? + var trigger: (@MainActor () -> Void)? + var roots: [String] = [] + /// Batches that reached the main actor. + var hops = 0 /// An event batch: these paths, each with `flags` (default: an item - /// created — a change that can alter the listing). + /// created — a change that can alter the listing), judged by the + /// REAL batch filter the watcher runs; an empty batch stands for + /// "something changed" and goes straight through. func fire(_ paths: [String], flags: UInt32 = UInt32(kFSEventStreamEventFlagItemCreated)) { - trigger?(paths.map { FolderListing.Change(path: $0, flags: flags) }) + guard !paths.isEmpty else { + hops += 1 + trigger?() + return + } + let counter = HopCounter() + let filter = FolderEventBatchFilter(roots: roots) { counter.add() } + let flagList = [FSEventStreamEventFlags](repeating: flags, count: paths.count) + flagList.withUnsafeBufferPointer { + _ = filter.handle(count: paths.count, paths: paths as CFArray, flags: $0.baseAddress!) + } + if counter.value > 0 { + hops += 1 + trigger?() + } } weak var token: Token? weak var earlierToken: Token? @@ -81,8 +100,9 @@ final class FolderBrowserStoreTests: XCTestCase { world.restored.append(folder.path) return world.restoreAnswer }, - watch: { folder, onChange in + watch: { folder, roots, onChange in world.watched.append(folder.path) + world.roots = roots world.trigger = onChange let token = Token() world.token = token @@ -514,6 +534,84 @@ final class FolderBrowserStoreTests: XCTestCase { XCTAssertEqual(names(browser), ["a.md"]) } + // MARK: Batch filter (the watcher's queue) + + /// A batch of `count` changes through the real filter, with a counter + /// for the hops it would make to the main actor. + private func hops(paths: [String], flags: [UInt32], roots: [String]) -> Int { + let counter = HopCounter() + let filter = FolderEventBatchFilter(roots: roots) { counter.add() } + flags.withUnsafeBufferPointer { + _ = filter.handle(count: paths.count, paths: paths as CFArray, flags: $0.baseAddress!) + } + return counter.value + } + + private final class HopCounter: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + var value: Int { lock.lock(); defer { lock.unlock() }; return count } + func add() { lock.lock(); count += 1; lock.unlock() } + } + + /// 10 000 irrelevant changes (an `npm install` under node_modules/, a + /// git object write, content writes, file chmods): no hop to the main + /// actor, so no scan. One relevant change in the middle: exactly one. + func testABatchHopsToTheMainActorOnlyForARelevantChange() async throws { + let notes = try folder("Notes", files: ["a.md"]) + let root = FolderAccessBroker.canonicalPath(notes) + let real = FolderListing.realPath(root) + let roots = [root, real] + let created = UInt32(kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemIsFile) + let written = UInt32(kFSEventStreamEventFlagItemModified | kFSEventStreamEventFlagItemIsFile) + let fileChmod = UInt32(kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemIsFile) + var paths: [String] = [] + var flags: [UInt32] = [] + for index in 0..<10_000 { + switch index % 4 { + case 0: paths.append(real + "/node_modules/pkg\(index)/index.js"); flags.append(created) + case 1: paths.append(real + "/.git/objects/\(index)"); flags.append(created) + case 2: paths.append(real + "/notes\(index).md"); flags.append(written) + default: paths.append(real + "/docs/n\(index).md"); flags.append(fileChmod) + } + } + XCTAssertEqual(hops(paths: paths, flags: flags, roots: roots), 0) + + var oneRelevant = paths + oneRelevant[5_000] = real + "/docs/new.md" + var oneFlags = flags + oneFlags[5_000] = created + XCTAssertEqual(hops(paths: oneRelevant, flags: oneFlags, roots: roots), 1, "once per batch") + + // Through the store: the irrelevant batch starts no scan. + let world = World() + let browser = store(world) + _ = await browser.open(notes) + let started = world.started + var hoppedBefore = world.hops + for (path, flag) in zip(paths.prefix(200), flags.prefix(200)) { world.fire([path], flags: flag) } + await settle(browser) + XCTAssertEqual(world.hops, hoppedBefore) + XCTAssertEqual(world.started, started) + hoppedBefore = world.hops + world.fire([real + "/docs/new.md"], flags: created) + await settle(browser) + XCTAssertEqual(world.hops, hoppedBefore + 1) + XCTAssertEqual(world.started, started + 1) + } + + /// A stopped filter (the watcher released) calls nothing. + func testAStoppedBatchFilterCallsNothing() { + let counter = HopCounter() + let filter = FolderEventBatchFilter(roots: ["/r"]) { counter.add() } + filter.stop() + let flags = [UInt32(kFSEventStreamEventFlagItemCreated)] + flags.withUnsafeBufferPointer { + _ = filter.handle(count: 1, paths: ["/r/a.md"] as CFArray, flags: $0.baseAddress!) + } + XCTAssertEqual(counter.value, 0) + } + // MARK: Real watcher /// The real watcher starts on a folder and stops when released (no event @@ -521,7 +619,7 @@ final class FolderBrowserStoreTests: XCTestCase { func testTheTreeWatcherStartsAndStops() { weak var released: FolderTreeWatcher? do { - let watcher = FolderTreeWatcher(root: root) { (_: [FolderListing.Change]) in } + let watcher = FolderTreeWatcher(root: root, roots: [root.path]) {} XCTAssertNotNil(watcher) released = watcher } diff --git a/QuickMD/QuickMDTests/FolderListingTests.swift b/QuickMD/QuickMDTests/FolderListingTests.swift index aa7567b..f43eb89 100644 --- a/QuickMD/QuickMDTests/FolderListingTests.swift +++ b/QuickMD/QuickMDTests/FolderListingTests.swift @@ -262,6 +262,49 @@ final class FolderListingTests: XCTestCase { roots: [root, real])) } + /// The watcher's allocation-free byte rule (`ChangeFilter`) decides + /// exactly as the String reference `isRelevantChange(_:roots:)`, over + /// generated paths: both root spellings, inside / outside / the root + /// itself, trailing slashes, double slashes, dot names, `node_modules` + /// and look-alikes, non-ASCII (NFC and NFD, a dot plus a combining mark), + /// every flag kind. + func testTheByteRuleAgreesWithTheReferenceRule() { + let roots = ["/var/f/Notes", "/private/var/f/Notes"] + let filter = FolderListing.ChangeFilter(roots: roots) + let prefixes = ["/var/f/Notes", "/private/var/f/Notes", "/var/f/Notes2", "/var/f", "/elsewhere", "/"] + let components = ["", "docs", ".git", "node_modules", "node_modules2", "xnode_modules", ".", "..", + "\u{E9}t\u{E9}", "e\u{301}te", ".\u{301}x", "a b", "Node_Modules", "\u{1F600}", "notes.md"] + let flagKinds: [UInt32] = [ + UInt32(kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemIsFile), + UInt32(kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemIsDir), + UInt32(kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemIsFile), + UInt32(kFSEventStreamEventFlagItemModified | kFSEventStreamEventFlagItemIsFile), + 0, + ] + var checked = 0 + for prefix in prefixes { + for first in components { + for second in components { + for tail in ["", "/", "//"] { + var path = prefix + if !first.isEmpty { path += "/" + first } + if !second.isEmpty { path += "/" + second } + path += tail + for flags in flagKinds { + let reference = FolderListing.isRelevantChange(.init(path: path, flags: flags), roots: roots) + let bytes = Array(path.utf8) + let fast = bytes.withUnsafeBufferPointer { filter.isRelevant(flags: flags, path: $0) } + XCTAssertEqual(fast, reference, "\(path) flags \(String(flags, radix: 16))") + checked += 1 + } + } + } + } + } + XCTAssertGreaterThan(checked, 3_000) + XCTAssertTrue(FolderListing.isSkippedName(".\u{301}x"), "a leading dot BYTE, as the byte rule") + } + /// The file cap still cuts in display order. func testTheFileCapCutsInDisplayOrder() throws { try make("r1.md", "r2.md", "a/m1.md", "a/m2.md", "b/n.md") From 991a9c9f39901ed3cc40e9f6034fe3da47191d1c Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 16:29:32 +0100 Subject: [PATCH 17/27] fix: Open Folder ignores file events for non-Markdown names (#62) A file or symlink event whose name has no Markdown extension cannot change the listing, whatever happened to it: a build writing thousands of object files re-read the whole tree every second. A rename delivers one event per name, so .txt -> .md and .md -> .txt are still seen. Folder events, events of unknown kind and "look again" flags stay relevant. Decided on bytes in the watcher's filter, with the String reference rule kept in step. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderListing.swift | 66 +++++++++++++++++-- .../FolderBrowserStoreTests.swift | 19 ++++++ QuickMD/QuickMDTests/FolderListingTests.swift | 52 ++++++++++++++- 3 files changed, 129 insertions(+), 8 deletions(-) diff --git a/QuickMD/QuickMD/FolderListing.swift b/QuickMD/QuickMD/FolderListing.swift index 8b6360a..06b310b 100644 --- a/QuickMD/QuickMD/FolderListing.swift +++ b/QuickMD/QuickMD/FolderListing.swift @@ -14,6 +14,25 @@ enum MarkdownFileKind { static func isMarkdown(_ url: URL) -> Bool { extensions.contains(url.pathExtension.lowercased()) } + + private static let extensionBytes: [[UInt8]] = extensions.map { Array($0.utf8) } + + /// The same test on a file NAME's UTF-8 bytes, without allocating (the + /// folder watcher's queue): the bytes after the last "." (not a leading + /// one), ASCII case-insensitive. + static func isMarkdownName(utf8 name: UnsafeBufferPointer) -> Bool { + var dot = name.count - 1 + while dot > 0, name[dot] != UInt8(ascii: ".") { dot -= 1 } + guard dot > 0 else { return false } + let length = name.count - dot - 1 + return extensionBytes.contains { candidate in + candidate.count == length && candidate.indices.allSatisfy { index in + var byte = name[dot + 1 + index] + if byte >= UInt8(ascii: "A"), byte <= UInt8(ascii: "Z") { byte += 32 } + return byte == candidate[index] + } + } + } } // MARK: - Sidebar row identity @@ -201,6 +220,13 @@ enum FolderListing { func isRelevant(flags: UInt32, path: UnsafeBufferPointer) -> Bool { guard FolderListing.isRelevantEventFlags(flags) else { return false } + if flags & FolderListing.lookAgainFlags != 0 { return true } + var end = path.count + if end > 0, path[end - 1] == FolderListing.slashByte { end -= 1 } + var start = end + while start > 0, path[start - 1] != FolderListing.slashByte { start -= 1 } + let name = UnsafeBufferPointer(rebasing: path[start.. Bool { let structural = UInt32(kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemRemoved | kFSEventStreamEventFlagItemRenamed) - let lookAgain = UInt32(kFSEventStreamEventFlagMustScanSubDirs | kFSEventStreamEventFlagRootChanged - | kFSEventStreamEventFlagUserDropped | kFSEventStreamEventFlagKernelDropped - | kFSEventStreamEventFlagEventIdsWrapped | kFSEventStreamEventFlagMount - | kFSEventStreamEventFlagUnmount) - if flags & (structural | lookAgain) != 0 { return true } + if flags & (structural | lookAgainFlags) != 0 { return true } if flags & UInt32(kFSEventStreamEventFlagItemChangeOwner) != 0, flags & UInt32(kFSEventStreamEventFlagItemIsDir) != 0 { return true } return flags == 0 @@ -265,8 +287,38 @@ enum FolderListing { /// `isRelevantChange(atPath:root:)`). The root's own event (its path IS /// the root) is judged by its flags alone. static func isRelevantChange(_ change: Change, roots: [String]) -> Bool { - isRelevantEventFlags(change.flags) - && roots.allSatisfy { isRelevantChange(atPath: change.path, root: $0) } + guard isRelevantEventFlags(change.flags) else { return false } + if change.flags & lookAgainFlags != 0 { return true } + var bytes = Array(change.path.utf8) + if bytes.last == slashByte { bytes.removeLast() } + let name = bytes.split(separator: slashByte, omittingEmptySubsequences: false).last.map(Array.init) ?? [] + if isNonMarkdownFileEvent(flags: change.flags, name: name) { return false } + return roots.allSatisfy { isRelevantChange(atPath: change.path, root: $0) } + } + + /// "Events were lost / look again": relevant whatever the path. + static let lookAgainFlags = UInt32(kFSEventStreamEventFlagMustScanSubDirs | kFSEventStreamEventFlagRootChanged + | kFSEventStreamEventFlagUserDropped | kFSEventStreamEventFlagKernelDropped + | kFSEventStreamEventFlagEventIdsWrapped | kFSEventStreamEventFlagMount + | kFSEventStreamEventFlagUnmount) + + /// A FILE (or symlink) event whose name is not Markdown cannot change a + /// listing of Markdown files, whatever happened to it (created, + /// removed, renamed): a build writing thousands of `.o` / `dist/` files + /// re-read the whole tree every second (GUI, 13 % CPU). A rename + /// delivers one event PER NAME (probed: `x.txt → x.md` gives + /// `Renamed|IsFile` for both paths), so `x.txt → x.md` is still seen + /// through the `x.md` event and `x.md → x.txt` through the old name. + /// Folders stay relevant (a folder moved in brings only its own event); + /// an event that is neither file nor symlink stays relevant. + static func isNonMarkdownFileEvent(flags: UInt32, name: [UInt8]) -> Bool { + name.withUnsafeBufferPointer { isNonMarkdownFileEvent(flags: flags, name: $0) } + } + + static func isNonMarkdownFileEvent(flags: UInt32, name: UnsafeBufferPointer) -> Bool { + let fileLike = UInt32(kFSEventStreamEventFlagItemIsFile | kFSEventStreamEventFlagItemIsSymlink) + guard flags & fileLike != 0, flags & UInt32(kFSEventStreamEventFlagItemIsDir) == 0 else { return false } + return !MarkdownFileKind.isMarkdownName(utf8: name) } /// `realpath(3)`: the spelling FSEvents reports (`/private/var/…`, where diff --git a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift index edb1cfe..4b041ac 100644 --- a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift +++ b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift @@ -600,6 +600,25 @@ final class FolderBrowserStoreTests: XCTestCase { XCTAssertEqual(world.started, started + 1) } + /// A build in the folder: 10 000 created `.o` files outside skipped + /// names → no hop, no scan. + func testTenThousandNonMarkdownFilesCauseNoHopAndNoScan() async throws { + let notes = try folder("Notes", files: ["a.md"]) + let real = FolderListing.realPath(FolderAccessBroker.canonicalPath(notes)) + let created = UInt32(kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemIsFile) + let paths = (0..<10_000).map { real + "/build/obj\($0 % 50)/unit\($0).o" } + XCTAssertEqual(hops(paths: paths, flags: Array(repeating: created, count: paths.count), + roots: [FolderAccessBroker.canonicalPath(notes), real]), 0) + let world = World() + let browser = store(world) + _ = await browser.open(notes) + let started = world.started, hopped = world.hops + world.fire(paths, flags: created) + await settle(browser) + XCTAssertEqual(world.hops, hopped) + XCTAssertEqual(world.started, started) + } + /// A stopped filter (the watcher released) calls nothing. func testAStoppedBatchFilterCallsNothing() { let counter = HopCounter() diff --git a/QuickMD/QuickMDTests/FolderListingTests.swift b/QuickMD/QuickMDTests/FolderListingTests.swift index f43eb89..ce89342 100644 --- a/QuickMD/QuickMDTests/FolderListingTests.swift +++ b/QuickMD/QuickMDTests/FolderListingTests.swift @@ -273,12 +273,15 @@ final class FolderListingTests: XCTestCase { let filter = FolderListing.ChangeFilter(roots: roots) let prefixes = ["/var/f/Notes", "/private/var/f/Notes", "/var/f/Notes2", "/var/f", "/elsewhere", "/"] let components = ["", "docs", ".git", "node_modules", "node_modules2", "xnode_modules", ".", "..", - "\u{E9}t\u{E9}", "e\u{301}te", ".\u{301}x", "a b", "Node_Modules", "\u{1F600}", "notes.md"] + "\u{E9}t\u{E9}", "e\u{301}te", ".\u{301}x", "a b", "Node_Modules", "\u{1F600}", "notes.md", + "N.MD", "x.o", "a.md.bak", ".md", "x.", "r\u{E9}.markdown"] let flagKinds: [UInt32] = [ UInt32(kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemIsFile), UInt32(kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemIsDir), UInt32(kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemIsFile), UInt32(kFSEventStreamEventFlagItemModified | kFSEventStreamEventFlagItemIsFile), + UInt32(kFSEventStreamEventFlagItemRenamed | kFSEventStreamEventFlagItemIsSymlink), + UInt32(kFSEventStreamEventFlagMustScanSubDirs), 0, ] var checked = 0 @@ -305,6 +308,53 @@ final class FolderListingTests: XCTestCase { XCTAssertTrue(FolderListing.isSkippedName(".\u{301}x"), "a leading dot BYTE, as the byte rule") } + /// A file event counts only for a Markdown name; folders and unknown + /// kinds always count; "look again" counts anywhere. Rename flags are + /// the probed ones (macOS 27: one `Renamed|IsFile` event per name; a + /// young file also carries its sticky `Created|Modified`). + func testFileEventsCountOnlyForMarkdownNames() { + let roots = ["/r/Notes", "/private/r/Notes"] + let filter = FolderListing.ChangeFilter(roots: roots) + func check(_ path: String, _ flags: UInt32, _ expected: Bool, line: UInt = #line) { + let reference = FolderListing.isRelevantChange(.init(path: path, flags: flags), roots: roots) + let fast = Array(path.utf8).withUnsafeBufferPointer { filter.isRelevant(flags: flags, path: $0) } + XCTAssertEqual(reference, expected, "reference: \(path)", line: line) + XCTAssertEqual(fast, expected, "byte rule: \(path)", line: line) + } + let file = kFSEventStreamEventFlagItemIsFile, dir = kFSEventStreamEventFlagItemIsDir + let created = UInt32(kFSEventStreamEventFlagItemCreated | file) + let removed = UInt32(kFSEventStreamEventFlagItemRemoved | file) + let renamed = UInt32(kFSEventStreamEventFlagItemRenamed | file) + let youngRenamed = UInt32(kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemRenamed + | kFSEventStreamEventFlagItemModified | file) + for name in ["build.dat", "main.o", "Makefile", "notes.md.bak", "x.md.", "a.mdx", "readme.txt"] { + check("/private/r/Notes/Attachments/" + name, created, false) + check("/private/r/Notes/Attachments/" + name, removed, false) + } + for name in ["a.md", "B.MD", "c.markdown", "d.MarkDown", "e.mdown", "f.mkd", "g.MKD"] { + check("/private/r/Notes/docs/" + name, created, true) + check("/private/r/Notes/docs/" + name, removed, true) + } + check("/private/r/Notes/x.dat", UInt32(kFSEventStreamEventFlagItemCreated | dir), true) // a folder + check("/private/r/Notes/x.dat/", UInt32(kFSEventStreamEventFlagItemRenamed | dir), true) + // x.txt → x.md (the new name tells) and x.md → x.txt (the old name tells). + check("/private/r/Notes/x.txt", renamed, false) + check("/private/r/Notes/x.md", renamed, true) + check("/private/r/Notes/y.txt", youngRenamed, false) + check("/private/r/Notes/y.md", renamed, true) + // A symlink named like data: not relevant; one named .md: relevant. + check("/private/r/Notes/link", UInt32(kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemIsSymlink), false) + check("/private/r/Notes/link.md", UInt32(kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemIsSymlink), true) + // Neither file nor folder, or no flags: relevant. + check("/private/r/Notes/thing.dat", UInt32(kFSEventStreamEventFlagItemCreated), true) + check("/private/r/Notes/thing.dat", 0, true) + // "Look again" counts whatever the path. + check("/private/r/Notes/.git/x.o", UInt32(kFSEventStreamEventFlagMustScanSubDirs), true) + check("/private/r/Notes/a.dat", UInt32(kFSEventStreamEventFlagMustScanSubDirs | file), true) + // A Markdown file under a skipped name still does not count. + check("/private/r/Notes/node_modules/pkg/README.md", created, false) + } + /// The file cap still cuts in display order. func testTheFileCapCutsInDisplayOrder() throws { try make("r1.md", "r2.md", "a/m1.md", "a/m2.md", "b/n.md") From d1d8333672dbc2717b36afe59dbba3a1316851bd Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 16:33:12 +0100 Subject: [PATCH 18/27] refactor: the folder scan's dot test is the byte rule of isSkippedName (#62) Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderListing.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/QuickMD/QuickMD/FolderListing.swift b/QuickMD/QuickMD/FolderListing.swift index 06b310b..ce927ce 100644 --- a/QuickMD/QuickMD/FolderListing.swift +++ b/QuickMD/QuickMD/FolderListing.swift @@ -419,7 +419,10 @@ enum FolderListing { var entries: [Entry] = [] for url in urls { let name = url.lastPathComponent - guard !name.hasPrefix("."), let values = try? url.resourceValues(forKeys: Set(keys)) else { continue } + // The dot test is the byte rule of `isSkippedName` (one rule for + // scan and watcher). `.skipsHiddenFiles` already removes dot names, + // so today this only guards against that option changing. + guard name.utf8.first != dotByte, let values = try? url.resourceValues(forKeys: Set(keys)) else { continue } if values.isHidden == true || values.isSymbolicLink == true { continue } // Built on `folder`, not taken from the enumeration: Foundation // hands back `/private/var/…` for a root spelled `/var/…`, and From ca99e0d9efc493f239db57509e846aa0db9a1806 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 16:36:39 +0100 Subject: [PATCH 19/27] fix: a hard-link event is never dropped as a non-Markdown file (#62) FSEvents may name a hard-linked file's event by another link, so an event carrying ItemIsHardlink or ItemIsLastHardlink no longer takes the non-Markdown-file exemption, in the reference rule and the byte rule. Two doc comments now name the watcher's real filter. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderBrowserStore.swift | 12 ++++++++---- QuickMD/QuickMD/FolderListing.swift | 16 ++++++++++++---- QuickMD/QuickMDTests/FolderListingTests.swift | 19 ++++++++++++++++--- 3 files changed, 36 insertions(+), 11 deletions(-) diff --git a/QuickMD/QuickMD/FolderBrowserStore.swift b/QuickMD/QuickMD/FolderBrowserStore.swift index cd03522..df8ddf5 100644 --- a/QuickMD/QuickMD/FolderBrowserStore.swift +++ b/QuickMD/QuickMD/FolderBrowserStore.swift @@ -14,10 +14,14 @@ import CoreServices /// bookmark cannot be restored, is forgotten without a word. /// - Watched with ONE `FSEventStream` over the whole tree (the listing is /// recursive; a vnode source per folder would not be), with item events. -/// A batch is dropped unless one change can alter the listing -/// (`FolderListing.isRelevantChange`: not under a skipped name such as -/// `.git` / `node_modules`, the scan's own rule; and an item created, -/// removed, renamed, or a FOLDER's permissions changed). +/// Each batch is judged OFF the main thread by `FolderEventBatchFilter` +/// (`FolderListing.ChangeFilter`, on bytes) and reaches the main actor +/// only when one change can alter the listing: the flags first (an item +/// created / removed / renamed, a FOLDER's permissions, or a "look again" +/// flag, which counts whatever the path); then a FILE or symlink event +/// whose name is not Markdown is dropped (never a hard-link event, whose +/// name may be another link's); then a path under a skipped name +/// (`.git`, `node_modules`, the scan's own rule) is dropped. /// - ONE scan at a time (measured in review: ten events 100 ms apart had /// started ten scans at once on the pool the document parse uses). Events /// during a scan only mark the listing dirty; exactly one more scan diff --git a/QuickMD/QuickMD/FolderListing.swift b/QuickMD/QuickMD/FolderListing.swift index ce927ce..bb45975 100644 --- a/QuickMD/QuickMD/FolderListing.swift +++ b/QuickMD/QuickMD/FolderListing.swift @@ -99,8 +99,10 @@ extension URL { /// - Skipped: hidden files and folders (`.git`, dot files, the Finder hidden /// flag), packages (an `.app`, a `.textbundle` — one document to Finder), /// `node_modules` (thousands of vendored READMEs nobody wants to read). The -/// name part of that rule is `isSkippedName`, shared with the watcher's -/// event filter (`isRelevantChange`) so the two never disagree. +/// name part of that rule is `isSkippedName` (decided on bytes), shared +/// with the watcher's event filter (`ChangeFilter`, run by +/// `FolderEventBatchFilter`; `isRelevantChange` is its String reference +/// form) so the two never disagree. /// - Symbolic links are never followed, to folders or files: a link back up /// the tree would loop, and a link out of the folder would list (and in the /// sandbox fail to open) files that are not in it. @@ -310,14 +312,20 @@ enum FolderListing { /// `Renamed|IsFile` for both paths), so `x.txt → x.md` is still seen /// through the `x.md` event and `x.md → x.txt` through the old name. /// Folders stay relevant (a folder moved in brings only its own event); - /// an event that is neither file nor symlink stays relevant. + /// an event that is neither file nor symlink stays relevant. A HARD-LINK + /// event (`ItemIsHardlink` / `ItemIsLastHardlink`) never takes the + /// exemption: FSEvents may name it by whichever link the kernel resolves + /// (`ln a.txt b.md`, `rm b.md` can arrive as `a.txt …|IsHardlink`), so + /// the name says nothing about which listed file changed. static func isNonMarkdownFileEvent(flags: UInt32, name: [UInt8]) -> Bool { name.withUnsafeBufferPointer { isNonMarkdownFileEvent(flags: flags, name: $0) } } static func isNonMarkdownFileEvent(flags: UInt32, name: UnsafeBufferPointer) -> Bool { let fileLike = UInt32(kFSEventStreamEventFlagItemIsFile | kFSEventStreamEventFlagItemIsSymlink) - guard flags & fileLike != 0, flags & UInt32(kFSEventStreamEventFlagItemIsDir) == 0 else { return false } + let hardLink = UInt32(kFSEventStreamEventFlagItemIsHardlink | kFSEventStreamEventFlagItemIsLastHardlink) + guard flags & fileLike != 0, flags & UInt32(kFSEventStreamEventFlagItemIsDir) == 0, + flags & hardLink == 0 else { return false } return !MarkdownFileKind.isMarkdownName(utf8: name) } diff --git a/QuickMD/QuickMDTests/FolderListingTests.swift b/QuickMD/QuickMDTests/FolderListingTests.swift index ce89342..219b10e 100644 --- a/QuickMD/QuickMDTests/FolderListingTests.swift +++ b/QuickMD/QuickMDTests/FolderListingTests.swift @@ -281,6 +281,10 @@ final class FolderListingTests: XCTestCase { UInt32(kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemIsFile), UInt32(kFSEventStreamEventFlagItemModified | kFSEventStreamEventFlagItemIsFile), UInt32(kFSEventStreamEventFlagItemRenamed | kFSEventStreamEventFlagItemIsSymlink), + UInt32(kFSEventStreamEventFlagItemRemoved | kFSEventStreamEventFlagItemIsFile + | kFSEventStreamEventFlagItemIsHardlink), + UInt32(kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemIsFile + | kFSEventStreamEventFlagItemIsLastHardlink), UInt32(kFSEventStreamEventFlagMustScanSubDirs), 0, ] @@ -315,11 +319,11 @@ final class FolderListingTests: XCTestCase { func testFileEventsCountOnlyForMarkdownNames() { let roots = ["/r/Notes", "/private/r/Notes"] let filter = FolderListing.ChangeFilter(roots: roots) - func check(_ path: String, _ flags: UInt32, _ expected: Bool, line: UInt = #line) { + func check(_ path: String, _ flags: UInt32, _ expected: Bool, _ note: String = "", line: UInt = #line) { let reference = FolderListing.isRelevantChange(.init(path: path, flags: flags), roots: roots) let fast = Array(path.utf8).withUnsafeBufferPointer { filter.isRelevant(flags: flags, path: $0) } - XCTAssertEqual(reference, expected, "reference: \(path)", line: line) - XCTAssertEqual(fast, expected, "byte rule: \(path)", line: line) + XCTAssertEqual(reference, expected, "reference: \(path) \(note)", line: line) + XCTAssertEqual(fast, expected, "byte rule: \(path) \(note)", line: line) } let file = kFSEventStreamEventFlagItemIsFile, dir = kFSEventStreamEventFlagItemIsDir let created = UInt32(kFSEventStreamEventFlagItemCreated | file) @@ -351,6 +355,15 @@ final class FolderListingTests: XCTestCase { // "Look again" counts whatever the path. check("/private/r/Notes/.git/x.o", UInt32(kFSEventStreamEventFlagMustScanSubDirs), true) check("/private/r/Notes/a.dat", UInt32(kFSEventStreamEventFlagMustScanSubDirs | file), true) + // A hard-link event never takes the non-Markdown exemption: its name + // may be another link's (`ln a.txt b.md`; `rm b.md` as `a.txt`). + check("/private/r/Notes/a.txt", UInt32(kFSEventStreamEventFlagItemRemoved | file + | kFSEventStreamEventFlagItemIsHardlink), true) + check("/private/r/Notes/a.txt", UInt32(kFSEventStreamEventFlagItemRemoved | file + | kFSEventStreamEventFlagItemIsLastHardlink), true) + check("/private/r/Notes/a.txt", UInt32(kFSEventStreamEventFlagItemModified | file + | kFSEventStreamEventFlagItemIsHardlink), false, + "a content write stays irrelevant") // A Markdown file under a skipped name still does not count. check("/private/r/Notes/node_modules/pkg/README.md", created, false) } From d9f5c2a719ebe7993498b57eaa17e3eb6856ac4b Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 17:08:00 +0100 Subject: [PATCH 20/27] fix: restoring the open folder resolves its paths off the main thread (#62) The restore's off-main work now also resolves both spellings of the root (canonical and realpath) through an injectable seam and carries them to the main actor, which starts the session and the watcher without a file-system call of its own. An explicit Open resolves synchronously as before, so a later Open still supersedes an earlier one. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderBrowserStore.swift | 46 ++++++++++++++++--- .../FolderBrowserStoreTests.swift | 46 ++++++++++++++++++- 2 files changed, 84 insertions(+), 8 deletions(-) diff --git a/QuickMD/QuickMD/FolderBrowserStore.swift b/QuickMD/QuickMD/FolderBrowserStore.swift index df8ddf5..8405dae 100644 --- a/QuickMD/QuickMD/FolderBrowserStore.swift +++ b/QuickMD/QuickMD/FolderBrowserStore.swift @@ -67,6 +67,24 @@ final class FolderBrowserStore: ObservableObject { var followUpDelay: @MainActor () async -> Void = { try? await Task.sleep(nanoseconds: 1_000_000_000) } + /// The two spellings of a folder's path (file-system calls: a + /// restore runs it OFF the main thread). + var resolveRoot: @Sendable (URL) -> RootSpellings = { FolderBrowserStore.rootSpellings(of: $0) } + } + + /// A root as the listing spells it (`canonical`: Foundation's disk + /// spelling, `/var/…`) and as FSEvents reports it (`real`: realpath, + /// `/private/var/…`). + struct RootSpellings: Equatable, Sendable { + let canonical: String + let real: String + } + + /// Resolves symlinks and the on-disk case twice — I/O on the folder's + /// volume. + nonisolated static func rootSpellings(of url: URL) -> RootSpellings { + let canonical = FolderAccessBroker.canonicalPath(url) + return RootSpellings(canonical: canonical, real: FolderListing.realPath(canonical)) } /// How an `open` ended. @@ -140,8 +158,10 @@ final class FolderBrowserStore: ObservableObject { didRestore = true let chosen = url.standardizedFileURL environment.defaults.set(chosen.path, forKey: Self.defaultsKey) - let root = URL(fileURLWithPath: FolderAccessBroker.canonicalPath(chosen), isDirectory: true) - let opened = begin(folder: chosen, root: root, restored: false) + // On the main actor, synchronously: the chooser has just touched the + // folder, and an await here would let two Opens finish out of order + // (the later choice must win). + let opened = begin(folder: chosen, spellings: environment.resolveRoot(chosen), restored: false) return await withCheckedContinuation { continuation in waiters.append((opened, continuation)) } @@ -166,15 +186,23 @@ final class FolderBrowserStore: ObservableObject { guard !didRestore else { return } didRestore = true guard folder == nil, let path = environment.defaults.string(forKey: Self.defaultsKey) else { return } - let canonical = await Task.detached(priority: .utility) { Self.restorableCanonicalPath(path) }.value + // Every file-system call of the restore runs here, off the main + // thread — the existence check AND both spellings of the root — and + // the main actor only receives the result: a remembered folder on a + // stalled share must not stall launch. + let resolve = environment.resolveRoot + let spellings = await Task.detached(priority: .utility) { () -> RootSpellings? in + guard Self.restorableCanonicalPath(path) != nil else { return nil } + return resolve(URL(fileURLWithPath: path, isDirectory: true)) + }.value // Opened, closed or replaced while the check ran: the reader acted. guard folder == nil, environment.defaults.string(forKey: Self.defaultsKey) == path else { return } let chosen = URL(fileURLWithPath: path, isDirectory: true).standardizedFileURL - guard let canonical, environment.restoreAccess(chosen) else { + guard let spellings, environment.restoreAccess(chosen) else { environment.defaults.removeObject(forKey: Self.defaultsKey) return } - begin(folder: chosen, root: URL(fileURLWithPath: canonical, isDirectory: true), restored: true) + begin(folder: chosen, spellings: spellings, restored: true) } /// Lists the folder again — at once, or after the running scan. @@ -207,13 +235,17 @@ final class FolderBrowserStore: ObservableObject { } @discardableResult - private func begin(folder chosen: URL, root: URL, restored: Bool) -> Session { + /// Starts a session on spellings resolved BEFORE: no file-system call + /// here (the watcher's `FSEventStreamCreate` / `Start` register paths + /// with fseventsd; they are not a read of the folder). + private func begin(folder chosen: URL, spellings: RootSpellings, restored: Bool) -> Session { endSession() let opened = Session(keepsWhenUnreadable: restored) + let root = URL(fileURLWithPath: spellings.canonical, isDirectory: true) session = opened folder = chosen listingRoot = root - eventRootPath = FolderListing.realPath(root.path) + eventRootPath = spellings.real groups = [] isTruncated = false isUnreadable = false diff --git a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift index 4b041ac..5e2b085 100644 --- a/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift +++ b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift @@ -25,6 +25,9 @@ final class FolderBrowserStoreTests: XCTestCase { var roots: [String] = [] /// Batches that reached the main actor. var hops = 0 + /// Calls of the path-resolving seam, and those made on the main + /// thread (counted from any thread). + let resolves = ResolveCounter() /// An event batch: these paths, each with `flags` (default: an item /// created — a change that can alter the listing), judged by the @@ -115,7 +118,11 @@ final class FolderBrowserStoreTests: XCTestCase { await world.end() return outcome }, - followUpDelay: { world.events.append("delay") })) + followUpDelay: { world.events.append("delay") }, + resolveRoot: { [resolves = world.resolves] url in + resolves.record(onMain: Thread.isMainThread) + return FolderBrowserStore.rootSpellings(of: url) + })) } private func folder(_ name: String, files: [String]) throws -> URL { @@ -547,6 +554,43 @@ final class FolderBrowserStoreTests: XCTestCase { return counter.value } + private final class ResolveCounter: @unchecked Sendable { + private let lock = NSLock() + private var all = 0 + private var main = 0 + var total: Int { lock.lock(); defer { lock.unlock() }; return all } + var onMain: Int { lock.lock(); defer { lock.unlock() }; return main } + func record(onMain isMain: Bool) { + lock.lock(); all += 1; if isMain { main += 1 }; lock.unlock() + } + } + + /// A restore resolves the root's spellings OFF the main thread only: + /// the main actor gets the result and starts the session without a + /// file-system call of its own (a stalled share must not stall launch). + func testARestoreResolvesTheRootOffTheMainThread() async throws { + let notes = try folder("Notes", files: ["a.md"]) + _ = await store(World()).open(notes) + let world = World() + let browser = store(world) + await browser.restore() + await settle(browser) + XCTAssertEqual(names(browser), ["a.md"]) + XCTAssertEqual(world.resolves.total, 1) + XCTAssertEqual(world.resolves.onMain, 0, "no path resolution on the main actor during a restore") + XCTAssertEqual(browser.listingRoot?.path, FolderAccessBroker.canonicalPath(notes)) + XCTAssertEqual(world.roots, [FolderAccessBroker.canonicalPath(notes), + FolderListing.realPath(FolderAccessBroker.canonicalPath(notes))], + "the watcher got the carried spellings") + // A gone folder is not resolved at all. + try FileManager.default.removeItem(at: notes) + _ = await store(World()).open(try folder("Other", files: ["b.md"])) + let otherWorld = World() + suite.defaults.set(notes.path, forKey: FolderBrowserStore.defaultsKey) + await store(otherWorld).restore() + XCTAssertEqual(otherWorld.resolves.total, 0) + } + private final class HopCounter: @unchecked Sendable { private let lock = NSLock() private var count = 0 From e5092995a52c97afb845af04e1a41996db3af8a7 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 17:08:00 +0100 Subject: [PATCH 21/27] fix: choosing the same folder again does not add a second grant (#62) registerUserChosenFolder is a no-op for a folder already granted in this session, and saveGrant leaves a folder that is already saved and active alone (no duplicate saved entry, no unbalanced access start); a saved folder that is not active gets a fresh bookmark without a second entry. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderAccessBroker.swift | 16 ++++++++- QuickMD/QuickMD/SandboxAccessManager.swift | 16 +++++++-- .../FolderAccessBrokerTests.swift | 33 +++++++++++++++++++ 3 files changed, 62 insertions(+), 3 deletions(-) diff --git a/QuickMD/QuickMD/FolderAccessBroker.swift b/QuickMD/QuickMD/FolderAccessBroker.swift index 8934fef..af4e73d 100644 --- a/QuickMD/QuickMD/FolderAccessBroker.swift +++ b/QuickMD/QuickMD/FolderAccessBroker.swift @@ -100,6 +100,16 @@ final class FolderAccessBroker { return path } + /// `folder` already has a saved bookmark AND an active access in this + /// process (exact folder, by canonical path): saving it again would only + /// add a duplicate entry and an unbalanced + /// `startAccessingSecurityScopedResource`. Used by + /// `SandboxAccessManager.saveGrant`. + nonisolated static func isActiveGrant(_ folder: URL, saved: [URL], active: [URL]) -> Bool { + let path = canonicalPath(folder) + return saved.contains { canonicalPath($0) == path } && active.contains { canonicalPath($0) == path } + } + /// `folder` is `path` or one of its ancestors. nonisolated static func covers(_ folder: String, _ path: String) -> Bool { folder == "/" || path == folder || path.hasPrefix(folder.hasSuffix("/") ? folder : folder + "/") @@ -141,8 +151,12 @@ final class FolderAccessBroker { /// (false). True when the grant was recorded. @discardableResult func registerUserChosenFolder(_ folder: URL) -> Bool { - guard environment.isSandboxed, environment.save(folder) else { return false } + guard environment.isSandboxed else { return false } let granted = Self.canonicalPath(folder) + // Chosen again (Open Folder on the same folder): already granted in + // this session — no second bookmark, no second access start. + if grantedFolders.contains(granted) { return true } + guard environment.save(folder) else { return false } if !grantedFolders.contains(granted) { grantedFolders.append(granted) } declinedFolders = declinedFolders.filter { !Self.covers(granted, $0) } environment.didGrant(folder) diff --git a/QuickMD/QuickMD/SandboxAccessManager.swift b/QuickMD/QuickMD/SandboxAccessManager.swift index df9dced..481c9fd 100644 --- a/QuickMD/QuickMD/SandboxAccessManager.swift +++ b/QuickMD/QuickMD/SandboxAccessManager.swift @@ -162,13 +162,25 @@ final class SandboxAccessManager { return selectedURL } - /// Saves the bookmark of a granted folder and starts access. + /// Saves the bookmark of a granted folder and starts access — once: a + /// folder already saved AND active (restored at launch, or granted + /// earlier this session) is left alone. Its bookmark needs no refresh + /// then: it was either created this session or resolved by + /// `restoreAccess`, which re-saves a stale one. A saved folder that is + /// not active gets a fresh bookmark (that IS the refresh) and its access + /// started, without a second entry in `savedFolders`. private func saveGrant(_ selectedURL: URL) -> Bool { + if FolderAccessBroker.isActiveGrant(selectedURL, saved: savedFolders, active: activeAccessURLs) { + return true + } do { let bookmarkData = try selectedURL.bookmarkData(options: .withSecurityScope) let key = Self.bookmarkKey(for: selectedURL) UserDefaults.standard.set(bookmarkData, forKey: key) - savedFolders.append(selectedURL) + let path = FolderAccessBroker.canonicalPath(selectedURL) + if !savedFolders.contains(where: { FolderAccessBroker.canonicalPath($0) == path }) { + savedFolders.append(selectedURL) + } if selectedURL.startAccessingSecurityScopedResource() { activeAccessURLs.append(selectedURL) return true diff --git a/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift b/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift index 74246a0..e611938 100644 --- a/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift +++ b/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift @@ -262,6 +262,39 @@ final class FolderAccessBrokerTests: XCTestCase { .granted, "outside the chosen folder nothing changed") } + /// The same folder chosen three times: one save (one bookmark, one + /// access start), one grant notice; a different folder still adds, and + /// coverage / declines are as after one registration. + func testTheSameChosenFolderRegisteredThreeTimesIsSavedOnce() async { + let world = World() + let access = broker(world) + _ = await access.requestAccess(forFileAt: file("elsewhere/x.png"), documentURL: document, explicit: false) + XCTAssertEqual(access.declinedFolders.count, 1) + for _ in 0..<3 { XCTAssertTrue(access.registerUserChosenFolder(file("docs"))) } + XCTAssertEqual(world.saves.count, 1, "one bookmark, one access start") + XCTAssertEqual(world.granted.count, 1) + XCTAssertEqual(access.grantedFolders, [FolderAccessBroker.canonicalPath(file("docs"))]) + XCTAssertEqual(access.declinedFolders.count, 1, "a decline elsewhere stays") + let covered = await access.requestAccess(forFileAt: file("docs/badges/a.svg"), documentURL: document, + explicit: false) + XCTAssertTrue(covered) + XCTAssertTrue(access.registerUserChosenFolder(file("elsewhere"))) + XCTAssertEqual(world.saves.count, 2, "a different folder still adds") + XCTAssertTrue(access.declinedFolders.isEmpty, "its grant clears the decline it covers") + } + + /// The manager's guard (`saveGrant`): saved AND active, by canonical + /// path, any spelling. + func testIsActiveGrantNeedsBothSavedAndActive() { + let docs = file("docs") + let spelledOtherwise = URL(fileURLWithPath: FolderAccessBroker.canonicalPath(docs) + "/badges/..") + XCTAssertTrue(FolderAccessBroker.isActiveGrant(docs, saved: [spelledOtherwise], active: [docs])) + XCTAssertFalse(FolderAccessBroker.isActiveGrant(docs, saved: [docs], active: []), "saved, not active") + XCTAssertFalse(FolderAccessBroker.isActiveGrant(docs, saved: [], active: [docs]), "active, not saved") + XCTAssertFalse(FolderAccessBroker.isActiveGrant(file("docs/images"), saved: [docs], active: [docs]), + "a subfolder is a different folder") + } + /// Unsandboxed (GitHub/Homebrew) the chooser's folder is only a path: /// nothing is saved, granted or announced. func testAUserChosenFolderIsNeverRegisteredUnsandboxed() { From 26115752bf7a98fe44321f323aa82aeab080646c Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 17:14:22 +0100 Subject: [PATCH 22/27] perf: no rule test outside a list item, one trim per line in renderLine Two exact shortcuts from the 1.16 review: the block loop asks whether a text line is a rule (for its owning item) only while an item is open, and renderLine hands the line it has already trimmed to orderedItem. A test pins the parse of eight adversarial documents to values captured before the change (indents compared by value, never as font constants). Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/MarkdownBlockParser.swift | 4 +- QuickMD/QuickMD/MarkdownRenderer.swift | 8 +- QuickMD/QuickMDTests/ListContentTests.swift | 145 ++++++++++++++++++++ 3 files changed, 154 insertions(+), 3 deletions(-) diff --git a/QuickMD/QuickMD/MarkdownBlockParser.swift b/QuickMD/QuickMD/MarkdownBlockParser.swift index 9cdaf06..0199d2c 100644 --- a/QuickMD/QuickMD/MarkdownBlockParser.swift +++ b/QuickMD/QuickMD/MarkdownBlockParser.swift @@ -821,9 +821,11 @@ struct MarkdownBlockParser: Sendable { nesting.blank() } else if let owner = nesting.text(line, sourceLine: sourceLine) { paragraphOwners[sourceLine] = owner - } else if MarkdownRenderer.isThematicBreak(line), let owner = nesting.items.last?.sourceLine { + } else if let owner = nesting.items.last?.sourceLine, MarkdownRenderer.isThematicBreak(line) { // A rule drawn by the text row: not an item paragraph (it // draws itself), but inside the item its indent reaches. + // The open-item test comes FIRST: outside a list (every + // plain paragraph line) the rule test cannot matter. ruleOwners[sourceLine] = owner } textBuffer.append((line: line, originalIndex: sourceLine)) diff --git a/QuickMD/QuickMD/MarkdownRenderer.swift b/QuickMD/QuickMD/MarkdownRenderer.swift index f33758f..e1ac0f3 100644 --- a/QuickMD/QuickMD/MarkdownRenderer.swift +++ b/QuickMD/QuickMD/MarkdownRenderer.swift @@ -298,7 +298,11 @@ struct MarkdownRenderer: Sendable { } private static func orderedItem(_ line: String) -> OrderedItem? { - let trimmed = markerLine(line) + orderedItem(line, trimmed: markerLine(line)) + } + + /// `orderedItem(line)` for a caller that has `markerLine(line)` already. + private static func orderedItem(_ line: String, trimmed: String) -> OrderedItem? { guard let match = trimmed.range(of: Self.orderedMarkerPattern, options: .regularExpression) else { return nil } let digits = trimmed.prefix(while: { $0.isASCII && $0.isNumber }) return OrderedItem(level: listLevel(for: line.prefix(while: { $0 == " " || $0 == "\t" })), @@ -547,7 +551,7 @@ struct MarkdownRenderer: Sendable { } // Ordered list - if let item = Self.orderedItem(line) { + if let item = Self.orderedItem(line, trimmed: trimmed) { let content = String(trimmed.dropFirst(item.markerLength)) return renderListItem(content, prefix: marker?.prefix ?? item.ownPrefix, hangingUnder: marker?.hang) } diff --git a/QuickMD/QuickMDTests/ListContentTests.swift b/QuickMD/QuickMDTests/ListContentTests.swift index 0e52a18..3a55de7 100644 --- a/QuickMD/QuickMDTests/ListContentTests.swift +++ b/QuickMD/QuickMDTests/ListContentTests.swift @@ -761,6 +761,151 @@ final class ListContentTests: XCTestCase { XCTAssertTrue(ruleShape("1. a\n\n* * *\n\n1. b").contains("T:HR")) } + // MARK: - Per-line shortcuts (1.16 review): same output + + /// Adversarial documents for the per-line shortcuts: a rule right after + /// an item, a rule after a hard break in an item's paragraph, `* * *` first, + /// a rule-looking line after a hard break, nested ordered + bullets, no + /// list at all, `)` → `.` with code and a picture, a task with a list. + private static let shortcutDocuments = [ + "1. a\n---\n2. b", + "1. a\n\n para \n * * *\n\n1. b", + "* * *\n1. a\n1. b", + "para \n- - -\nmore", + "1. a\n - x\n 1. y\n 1. z\n - w\n1. b\n\n text\n\n10. c", + "# T\n\nplain para\nline two\n\n> q\n\n```\ncode\n```\n\n| a |\n|---|\n| 1 |\n\n***\n\nend 3. x", + "1) a\n\n code\n\n2) b\n1. c\n\n![i](x.png)\n\n1. d", + "- [ ] t\n 1. a\n 1. b\n\n * * *\n- [x] u", + ] + + /// Every block, every paragraph's text and its indents, every code + /// block's list indent — what the parse decides. The indents come out + /// as numbers in `numbers`, the text holds `«#;#»` in their place, so a + /// pin compares the structure exactly and the points by value + /// (`symbolicIndent`), never as font-resolved constants (constraint 28). + private func dump(_ markdown: String) throws -> (text: String, numbers: [CGFloat]) { + var numbers: [CGFloat] = [] + let text = try parse(markdown).map { block -> String in + var line = block.id.split(separator: "-").first.map(String.init) ?? block.id + line += " src\(block.sourceLine)" + if block.listIndent > 0 { line += " li«#»"; numbers.append(block.listIndent) } + for p in try paragraphs(block) { + line += " | " + p.text + if let style = p.style { + line += " «#;#»" + numbers += [style.firstLineHeadIndent, style.headIndent] + } + } + return line + }.joined(separator: "\n") + return (text, numbers) + } + + /// Body-font width of a marker string, as the renderer measures it. + private func markerWidth(_ s: String) -> CGFloat { + (s as NSString).size(withAttributes: [.font: theme.fonts.appKit(size: 14)]).width + } + + /// The strings an indent is made of: list gutter 16 + W(a) − W(b). + private static let indentParts: [String] = { + var parts = [""] + for level in 0..<3 { + let indent = String(repeating: " ", count: level) + parts += (0...12).map { indent + "\($0). " } + ["• ", "☐ ", "☑ "].map { indent + $0 } + } + return parts + (1...3).map { String(repeating: " ", count: $0) } + }() + + /// `g+W⟨a⟩-W⟨b⟩` (or `0`) for a captured indent value. + private func symbolicIndent(_ value: CGFloat) -> String { + if abs(value) < 0.005 { return "0" } + for a in Self.indentParts { + for b in Self.indentParts where abs(16 + (markerWidth(a) - markerWidth(b)) - value) < 0.005 { + return "g+W⟨\(a)⟩-W⟨\(b)⟩" + } + } + return "?\(value)" + } + + /// Evaluates one `symbolicIndent` expression with the current font. + private func evaluateIndent(_ expression: String) -> CGFloat { + if expression == "0" { return 0 } + let parts = expression.components(separatedBy: "⟩-W⟨") + let a = String(parts[0].dropFirst("g+W⟨".count)), b = String(parts[1].dropLast()) + return 16 + (markerWidth(a) - markerWidth(b)) + } + + /// The per-line shortcuts of the 1.16 review (the rule test only while an + /// item is open, one trim per line in `renderLine`) change nothing: each + /// document parses to the + /// dump captured on the code BEFORE them (release/1.16 89971ab). The + /// indents were captured as `symbolicIndent` expressions and are + /// compared by value with the current font. + func testThePerLineShortcutsChangeNoOutput() throws { + let captured = [ + """ + text src0 | 1. a «g+W⟨⟩-W⟨⟩;g+W⟨1. ⟩-W⟨⟩» + text src1 | ──────────────────────────────── «0;0» + text src2 | 2. b «g+W⟨⟩-W⟨⟩;g+W⟨2. ⟩-W⟨⟩» + """, + """ + text src0 | 1. a «g+W⟨2. ⟩-W⟨1. ⟩;g+W⟨2. ⟩-W⟨⟩» + text src2 | para «g+W⟨2. ⟩-W⟨ ⟩;g+W⟨2. ⟩-W⟨⟩» + text src3 | ──────────────────────────────── «0;0» + text src5 | 2. b «g+W⟨⟩-W⟨⟩;g+W⟨2. ⟩-W⟨⟩» + """, + """ + text src0 | ──────────────────────────────── «0;0» + text src1 | 1. a «g+W⟨2. ⟩-W⟨1. ⟩;g+W⟨2. ⟩-W⟨⟩» | 2. b «g+W⟨⟩-W⟨⟩;g+W⟨2. ⟩-W⟨⟩» + """, + """ + text src0 | para + text src1 | ──────────────────────────────── «0;0» + text src2 | more + """, + """ + text src0 | 1. a «g+W⟨3. ⟩-W⟨1. ⟩;g+W⟨3. ⟩-W⟨⟩» | • x «g+W⟨⟩-W⟨⟩;g+W⟨ • ⟩-W⟨⟩» | 1. y «g+W⟨2. ⟩-W⟨1. ⟩;g+W⟨ 2. ⟩-W⟨⟩» | 2. z «g+W⟨⟩-W⟨⟩;g+W⟨ 2. ⟩-W⟨⟩» | • w «g+W⟨⟩-W⟨⟩;g+W⟨ • ⟩-W⟨⟩» | 2. b «g+W⟨3. ⟩-W⟨2. ⟩;g+W⟨3. ⟩-W⟨⟩» + text src7 | text «g+W⟨3. ⟩-W⟨ ⟩;g+W⟨3. ⟩-W⟨⟩» + text src9 | 3. c «g+W⟨⟩-W⟨⟩;g+W⟨3. ⟩-W⟨⟩» + """, + """ + heading src0 + text src2 | plain para line two + blockquote src5 + code src7 + table src11 + text src15 | ──────────────────────────────── «0;0» + text src17 | end 3. x + """, + """ + text src0 | 1. a «g+W⟨2. ⟩-W⟨1. ⟩;g+W⟨2. ⟩-W⟨⟩» + code src2 li«g+W⟨2. ⟩-W⟨⟩» + text src4 | 2. b «g+W⟨⟩-W⟨⟩;g+W⟨2. ⟩-W⟨⟩» | 1. c «g+W⟨⟩-W⟨⟩;g+W⟨1. ⟩-W⟨⟩» + image src7 + text src9 | 1. d «g+W⟨⟩-W⟨⟩;g+W⟨1. ⟩-W⟨⟩» + """, + """ + text src0 | ☐ t «g+W⟨⟩-W⟨⟩;g+W⟨☐ ⟩-W⟨⟩» | 1. a «g+W⟨2. ⟩-W⟨1. ⟩;g+W⟨ 2. ⟩-W⟨⟩» | 2. b «g+W⟨⟩-W⟨⟩;g+W⟨ 2. ⟩-W⟨⟩» + text src4 | ──────────────────────────────── «0;0» + text src5 | ☑ u «g+W⟨⟩-W⟨⟩;g+W⟨☑ ⟩-W⟨⟩» + """ + ] + XCTAssertEqual(captured.count, Self.shortcutDocuments.count) + for (doc, expected) in zip(Self.shortcutDocuments, captured) { + let actual = try dump(doc) + // Structure: the expressions back to holes. + let holes = try NSRegularExpression(pattern: "(?<=«|;|li«)(0|g\\+W⟨[^⟩]*⟩-W⟨[^⟩]*⟩)(?=»|;)") + let range = NSRange(expected.startIndex..., in: expected) + let expressions = holes.matches(in: expected, range: range).map { (expected as NSString).substring(with: $0.range) } + let skeleton = holes.stringByReplacingMatches(in: expected, range: range, withTemplate: "#") + XCTAssertEqual(actual.text, skeleton, doc.debugDescription) + XCTAssertEqual(actual.numbers.count, expressions.count, doc.debugDescription) + for (value, expression) in zip(actual.numbers, expressions) { + XCTAssertEqual(value, evaluateIndent(expression), accuracy: 0.01, "\(doc.debugDescription): \(expression)") + } + } + } + // MARK: - Content column func testContentColumnOfAnItem() { From ca02f6065ca398391e1dd42f1912ef2a5942a87e Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 17:20:29 +0100 Subject: [PATCH 23/27] fix: a chosen folder in another spelling keeps its own bookmark (#62) The repeated-grant guard now compares the EXACT bookmark key that restoreAccess looks up for the chosen URL (bookmarkKeyPath, shared with SandboxAccessManager.bookmarkKey), not the canonical path. A folder granted as /private/tmp/x and chosen as /tmp/x (or through a symlink) is saved under the chosen spelling again, so it is restored at relaunch; the same spelling chosen again is still saved once. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/FolderAccessBroker.swift | 42 ++++++++++++---- QuickMD/QuickMD/SandboxAccessManager.swift | 7 +-- .../FolderAccessBrokerTests.swift | 49 +++++++++++++++++-- 3 files changed, 81 insertions(+), 17 deletions(-) diff --git a/QuickMD/QuickMD/FolderAccessBroker.swift b/QuickMD/QuickMD/FolderAccessBroker.swift index af4e73d..239e566 100644 --- a/QuickMD/QuickMD/FolderAccessBroker.swift +++ b/QuickMD/QuickMD/FolderAccessBroker.swift @@ -66,6 +66,8 @@ final class FolderAccessBroker { private let environment: Environment private(set) var grantedFolders: [String] = [] + /// Bookmark keys (`bookmarkKeyPath`) this broker saved in this session. + private var savedKeyPaths: Set = [] private(set) var declinedFolders: Set = [] /// The panel being shown (or about to be): requests wait for it. private var pending: Task? @@ -100,14 +102,27 @@ final class FolderAccessBroker { return path } - /// `folder` already has a saved bookmark AND an active access in this - /// process (exact folder, by canonical path): saving it again would only - /// add a duplicate entry and an unbalanced - /// `startAccessingSecurityScopedResource`. Used by - /// `SandboxAccessManager.saveGrant`. + /// The path a bookmark of `folder` is stored and looked up under + /// (`SandboxAccessManager.bookmarkKey` = prefix + this). EXACT, not + /// canonical: `restoreAccess` looks a remembered folder up by the + /// spelling it was remembered with (`/tmp/x` and `/private/tmp/x` are two + /// keys). + nonisolated static func bookmarkKeyPath(_ folder: URL) -> String { + folder.standardizedFileURL.path + } + + /// `folder` already has a bookmark under ITS OWN key (the exact one a + /// later `restoreAccess(folder)` looks up) AND an active access to the + /// same folder (by canonical path: a restored bookmark resolves to its + /// own spelling). Saving it again would only add a duplicate entry and + /// an unbalanced `startAccessingSecurityScopedResource`. Another + /// spelling of a granted folder is NOT a repeat: it gets its own key, + /// or the folder remembered under it would be forgotten at relaunch. + /// Used by `SandboxAccessManager.saveGrant`. nonisolated static func isActiveGrant(_ folder: URL, saved: [URL], active: [URL]) -> Bool { + let key = bookmarkKeyPath(folder) let path = canonicalPath(folder) - return saved.contains { canonicalPath($0) == path } && active.contains { canonicalPath($0) == path } + return saved.contains { bookmarkKeyPath($0) == key } && active.contains { canonicalPath($0) == path } } /// `folder` is `path` or one of its ancestors. @@ -153,10 +168,18 @@ final class FolderAccessBroker { func registerUserChosenFolder(_ folder: URL) -> Bool { guard environment.isSandboxed else { return false } let granted = Self.canonicalPath(folder) - // Chosen again (Open Folder on the same folder): already granted in - // this session — no second bookmark, no second access start. - if grantedFolders.contains(granted) { return true } + let key = Self.bookmarkKeyPath(folder) + // Chosen again IN THE SAME SPELLING: already granted and saved under + // the key a restore will look up — no second bookmark, no second + // access start. A different spelling of a granted folder is saved + // (its own key), or Open Folder's remembered path would find no + // bookmark at relaunch. + if grantedFolders.contains(granted), + savedKeyPaths.contains(key) || environment.savedFolders().contains(where: { Self.bookmarkKeyPath($0) == key }) { + return true + } guard environment.save(folder) else { return false } + savedKeyPaths.insert(key) if !grantedFolders.contains(granted) { grantedFolders.append(granted) } declinedFolders = declinedFolders.filter { !Self.covers(granted, $0) } environment.didGrant(folder) @@ -200,6 +223,7 @@ final class FolderAccessBroker { declinedFolders.insert(Self.canonicalPath(folder)) return } + savedKeyPaths.insert(Self.bookmarkKeyPath(chosen)) let granted = Self.canonicalPath(chosen) grantedFolders.append(granted) declinedFolders = declinedFolders.filter { !Self.covers(granted, $0) } diff --git a/QuickMD/QuickMD/SandboxAccessManager.swift b/QuickMD/QuickMD/SandboxAccessManager.swift index 481c9fd..b4dd69d 100644 --- a/QuickMD/QuickMD/SandboxAccessManager.swift +++ b/QuickMD/QuickMD/SandboxAccessManager.swift @@ -177,8 +177,8 @@ final class SandboxAccessManager { let bookmarkData = try selectedURL.bookmarkData(options: .withSecurityScope) let key = Self.bookmarkKey(for: selectedURL) UserDefaults.standard.set(bookmarkData, forKey: key) - let path = FolderAccessBroker.canonicalPath(selectedURL) - if !savedFolders.contains(where: { FolderAccessBroker.canonicalPath($0) == path }) { + let keyPath = FolderAccessBroker.bookmarkKeyPath(selectedURL) + if !savedFolders.contains(where: { FolderAccessBroker.bookmarkKeyPath($0) == keyPath }) { savedFolders.append(selectedURL) } if selectedURL.startAccessingSecurityScopedResource() { @@ -201,6 +201,7 @@ final class SandboxAccessManager { /// Generate a UserDefaults key for a directory path. private static func bookmarkKey(for directoryURL: URL) -> String { - return bookmarkKeyPrefix + directoryURL.standardizedFileURL.path + // One definition of the key path, shared with the broker's dedupe. + return bookmarkKeyPrefix + FolderAccessBroker.bookmarkKeyPath(directoryURL) } } diff --git a/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift b/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift index e611938..3148aa2 100644 --- a/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift +++ b/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift @@ -283,18 +283,57 @@ final class FolderAccessBrokerTests: XCTestCase { XCTAssertTrue(access.declinedFolders.isEmpty, "its grant clears the decline it covers") } - /// The manager's guard (`saveGrant`): saved AND active, by canonical - /// path, any spelling. - func testIsActiveGrantNeedsBothSavedAndActive() { + /// The manager's guard (`saveGrant`): saved under THIS spelling's key + /// AND active (any spelling of the same folder). + func testIsActiveGrantNeedsItsOwnKeySavedAndAnActiveAccess() throws { let docs = file("docs") - let spelledOtherwise = URL(fileURLWithPath: FolderAccessBroker.canonicalPath(docs) + "/badges/..") - XCTAssertTrue(FolderAccessBroker.isActiveGrant(docs, saved: [spelledOtherwise], active: [docs])) + let alias = file("alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: docs) + let resolved = URL(fileURLWithPath: FolderAccessBroker.canonicalPath(docs)) + XCTAssertTrue(FolderAccessBroker.isActiveGrant(docs, saved: [docs], active: [resolved]), + "own key saved; a restored access in the resolved spelling is active") + XCTAssertTrue(FolderAccessBroker.isActiveGrant(docs, saved: [file("docs/badges/..")], active: [docs]), + "`..` standardizes to the same key") + XCTAssertFalse(FolderAccessBroker.isActiveGrant(alias, saved: [docs], active: [docs]), + "another spelling of a granted folder needs its own key") XCTAssertFalse(FolderAccessBroker.isActiveGrant(docs, saved: [docs], active: []), "saved, not active") XCTAssertFalse(FolderAccessBroker.isActiveGrant(docs, saved: [], active: [docs]), "active, not saved") XCTAssertFalse(FolderAccessBroker.isActiveGrant(file("docs/images"), saved: [docs], active: [docs]), "a subfolder is a different folder") } + /// Granted under spelling X by the broker's own panel (a picture's + /// folder), then chosen as spelling Y (a symlink to it) through Open + /// Folder: Y is saved under ITS key — the one `restoreAccess(Y)` looks + /// up at relaunch — so the remembered folder comes back with access. + /// Y chosen again: no second save. + func testAChosenFolderInAnotherSpellingIsSavedUnderItsOwnKey() async throws { + let alias = file("alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: file("docs")) + XCTAssertEqual(FolderAccessBroker.canonicalPath(alias), FolderAccessBroker.canonicalPath(file("docs"))) + let world = World() + world.answer = { $0 } + let access = broker(world) + let granted = await access.requestAccess(forFileAt: file("docs/badges/a.svg"), documentURL: document, + explicit: false) + XCTAssertTrue(granted) + XCTAssertEqual(world.saves.map(FolderAccessBroker.bookmarkKeyPath), [FolderAccessBroker.bookmarkKeyPath(file("docs"))]) + XCTAssertTrue(access.registerUserChosenFolder(alias)) + XCTAssertEqual(world.saves.map(FolderAccessBroker.bookmarkKeyPath), + [FolderAccessBroker.bookmarkKeyPath(file("docs")), FolderAccessBroker.bookmarkKeyPath(alias)], + "saved under the key restore looks up for the chosen spelling") + XCTAssertTrue(access.registerUserChosenFolder(alias)) + XCTAssertTrue(access.registerUserChosenFolder(file("docs"))) + XCTAssertEqual(world.saves.count, 2, "each spelling once") + // A bookmark saved in an earlier launch under Y counts as saved. + let later = World() + later.saved = [alias] + let next = broker(later) + _ = await next.requestAccess(forFileAt: file("docs/a.png"), documentURL: document, explicit: false) + XCTAssertTrue(next.registerUserChosenFolder(alias)) + XCTAssertTrue(later.saves.isEmpty, "already under its key from the earlier launch") + } + /// Unsandboxed (GitHub/Homebrew) the chooser's folder is only a path: /// nothing is saved, granted or announced. func testAUserChosenFolderIsNeverRegisteredUnsandboxed() { From 952cf340c5036b0a38439843bc22d87f8915e3d9 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 18:16:40 +0100 Subject: [PATCH 24/27] fix: File menu shows Open Recent again instead of a dead "NSMenuItem" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With CommandGroup(replacing: .saveItem), SwiftUI's first lazy update of the main menu removes AppKit's Open Recent item and inserts a bare NSMenuItem() that it never configures. OpenRecentMenu, installed in applicationDidFinishLaunching, watches the menu's add / change notifications and turns that blank item (the one right after Open…) into Open Recent in place, with a submenu of its own: the recent list without file-system access, same-name entries with their folder, Clear Menu. Entries open through DocumentOpener; a failure shows the Open Folder flow's alert, now one shared MessageAlert. Healthy shapes are left alone. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD.xcodeproj/project.pbxproj | 10 + QuickMD/QuickMD/OpenRecentMenu.swift | 188 ++++++++ QuickMD/QuickMD/QuickMDApp.swift | 44 +- .../QuickMDTests/OpenRecentMenuTests.swift | 402 ++++++++++++++++++ 4 files changed, 642 insertions(+), 2 deletions(-) create mode 100644 QuickMD/QuickMD/OpenRecentMenu.swift create mode 100644 QuickMD/QuickMDTests/OpenRecentMenuTests.swift diff --git a/QuickMD/QuickMD.xcodeproj/project.pbxproj b/QuickMD/QuickMD.xcodeproj/project.pbxproj index fbe491a..bd913a6 100644 --- a/QuickMD/QuickMD.xcodeproj/project.pbxproj +++ b/QuickMD/QuickMD.xcodeproj/project.pbxproj @@ -162,6 +162,9 @@ F62A000001000004 /* FolderBrowserStore.swift in Sources (Tests) */ = {isa = PBXBuildFile; fileRef = F62A000000000003 /* FolderBrowserStore.swift */; }; F62A000001000005 /* FolderListingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F62A000000000005 /* FolderListingTests.swift */; }; F62A000001000006 /* FolderBrowserStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F62A000000000006 /* FolderBrowserStoreTests.swift */; }; + A1B2C3D401000470 /* OpenRecentMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000470 /* OpenRecentMenu.swift */; }; + A1B2C3D401000471 /* OpenRecentMenu.swift in Sources (Tests) */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000470 /* OpenRecentMenu.swift */; }; + A1B2C3D401000472 /* OpenRecentMenuTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000472 /* OpenRecentMenuTests.swift */; }; A1B2C3D401000400 /* TableRulesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000400 /* TableRulesTests.swift */; }; A1B2C3D4010004A1 /* FootnoteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000004A0 /* FootnoteTests.swift */; }; A1B2C3D40100006B /* BlockHeightMeasurer.swift in Sources (Tests) */ = {isa = PBXBuildFile; fileRef = A1B2C3D400000069 /* BlockHeightMeasurer.swift */; }; @@ -259,6 +262,8 @@ F62A000000000003 /* FolderBrowserStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderBrowserStore.swift; sourceTree = ""; }; F62A000000000005 /* FolderListingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderListingTests.swift; sourceTree = ""; }; F62A000000000006 /* FolderBrowserStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderBrowserStoreTests.swift; sourceTree = ""; }; + A1B2C3D400000470 /* OpenRecentMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenRecentMenu.swift; sourceTree = ""; }; + A1B2C3D400000472 /* OpenRecentMenuTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenRecentMenuTests.swift; sourceTree = ""; }; A1B2C3D400000400 /* TableRulesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRulesTests.swift; sourceTree = ""; }; A1B2C3D4000004A0 /* FootnoteTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FootnoteTests.swift; sourceTree = ""; }; A1B2C3D40000006C /* VirtualBlockList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VirtualBlockList.swift; sourceTree = ""; }; @@ -448,6 +453,7 @@ A1B2C3D400000468 /* FolderAccessBrokerTests.swift */, F62A000000000005 /* FolderListingTests.swift */, F62A000000000006 /* FolderBrowserStoreTests.swift */, + A1B2C3D400000472 /* OpenRecentMenuTests.swift */, A1B2C3D400000400 /* TableRulesTests.swift */, A1B2C3D4000004E1 /* SideBySideTests.swift */, A1B2C3D400000421 /* ListContentTests.swift */, @@ -504,6 +510,7 @@ A1B2C3D400000466 /* FolderAccessBroker.swift */, F62A000000000001 /* FolderListing.swift */, F62A000000000003 /* FolderBrowserStore.swift */, + A1B2C3D400000470 /* OpenRecentMenu.swift */, A1B2C3D4000004E0 /* SideBySide.swift */, A1B2C3D400000420 /* ListNesting.swift */, A1B2C3D400000301 /* ReferenceLinks.swift */, @@ -817,6 +824,7 @@ A1B2C3D401000466 /* FolderAccessBroker.swift in Sources */, F62A000001000001 /* FolderListing.swift in Sources */, F62A000001000003 /* FolderBrowserStore.swift in Sources */, + A1B2C3D401000470 /* OpenRecentMenu.swift in Sources */, A1B2C3D4010004E0 /* SideBySide.swift in Sources */, A1B2C3D401000420 /* ListNesting.swift in Sources */, A1B2C3D401000301 /* ReferenceLinks.swift in Sources */, @@ -904,6 +912,7 @@ A1B2C3D401000468 /* FolderAccessBrokerTests.swift in Sources */, F62A000001000005 /* FolderListingTests.swift in Sources */, F62A000001000006 /* FolderBrowserStoreTests.swift in Sources */, + A1B2C3D401000472 /* OpenRecentMenuTests.swift in Sources */, A1B2C3D401000400 /* TableRulesTests.swift in Sources */, A1B2C3D4010004E2 /* SideBySideTests.swift in Sources */, A1B2C3D401000422 /* ListContentTests.swift in Sources */, @@ -925,6 +934,7 @@ A1B2C3D401000467 /* FolderAccessBroker.swift in Sources (Tests) */, F62A000001000002 /* FolderListing.swift in Sources (Tests) */, F62A000001000004 /* FolderBrowserStore.swift in Sources (Tests) */, + A1B2C3D401000471 /* OpenRecentMenu.swift in Sources (Tests) */, A1B2C3D4010004E1 /* SideBySide.swift in Sources (Tests) */, A1B2C3D401000421 /* ListNesting.swift in Sources (Tests) */, A1B2C3D401000302 /* ReferenceLinks.swift in Sources (Tests) */, diff --git a/QuickMD/QuickMD/OpenRecentMenu.swift b/QuickMD/QuickMD/OpenRecentMenu.swift new file mode 100644 index 0000000..a9995d5 --- /dev/null +++ b/QuickMD/QuickMD/OpenRecentMenu.swift @@ -0,0 +1,188 @@ +import AppKit +import UniformTypeIdentifiers + +/// Repairs File ▸ Open Recent when SwiftUI leaves it blank. +/// +/// Why this exists (measured on macOS 27.2.1 with minimal +/// `DocumentGroup(viewing:)` apps): at launch the File menu holds AppKit's +/// own Open Recent item. On SwiftUI's first lazy update of the main menu +/// (the reader opens the menu, or accessibility reads it), an app with +/// `CommandGroup(replacing: .saveItem)` — QuickMD's Close, which must stay +/// (constraint 3) — gets that item REMOVED and a bare `NSMenuItem()` +/// inserted at the same index, never configured: a grey, dead item titled +/// "NSMenuItem". Replacing `.newItem` does not help (two Open… items), and +/// `NSDocumentController.shared` must not be touched before +/// `applicationDidFinishLaunching` (SwiftUI installs its own controller in +/// its `applicationWillFinishLaunching`). +/// +/// The repair: the item right after Open… (`openDocument:`) is mutated IN +/// PLACE when it is blank — title and a submenu of ours. SwiftUI keeps a +/// reference to that object, so it is never replaced, removed or +/// re-inserted; later SwiftUI updates leave it alone. Wherever the system +/// item is healthy this is a no-op. Public API only (App Store). +/// +/// The submenu never touches the file system when it opens: a recent file +/// may sit on an unmounted volume. Names come from the URL, icons from the +/// extension's content type. +@MainActor +final class OpenRecentMenu: NSObject, NSMenuDelegate { + /// What the menu does, injected so tests touch no process-wide state + /// (the live one is `OpenRecentMenu.shared`, in `QuickMDApp.swift`). + struct Environment { + /// The recent list, in the order to show it. + var recents: @MainActor () -> [URL] + /// Opens a chosen entry; the closure receives a failure message. + var open: @MainActor (URL, _ onFailure: @escaping (String) -> Void) -> Void + /// Shows a failure message reported by `open`. + var reportFailure: @MainActor (String) -> Void + /// Clear Menu. + var clear: @MainActor () -> Void + } + + static let title = "Open Recent" + static let clearTitle = "Clear Menu" + /// Icon size of an entry, as the system menu draws it. + static let iconSize = NSSize(width: 16, height: 16) + + private let mainMenu: @MainActor () -> NSMenu? + private let environment: Environment + private var isInstalled = false + /// Set while the repair mutates the slot: setting `title` / `submenu` + /// posts `NSMenu.didChangeItemNotification` synchronously, which would + /// otherwise re-enter and build a second submenu. + private var isRepairing = false + /// One icon per extension (a copy sized for the menu; NSWorkspace's + /// image is shared and must not be resized). + private var iconsByExtension: [String: NSImage] = [:] + + /// Submenus built by repairs so far (one per repaired slot). Tests read + /// it to prove one event builds one submenu. + private(set) var submenusBuilt = 0 + + init(mainMenu: @escaping @MainActor () -> NSMenu?, environment: Environment) { + self.mainMenu = mainMenu + self.environment = environment + super.init() + } + + deinit { + NotificationCenter.default.removeObserver(self) + } + + /// Starts watching the main menu and repairs it once now. Idempotent. + /// Call no earlier than `applicationDidFinishLaunching`. + func install() { + guard !isInstalled else { return } + isInstalled = true + let center = NotificationCenter.default + // Selector-based and synchronous: the menu must be right before it + // is drawn, so no hop to a later main-queue turn. + center.addObserver(self, selector: #selector(menuItemsDidChange(_:)), + name: NSMenu.didAddItemNotification, object: nil) + center.addObserver(self, selector: #selector(menuItemsDidChange(_:)), + name: NSMenu.didChangeItemNotification, object: nil) + guard let main = mainMenu() else { return } + for case let menu? in main.items.map(\.submenu) { + repairIfNeeded(in: menu) + } + } + + /// Every menu in the app posts these (context menus too), so the cheap + /// test comes first: only a top-level submenu of the main menu counts. + @objc private func menuItemsDidChange(_ notification: Notification) { + guard !isRepairing, + let menu = notification.object as? NSMenu, + let main = menu.supermenu, main === mainMenu() else { return } + repairIfNeeded(in: menu) + } + + /// The item right after Open… when it is blank: not a separator, no + /// submenu, no action, no view. The title is deliberately not tested — + /// a partly reset item must still be repaired. + static func blankSlot(in menu: NSMenu) -> NSMenuItem? { + let openDocument = #selector(NSDocumentController.openDocument(_:)) + guard let index = menu.items.firstIndex(where: { $0.action == openDocument }), + index + 1 < menu.numberOfItems, + let slot = menu.item(at: index + 1) else { return nil } + guard !slot.isSeparatorItem, slot.submenu == nil, slot.action == nil, slot.view == nil else { + return nil + } + return slot + } + + private func repairIfNeeded(in menu: NSMenu) { + guard let slot = Self.blankSlot(in: menu) else { return } + isRepairing = true + defer { isRepairing = false } + let submenu = NSMenu(title: Self.title) + submenu.delegate = self + // Enabled states are set per item: accessibility reads them without + // the menu ever being validated. + submenu.autoenablesItems = false + // Filled before it is attached, so its own notifications come from a + // menu that is not under the main menu yet. + fill(submenu) + submenusBuilt += 1 + slot.submenu = submenu + slot.title = Self.title + slot.isEnabled = true + } + + // MARK: - Content + + func menuNeedsUpdate(_ menu: NSMenu) { + fill(menu) + } + + private func fill(_ menu: NSMenu) { + menu.removeAllItems() + let urls = environment.recents() + var nameCounts: [String: Int] = [:] + for url in urls { nameCounts[url.lastPathComponent, default: 0] += 1 } + for url in urls { + let name = url.lastPathComponent + // Two entries with one name: each says its folder, as the + // system menu does. + let title = (nameCounts[name] ?? 0) > 1 + ? "\(name) \u{2014} \(url.deletingLastPathComponent().lastPathComponent)" + : name + let item = NSMenuItem(title: title, action: #selector(openEntry(_:)), keyEquivalent: "") + item.target = self + item.representedObject = url + item.image = icon(for: url) + item.isEnabled = true + menu.addItem(item) + } + if !urls.isEmpty { menu.addItem(.separator()) } + let clear = NSMenuItem(title: Self.clearTitle, action: #selector(clearMenu(_:)), keyEquivalent: "") + clear.target = self + clear.isEnabled = !urls.isEmpty + menu.addItem(clear) + } + + /// The content type's icon from the extension alone — no + /// `icon(forFile:)`, which reads the file (and may wake a volume). + private func icon(for url: URL) -> NSImage { + let ext = url.pathExtension.lowercased() + if let cached = iconsByExtension[ext] { return cached } + let type = UTType(filenameExtension: ext) ?? .data + let image = (NSWorkspace.shared.icon(for: type).copy() as? NSImage) ?? NSImage() + image.size = Self.iconSize + iconsByExtension[ext] = image + return image + } + + // MARK: - Actions + + @objc private func openEntry(_ sender: NSMenuItem) { + guard let url = sender.representedObject as? URL else { return } + environment.open(url) { [weak self] message in + self?.environment.reportFailure(message) + } + } + + @objc private func clearMenu(_ sender: NSMenuItem) { + environment.clear() + if let menu = sender.menu { fill(menu) } + } +} diff --git a/QuickMD/QuickMD/QuickMDApp.swift b/QuickMD/QuickMD/QuickMDApp.swift index 2997846..5059f93 100644 --- a/QuickMD/QuickMD/QuickMDApp.swift +++ b/QuickMD/QuickMD/QuickMDApp.swift @@ -34,11 +34,15 @@ struct QuickMDApp: App { MarkdownView(document: file.document, documentURL: file.fileURL) } .commands { - // Right after the system's Open… / Open Recent; app-level, so it - // works with no window. The .saveItem group below is not touched. + // Lands BEFORE the system's Open… (New / Open Folder… / Open… / + // Open Recent); app-level, so it works with no window. The + // .saveItem group below is not touched. CommandGroup(after: .newItem) { OpenFolderCommand() } + // Replacing .saveItem makes SwiftUI's first menu update leave a + // blank "NSMenuItem" where Open Recent was; `OpenRecentMenu` + // (installed in `applicationDidFinishLaunching`) repairs it in place. CommandGroup(replacing: .saveItem) { Button("Close") { EditCloseGuard.requestClose(NSApp.keyWindow) @@ -199,6 +203,15 @@ enum OpenFolderFlow { } private static func alert(_ message: String) { + MessageAlert.run(message) + } +} + +/// The app-modal message alert of the flows that may run with no window +/// (Open Folder, File ▸ Open Recent): one message, OK. +@MainActor +enum MessageAlert { + static func run(_ message: String) { let alert = NSAlert() alert.messageText = message alert.addButton(withTitle: "OK") @@ -206,6 +219,33 @@ enum OpenFolderFlow { } } +// MARK: - Open Recent repair + +extension OpenRecentMenu { + /// The app's instance: the system's recent list (it follows the user's + /// setting for the number of items), opened through `DocumentOpener`, + /// cleared through `RecentDocumentsStore` (session list and system list + /// together, as the sidebar's trash button does). + static let shared = OpenRecentMenu( + mainMenu: { NSApp.mainMenu }, + environment: .init( + recents: { NSDocumentController.shared.recentDocumentURLs }, + open: { url, onFailure in DocumentOpener.open(url, onFailure: onFailure) }, + reportFailure: { MessageAlert.run($0) }, + clear: { RecentDocumentsStore.shared.clear() })) +} + +extension QuickMDAppDelegate { + /// Lives here, not next to the delegate in `EditCloseGuard.swift`: the + /// test target compiles that file but not the live dependencies above. + /// Not earlier than this: SwiftUI installs its document controller in + /// its own `applicationWillFinishLaunching`. + @MainActor + func applicationDidFinishLaunching(_ notification: Notification) { + OpenRecentMenu.shared.install() + } +} + /// View ▸ Bigger / Smaller / Actual Size — scales the rendered text of the /// frontmost document only, via @FocusedValue (same routing as ⌘F and ⌘⇧T), /// so zooming one tab leaves the others alone. diff --git a/QuickMD/QuickMDTests/OpenRecentMenuTests.swift b/QuickMD/QuickMDTests/OpenRecentMenuTests.swift new file mode 100644 index 0000000..8366429 --- /dev/null +++ b/QuickMD/QuickMDTests/OpenRecentMenuTests.swift @@ -0,0 +1,402 @@ +import XCTest +import AppKit + +/// `OpenRecentMenu`: SwiftUI's first menu update leaves a blank +/// `NSMenuItem()` where File ▸ Open Recent was (an app that replaces +/// `.saveItem`); the repair turns THAT object into Open Recent with a +/// submenu of ours and leaves every healthy shape alone. Every test builds +/// its own menu tree and its own instance with an injected main menu and +/// environment: nothing here touches `NSApp.mainMenu`, +/// `NSDocumentController.shared`, the real recent list, or opens anything. +/// The repair is synchronous, so there are no waits and no run-loop spins. +@MainActor +final class OpenRecentMenuTests: XCTestCase { + + @MainActor + private final class World { + var recents: [URL] = [] + var recentsReads = 0 + var opened: [URL] = [] + var pendingFailure: ((String) -> Void)? + var failures: [String] = [] + var clears = 0 + + var environment: OpenRecentMenu.Environment { + .init( + recents: { [unowned self] in recentsReads += 1; return recents }, + open: { [unowned self] url, onFailure in opened.append(url); pendingFailure = onFailure }, + reportFailure: { [unowned self] in failures.append($0) }, + clear: { [unowned self] in clears += 1 }) + } + } + + private struct Tree { + let main: NSMenu + let file: NSMenu + } + + private let openDocument = #selector(NSDocumentController.openDocument(_:)) + private var world: World! + + override func setUp() { + super.setUp() + world = World() + } + + override func tearDown() { + world = nil + super.tearDown() + } + + // MARK: - Helpers + + private func openItem() -> NSMenuItem { + NSMenuItem(title: "Open\u{2026}", action: openDocument, keyEquivalent: "o") + } + + private func closeItem() -> NSMenuItem { + NSMenuItem(title: "Close", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w") + } + + /// A healthy system Open Recent: a plain item with its own submenu. + private func systemOpenRecent() -> NSMenuItem { + let item = NSMenuItem(title: "Open Recent", action: nil, keyEquivalent: "") + item.submenu = NSMenu(title: "Open Recent") + return item + } + + /// Main menu ▸ File with these items, the way the app's File menu sits. + private func makeTree(_ fileItems: [NSMenuItem]) -> Tree { + let main = NSMenu(title: "Main") + main.addItem(NSMenuItem(title: "QuickMD", action: nil, keyEquivalent: "")) + main.items[0].submenu = NSMenu(title: "QuickMD") + let file = NSMenu(title: "File") + for item in fileItems { file.addItem(item) } + let fileItem = NSMenuItem(title: "File", action: nil, keyEquivalent: "") + fileItem.submenu = file + main.addItem(fileItem) + return Tree(main: main, file: file) + } + + /// New / Open… / / separator / Close. + private func makeFileMenu(slot: NSMenuItem) -> Tree { + makeTree([NSMenuItem(title: "New", action: nil, keyEquivalent: "n"), + openItem(), slot, .separator(), closeItem()]) + } + + private func makeRepair(for tree: Tree) -> OpenRecentMenu { + let main = tree.main + return OpenRecentMenu(mainMenu: { main }, environment: world.environment) + } + + /// What SwiftUI does on its first update: the slot removed, a bare + /// `NSMenuItem()` inserted at the same index. + @discardableResult + private func simulateSwiftUIRebuild(_ file: NSMenu, at index: Int = 2) -> NSMenuItem { + file.removeItem(at: index) + let blank = NSMenuItem() + file.insertItem(blank, at: index) + return blank + } + + private func repairedSubmenu(_ tree: Tree, repair: OpenRecentMenu, + file: StaticString = #filePath, line: UInt = #line) -> NSMenu? { + let slot = tree.file.item(at: 2) + XCTAssertEqual(slot?.title, OpenRecentMenu.title, file: file, line: line) + XCTAssertTrue(slot?.submenu?.delegate === repair, file: file, line: line) + return slot?.submenu + } + + private func perform(_ item: NSMenuItem) { + guard let action = item.action, let target = item.target as? NSObject else { + return XCTFail("\(item.title) has no target/action") + } + _ = target.perform(action, with: item) + } + + private func url(_ path: String) -> URL { URL(fileURLWithPath: path) } + + // MARK: - Detection and repair + + func testABlankSlotAfterOpenBecomesOpenRecentInPlace() { + let blank = NSMenuItem() + let tree = makeFileMenu(slot: blank) + let repair = makeRepair(for: tree) + repair.install() + + XCTAssertTrue(tree.file.item(at: 2) === blank, "the same object, never replaced") + XCTAssertEqual(tree.file.numberOfItems, 5) + XCTAssertEqual(blank.title, "Open Recent") + XCTAssertNotNil(blank.submenu) + XCTAssertTrue(blank.submenu?.delegate === repair) + XCTAssertTrue(blank.isEnabled) + XCTAssertEqual(repair.submenusBuilt, 1) + } + + func testAPartlyResetSlotWithATitleIsStillRepaired() { + let slot = NSMenuItem(title: "Open Recent", action: nil, keyEquivalent: "") + let tree = makeFileMenu(slot: slot) + let repair = makeRepair(for: tree) + repair.install() + XCTAssertTrue(slot.submenu?.delegate === repair) + } + + func testHealthyShapesAreLeftUntouched() { + // A healthy system submenu. + do { + let slot = systemOpenRecent() + let systemSubmenu = slot.submenu + let tree = makeFileMenu(slot: slot) + let repair = makeRepair(for: tree) + repair.install() + XCTAssertEqual(slot.title, "Open Recent") + XCTAssertTrue(slot.submenu === systemSubmenu) + XCTAssertEqual(repair.submenusBuilt, 0) + } + // A separator right after Open…. + do { + let slot = NSMenuItem.separator() + let tree = makeFileMenu(slot: slot) + let repair = makeRepair(for: tree) + repair.install() + XCTAssertTrue(tree.file.item(at: 2) === slot) + XCTAssertNil(slot.submenu) + XCTAssertEqual(repair.submenusBuilt, 0) + } + // An item with an action. + do { + let slot = NSMenuItem(title: "Import", action: #selector(NSResponder.selectAll(_:)), keyEquivalent: "") + let tree = makeFileMenu(slot: slot) + let repair = makeRepair(for: tree) + repair.install() + XCTAssertEqual(slot.title, "Import") + XCTAssertNil(slot.submenu) + XCTAssertEqual(repair.submenusBuilt, 0) + } + // An item with a view. + do { + let slot = NSMenuItem() + slot.view = NSView(frame: NSRect(x: 0, y: 0, width: 10, height: 10)) + let tree = makeFileMenu(slot: slot) + let repair = makeRepair(for: tree) + repair.install() + XCTAssertNil(slot.submenu) + XCTAssertEqual(repair.submenusBuilt, 0) + } + // A menu without Open…: its blank item is not the slot. + do { + let blank = NSMenuItem() + let title = blank.title + let tree = makeTree([NSMenuItem(title: "New", action: nil, keyEquivalent: "n"), blank, closeItem()]) + let repair = makeRepair(for: tree) + repair.install() + XCTAssertEqual(blank.title, title) + XCTAssertNil(blank.submenu) + XCTAssertEqual(repair.submenusBuilt, 0) + } + // Open… as the last item: no slot. + do { + let tree = makeTree([NSMenuItem(title: "New", action: nil, keyEquivalent: "n"), openItem()]) + let repair = makeRepair(for: tree) + repair.install() + XCTAssertEqual(tree.file.numberOfItems, 2) + XCTAssertNil(tree.file.item(at: 1)?.submenu) + XCTAssertEqual(repair.submenusBuilt, 0) + } + // The blank item is BEFORE Open…, not after it. + do { + let blank = NSMenuItem() + let tree = makeTree([blank, openItem(), systemOpenRecent()]) + let repair = makeRepair(for: tree) + repair.install() + XCTAssertNil(blank.submenu) + XCTAssertEqual(repair.submenusBuilt, 0) + } + } + + func testTheSwiftUIRebuildIsRepairedByTheNotificationAlone() { + let tree = makeFileMenu(slot: systemOpenRecent()) + let repair = makeRepair(for: tree) + repair.install() + XCTAssertEqual(repair.submenusBuilt, 0, "healthy at install") + + let blank = simulateSwiftUIRebuild(tree.file) + + // Synchronously, before anything else runs. + XCTAssertTrue(tree.file.item(at: 2) === blank) + XCTAssertEqual(blank.title, "Open Recent") + XCTAssertTrue(blank.submenu?.delegate === repair) + XCTAssertEqual(repair.submenusBuilt, 1) + } + + func testAChangeThatBlanksTheSlotIsRepaired() { + let slot = systemOpenRecent() + let tree = makeFileMenu(slot: slot) + let repair = makeRepair(for: tree) + repair.install() + + // SwiftUI resetting the item in place instead of replacing it. + slot.submenu = nil + XCTAssertTrue(slot.submenu?.delegate === repair) + XCTAssertEqual(repair.submenusBuilt, 1) + } + + func testABlankItemOutsideTheMainMenuIsIgnored() { + let tree = makeFileMenu(slot: systemOpenRecent()) + let repair = makeRepair(for: tree) + repair.install() + + // A context menu of the same shape, attached nowhere. + let context = NSMenu(title: "Context") + context.addItem(openItem()) + context.addItem(systemOpenRecent()) + let contextBlank = simulateSwiftUIRebuild(context, at: 1) + XCTAssertNil(contextBlank.submenu) + + // The same shape under ANOTHER main menu. + let other = makeFileMenu(slot: systemOpenRecent()) + let otherBlank = simulateSwiftUIRebuild(other.file) + XCTAssertNil(otherBlank.submenu) + + // A submenu nested one level deeper under our main menu. + let nested = NSMenu(title: "Nested") + nested.addItem(openItem()) + nested.addItem(systemOpenRecent()) + let holder = NSMenuItem(title: "More", action: nil, keyEquivalent: "") + holder.submenu = nested + tree.file.addItem(holder) + let nestedBlank = simulateSwiftUIRebuild(nested, at: 1) + XCTAssertNil(nestedBlank.submenu) + + XCTAssertEqual(repair.submenusBuilt, 0) + } + + func testOneEventBuildsOneSubmenuAndLaterChangesKeepIt() { + let tree = makeFileMenu(slot: systemOpenRecent()) + let repair = makeRepair(for: tree) + repair.install() + + let blank = simulateSwiftUIRebuild(tree.file) + XCTAssertEqual(repair.submenusBuilt, 1, "the nested change notifications build nothing") + let submenu = blank.submenu + + // Unrelated later changes in the File menu. + tree.file.item(at: 4)?.title = "Close Window" + tree.file.addItem(NSMenuItem(title: "Print", action: #selector(NSView.printView(_:)), keyEquivalent: "p")) + blank.title = "Open Recent" + XCTAssertTrue(blank.submenu === submenu) + XCTAssertEqual(repair.submenusBuilt, 1) + + // Installing again adds no second set of observers. + repair.install() + tree.file.addItem(NSMenuItem(title: "Other", action: nil, keyEquivalent: "")) + XCTAssertTrue(blank.submenu === submenu) + XCTAssertEqual(repair.submenusBuilt, 1) + } + + func testObserversGoAwayWithTheInstance() { + let tree = makeFileMenu(slot: systemOpenRecent()) + weak var weakRepair: OpenRecentMenu? + autoreleasepool { + let repair = makeRepair(for: tree) + repair.install() + weakRepair = repair + } + XCTAssertNil(weakRepair, "nothing keeps the instance alive") + + let blank = simulateSwiftUIRebuild(tree.file) + XCTAssertNil(blank.submenu, "a released instance repairs nothing") + } + + // MARK: - Content + + func testEntriesKeepTheListOrderAndEndWithAnEnabledClearMenu() throws { + world.recents = [url("/Notes/b.md"), url("/Notes/a.markdown"), url("/Other/c.txt")] + let tree = makeFileMenu(slot: NSMenuItem()) + let repair = makeRepair(for: tree) + repair.install() + let submenu = try XCTUnwrap(repairedSubmenu(tree, repair: repair)) + + XCTAssertEqual(submenu.items.map(\.title), ["b.md", "a.markdown", "c.txt", "", "Clear Menu"]) + XCTAssertEqual(submenu.items.prefix(3).compactMap { $0.representedObject as? URL }, world.recents) + XCTAssertTrue(submenu.items[3].isSeparatorItem) + XCTAssertFalse(submenu.autoenablesItems, "enabled states are explicit") + XCTAssertEqual(submenu.items.filter { !$0.isSeparatorItem }.map(\.isEnabled), [true, true, true, true]) + for entry in submenu.items.prefix(3) { + XCTAssertEqual(entry.image?.size, OpenRecentMenu.iconSize) + } + } + + func testEntriesThatShareANameSayTheirFolder() throws { + world.recents = [url("/A/README.md"), url("/Notes/plan.md"), url("/B/README.md")] + let tree = makeFileMenu(slot: NSMenuItem()) + let repair = makeRepair(for: tree) + repair.install() + let submenu = try XCTUnwrap(repairedSubmenu(tree, repair: repair)) + + XCTAssertEqual(submenu.items.prefix(3).map(\.title), + ["README.md \u{2014} A", "plan.md", "README.md \u{2014} B"]) + } + + func testAnEmptyListGivesOnlyADisabledClearMenu() throws { + let tree = makeFileMenu(slot: NSMenuItem()) + let repair = makeRepair(for: tree) + repair.install() + let submenu = try XCTUnwrap(repairedSubmenu(tree, repair: repair)) + + XCTAssertEqual(submenu.items.map(\.title), ["Clear Menu"]) + XCTAssertFalse(submenu.items[0].isSeparatorItem) + XCTAssertFalse(submenu.items[0].isEnabled) + } + + func testTheListIsReadAgainWhenTheMenuUpdates() throws { + let tree = makeFileMenu(slot: NSMenuItem()) + let repair = makeRepair(for: tree) + repair.install() + let submenu = try XCTUnwrap(repairedSubmenu(tree, repair: repair)) + XCTAssertEqual(world.recentsReads, 1, "filled once at repair time") + + world.recents = [url("/Notes/new.md")] + repair.menuNeedsUpdate(submenu) + + XCTAssertEqual(world.recentsReads, 2) + XCTAssertEqual(submenu.items.map(\.title), ["new.md", "", "Clear Menu"]) + XCTAssertTrue(submenu.items[2].isEnabled) + } + + // MARK: - Actions + + func testChoosingAnEntryOpensExactlyThatURLAndReportsAFailure() throws { + world.recents = [url("/Notes/one.md"), url("/Notes/two.md")] + let tree = makeFileMenu(slot: NSMenuItem()) + let repair = makeRepair(for: tree) + repair.install() + let submenu = try XCTUnwrap(repairedSubmenu(tree, repair: repair)) + + perform(submenu.items[1]) + XCTAssertEqual(world.opened, [url("/Notes/two.md")]) + XCTAssertTrue(world.failures.isEmpty) + + world.pendingFailure?("Couldn\u{2019}t open \u{201C}two.md\u{201D}") + XCTAssertEqual(world.failures, ["Couldn\u{2019}t open \u{201C}two.md\u{201D}"]) + XCTAssertEqual(world.clears, 0) + } + + func testClearMenuCallsClear() throws { + world.recents = [url("/Notes/one.md")] + let tree = makeFileMenu(slot: NSMenuItem()) + let repair = makeRepair(for: tree) + repair.install() + let submenu = try XCTUnwrap(repairedSubmenu(tree, repair: repair)) + + let clear = try XCTUnwrap(submenu.items.last) + XCTAssertEqual(clear.title, "Clear Menu") + world.recents = [] + perform(clear) + + XCTAssertEqual(world.clears, 1) + XCTAssertTrue(world.opened.isEmpty) + XCTAssertEqual(submenu.items.map(\.title), ["Clear Menu"], "the emptied list shows at once") + XCTAssertFalse(submenu.items[0].isEnabled) + } +} From 3178d57b76398f254196d0dddcd7c8de33292433 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 18:37:55 +0100 Subject: [PATCH 25/27] fix: Open Recent entries draw their icons on macOS 27 macOS 27 decides menu item image visibility and typically hides them; each entry now asks for a visible image through the 27 SDK's preferredImageVisibility, called by name behind responds(to:) because CI builds with an older SDK. Clear Menu and the separator are untouched; macOS 13-26 call nothing. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/OpenRecentMenu.swift | 16 ++++++++++ .../QuickMDTests/OpenRecentMenuTests.swift | 31 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/QuickMD/QuickMD/OpenRecentMenu.swift b/QuickMD/QuickMD/OpenRecentMenu.swift index a9995d5..beed8fe 100644 --- a/QuickMD/QuickMD/OpenRecentMenu.swift +++ b/QuickMD/QuickMD/OpenRecentMenu.swift @@ -150,6 +150,7 @@ final class OpenRecentMenu: NSObject, NSMenuDelegate { item.target = self item.representedObject = url item.image = icon(for: url) + Self.requestVisibleImage(for: item) item.isEnabled = true menu.addItem(item) } @@ -160,6 +161,21 @@ final class OpenRecentMenu: NSObject, NSMenuDelegate { menu.addItem(clear) } + /// The KVC key of `NSMenuItem.preferredImageVisibility` (macOS 27 SDK). + static let imageVisibilityKey = "preferredImageVisibility" + + /// On macOS 27 and later AppKit decides whether a menu item's image is + /// drawn and typically hides it (SDK header `NSMenuItem.h`); the + /// system's own Open Recent shows document icons, so ours asks for + /// them. `preferredImageVisibility` is public API of the macOS 27 SDK, + /// called by name only because CI builds with an older SDK that lacks + /// the symbol; 1 is `NSMenuItemImageVisibilityVisible`. On macOS 13–26 + /// the item does not respond and nothing is called (images show there). + static func requestVisibleImage(for item: NSMenuItem) { + guard item.responds(to: NSSelectorFromString("setPreferredImageVisibility:")) else { return } + item.setValue(NSNumber(value: 1), forKey: imageVisibilityKey) + } + /// The content type's icon from the extension alone — no /// `icon(forFile:)`, which reads the file (and may wake a volume). private func icon(for url: URL) -> NSImage { diff --git a/QuickMD/QuickMDTests/OpenRecentMenuTests.swift b/QuickMD/QuickMDTests/OpenRecentMenuTests.swift index 8366429..985981d 100644 --- a/QuickMD/QuickMDTests/OpenRecentMenuTests.swift +++ b/QuickMD/QuickMDTests/OpenRecentMenuTests.swift @@ -327,6 +327,37 @@ final class OpenRecentMenuTests: XCTestCase { } } + /// Where AppKit has `preferredImageVisibility` (macOS 27+), entries ask + /// for their icon to be drawn and Clear Menu / the separator are left at + /// the default; elsewhere the request is a no-op. Decided by + /// `responds(to:)`, never by the OS version. + func testEntryIconsAskToBeVisibleWhereAppKitDecidesVisibility() throws { + world.recents = [url("/Notes/one.md"), url("/Notes/two.txt")] + let tree = makeFileMenu(slot: NSMenuItem()) + let repair = makeRepair(for: tree) + repair.install() + let submenu = try XCTUnwrap(repairedSubmenu(tree, repair: repair)) + let entries = Array(submenu.items.prefix(2)) + let clear = try XCTUnwrap(submenu.items.last) + + for entry in entries { XCTAssertEqual(entry.image?.size, OpenRecentMenu.iconSize) } + XCTAssertNil(clear.image) + + let key = OpenRecentMenu.imageVisibilityKey + guard NSMenuItem().responds(to: NSSelectorFromString("setPreferredImageVisibility:")) else { + // No such property: the request must not crash and sets nothing. + OpenRecentMenu.requestVisibleImage(for: NSMenuItem()) + return + } + let defaultValue = (NSMenuItem().value(forKey: key) as? NSNumber)?.intValue + for entry in entries { + XCTAssertEqual((entry.value(forKey: key) as? NSNumber)?.intValue, 1, entry.title) + } + XCTAssertEqual((clear.value(forKey: key) as? NSNumber)?.intValue, defaultValue) + XCTAssertEqual((submenu.items[2].value(forKey: key) as? NSNumber)?.intValue, defaultValue, + "the separator") + } + func testEntriesThatShareANameSayTheirFolder() throws { world.recents = [url("/A/README.md"), url("/Notes/plan.md"), url("/B/README.md")] let tree = makeFileMenu(slot: NSMenuItem()) From bf2a3a71334ff75c30afe2e99f476e57e4b9f919 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 18:42:29 +0100 Subject: [PATCH 26/27] fix: Open Recent is repaired when a File menu is attached to the main menu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A change on the main menu itself (a File menu built detached, then attached) now runs the repair over its top-level submenus; before, only changes inside a top-level submenu did. Documents that nothing of ours may sit directly after the system's Open… (a disabled button there would look like the blank), and states what the one-submenu test proves. Co-Authored-By: Claude Opus 5.5 --- QuickMD/QuickMD/OpenRecentMenu.swift | 32 +++++++++++++++---- QuickMD/QuickMD/QuickMDApp.swift | 2 ++ .../QuickMDTests/OpenRecentMenuTests.swift | 30 ++++++++++++++++- 3 files changed, 56 insertions(+), 8 deletions(-) diff --git a/QuickMD/QuickMD/OpenRecentMenu.swift b/QuickMD/QuickMD/OpenRecentMenu.swift index beed8fe..615b187 100644 --- a/QuickMD/QuickMD/OpenRecentMenu.swift +++ b/QuickMD/QuickMD/OpenRecentMenu.swift @@ -49,7 +49,9 @@ final class OpenRecentMenu: NSObject, NSMenuDelegate { private var isInstalled = false /// Set while the repair mutates the slot: setting `title` / `submenu` /// posts `NSMenu.didChangeItemNotification` synchronously, which would - /// otherwise re-enter and build a second submenu. + /// otherwise re-enter. With today's order (submenu first) a nested + /// notification already sees a healthy slot; the flag is defence for any + /// future order of the three assignments. private var isRepairing = false /// One icon per extension (a copy sized for the menu; NSWorkspace's /// image is shared and must not be resized). @@ -81,24 +83,40 @@ final class OpenRecentMenu: NSObject, NSMenuDelegate { name: NSMenu.didAddItemNotification, object: nil) center.addObserver(self, selector: #selector(menuItemsDidChange(_:)), name: NSMenu.didChangeItemNotification, object: nil) - guard let main = mainMenu() else { return } + if let main = mainMenu() { repairTopLevelMenus(of: main) } + } + + private func repairTopLevelMenus(of main: NSMenu) { for case let menu? in main.items.map(\.submenu) { repairIfNeeded(in: menu) } } /// Every menu in the app posts these (context menus too), so the cheap - /// test comes first: only a top-level submenu of the main menu counts. + /// test comes first: only the main menu itself or one of its top-level + /// submenus counts. A change ON the main menu is what attaching a File + /// menu built while detached posts (`fileItem.submenu = newFile`) — the + /// only notification such a rebuild would give. @objc private func menuItemsDidChange(_ notification: Notification) { - guard !isRepairing, - let menu = notification.object as? NSMenu, - let main = menu.supermenu, main === mainMenu() else { return } - repairIfNeeded(in: menu) + guard !isRepairing, let menu = notification.object as? NSMenu else { return } + if let main = menu.supermenu { + guard main === mainMenu() else { return } + repairIfNeeded(in: menu) + } else if menu === mainMenu() { + repairTopLevelMenus(of: menu) + } } /// The item right after Open… when it is blank: not a separator, no /// submenu, no action, no view. The title is deliberately not tested — /// a partly reset item must still be repaired. + /// + /// Assumption: nothing of ours sits directly after the system's Open…. + /// A disabled SwiftUI Button there also has no action and no submenu and + /// would be taken for the blank. There is deliberately no class check: + /// the blank's class is known only for macOS 27.2.1, and a repair that + /// silently stops on another macOS is worse than this rule + /// (`CommandGroup(after: .newItem)` lands BEFORE Open…). static func blankSlot(in menu: NSMenu) -> NSMenuItem? { let openDocument = #selector(NSDocumentController.openDocument(_:)) guard let index = menu.items.firstIndex(where: { $0.action == openDocument }), diff --git a/QuickMD/QuickMD/QuickMDApp.swift b/QuickMD/QuickMD/QuickMDApp.swift index 5059f93..843655a 100644 --- a/QuickMD/QuickMD/QuickMDApp.swift +++ b/QuickMD/QuickMD/QuickMDApp.swift @@ -43,6 +43,8 @@ struct QuickMDApp: App { // Replacing .saveItem makes SwiftUI's first menu update leave a // blank "NSMenuItem" where Open Recent was; `OpenRecentMenu` // (installed in `applicationDidFinishLaunching`) repairs it in place. + // It takes the item right after Open… for that blank, so nothing + // of ours may sit directly after the system's Open…. CommandGroup(replacing: .saveItem) { Button("Close") { EditCloseGuard.requestClose(NSApp.keyWindow) diff --git a/QuickMD/QuickMDTests/OpenRecentMenuTests.swift b/QuickMD/QuickMDTests/OpenRecentMenuTests.swift index 985981d..f6c6615 100644 --- a/QuickMD/QuickMDTests/OpenRecentMenuTests.swift +++ b/QuickMD/QuickMDTests/OpenRecentMenuTests.swift @@ -271,13 +271,41 @@ final class OpenRecentMenuTests: XCTestCase { XCTAssertEqual(repair.submenusBuilt, 0) } + func testAFileMenuBuiltDetachedIsRepairedWhenItIsAttached() throws { + let tree = makeFileMenu(slot: systemOpenRecent()) + let repair = makeRepair(for: tree) + repair.install() + let fileItem = try XCTUnwrap(tree.main.items.first { $0.submenu === tree.file }) + + // A new File menu built while detached: its own notifications come + // from a menu under nothing and are ignored. + let blank = NSMenuItem() + let newFile = NSMenu(title: "File") + for item in [NSMenuItem(title: "New", action: nil, keyEquivalent: "n"), openItem(), blank, closeItem()] { + newFile.addItem(item) + } + XCTAssertNil(blank.submenu) + XCTAssertEqual(repair.submenusBuilt, 0) + + // Attaching it posts a change on the main menu only. + fileItem.submenu = newFile + + XCTAssertTrue(newFile.item(at: 2) === blank) + XCTAssertEqual(blank.title, OpenRecentMenu.title) + XCTAssertTrue(blank.submenu?.delegate === repair) + XCTAssertEqual(repair.submenusBuilt, 1) + } + func testOneEventBuildsOneSubmenuAndLaterChangesKeepIt() { let tree = makeFileMenu(slot: systemOpenRecent()) let repair = makeRepair(for: tree) repair.install() + // Proves one event builds one submenu. It does not prove the + // `isRepairing` guard: with the submenu assigned first, a nested + // notification already sees a healthy slot. let blank = simulateSwiftUIRebuild(tree.file) - XCTAssertEqual(repair.submenusBuilt, 1, "the nested change notifications build nothing") + XCTAssertEqual(repair.submenusBuilt, 1, "one event, one submenu") let submenu = blank.submenu // Unrelated later changes in the File menu. From ce51c4c774be5f86b854731a742463aab37fa0e1 Mon Sep 17 00:00:00 2001 From: Bartosz Sroczynski Date: Tue, 17 Nov 2026 18:51:32 +0100 Subject: [PATCH 27/27] release: v1.16.0 (34) - Open Folder, numbered lists that count, Open Recent back Version 1.16.0 (build 34), CHANGELOG, README (Open Folder, its shortcut, the plan issue #63), PRIVACY (what Open Folder reads and remembers). Co-Authored-By: Claude Fable 5.2 --- PRIVACY.md | 7 ++++--- QuickMD/CHANGELOG.md | 14 ++++++++++++++ QuickMD/QuickMD.xcodeproj/project.pbxproj | 8 ++++---- README.md | 6 ++++-- 4 files changed, 26 insertions(+), 9 deletions(-) diff --git a/PRIVACY.md b/PRIVACY.md index 8c09b1e..effc1d1 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,6 +1,6 @@ # Privacy Policy for QuickMD -**Last updated: November 4, 2026** +**Last updated: November 17, 2026** ## Overview @@ -33,6 +33,7 @@ Specifically, QuickMD does NOT collect: QuickMD works with the files **you open**, and with what those files point to. - It reads the Markdown file you open, the local images that file references, and another Markdown file when you click a link to it +- If you use File > Open Folder, it reads the names of the files and folders inside the folder you choose to list its Markdown files in the sidebar, keeps that list current while the folder is open, and remembers the folder on your Mac until you close it. A file from the list is read only when you click it. - It writes to a file only when you ask it to: saving your changes in Source Edit writes to the document you are editing; "Save a Copy" and "Export as PDF" write where you choose - Your settings, the list of recent documents and any custom themes you add are stored on your Mac - The Mac App Store version also notes on which days you open documents, so it asks for a rating at most once per version. This stays on your Mac and is never sent anywhere. @@ -76,7 +77,7 @@ QuickMD is distributed in two builds, and macOS limits them differently. | Permission | Purpose | |------------|---------| | **User Selected File (Read/Write)** | To read the Markdown files you open and to save your Source Edit changes to them | -| **App-Scoped Bookmarks** | To remember a folder you allowed, so images next to your documents keep loading | +| **App-Scoped Bookmarks** | To remember a folder you allowed or opened, so images next to your documents keep loading and an opened folder's list is there next time | | **Outgoing Network Connections** | To fetch remote images from URLs in your Markdown files | | **Printing** | To print and export to PDF | @@ -87,7 +88,7 @@ It cannot read anything else unless you grant access to a folder when macOS asks Neither build accesses: - Your contacts, calendar, or location - Your camera, microphone, or photos -- Files other than the documents you open, what they reference, and QuickMD's own settings and themes +- Files other than the documents you open, what they reference, the names of the files in a folder you open, and QuickMD's own settings and themes ### Open Source diff --git a/QuickMD/CHANGELOG.md b/QuickMD/CHANGELOG.md index b488e81..b94ef14 100644 --- a/QuickMD/CHANGELOG.md +++ b/QuickMD/CHANGELOG.md @@ -5,6 +5,20 @@ All notable changes to QuickMD will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.16.0] - 2026-11-17 + +Open a folder and read its Markdown files from the sidebar; numbered lists count up from their first number. + +### Added +- **Open Folder** (File ▸ Open Folder…, ⇧⌘O): the Documents sidebar lists the Markdown files of a folder, subfolders included, above your recent documents. A click opens the file in a tab. The folder stays until you close it. Thanks to @aginanjar for the suggestion (#62). + +### Fixed +- **Numbered lists count up from their first number:** `1.` `1.` `1.` is shown as 1, 2, 3, and a list that starts with `5.` goes on with 6, whatever numbers follow in the source. Switching between `1.` and `1)` starts a new list. Thanks to @jmataraz for the report (#61). +- A formula used as link text is drawn in the link's colour and underlined (in print/PDF: in the link's colour). +- A line of three or more `*`, `-` or `_` with spaces between them (`* * *`) is a horizontal rule. +- A recent document that cannot be opened says so instead of doing nothing. +- **File ▸ Open Recent is back:** on macOS 27 the menu showed an empty grey item in its place. + ## [1.15.1] - 2026-11-15 Formulas: no more repeated characters inside brackets, a crash on a malformed formula, signs and spaces as LaTeX sets them. diff --git a/QuickMD/QuickMD.xcodeproj/project.pbxproj b/QuickMD/QuickMD.xcodeproj/project.pbxproj index bd913a6..418175f 100644 --- a/QuickMD/QuickMD.xcodeproj/project.pbxproj +++ b/QuickMD/QuickMD.xcodeproj/project.pbxproj @@ -1111,7 +1111,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 33; + CURRENT_PROJECT_VERSION = 34; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = VJ92852M32; ENABLE_APP_SANDBOX = YES; @@ -1136,7 +1136,7 @@ "$(inherited)", "@executable_path/../Frameworks", ); - MARKETING_VERSION = 1.15.1; + MARKETING_VERSION = 1.16.0; PRODUCT_BUNDLE_IDENTIFIER = pl.falami.studio.QuickMD; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; @@ -1155,7 +1155,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 33; + CURRENT_PROJECT_VERSION = 34; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = VJ92852M32; ENABLE_APP_SANDBOX = YES; @@ -1180,7 +1180,7 @@ "$(inherited)", "@executable_path/../Frameworks", ); - MARKETING_VERSION = 1.15.1; + MARKETING_VERSION = 1.16.0; PRODUCT_BUNDLE_IDENTIFIER = pl.falami.studio.QuickMD; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; diff --git a/README.md b/README.md index c0cd3cc..95d13b2 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ Perfect for developers, writers, students, and anyone who works with Markdown da - Find in document (`⌘F`) with match count and per-word navigation - Word-level highlighting across all block types (text, code, tables, blockquotes) - Table of Contents sidebar (`⌘⇧T`) — auto-generated from headings; right-click it to list every level or stop at H2, H3 or H4 +- **Open Folder** (`⇧⌘O`) — the Documents sidebar lists the Markdown files of a folder, subfolders included, above your recent documents; a click opens the file in a tab - Reading mode (`⌘⇧R`) — hides both sidebars and the hover buttons and centres the text in a comfortable column (720 pt at 100 %, growing with zoom); `Esc` brings everything back - **Select across the whole document** — drag through paragraphs, headings, lists, quotes, code and tables (a word, a cell or a range of cells), it scrolls for you, Shift-click to extend, `⌘A` / `⌘C` to copy clean text (table cells as tab-separated values, math as LaTeX). Every copy shows how many characters and words were copied; optional auto-copy of selections in Settings → General - Copy entire document (`⌘⇧C`) or individual sections (hover heading → copy icon) @@ -173,6 +174,7 @@ Now all your Markdown files will open instantly with QuickMD! | Shortcut | Action | |----------|--------| | `⌘O` | Open file | +| `⇧⌘O` | Open Folder | | `⌘W` | Close tab (or window if last tab) | | `⌘R` | Reload the document from disk | | `⌥⌘E` | Edit the Markdown source in place / done editing | @@ -202,7 +204,7 @@ Now all your Markdown files will open instantly with QuickMD! - Per-block **vector PDF export** — selectable text, embedded fonts, Mermaid diagrams as images, multi-page pagination - Source Edit writes the file in place (inode, permissions and extended attributes survive) and re-encodes exactly what it decoded; the unsaved-changes guard sits in front of the window's own delegate, so the system's document machinery is untouched - The Mac App Store build runs in the App Sandbox (security-scoped bookmarks for local images); the GitHub and Homebrew build is Developer ID signed and notarized, not sandboxed -- 1,200+ unit tests; GitHub Actions builds every flavor on each push +- 1,300+ unit tests; GitHub Actions builds every flavor on each push ### Where Things Live @@ -278,7 +280,7 @@ Donations help renew the qmd.app domain - [see the goal on qmd.app](https://qmd. ## Roadmap -What has shipped, release by release, is in the [CHANGELOG](QuickMD/CHANGELOG.md). What is planned for the next version is listed in [this issue](https://github.com/b451c/quickmd/issues/54): comment there, or open a new issue if something is missing for you. +What has shipped, release by release, is in the [CHANGELOG](QuickMD/CHANGELOG.md). What is planned for the next version is listed in [this issue](https://github.com/b451c/quickmd/issues/63): comment there, or open a new issue if something is missing for you. ## Contributing