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 1803afd..418175f 100644 --- a/QuickMD/QuickMD.xcodeproj/project.pbxproj +++ b/QuickMD/QuickMD.xcodeproj/project.pbxproj @@ -156,6 +156,15 @@ 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 */; }; + 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 */; }; @@ -249,6 +258,12 @@ 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 = ""; }; + 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 = ""; }; @@ -436,6 +451,9 @@ A1B2C3D400000462 /* ImageRowTests.swift */, A1B2C3D400000465 /* LocalLinkSafetyTests.swift */, A1B2C3D400000468 /* FolderAccessBrokerTests.swift */, + F62A000000000005 /* FolderListingTests.swift */, + F62A000000000006 /* FolderBrowserStoreTests.swift */, + A1B2C3D400000472 /* OpenRecentMenuTests.swift */, A1B2C3D400000400 /* TableRulesTests.swift */, A1B2C3D4000004E1 /* SideBySideTests.swift */, A1B2C3D400000421 /* ListContentTests.swift */, @@ -490,6 +508,9 @@ A1B2C3D400000460 /* ImageRowLayout.swift */, A1B2C3D400000463 /* LocalLinkSafety.swift */, A1B2C3D400000466 /* FolderAccessBroker.swift */, + F62A000000000001 /* FolderListing.swift */, + F62A000000000003 /* FolderBrowserStore.swift */, + A1B2C3D400000470 /* OpenRecentMenu.swift */, A1B2C3D4000004E0 /* SideBySide.swift */, A1B2C3D400000420 /* ListNesting.swift */, A1B2C3D400000301 /* ReferenceLinks.swift */, @@ -801,6 +822,9 @@ 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 */, + A1B2C3D401000470 /* OpenRecentMenu.swift in Sources */, A1B2C3D4010004E0 /* SideBySide.swift in Sources */, A1B2C3D401000420 /* ListNesting.swift in Sources */, A1B2C3D401000301 /* ReferenceLinks.swift in Sources */, @@ -886,6 +910,9 @@ 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 */, + A1B2C3D401000472 /* OpenRecentMenuTests.swift in Sources */, A1B2C3D401000400 /* TableRulesTests.swift in Sources */, A1B2C3D4010004E2 /* SideBySideTests.swift in Sources */, A1B2C3D401000422 /* ListContentTests.swift in Sources */, @@ -905,6 +932,9 @@ 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) */, + A1B2C3D401000471 /* OpenRecentMenu.swift in Sources (Tests) */, A1B2C3D4010004E1 /* SideBySide.swift in Sources (Tests) */, A1B2C3D401000421 /* ListNesting.swift in Sources (Tests) */, A1B2C3D401000302 /* ReferenceLinks.swift in Sources (Tests) */, @@ -1081,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; @@ -1106,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 = ""; @@ -1125,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; @@ -1150,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/QuickMD/QuickMD/BlockHeightMeasurer.swift b/QuickMD/QuickMD/BlockHeightMeasurer.swift index dd34c6c..66cdcc7 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,199 @@ 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 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. + /// - 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), 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) { + 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. + 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.. 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); a typeset + // box is centred on the cap height (`bounds(for:)`). + let location = layoutManager.location(forGlyphAt: glyph) + let bottom = origin.y + fragment.minY + location.y + 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) + } + } + } } // MARK: - AttributedString → NSAttributedString @@ -958,14 +1178,15 @@ enum BlockTextConverter { attrIndex = end } - if let image = math.inlineImage(latex, theme, mathFontSize) { + if let image = math.formulaImage(latex, theme: theme, fontSize: mathFontSize, color: link?.color) { // Centred against the cap height of the text around it // (14 pt body × zoom, or the heading's); scaled down when // wider than the line, its source when even half its size // does not fit (`FittingMathAttachment`). let attachment = FittingMathAttachment( image: image, capHeight: theme.fonts.appKit(size: mathFontSize).capHeight, - source: inlineFallback(latex, theme: theme, fontSize: mathFontSize, link: link)) + source: inlineFallback(latex, theme: theme, fontSize: mathFontSize, link: link), + linkUnderline: link?.underline(fontSize: mathFontSize, theme: theme)) // Tagged with its source so a copy can write `$latex$` // instead of U+FFFC (DocumentCopyBuilder). Draws nothing, // lays out nothing — the measured height is unchanged. @@ -978,7 +1199,10 @@ enum BlockTextConverter { range: NSRange(location: 0, length: embedded.length)) } // A formula in link text is part of the link: clickable, - // underlined like the text around it. + // in the link's colour (its image) and underlined like + // the text around it — TextKit draws no underline under + // an attachment, so the attachment draws it + // (`drawLinkUnderline`, from the view's layout manager). link?.apply(to: embedded, colors: false) result.append(embedded) } else { @@ -1015,6 +1239,9 @@ enum BlockTextConverter { let url: URL let color: NSColor? let underline: Int? + /// The font of the formula's run: the link text's, whose underline + /// metrics the formula's underline takes. + let font: NSFont? /// Nil when the formula is not in a link. init?(of source: AttributedSubstring) { @@ -1022,6 +1249,16 @@ enum BlockTextConverter { self.url = url color = run[AttributeScopes.AppKitAttributes.ForegroundColorAttribute.self] underline = run[AttributeScopes.AppKitAttributes.UnderlineStyleAttribute.self]?.rawValue + font = run[AttributeScopes.AppKitAttributes.FontAttribute.self] + } + + /// The underline a typeset formula in this link draws (v1.16), or nil + /// when the link is not underlined. `fontSize`/`theme` stand in for a + /// run without a font (text set by hand). + func underline(fontSize: CGFloat, theme: MarkdownTheme) -> 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/FolderAccessBroker.swift b/QuickMD/QuickMD/FolderAccessBroker.swift index fa3df20..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,6 +102,29 @@ final class FolderAccessBroker { return path } + /// 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 { bookmarkKeyPath($0) == key } && 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 + "/") @@ -132,6 +157,35 @@ 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 else { return false } + let granted = Self.canonicalPath(folder) + 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) + 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 } @@ -169,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/FolderBrowserStore.swift b/QuickMD/QuickMD/FolderBrowserStore.swift new file mode 100644 index 0000000..8405dae --- /dev/null +++ b/QuickMD/QuickMD/FolderBrowserStore.swift @@ -0,0 +1,465 @@ +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. 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), with item events. +/// 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 +/// 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, 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 { + 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 (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 + 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) + } + /// 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. + 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? + + /// 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 { + 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 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) + // 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)) + } + } + + /// Forgets the folder: no list, no watcher, nothing remembered. + func close() { + endSession() + folder = nil + listingRoot = nil + eventRootPath = nil + groups = [] + isTruncated = false + isLoading = false + isUnreadable = false + environment.defaults.removeObject(forKey: Self.defaultsKey) + } + + /// 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 } + // 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 spellings, environment.restoreAccess(chosen) else { + environment.defaults.removeObject(forKey: Self.defaultsKey) + return + } + begin(folder: chosen, spellings: spellings, restored: 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 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 + } + } + + @discardableResult + /// 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 = spellings.real + groups = [] + isTruncated = false + isUnreadable = false + isLoading = true + // 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() + return opened + } + + /// 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 + resumeWaiters(.superseded) { _ in true } + } + + private func startScanLoopIfNeeded() { + guard scanLoop == nil, let current = session else { return } + scanLoop = Task { [weak self] in + await self?.runScans(for: current) + } + } + + /// 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: + 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 } + 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 + +/// 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), 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 let filter: FolderEventBatchFilter + private let queue = DispatchQueue(label: "pl.falami.studio.QuickMD.folder-watch", qos: .utility) + private var stream: FSEventStreamRef? + + 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 } + let paths = Unmanaged.fromOpaque(eventPaths).takeUnretainedValue() + Unmanaged.fromOpaque(info).takeUnretainedValue() + .handle(count: count, paths: paths, flags: eventFlags) + } + let flags = FSEventStreamCreateFlags(kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagUseCFTypes + | kFSEventStreamCreateFlagFileEvents) + guard let stream = FSEventStreamCreate(kCFAllocatorDefault, callback, &context, [root.path] as CFArray, + FSEventStreamEventId(kFSEventStreamEventIdSinceNow), latency, + flags) else { + return nil + } + FSEventStreamSetDispatchQueue(stream, queue) + guard FSEventStreamStart(stream) else { + FSEventStreamInvalidate(stream) + FSEventStreamRelease(stream) + return nil + } + self.stream = stream + } + + deinit { + filter.stop() + guard let stream else { return } + FSEventStreamStop(stream) + FSEventStreamInvalidate(stream) + let filter = self.filter + queue.async { + FSEventStreamRelease(stream) + withExtendedLifetime(filter) {} + } + } +} diff --git a/QuickMD/QuickMD/FolderListing.swift b/QuickMD/QuickMD/FolderListing.swift new file mode 100644 index 0000000..bb45975 --- /dev/null +++ b/QuickMD/QuickMD/FolderListing.swift @@ -0,0 +1,459 @@ +import Foundation +import CoreServices + +// 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()) + } + + 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 + +/// 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 — +/// what the Documents sidebar lists after File ▸ Open Folder. A list to read +/// from, never a file manager. +/// +/// 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.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. 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 +/// 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). The +/// 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. +/// - 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`). +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 + /// 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. + 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 } + /// The subfolder header's sidebar row (`SidebarRowID`). + var rowID: SidebarRowID { .folderGroup(relativePath) } + } + + struct Result: Equatable, Sendable { + /// Folders that hold Markdown files, in display order (root first). + let groups: [Group] + /// A limit stopped the walk: more files may exist than are listed. + 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 + } + } + + /// 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. + /// 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 { + 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 + /// `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. + /// 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 + "/" + 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 } + 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.., 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 + /// `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) + if flags & (structural | lookAgainFlags) != 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 { + 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. 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) + let hardLink = UInt32(kFSEventStreamEventFlagItemIsHardlink | kFSEventStreamEventFlagItemIsLastHardlink) + guard flags & fileLike != 0, flags & UInt32(kFSEventStreamEventFlagItemIsDir) == 0, + flags & hardLink == 0 else { return false } + return !MarkdownFileKind.isMarkdownName(utf8: name) + } + + /// `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, .volumeIdentifierKey, + .isVolumeKey] + + /// 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 { + // 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) else { + return .unreadable + } + guard isDirectory.boolValue else { return .missing } + 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 + var foldersRead = 1 + var truncated = false + var cancelled = false + + /// Depth-first, children in Finder order: a folder's files, then its + /// subfolders — the display order (see the type). + func visit(_ 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, !cancelled else { return } + if isCancelled() { + cancelled = true + return + } + if entry.isVolume { continue } + if let volume, let own = entry.volume, !own.isEqual(volume) { continue } + guard foldersRead < limits.maxFolders, entriesRead <= limits.maxEntriesRead else { + truncated = true + return + } + foldersRead += 1 + 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) + visit(children, relativePath: path, depth: depth + 1) + } + } + 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. The directory read prefetches exactly the keys the rules + /// 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 + // 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 + // the listing must keep the root's (canonical) spelling. + if values.isDirectory == true { + 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: folder.appendingPathComponent(name, isDirectory: false), kind: .markdown, + volume: nil)) + } + } + 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/MarkdownBlockParser.swift b/QuickMD/QuickMD/MarkdownBlockParser.swift index 6c5a376..0199d2c 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]) } } - let hangs = renderer.widestOrderedPrefixes(lines) + // 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`. 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 +2188,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/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.. 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. 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?]? = nil) -> [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 +258,57 @@ 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 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 } - 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)? { - 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) + /// 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? { + 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" })), + 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 @@ -384,16 +431,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 @@ -404,17 +452,46 @@ 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...]) } 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 + 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 @@ -424,7 +501,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 } @@ -440,7 +517,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 @@ -454,7 +534,7 @@ struct MarkdownRenderer: Sendable { } // Horizontal rule - if trimmed.range(of: MarkdownTheme.horizontalRulePattern, options: .regularExpression) != nil { + if Self.isRuleRun(trimmed) { return renderHorizontalRule() } @@ -467,16 +547,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, trimmed: trimmed) { + let content = String(trimmed.dropFirst(item.markerLength)) + return renderListItem(content, prefix: marker?.prefix ?? item.ownPrefix, hangingUnder: marker?.hang) } // Empty line @@ -732,9 +809,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 +820,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 +836,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 +847,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/QuickMD/MarkdownTheme.swift b/QuickMD/QuickMD/MarkdownTheme.swift index 2b88853..aabeb42 100644 --- a/QuickMD/QuickMD/MarkdownTheme.swift +++ b/QuickMD/QuickMD/MarkdownTheme.swift @@ -297,9 +297,6 @@ 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 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/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/OpenRecentMenu.swift b/QuickMD/QuickMD/OpenRecentMenu.swift new file mode 100644 index 0000000..615b187 --- /dev/null +++ b/QuickMD/QuickMD/OpenRecentMenu.swift @@ -0,0 +1,222 @@ +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. 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). + 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) + 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 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 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 }), + 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) + Self.requestVisibleImage(for: item) + 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 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 { + 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 1f65039..843655a 100644 --- a/QuickMD/QuickMD/QuickMDApp.swift +++ b/QuickMD/QuickMD/QuickMDApp.swift @@ -34,6 +34,17 @@ struct QuickMDApp: App { MarkdownView(document: file.document, documentURL: file.fileURL) } .commands { + // 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. + // 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) @@ -102,6 +113,141 @@ 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). 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 = { + 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, roots, onChange in + // Called on the watcher's queue, once per relevant batch. + FolderTreeWatcher(root: root, roots: roots) { + Task { @MainActor in onChange() } + } + })) + }() +} + +/// 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 + let name = folder.lastPathComponent + 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 { + 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) } + } + } + + /// 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) { + 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") + alert.runModal() + } +} + +// 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/QuickMD/SandboxAccessManager.swift b/QuickMD/QuickMD/SandboxAccessManager.swift index 73cf00a..b4dd69d 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 @@ -152,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 keyPath = FolderAccessBroker.bookmarkKeyPath(selectedURL) + if !savedFolders.contains(where: { FolderAccessBroker.bookmarkKeyPath($0) == keyPath }) { + savedFolders.append(selectedURL) + } if selectedURL.startAccessingSecurityScopedResource() { activeAccessURLs.append(selectedURL) return true @@ -179,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/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/QuickMD/Views/RecentDocumentsSidebar.swift b/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift index ca8fe2f..5f30396 100644 --- a/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift +++ b/QuickMD/QuickMD/Views/RecentDocumentsSidebar.swift @@ -3,15 +3,33 @@ 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 + /// 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) { @@ -59,7 +77,26 @@ struct RecentDocumentsSidebar: View { Divider() - if store.documents.isEmpty { + 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 { + 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)) @@ -87,9 +124,105 @@ 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 + 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 + } + } + + /// 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: \.sidebarRecentRowID) { 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.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 { + // Only a COMPLETE scan may say there are none. + if !folders.isLoading && !folders.isUnreadable { + folderNote(folders.isTruncated ? "This folder is too large to list" : "No Markdown files") + } + } else { + ForEach(folders.groups, id: \.rowID) { 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: \.sidebarFolderRowID) { url in + FolderFileRow(url: url, isCurrent: isCurrentInFolder(url), theme: theme, + onOpen: { openDocument(url) }) + } + } + if folders.isTruncated { + folderNote("Showing the first \(folders.fileCount.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 + } + + /// 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) + } +} + +// 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 +230,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) } } diff --git a/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift b/QuickMD/QuickMDTests/FolderAccessBrokerTests.swift index d9319b2..3148aa2 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,116 @@ 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") + } + + /// 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 under THIS spelling's key + /// AND active (any spelling of the same folder). + func testIsActiveGrantNeedsItsOwnKeySavedAndAnActiveAccess() throws { + let docs = file("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() { + 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..5e2b085 --- /dev/null +++ b/QuickMD/QuickMDTests/FolderBrowserStoreTests.swift @@ -0,0 +1,691 @@ +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, +/// 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 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 + /// 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)) { + 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? + // 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! + 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, roots, onChange in + world.watched.append(folder.path) + world.roots = roots + world.trigger = onChange + 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") }, + 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 { + 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) + } + return url + } + + private func names(_ store: FolderBrowserStore) -> [String] { + 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) + 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), 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 { + 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), path(second)) + } + + 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) + XCTAssertNil(browser.listingRoot) + XCTAssertTrue(browser.groups.isEmpty) + XCTAssertNil(world.token, "the watcher stopped") + XCTAssertNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + 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) + // Next launch: a new store over the same defaults. + let world = World() + let browser = store(world) + 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, [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) + try FileManager.default.removeItem(at: notes) + let world = World() + let browser = store(world) + await 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) + 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.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.fire([]) + await settle(browser) + XCTAssertFalse(browser.isUnreadable, "tried again on the next event") + } + + /// 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) + 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) + XCTAssertNotNil(suite.defaults.string(forKey: FolderBrowserStore.defaultsKey)) + world.forced = nil + world.fire([]) + 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 { + 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.fire([]) + 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 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.fire([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") + } + + /// 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) + world.hold = true + let opening = Task { await browser.open(notes) } + await until { world.started == 1 && !world.gates.isEmpty } + 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() + 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.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.fire([real + "/.git/index", real + "/docs/node_modules"]) + await settle(browser) + XCTAssertEqual(world.started, 1, "in the realpath spelling too") + world.fire([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.fire([]) + await settle(browser) + XCTAssertEqual(world.started, 2) + XCTAssertEqual(changes, 0) + try Data("# b\n".utf8).write(to: notes.appendingPathComponent("b.md")) + world.fire([]) + 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, "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.fire([]) + world.release() + let result = await opening.value + XCTAssertEqual(result, .listed) + XCTAssertEqual(names(browser), ["a.md"], "published before open returned") + 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: 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 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 + 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 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() + 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 + /// is waited for: delivery timing is the system's). + func testTheTreeWatcherStartsAndStops() { + weak var released: FolderTreeWatcher? + do { + let watcher = FolderTreeWatcher(root: root, roots: [root.path]) {} + XCTAssertNotNil(watcher) + released = watcher + } + XCTAssertNil(released) + } +} diff --git a/QuickMD/QuickMDTests/FolderListingTests.swift b/QuickMD/QuickMDTests/FolderListingTests.swift new file mode 100644 index 0000000..219b10e --- /dev/null +++ b/QuickMD/QuickMDTests/FolderListingTests.swift @@ -0,0 +1,454 @@ +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 +/// 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 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 + (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(scan()), ["/: 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(scan()), [ + "/: 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(scan()), ["/: 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(scan()), ["/: 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 = scan()?.files.map(\.lastPathComponent) + XCTAssertEqual(listed, (0...8).map { "f\($0).md" }, "the root and 8 folders below it") + 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 = scan(.init(maxDepth: 8, maxFiles: 4)) + XCTAssertEqual(shape(limited), ["/: a.md b.md c.md", "sub: d.md"]) + XCTAssertEqual(limited?.isTruncated, true) + 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) + XCTAssertEqual(FolderListing.Limits().maxDepth, 8) + } + + func testPreferredFileIsTheRootReadmeElseTheFirstListed() throws { + try make("guide.md", "ReadMe.md", "sub/README.md") + XCTAssertEqual(scan()?.preferredFile?.lastPathComponent, "ReadMe.md") + try FileManager.default.removeItem(at: root.appendingPathComponent("ReadMe.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(scan()?.preferredFile?.lastPathComponent, "README.md", + "no root files: the first listed one") + try FileManager.default.removeItem(at: root.appendingPathComponent("sub")) + XCTAssertNil(scan()?.preferredFile) + XCTAssertEqual(scan()?.groups, [], "an empty folder lists, with nothing in it") + } + + 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") + } + + /// 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 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 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 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")) + } + + /// 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 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", + "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(kFSEventStreamEventFlagItemRemoved | kFSEventStreamEventFlagItemIsFile + | kFSEventStreamEventFlagItemIsHardlink), + UInt32(kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemIsFile + | kFSEventStreamEventFlagItemIsLastHardlink), + UInt32(kFSEventStreamEventFlagMustScanSubDirs), + 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") + } + + /// 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, _ 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) \(note)", line: line) + XCTAssertEqual(fast, expected, "byte rule: \(path) \(note)", 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 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) + } + + /// 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 { + 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, maxFolders: 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 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") + } + + /// 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 { + 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 `
    • 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]") + // 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") } + let shown = String(MarkdownRenderer(theme: theme).renderQuotedBody(quote).characters) + XCTAssertEqual(shown.components(separatedBy: "7. ").count - 1, 2, shown) + 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:• *"]) + } + + /// 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 { + //

      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: - 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() { diff --git a/QuickMD/QuickMDTests/MathInTextKindsTests.swift b/QuickMD/QuickMDTests/MathInTextKindsTests.swift index 904251a..345e850 100644 --- a/QuickMD/QuickMDTests/MathInTextKindsTests.swift +++ b/QuickMD/QuickMDTests/MathInTextKindsTests.swift @@ -1049,6 +1049,301 @@ 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") + } + } + } + } + + /// 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. + @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 diff --git a/QuickMD/QuickMDTests/OpenRecentMenuTests.swift b/QuickMD/QuickMDTests/OpenRecentMenuTests.swift new file mode 100644 index 0000000..f6c6615 --- /dev/null +++ b/QuickMD/QuickMDTests/OpenRecentMenuTests.swift @@ -0,0 +1,461 @@ +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 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, "one event, one submenu") + 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) + } + } + + /// 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()) + 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) + } +} 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..a335b44 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 @@ -459,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")) 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