Tests/OrgEditorAppKitTests/InlineImagesEditorTests.swift

157 lines · 8322 bytes

11 symbols in this file
  1import AppKit
  2import OrgCore
  3@testable import OrgEditorAppKit
  4import Testing
  5
  6@MainActor
  7struct InlineImagesEditorTests {
  8    static let filler = String(repeating: "word ", count: 40)
  9    static let text = "* Images\n\(filler)[[file:pic.png]] \(filler)\n[[file:pic.png]]\n| a | [[file:pic.png]] | [[./pic.png]] |\n"
 10        + "Described [[file:pic.png][a figure]] here\nMissing [[file:missing.png]] here\n"
 11
 12    /// A folder holding `pic.png`, 100 by 60 points, and `wide.png`, 2000 by 100.
 13    static func folder() throws -> URL {
 14        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-images-\(UUID().uuidString)")
 15        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 16        for (name, width, height) in [("pic.png", 100, 60), ("wide.png", 2000, 100)] {
 17            let bitmap = try #require(NSBitmapImageRep(
 18                bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
 19                colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0
 20            ))
 21            try #require(bitmap.representation(using: .png, properties: [:])).write(to: folder.appendingPathComponent(name))
 22        }
 23        return folder
 24    }
 25
 26    static func harness(_ folder: URL) -> Harness {
 27        let h = Harness(text)
 28        h.editor.baseDirectory = folder
 29        return h
 30    }
 31
 32    static func box(_ h: Harness, at offset: Int) -> InlineImageBox? {
 33        h.textView.textStorage?.attribute(.orgImage, at: offset, effectiveRange: nil) as? InlineImageBox
 34    }
 35
 36    static func fragment(_ h: Harness, at offset: Int) -> NSTextLayoutFragment? {
 37        h.layout()
 38        let manager = h.editor.textLayoutManager
 39        let content = manager.textContentManager!
 40        guard let location = content.location(content.documentRange.location, offsetBy: offset) else { return nil }
 41        return manager.textLayoutFragment(for: location)
 42    }
 43
 44    @Test func anImageInWrappedTextMakesOnlyItsLineTall() throws {
 45        let folder = try Self.folder()
 46        defer { try? FileManager.default.removeItem(at: folder) }
 47        let h = Self.harness(folder)
 48        let ns = Self.text as NSString
 49        let link = ns.range(of: "[[file:pic.png]]")
 50        #expect(Self.box(h, at: link.location) == nil)
 51        h.editor.run("org.toggle-inline-images")
 52
 53        let box = try #require(Self.box(h, at: link.location))
 54        #expect(box.inText && !box.below && box.size == CGSize(width: 100, height: 60))
 55        #expect(Self.box(h, at: link.location + 1) == nil)
 56        let fragment = try #require(Self.fragment(h, at: link.location) as? ImageFragment)
 57        let lines = fragment.textLineFragments.filter { $0.characterRange.length > 0 }
 58        #expect(lines.count > 2)
 59        let tall = lines.filter { $0.typographicBounds.height >= 59 }
 60        #expect(tall.count == 1 && NSLocationInRange(link.location - NSMaxRange(ns.lineRange(for: NSRange(location: 0, length: 0))), tall[0].characterRange))
 61        #expect(lines.filter { $0.typographicBounds.height < 30 }.count == lines.count - 1)
 62        // The image covers the link's place: from its first character, 100 points wide, in the tall line.
 63        let frame = try #require(ImageFragment.frames(of: fragment).first).frame
 64        let bounds = tall[0].typographicBounds
 65        #expect(frame.width == 100 && frame.height == 60)
 66        #expect(frame.minY >= bounds.minY - 1 && frame.maxY <= bounds.maxY + 1)
 67        let start = tall[0].locationForCharacter(at: tall[0].characterRange.location + 0).x
 68        #expect(frame.minX >= bounds.minX + start)
 69        let paragraphStart = NSMaxRange(ns.lineRange(for: NSRange(location: 0, length: 0)))
 70        let before = tall[0].locationForCharacter(at: link.location - paragraphStart).x
 71        let after = tall[0].locationForCharacter(at: NSMaxRange(link) - paragraphStart).x
 72        #expect(abs(after - before - 100) < 1)
 73    }
 74
 75    @Test func theCaretsLineShowsTheLinkWithTheImageUnderIt() throws {
 76        let folder = try Self.folder()
 77        defer { try? FileManager.default.removeItem(at: folder) }
 78        let h = Self.harness(folder)
 79        let ns = Self.text as NSString
 80        let link = ns.range(of: "[[file:pic.png]]")
 81        h.editor.run("org.toggle-inline-images")
 82        h.caret(at: link.location + 3)
 83        h.editor.revealCaretLine()
 84
 85        let box = try #require(Self.box(h, at: link.location))
 86        #expect(box.inText && box.below)
 87        let storage = try #require(h.textView.textStorage)
 88        #expect(storage.attribute(.kern, at: link.location, effectiveRange: nil) == nil)
 89        let fragment = try #require(Self.fragment(h, at: link.location) as? ImageFragment)
 90        let lines = fragment.textLineFragments.filter { $0.characterRange.length > 0 }
 91        #expect(lines.allSatisfy { $0.typographicBounds.height < 30 })
 92        let frame = try #require(ImageFragment.frames(of: fragment).first).frame
 93        #expect(frame.minY >= lines.last!.typographicBounds.maxY)
 94        #expect(fragment.layoutFragmentFrame.height >= frame.maxY)
 95
 96        // Away again, the image is back in the text.
 97        h.caret(at: 0)
 98        h.editor.revealCaretLine()
 99        #expect(Self.box(h, at: link.location)?.below == false)
100    }
101
102    @Test func aLinkAloneKeepsItsLineAndATableRowShowsEachImage() throws {
103        let folder = try Self.folder()
104        defer { try? FileManager.default.removeItem(at: folder) }
105        let h = Self.harness(folder)
106        let ns = Self.text as NSString
107        h.editor.run("org.toggle-inline-images")
108
109        let alone = ns.range(of: "\n[[file:pic.png]]\n").location + 1
110        let box = try #require(Self.box(h, at: alone))
111        #expect(!box.inText && !box.below)
112        #expect(Self.box(h, at: alone + 5) === box)
113
114        let row = ns.range(of: "| a |").location
115        let fragment = try #require(Self.fragment(h, at: row) as? ImageFragment)
116        let frames = ImageFragment.frames(of: fragment).map(\.frame)
117        #expect(frames.count == 2 && frames[1].minX >= frames[0].maxX)
118        #expect(fragment.textLineFragments[0].typographicBounds.height >= 59)
119    }
120
121    /// Images wider than the text fit it, and fit it again when the view's width changes.
122    @Test func wideImagesFollowTheViewsWidth() async throws {
123        let folder = try Self.folder()
124        defer { try? FileManager.default.removeItem(at: folder) }
125        let h = Harness("* Wide\n[[file:wide.png]]\nIn text [[file:wide.png]] here\n")
126        h.editor.baseDirectory = folder
127        h.editor.run("org.toggle-inline-images")
128        func widths() -> [CGFloat] { [7, 33].compactMap { Self.box(h, at: $0)?.size.width } }
129        let container = try #require(h.textView.textContainer).size.width
130        #expect(container > 300 && widths() == [container - 40, container - 40])
131
132        h.window.setContentSize(NSSize(width: 420, height: 800))
133        h.window.contentView?.layoutSubtreeIfNeeded()
134        try await Task.sleep(for: .milliseconds(100))
135        let narrower = try #require(h.textView.textContainer).size.width
136        #expect(narrower < container && widths() == [narrower - 40, narrower - 40])
137    }
138
139    @Test func describedLinksNeedTheirCommandAndMissingFilesStayLinks() throws {
140        let folder = try Self.folder()
141        defer { try? FileManager.default.removeItem(at: folder) }
142        let h = Self.harness(folder)
143        let ns = Self.text as NSString
144        let described = ns.range(of: "[[file:pic.png][a figure]]").location
145        let missing = ns.range(of: "[[file:missing.png]]").location
146        var messages: [String] = []
147        h.editor.onMessage = { messages.append($0) }
148
149        h.editor.run("org.toggle-inline-images")
150        #expect(Self.box(h, at: described) == nil && Self.box(h, at: missing) == nil)
151        h.editor.run("org.toggle-inline-images-linked")
152        #expect(!h.editor.showsImages && Self.box(h, at: ns.range(of: "[[file:pic.png]]").location) == nil)
153        h.editor.run("org.toggle-inline-images-linked")
154        #expect(h.editor.showsImages && Self.box(h, at: described)?.inText == true && Self.box(h, at: missing) == nil)
155        #expect(messages == ["4 images displayed inline", "Inline image display turned off", "5 images displayed inline"])
156    }
157}