Commit 4e8f923e9d

4e8f923e9db9ee53f2c3ed3614e827ba046c0d47

parent: 09c5ecd551

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-22 08:13 UTC

Fit inline images to the Mac editor's width when it changes

Images shown as a file opened were sized before the view had its width,
and were not sized again when the window was resized.

Ref #113

Layout: unified · split

Sources/OrgEditorAppKit/Keys.swift +9
@@ -59,10 +59,19 @@ final class OrgTextView: NSTextView {
59 didSet { if textWidth != oldValue { updateGutter() } } 59 didSet { if textWidth != oldValue { updateGutter() } }
60 } 60 }
61 61
62 /// The view has another width; during a live resize, called once at its end.
63 var onWidthChange: (() -> Void)?
64
62 override func setFrameSize(_ newSize: NSSize) { 65 override func setFrameSize(_ newSize: NSSize) {
63 let widthChanged = newSize.width != frame.width 66 let widthChanged = newSize.width != frame.width
64 super.setFrameSize(newSize) 67 super.setFrameSize(newSize)
65 if widthChanged, textWidth > 0 { updateGutter() } 68 if widthChanged, textWidth > 0 { updateGutter() }
69 if widthChanged, !inLiveResize { onWidthChange?() }
70 }
71
72 override func viewDidEndLiveResize() {
73 super.viewDidEndLiveResize()
74 onWidthChange?()
66 } 75 }
67 var lineNumbersType = LineNumbersType.absolute { 76 var lineNumbersType = LineNumbersType.absolute {
68 didSet { if lineNumbersType != oldValue { needsDisplay = true } } 77 didSet { if lineNumbersType != oldValue { needsDisplay = true } }
Sources/OrgEditorAppKit/OrgEditor+Images.swift +16 −1
@@ -31,6 +31,20 @@ extension OrgEditor {
31 redrawViews() 31 redrawViews()
32 } 32 }
33 33
34 /// The widest an image shows: the text's width, less a margin.
35 private var imageMaxWidth: CGFloat { max(80, (textView.textContainer?.size.width ?? 600) - 40) }
36
37 /// Sizes images again once the view's width has changed, after the layout pass that changed it.
38 func fitImages() {
39 guard showsImages, !fittingImages else { return }
40 fittingImages = true
41 DispatchQueue.main.async { [weak self] in
42 guard let self else { return }
43 self.fittingImages = false
44 if self.showsImages, self.imageWidth != self.imageMaxWidth { self.refreshImages() }
45 }
46 }
47
34 /// `attachment:` links' files, for inline images. 48 /// `attachment:` links' files, for inline images.
35 private var attachment: ((String, Int) -> String?)? { 49 private var attachment: ((String, Int) -> String?)? {
36 guard let attachmentPath else { return nil } 50 guard let attachmentPath else { return nil }
@@ -68,7 +82,8 @@ extension OrgEditor {
68 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) { 82 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
69 guard showsImages, isOrg else { return } 83 guard showsImages, isOrg else { return }
70 let text = storage.string as NSString 84 let text = storage.string as NSString
71 let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40) 85 let maxWidth = imageMaxWidth
86 imageWidth = maxWidth
72 let links = InlineImages.links(document.tree, in: range, includeLinked: imagesIncludeLinked, remote: remote, attachment: attachment) 87 let links = InlineImages.links(document.tree, in: range, includeLinked: imagesIncludeLinked, remote: remote, attachment: attachment)
73 for placement in Presentation.imagePlacements(links, in: text) { 88 for placement in Presentation.imagePlacements(links, in: text) {
74 guard let picture = loadImage(placement.link.image.path) else { continue } 89 guard let picture = loadImage(placement.link.image.path) else { continue }
Sources/OrgEditorAppKit/OrgEditor.swift +4
@@ -184,6 +184,7 @@ public final class OrgEditor: NSObject {
184 onImage(data, ext) 184 onImage(data, ext)
185 return true 185 return true
186 } 186 }
187 view.onWidthChange = { [weak self] in self?.fitImages() }
187 view.onMouseDown = { [weak self, unowned view] in 188 view.onMouseDown = { [weak self, unowned view] in
188 self?.active = view 189 self?.active = view
189 self?.markActive = false 190 self?.markActive = false
@@ -708,6 +709,9 @@ public final class OrgEditor: NSObject {
708 public internal(set) var showsImages = false 709 public internal(set) var showsImages = false
709 /// Links with a description show their image too. 710 /// Links with a description show their image too.
710 var imagesIncludeLinked = false 711 var imagesIncludeLinked = false
712 /// The width images were last sized for, and whether sizing them again is waiting.
713 var imageWidth: CGFloat = 0
714 var fittingImages = false
711 /// `org-latex-preview`: LaTeX fragments show as typeset math. 715 /// `org-latex-preview`: LaTeX fragments show as typeset math.
712 public internal(set) var showsLatex = false 716 public internal(set) var showsLatex = false
713 /// An `attachment:` link's file, from its name, offset and the tree: the app's 717 /// An `attachment:` link's file, from its name, offset and the tree: the app's
Tests/OrgEditorAppKitTests/InlineImagesEditorTests.swift +26 −6
@@ -9,15 +9,17 @@ struct InlineImagesEditorTests {
9 static let text = "* Images\n\(filler)[[file:pic.png]] \(filler)\n[[file:pic.png]]\n| a | [[file:pic.png]] | [[./pic.png]] |\n" 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" 10 + "Described [[file:pic.png][a figure]] here\nMissing [[file:missing.png]] here\n"
11 11
12 /// A folder holding `pic.png`, 100 by 60 points. 12 /// A folder holding `pic.png`, 100 by 60 points, and `wide.png`, 2000 by 100.
13 static func folder() throws -> URL { 13 static func folder() throws -> URL {
14 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-images-\(UUID().uuidString)") 14 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-images-\(UUID().uuidString)")
15 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 15 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
16 let bitmap = try #require(NSBitmapImageRep( 16 for (name, width, height) in [("pic.png", 100, 60), ("wide.png", 2000, 100)] {
17 bitmapDataPlanes: nil, pixelsWide: 100, pixelsHigh: 60, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, 17 let bitmap = try #require(NSBitmapImageRep(
18 colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0 18 bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
19 )) 19 colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0
20 try #require(bitmap.representation(using: .png, properties: [:])).write(to: folder.appendingPathComponent("pic.png")) 20 ))
21 try #require(bitmap.representation(using: .png, properties: [:])).write(to: folder.appendingPathComponent(name))
22 }
21 return folder 23 return folder
22 } 24 }
23 25
@@ -116,6 +118,24 @@ struct InlineImagesEditorTests {
116 #expect(fragment.textLineFragments[0].typographicBounds.height >= 59) 118 #expect(fragment.textLineFragments[0].typographicBounds.height >= 59)
117 } 119 }
118 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
119 @Test func describedLinksNeedTheirCommandAndMissingFilesStayLinks() throws { 139 @Test func describedLinksNeedTheirCommandAndMissingFilesStayLinks() throws {
120 let folder = try Self.folder() 140 let folder = try Self.folder()
121 defer { try? FileManager.default.removeItem(at: folder) } 141 defer { try? FileManager.default.removeItem(at: folder) }
docs/manual/guide/09-links.org +1 −1
@@ -633,7 +633,7 @@ Insert Link. Setting up a browser bookmarklet, and =org-protocol://capture=, are
633 633
634The iOS app follows links: tap a link in the reader. Org files open in the app, and 634The iOS app follows links: tap a link in the reader. Org files open in the app, and
635web, mail and other files go to the system. The iOS editor shows inline images as the 635web, mail and other files go to the system. The iOS editor shows inline images as the
636Mac does; the reader doesn't. In the editor, Store Link, Store ID Link and Insert Link… 636Mac does, and so does the reader, except in headings. In the editor, Store Link, Store ID Link and Insert Link…
637are in Commands, and on a hardware keyboard the Emacs keys run them; they work as 637are in Commands, and on a hardware keyboard the Emacs keys run them; they work as
638described above, and stored links last until the app quits. =org-protocol://store-link= 638described above, and stored links last until the app quits. =org-protocol://store-link=
639links opened on the device are stored and copied too. More ▸ Backlinks lists the same 639links opened on the device are stored and copied too. More ▸ Backlinks lists the same