Remote inline images !282
13 files changed, +208 −15
Layout: unified · split
Sources/OrgApp/EmacsImport.swift +3
| @@ -543,6 +543,9 @@ public struct EmacsImport: Sendable { | |||
| 543 | else if let keywords = value.elements?.compactMap(\.string), !keywords.isEmpty, keywords.count == value.elements?.count { | 543 | else if let keywords = value.elements?.compactMap(\.string), !keywords.isEmpty, keywords.count == value.elements?.count { |
| 544 | add(name, .string(keywords.joined(separator: " "))) | 544 | add(name, .string(keywords.joined(separator: " "))) |
| 545 | } else { note("unexpected value \(value.description)") } | 545 | } else { note("unexpected value \(value.description)") } |
| 546 | case "org-display-remote-inline-images": | ||
| 547 | guard let mode = value.symbol, ["skip", "download", "cache"].contains(mode) else { return note("not skip, download or cache") } | ||
| 548 | add(name, .string(mode)) | ||
| 546 | case "org-icalendar-combined-agenda-file": | 549 | case "org-icalendar-combined-agenda-file": |
| 547 | guard let file = value.string ?? Self.evaluate(value, env)?.string else { return note("not a file name") } | 550 | guard let file = value.string ?? Self.evaluate(value, env)?.string else { return note("not a file name") } |
| 548 | add(name, .string(file)) | 551 | add(name, .string(file)) |
Sources/OrgApp/OrgPreferences.swift +1
| @@ -36,6 +36,7 @@ public enum OrgPreferences { | |||
| 36 | ) | 36 | ) |
| 37 | options.electricPair = bool("electricPair", defaults) | 37 | options.electricPair = bool("electricPair", defaults) |
| 38 | options.startupWithLatexPreview = bool("startupWithLatexPreview", defaults) | 38 | options.startupWithLatexPreview = bool("startupWithLatexPreview", defaults) |
| 39 | options.remoteInlineImages = string("remoteInlineImages", defaults) | ||
| 39 | options.enforceTodoDependencies = bool("enforceTodoDependencies", defaults) | 40 | options.enforceTodoDependencies = bool("enforceTodoDependencies", defaults) |
| 40 | options.enforceTodoCheckboxDependencies = bool("enforceTodoCheckboxDependencies", defaults) | 41 | options.enforceTodoCheckboxDependencies = bool("enforceTodoCheckboxDependencies", defaults) |
| 41 | options.archiveLocation = string("archiveLocation", defaults).nonEmpty | 42 | options.archiveLocation = string("archiveLocation", defaults).nonEmpty |
Sources/OrgApp/UserConfig.swift +3
| @@ -147,6 +147,9 @@ public enum UserConfig { | |||
| 147 | comment: "show image links as images when a file opens; #+STARTUP: (no)inlineimages overrides", legacy: ""), | 147 | comment: "show image links as images when a file opens; #+STARTUP: (no)inlineimages overrides", legacy: ""), |
| 148 | Setting(section: "", key: "org-startup-with-latex-preview", defaultsKey: "startupWithLatexPreview", kind: .bool, fallback: .bool(false), | 148 | Setting(section: "", key: "org-startup-with-latex-preview", defaultsKey: "startupWithLatexPreview", kind: .bool, fallback: .bool(false), |
| 149 | comment: "show LaTeX fragments as typeset math when a file opens; #+STARTUP: (no)latexpreview overrides", legacy: ""), | 149 | comment: "show LaTeX fragments as typeset math when a file opens; #+STARTUP: (no)latexpreview overrides", legacy: ""), |
| 150 | Setting(section: "", key: "org-display-remote-inline-images", defaultsKey: "remoteInlineImages", | ||
| 151 | kind: .choice([("skip", "skip"), ("download", "download"), ("cache", "cache")]), fallback: .string("skip"), | ||
| 152 | comment: "images at http(s) links: skip, download (each run) or cache (kept on disk)", legacy: ""), | ||
| 150 | Setting(section: "", key: "org-use-speed-commands", defaultsKey: "useSpeedCommands", kind: .bool, fallback: .bool(false), | 153 | Setting(section: "", key: "org-use-speed-commands", defaultsKey: "useSpeedCommands", kind: .bool, fallback: .bool(false), |
| 151 | comment: "single keys at the start of a heading line run commands (n, p, t, c, …)", legacy: ""), | 154 | comment: "single keys at the start of a heading line run commands (n, p, t, c, …)", legacy: ""), |
| 152 | Setting(section: "", key: "org-cycle-hide-drawer-startup", defaultsKey: "hideDrawerStartup", kind: .bool, fallback: .bool(true), | 155 | Setting(section: "", key: "org-cycle-hide-drawer-startup", defaultsKey: "hideDrawerStartup", kind: .bool, fallback: .bool(true), |
Sources/OrgCore/Commands/Command.swift +2
| @@ -56,6 +56,8 @@ public struct EditingOptions: Sendable, Equatable, Codable { | |||
| 56 | public var startupWithInlineImages: Bool | 56 | public var startupWithInlineImages: Bool |
| 57 | /// `org-startup-with-latex-preview`. | 57 | /// `org-startup-with-latex-preview`. |
| 58 | public var startupWithLatexPreview = false | 58 | public var startupWithLatexPreview = false |
| 59 | /// `org-display-remote-inline-images`: `skip`, `download` or `cache`. | ||
| 60 | public var remoteInlineImages = "skip" | ||
| 59 | /// `org-startup-indented`: org-indent's virtual indentation. | 61 | /// `org-startup-indented`: org-indent's virtual indentation. |
| 60 | public var startupIndented = true | 62 | public var startupIndented = true |
| 61 | /// `org-hide-leading-stars`; org-indent hides them too. | 63 | /// `org-hide-leading-stars`; org-indent hides them too. |
Sources/OrgCore/Commands/InlineImages.swift +7 −3
| @@ -11,13 +11,17 @@ public enum InlineImages { | |||
| 11 | static let extensions = "png|jpe?g|gif|svg|webp|tiff?|bmp|heic|avif" | 11 | static let extensions = "png|jpe?g|gif|svg|webp|tiff?|bmp|heic|avif" |
| 12 | static let pattern = try! NSRegularExpression(pattern: "^[ \\t]*\\[\\[(?:file:)?([^\\]\\n]+\\.(?:\(extensions)))\\]\\][ \\t]*$", options: .caseInsensitive) | 12 | static let pattern = try! NSRegularExpression(pattern: "^[ \\t]*\\[\\[(?:file:)?([^\\]\\n]+\\.(?:\(extensions)))\\]\\][ \\t]*$", options: .caseInsensitive) |
| 13 | 13 | ||
| 14 | /// The image on the line at `lineStart`, if the line is an image link. | 14 | /// The image on the line at `lineStart`, if the line is an image link; with `remote`, |
| 15 | public static func image(atLine lineStart: Int, in text: NSString) -> Image? { | 15 | /// http and https links too (`org-display-remote-inline-images` other than `skip`). |
| 16 | public static func image(atLine lineStart: Int, in text: NSString, remote: Bool = false) -> Image? { | ||
| 16 | let line = text.lineRange(for: NSRange(location: lineStart, length: 0)) | 17 | let line = text.lineRange(for: NSRange(location: lineStart, length: 0)) |
| 17 | let content = text.substring(with: line).trimmingCharacters(in: .newlines) | 18 | let content = text.substring(with: line).trimmingCharacters(in: .newlines) |
| 18 | guard let m = pattern.firstMatch(in: content, range: NSRange(location: 0, length: (content as NSString).length)) else { return nil } | 19 | guard let m = pattern.firstMatch(in: content, range: NSRange(location: 0, length: (content as NSString).length)) else { return nil } |
| 19 | let path = (content as NSString).substring(with: m.range(at: 1)) | 20 | let path = (content as NSString).substring(with: m.range(at: 1)) |
| 20 | guard !path.contains("://"), !path.hasPrefix("attachment:") else { return nil } | 21 | guard !path.hasPrefix("attachment:") else { return nil } |
| 22 | if path.contains("://") { | ||
| 23 | guard remote, path.range(of: "^https?://", options: [.regularExpression, .caseInsensitive]) != nil else { return nil } | ||
| 24 | } | ||
| 21 | // `#+ATTR_ORG: :width N` in the affiliated keywords above. | 25 | // `#+ATTR_ORG: :width N` in the affiliated keywords above. |
| 22 | var width: Int? | 26 | var width: Int? |
| 23 | var at = line.location | 27 | var at = line.location |
Sources/OrgEditorAppKit/OrgEditor+Images.swift +15 −2
| @@ -1,6 +1,7 @@ | |||
| 1 | #if os(macOS) | 1 | #if os(macOS) |
| 2 | import AppKit | 2 | import AppKit |
| 3 | import OrgCore | 3 | import OrgCore |
| 4 | import OrgPresentation | ||
| 4 | 5 | ||
| 5 | extension OrgEditor { | 6 | extension OrgEditor { |
| 6 | // MARK: - Inline images | 7 | // MARK: - Inline images |
| @@ -16,7 +17,7 @@ extension OrgEditor { | |||
| 16 | var offset = 0 | 17 | var offset = 0 |
| 17 | while offset < ns.length { | 18 | while offset < ns.length { |
| 18 | let line = ns.lineRange(for: NSRange(location: offset, length: 0)) | 19 | let line = ns.lineRange(for: NSRange(location: offset, length: 0)) |
| 19 | if let image = InlineImages.image(atLine: line.location, in: ns), loadImage(image.path) != nil { count += 1 } | 20 | if let image = InlineImages.image(atLine: line.location, in: ns, remote: remote), loadImage(image.path) != nil { count += 1 } |
| 20 | offset = NSMaxRange(line) | 21 | offset = NSMaxRange(line) |
| 21 | } | 22 | } |
| 22 | onMessage?("\(count) images displayed inline") | 23 | onMessage?("\(count) images displayed inline") |
| @@ -33,7 +34,19 @@ extension OrgEditor { | |||
| 33 | redrawViews() | 34 | redrawViews() |
| 34 | } | 35 | } |
| 35 | 36 | ||
| 37 | /// Whether http(s) links show, as `org-display-remote-inline-images` says. | ||
| 38 | private var remote: Bool { options.remoteInlineImages != "skip" } | ||
| 39 | |||
| 36 | private func loadImage(_ path: String) -> NSImage? { | 40 | private func loadImage(_ path: String) -> NSImage? { |
| 41 | if path.contains("://") { | ||
| 42 | guard let url = URL(string: path) else { return nil } | ||
| 43 | let mode = RemoteImages.Mode(rawValue: options.remoteInlineImages) ?? .skip | ||
| 44 | let data = RemoteImages.shared.data(for: url, mode: mode) { [weak self] in | ||
| 45 | guard let self, self.showsImages else { return } | ||
| 46 | self.refreshImages() | ||
| 47 | } | ||
| 48 | return data.flatMap(NSImage.init(data:)) | ||
| 49 | } | ||
| 37 | let expanded = (path as NSString).expandingTildeInPath | 50 | let expanded = (path as NSString).expandingTildeInPath |
| 38 | let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded) | 51 | let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded) |
| 39 | let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0 | 52 | let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0 |
| @@ -54,7 +67,7 @@ extension OrgEditor { | |||
| 54 | while location < range.upperBound, location < text.length { | 67 | while location < range.upperBound, location < text.length { |
| 55 | let line = text.lineRange(for: NSRange(location: location, length: 0)) | 68 | let line = text.lineRange(for: NSRange(location: location, length: 0)) |
| 56 | location = NSMaxRange(line) | 69 | location = NSMaxRange(line) |
| 57 | guard let image = InlineImages.image(atLine: line.location, in: text), let picture = loadImage(image.path) else { continue } | 70 | guard let image = InlineImages.image(atLine: line.location, in: text, remote: remote), let picture = loadImage(image.path) else { continue } |
| 58 | var width = image.width.map(CGFloat.init) ?? picture.size.width | 71 | var width = image.width.map(CGFloat.init) ?? picture.size.width |
| 59 | width = min(width, maxWidth) | 72 | width = min(width, maxWidth) |
| 60 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 | 73 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 |
Sources/OrgPresentation/RemoteImages.swift added +74
| @@ -0,0 +1,74 @@ | |||
| 1 | import CryptoKit | ||
| 2 | import Foundation | ||
| 3 | import Observation | ||
| 4 | |||
| 5 | /// `org-display-remote-inline-images`: images at http and https links, fetched in the | ||
| 6 | /// background. `download` keeps them while the app runs; `cache` keeps them on disk too. | ||
| 7 | @MainActor | ||
| 8 | @Observable | ||
| 9 | public final class RemoteImages { | ||
| 10 | public static let shared = RemoteImages() | ||
| 11 | |||
| 12 | public enum Mode: String, Sendable { | ||
| 13 | case skip, download, cache | ||
| 14 | } | ||
| 15 | |||
| 16 | /// Changes when an image arrives, for views that show them. | ||
| 17 | public private(set) var version = 0 | ||
| 18 | @ObservationIgnored private var memory: [URL: Data] = [:] | ||
| 19 | @ObservationIgnored private var loading: Set<URL> = [] | ||
| 20 | @ObservationIgnored private var failed: Set<URL> = [] | ||
| 21 | @ObservationIgnored private var waiting: [URL: [@MainActor () -> Void]] = [:] | ||
| 22 | @ObservationIgnored let directory: URL | ||
| 23 | @ObservationIgnored let fetch: @Sendable (URL) async throws -> Data | ||
| 24 | |||
| 25 | public init(directory: URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("RemoteImages"), | ||
| 26 | fetch: @escaping @Sendable (URL) async throws -> Data = RemoteImages.download) { | ||
| 27 | self.directory = directory | ||
| 28 | self.fetch = fetch | ||
| 29 | } | ||
| 30 | |||
| 31 | /// An http(s) GET; other statuses than 2xx fail. | ||
| 32 | public nonisolated static func download(_ url: URL) async throws -> Data { | ||
| 33 | let (data, response) = try await URLSession.shared.data(from: url) | ||
| 34 | if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { throw URLError(.badServerResponse) } | ||
| 35 | return data | ||
| 36 | } | ||
| 37 | |||
| 38 | /// The image's data when it's here; otherwise nil, and `loaded` runs when it has come. | ||
| 39 | /// A link that failed isn't fetched again while the app runs. | ||
| 40 | public func data(for url: URL, mode: Mode, loaded: @escaping @MainActor () -> Void) -> Data? { | ||
| 41 | guard mode != .skip, let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else { return nil } | ||
| 42 | if let data = memory[url] { return data } | ||
| 43 | if mode == .cache, let data = try? Data(contentsOf: file(url)) { | ||
| 44 | memory[url] = data | ||
| 45 | return data | ||
| 46 | } | ||
| 47 | guard !failed.contains(url) else { return nil } | ||
| 48 | waiting[url, default: []].append(loaded) | ||
| 49 | guard loading.insert(url).inserted else { return nil } | ||
| 50 | let fetch = self.fetch | ||
| 51 | Task { | ||
| 52 | let data = try? await fetch(url) | ||
| 53 | loading.remove(url) | ||
| 54 | if let data { | ||
| 55 | memory[url] = data | ||
| 56 | if mode == .cache { | ||
| 57 | try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) | ||
| 58 | try? data.write(to: file(url), options: .atomic) | ||
| 59 | } | ||
| 60 | } else { | ||
| 61 | failed.insert(url) | ||
| 62 | } | ||
| 63 | version += 1 | ||
| 64 | for callback in waiting.removeValue(forKey: url) ?? [] { callback() } | ||
| 65 | } | ||
| 66 | return nil | ||
| 67 | } | ||
| 68 | |||
| 69 | /// The cached copy's file, named by a hash of the link. | ||
| 70 | func file(_ url: URL) -> URL { | ||
| 71 | let hash = SHA256.hash(data: Data(url.absoluteString.utf8)).map { String(format: "%02x", $0) }.joined() | ||
| 72 | return directory.appendingPathComponent(hash + (url.pathExtension.isEmpty ? "" : "." + url.pathExtension)) | ||
| 73 | } | ||
| 74 | } | ||
Sources/OrgstarMobile/MobileEditor+Display.swift +20 −4
| @@ -60,7 +60,8 @@ extension MobileEditor { | |||
| 60 | var offset = 0 | 60 | var offset = 0 |
| 61 | while offset < ns.length { | 61 | while offset < ns.length { |
| 62 | let line = ns.lineRange(for: NSRange(location: offset, length: 0)) | 62 | let line = ns.lineRange(for: NSRange(location: offset, length: 0)) |
| 63 | if let image = InlineImages.image(atLine: line.location, in: ns), Self.loadImage(image.path, relativeTo: baseDirectory) != nil { count += 1 } | 63 | if let image = InlineImages.image(atLine: line.location, in: ns, remote: options.remoteInlineImages != "skip"), |
| 64 | loadImage(image.path) != nil { count += 1 } | ||
| 64 | offset = NSMaxRange(line) | 65 | offset = NSMaxRange(line) |
| 65 | } | 66 | } |
| 66 | onMessage?("\(count) images displayed inline") | 67 | onMessage?("\(count) images displayed inline") |
| @@ -69,8 +70,22 @@ extension MobileEditor { | |||
| 69 | } | 70 | } |
| 70 | } | 71 | } |
| 71 | 72 | ||
| 72 | /// An image link's image, by its path or one relative to `baseDirectory`. | 73 | /// An image link's image here: remote ones as `org-display-remote-inline-images` says, |
| 73 | static func loadImage(_ path: String, relativeTo baseDirectory: URL?) -> UIImage? { | 74 | /// restyled when they come. |
| 75 | func loadImage(_ path: String) -> UIImage? { | ||
| 76 | Self.loadImage(path, relativeTo: baseDirectory, remote: RemoteImages.Mode(rawValue: options.remoteInlineImages) ?? .skip) { [weak self] in | ||
| 77 | guard let self, self.showsImages else { return } | ||
| 78 | self.restyleAll() | ||
| 79 | } | ||
| 80 | } | ||
| 81 | |||
| 82 | /// An image link's image, by its path or one relative to `baseDirectory`; an http(s) | ||
| 83 | /// link's when `remote` allows it and it has come, `loaded` running when it does. | ||
| 84 | static func loadImage(_ path: String, relativeTo baseDirectory: URL?, remote: RemoteImages.Mode = .skip, loaded: @escaping @MainActor () -> Void = {}) -> UIImage? { | ||
| 85 | if path.contains("://") { | ||
| 86 | guard let url = URL(string: path) else { return nil } | ||
| 87 | return RemoteImages.shared.data(for: url, mode: remote, loaded: loaded).flatMap(UIImage.init(data:)) | ||
| 88 | } | ||
| 74 | let expanded = (path as NSString).expandingTildeInPath | 89 | let expanded = (path as NSString).expandingTildeInPath |
| 75 | let url: URL | 90 | let url: URL |
| 76 | if expanded.hasPrefix("/") { | 91 | if expanded.hasPrefix("/") { |
| @@ -99,7 +114,8 @@ extension MobileEditor { | |||
| 99 | while location < range.upperBound, location < text.length { | 114 | while location < range.upperBound, location < text.length { |
| 100 | let line = text.lineRange(for: NSRange(location: location, length: 0)) | 115 | let line = text.lineRange(for: NSRange(location: location, length: 0)) |
| 101 | location = NSMaxRange(line) | 116 | location = NSMaxRange(line) |
| 102 | guard let image = InlineImages.image(atLine: line.location, in: text), let picture = Self.loadImage(image.path, relativeTo: baseDirectory) else { continue } | 117 | guard let image = InlineImages.image(atLine: line.location, in: text, remote: options.remoteInlineImages != "skip"), |
| 118 | let picture = loadImage(image.path) else { continue } | ||
| 103 | let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth) | 119 | let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth) |
| 104 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 | 120 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 |
| 105 | let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0)) | 121 | let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0)) |
Sources/OrgstarMobile/ReaderScreen.swift +5 −2
| @@ -211,6 +211,9 @@ struct ReaderScreen: View { | |||
| 211 | /// Text, and with inline images on, lines that are only an image link shown as the image. | 211 | /// Text, and with inline images on, lines that are only an image link shown as the image. |
| 212 | private func parts(_ tree: OrgTree, _ range: Range<Int>) -> [Part] { | 212 | private func parts(_ tree: OrgTree, _ range: Range<Int>) -> [Part] { |
| 213 | guard startup?.inlineImages == true, let path = session.path else { return [Part(range: range)] } | 213 | guard startup?.inlineImages == true, let path = session.path else { return [Part(range: range)] } |
| 214 | // Read so that the view draws again when a remote image arrives. | ||
| 215 | _ = RemoteImages.shared.version | ||
| 216 | let remote = RemoteImages.Mode(rawValue: session.options.remoteInlineImages) ?? .skip | ||
| 214 | let base = URL(fileURLWithPath: path).deletingLastPathComponent() | 217 | let base = URL(fileURLWithPath: path).deletingLastPathComponent() |
| 215 | let ns = tree.text as NSString | 218 | let ns = tree.text as NSString |
| 216 | var parts: [Part] = [] | 219 | var parts: [Part] = [] |
| @@ -219,8 +222,8 @@ struct ReaderScreen: View { | |||
| 219 | while location < range.upperBound { | 222 | while location < range.upperBound { |
| 220 | let line = ns.lineRange(for: NSRange(location: location, length: 0)) | 223 | let line = ns.lineRange(for: NSRange(location: location, length: 0)) |
| 221 | location = NSMaxRange(line) | 224 | location = NSMaxRange(line) |
| 222 | guard folded.allSatisfy({ !$0.contains(line.location) }), let image = InlineImages.image(atLine: line.location, in: ns), | 225 | guard folded.allSatisfy({ !$0.contains(line.location) }), let image = InlineImages.image(atLine: line.location, in: ns, remote: remote != .skip), |
| 223 | let picture = MobileEditor.loadImage(image.path, relativeTo: base) else { continue } | 226 | let picture = MobileEditor.loadImage(image.path, relativeTo: base, remote: remote) else { continue } |
| 224 | if textStart < line.location { parts.append(Part(range: textStart..<line.location)) } | 227 | if textStart < line.location { parts.append(Part(range: textStart..<line.location)) } |
| 225 | parts.append(Part(range: line.location..<min(NSMaxRange(line), range.upperBound), image: (picture, image.path, image.width))) | 228 | parts.append(Part(range: line.location..<min(NSMaxRange(line), range.upperBound), image: (picture, image.path, image.width))) |
| 226 | textStart = min(NSMaxRange(line), range.upperBound) | 229 | textStart = min(NSMaxRange(line), range.upperBound) |
Tests/OrgPresentationTests/RemoteImagesTests.swift added +51
| @@ -0,0 +1,51 @@ | |||
| 1 | import Foundation | ||
| 2 | import OrgCore | ||
| 3 | @testable import OrgPresentation | ||
| 4 | import Testing | ||
| 5 | |||
| 6 | @MainActor | ||
| 7 | struct RemoteImagesTests { | ||
| 8 | final class Counter: @unchecked Sendable { | ||
| 9 | var calls = 0 | ||
| 10 | } | ||
| 11 | |||
| 12 | @Test func linksNeedTheSetting() { | ||
| 13 | let text = "[[https://example.com/a.png]]\n[[ftp://example.com/b.png]]\n[[file:c.png]]\n" as NSString | ||
| 14 | #expect(InlineImages.image(atLine: 0, in: text) == nil) | ||
| 15 | #expect(InlineImages.image(atLine: 0, in: text, remote: true)?.path == "https://example.com/a.png") | ||
| 16 | #expect(InlineImages.image(atLine: 30, in: text, remote: true) == nil) | ||
| 17 | #expect(InlineImages.image(atLine: 58, in: text, remote: true)?.path == "c.png") | ||
| 18 | } | ||
| 19 | |||
| 20 | @Test func downloadsOnceAndCaches() async throws { | ||
| 21 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-remote-\(UUID().uuidString)") | ||
| 22 | defer { try? FileManager.default.removeItem(at: folder) } | ||
| 23 | let counter = Counter() | ||
| 24 | let images = RemoteImages(directory: folder) { url in | ||
| 25 | counter.calls += 1 | ||
| 26 | if url.lastPathComponent == "missing.png" { throw URLError(.badServerResponse) } | ||
| 27 | return Data("image".utf8) | ||
| 28 | } | ||
| 29 | let url = URL(string: "https://example.com/a.png")! | ||
| 30 | #expect(images.data(for: url, mode: .skip) {} == nil) | ||
| 31 | var arrived = false | ||
| 32 | #expect(images.data(for: url, mode: .cache) { arrived = true } == nil) | ||
| 33 | #expect(images.data(for: url, mode: .cache) {} == nil) | ||
| 34 | while !arrived { try await Task.sleep(for: .milliseconds(10)) } | ||
| 35 | #expect(images.data(for: url, mode: .cache) {} == Data("image".utf8)) | ||
| 36 | #expect(counter.calls == 1) | ||
| 37 | // A new run reads the cached copy. | ||
| 38 | let again = RemoteImages(directory: folder) { _ in Issue.record("fetched again"); return Data() } | ||
| 39 | #expect(again.data(for: url, mode: .cache) {} == Data("image".utf8)) | ||
| 40 | #expect(again.data(for: url, mode: .download) {} == Data("image".utf8)) | ||
| 41 | |||
| 42 | let missing = URL(string: "https://example.com/missing.png")! | ||
| 43 | var done = false | ||
| 44 | #expect(images.data(for: missing, mode: .download) { done = true } == nil) | ||
| 45 | while !done { try await Task.sleep(for: .milliseconds(10)) } | ||
| 46 | #expect(images.data(for: missing, mode: .download) {} == nil) | ||
| 47 | #expect(counter.calls == 2) | ||
| 48 | #expect(images.version == 2) | ||
| 49 | #expect(images.data(for: URL(string: "file:///tmp/a.png")!, mode: .cache) {} == nil) | ||
| 50 | } | ||
| 51 | } | ||
docs/manual/guide/02-the-editor.org +1 −1
| @@ -66,7 +66,7 @@ A line shows as an image when it holds nothing but a link to an image file with | |||
| 66 | #+END_SRC | 66 | #+END_SRC |
| 67 | 67 | ||
| 68 | - Recognised extensions: =png=, =jpg=, =jpeg=, =gif=, =svg=, =webp=, =tif=, =tiff=, =bmp=, =heic=, =avif=. | 68 | - Recognised extensions: =png=, =jpg=, =jpeg=, =gif=, =svg=, =webp=, =tif=, =tiff=, =bmp=, =heic=, =avif=. |
| 69 | - Paths are relative to the file's folder; =~= is expanded. Remote URLs are not displayed. | 69 | - Paths are relative to the file's folder; =~= is expanded. Images at http(s) links show when =org-display-remote-inline-images= is =download= or =cache=; see [[file:09-links.org::*Remote images][Remote images]]. |
| 70 | - =#+ATTR_ORG: :width N= sets the width in points. Images are never wider than the editor. | 70 | - =#+ATTR_ORG: :width N= sets the width in points. Images are never wider than the editor. |
| 71 | - The link text is hidden while its image shows, except on the caret's line. | 71 | - The link text is hidden while its image shows, except on the caret's line. |
| 72 | 72 | ||
docs/manual/guide/09-links.org +23 −3
| @@ -302,9 +302,29 @@ to a file ending in =.png=, =.jpg=, =.jpeg=, =.gif=, =.svg=, =.webp=, =.tif=, =. | |||
| 302 | [[./photo.jpg]] | 302 | [[./photo.jpg]] |
| 303 | #+END_SRC | 303 | #+END_SRC |
| 304 | 304 | ||
| 305 | Relative paths are resolved against the file's folder. Web addresses and | 305 | Relative paths are resolved against the file's folder. =attachment:= links are not |
| 306 | =attachment:= links are not shown as images. The link text is hidden while the image | 306 | shown as images. The link text is hidden while the image is shown, except on the line |
| 307 | is shown, except on the line that holds the caret. | 307 | that holds the caret. |
| 308 | |||
| 309 | ** Remote images | ||
| 310 | |||
| 311 | Images at =http= and =https= links show as =org-display-remote-inline-images= in | ||
| 312 | =config.toml= says: | ||
| 313 | |||
| 314 | | Value | Remote images | | ||
| 315 | |------------+------------------------------------------------------------------------------| | ||
| 316 | | =skip= | Not shown; the default | | ||
| 317 | | =download= | Fetched the first time they're shown, and kept until orgstar quits | | ||
| 318 | | =cache= | Fetched once and kept on disk, in the app's cache folder, for later launches | | ||
| 319 | |||
| 320 | #+BEGIN_SRC org | ||
| 321 | [[https://example.com/chart.png]] | ||
| 322 | #+END_SRC | ||
| 323 | |||
| 324 | An image is fetched in the background; the link shows as text until it arrives. A link | ||
| 325 | that can't be fetched stays text, and isn't tried again until orgstar starts again. This | ||
| 326 | applies to the editor on the Mac and iOS and to the iOS reader. Emacs's =download= | ||
| 327 | fetches the image each time it's displayed; orgstar keeps it for the session instead. | ||
| 308 | 328 | ||
| 309 | ** Sizing | 329 | ** Sizing |
| 310 | 330 | ||
docs/manual/guide/13-configuration.org +3
| @@ -147,6 +147,7 @@ These settings have no control in the Settings window. Some are in the View menu | |||
| 147 | | =org-startup-align-all-tables= | | | 147 | | =org-startup-align-all-tables= | | |
| 148 | | =org-startup-with-inline-images= | | | 148 | | =org-startup-with-inline-images= | | |
| 149 | | =org-startup-with-latex-preview= | | | 149 | | =org-startup-with-latex-preview= | | |
| 150 | | =org-display-remote-inline-images= | | | ||
| 150 | | =org-cycle-hide-drawer-startup= | | | 151 | | =org-cycle-hide-drawer-startup= | | |
| 151 | | =org-cycle-hide-block-startup= | | | 152 | | =org-cycle-hide-block-startup= | | |
| 152 | | =org-use-speed-commands= | | | 153 | | =org-use-speed-commands= | | |
| @@ -214,6 +215,7 @@ A key you remove from the file goes back to its default. A key that isn't in the | |||
| 214 | | =spell-check= | boolean | =false= | Check spelling while typing, outside code, links, dates, tags and keywords. | | 215 | | =spell-check= | boolean | =false= | Check spelling while typing, outside code, links, dates, tags and keywords. | |
| 215 | | =electric-pair-mode= | boolean | =true= | Type brackets, =<>= and quotes in pairs. Mirrors =electric-pair-mode=. | | 216 | | =electric-pair-mode= | boolean | =true= | Type brackets, =<>= and quotes in pairs. Mirrors =electric-pair-mode=. | |
| 216 | | =org-startup-with-inline-images= | boolean | =false= | Show image links as images when a file opens. =#+STARTUP: inlineimages= / =noinlineimages= override it. Mirrors =org-startup-with-inline-images=. | | 217 | | =org-startup-with-inline-images= | boolean | =false= | Show image links as images when a file opens. =#+STARTUP: inlineimages= / =noinlineimages= override it. Mirrors =org-startup-with-inline-images=. | |
| 218 | | =org-display-remote-inline-images= | string | ="skip"= | Images at http(s) links: =skip=, =download= (kept until orgstar quits) or =cache= (kept on disk). See [[file:09-links.org][Links]]. Mirrors =org-display-remote-inline-images=. | | ||
| 217 | | =org-startup-with-latex-preview= | boolean | =false= | Show LaTeX fragments as typeset math when a file opens. =#+STARTUP: latexpreview= / =nolatexpreview= override it. Mirrors =org-startup-with-latex-preview=. | | 219 | | =org-startup-with-latex-preview= | boolean | =false= | Show LaTeX fragments as typeset math when a file opens. =#+STARTUP: latexpreview= / =nolatexpreview= override it. Mirrors =org-startup-with-latex-preview=. | |
| 218 | | =org-use-speed-commands= | boolean | =false= | Single keys at the start of a heading line run commands (=n=, =p=, =t=, =c=, …). Mirrors =org-use-speed-commands=. | | 220 | | =org-use-speed-commands= | boolean | =false= | Single keys at the start of a heading line run commands (=n=, =p=, =t=, =c=, …). Mirrors =org-use-speed-commands=. | |
| 219 | | =org-cycle-hide-drawer-startup= | boolean | =true= | Fold drawers when a file opens. =#+STARTUP: hidedrawers= / =nohidedrawers= override it. Mirrors =org-cycle-hide-drawer-startup=. | | 221 | | =org-cycle-hide-drawer-startup= | boolean | =true= | Fold drawers when a file opens. =#+STARTUP: hidedrawers= / =nohidedrawers= override it. Mirrors =org-cycle-hide-drawer-startup=. | |
| @@ -543,6 +545,7 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, = | |||
| 543 | | =org-icalendar-use-deadline=, =org-icalendar-use-scheduled= | The list's symbols, separated by spaces | | 545 | | =org-icalendar-use-deadline=, =org-icalendar-use-scheduled= | The list's symbols, separated by spaces | |
| 544 | | =org-icalendar-include-todo= | =nil=, =t=, =all= or =unblocked=, or a list of keywords separated by spaces | | 546 | | =org-icalendar-include-todo= | =nil=, =t=, =all= or =unblocked=, or a list of keywords separated by spaces | |
| 545 | | =org-icalendar-combined-agenda-file= | The file name, from a string or a simple form | | 547 | | =org-icalendar-combined-agenda-file= | The file name, from a string or a simple form | |
| 548 | | =org-display-remote-inline-images= | The symbol as a string, when it's =skip=, =download= or =cache= | | ||
| 546 | | =org-publish-project-alist= | A =[[publish]]= table in =config.toml= per project whose publishing functions are =org-html-publish-to-html=, =org-md-publish-to-md= or =org-publish-attachment=: the directories, =:base-extension=, =:recursive=, =:exclude=, =:include=, =:body-only=, the sitemap properties and =:components=. Other properties are reported as left out | | 549 | | =org-publish-project-alist= | A =[[publish]]= table in =config.toml= per project whose publishing functions are =org-html-publish-to-html=, =org-md-publish-to-md= or =org-publish-attachment=: the directories, =:base-extension=, =:recursive=, =:exclude=, =:include=, =:body-only=, the sitemap properties and =:components=. Other properties are reported as left out | |
| 547 | | =org-log-done=, =org-log-reschedule=, =org-log-redeadline= | The same key: =nil=, =time= (also =t=) or =note= | | 550 | | =org-log-done=, =org-log-reschedule=, =org-log-redeadline= | The same key: =nil=, =time= (also =t=) or =note= | |
| 548 | | =org-log-into-drawer= | A string as given; =t= becomes ="LOGBOOK"=; =nil= becomes =""= | | 551 | | =org-log-into-drawer= | A string as given; =t= becomes ="LOGBOOK"=; =nil= becomes =""= | |