Commit 42e3e3e8fa
Verified · cmc
Layout: unified · split
Sources/OrgApp/AttachActions.swift +55 −4
| @@ -7,7 +7,8 @@ import OrgCore | |||
| 7 | public struct AttachActions { | 7 | public struct AttachActions { |
| 8 | /// The open file's entry at the caret; nil when no file is open. | 8 | /// The open file's entry at the caret; nil when no file is open. |
| 9 | public var entry: () -> Attachments.Entry? | 9 | public var entry: () -> Attachments.Entry? |
| 10 | public var apply: (String) -> Void | 10 | /// The buffer's new text, and where the caret goes; nil keeps it where it is. |
| 11 | public var apply: (String, Int?) -> Void | ||
| 11 | public var show: (String) -> Void | 12 | public var show: (String) -> Void |
| 12 | public var ask: (Prompt, @escaping (String?) -> Void) -> Void | 13 | public var ask: (Prompt, @escaping (String?) -> Void) -> Void |
| 13 | public var storeLink: (StoredLink) -> Void | 14 | public var storeLink: (StoredLink) -> Void |
| @@ -19,7 +20,7 @@ public struct AttachActions { | |||
| 19 | public var pick: (Attachments.Method) -> Void | 20 | public var pick: (Attachments.Method) -> Void |
| 20 | 21 | ||
| 21 | public init( | 22 | public init( |
| 22 | entry: @escaping () -> Attachments.Entry?, apply: @escaping (String) -> Void, show: @escaping (String) -> Void, | 23 | entry: @escaping () -> Attachments.Entry?, apply: @escaping (String, Int?) -> Void, show: @escaping (String) -> Void, |
| 23 | ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, storeLink: @escaping (StoredLink) -> Void, | 24 | ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, storeLink: @escaping (StoredLink) -> Void, |
| 24 | open: @escaping (String) -> Void, reveal: @escaping (String) -> Void, pick: @escaping (Attachments.Method) -> Void | 25 | open: @escaping (String) -> Void, reveal: @escaping (String) -> Void, pick: @escaping (Attachments.Method) -> Void |
| 25 | ) { | 26 | ) { |
| @@ -47,10 +48,10 @@ public struct AttachActions { | |||
| 47 | let original = entry.text | 48 | let original = entry.text |
| 48 | do { | 49 | do { |
| 49 | let message = try body(&entry) | 50 | let message = try body(&entry) |
| 50 | if entry.text != original { apply(entry.text) } | 51 | if entry.text != original { apply(entry.text, nil) } |
| 51 | if let message { show(message) } | 52 | if let message { show(message) } |
| 52 | } catch { | 53 | } catch { |
| 53 | if entry.text != original { apply(entry.text) } | 54 | if entry.text != original { apply(entry.text, nil) } |
| 54 | show((error as? Attachments.Failure)?.description ?? error.localizedDescription) | 55 | show((error as? Attachments.Failure)?.description ?? error.localizedDescription) |
| 55 | } | 56 | } |
| 56 | } | 57 | } |
| @@ -184,6 +185,56 @@ public struct AttachActions { | |||
| 184 | } | 185 | } |
| 185 | } | 186 | } |
| 186 | 187 | ||
| 188 | /// Runs `body` on the entry and puts the links it returns at the caret. | ||
| 189 | private func insert(_ body: (inout Attachments.Entry) throws -> [String]) { | ||
| 190 | guard var entry = entry() else { return show("No file is open") } | ||
| 191 | let original = entry.text | ||
| 192 | do { | ||
| 193 | let links = try body(&entry) | ||
| 194 | guard !links.isEmpty else { return } | ||
| 195 | let (text, caret) = ImageYank.inserting(links, into: entry.text, at: ImageYank.map(entry.offset, from: original, to: entry.text)) | ||
| 196 | apply(text, caret) | ||
| 197 | let names = links.compactMap { $0.firstMatch(of: /^\[\[attachment:(.*)\]\]$/).map { String($0.1) } } | ||
| 198 | if let message = Self.attached(names) { show(message) } | ||
| 199 | } catch { | ||
| 200 | if entry.text != original { apply(entry.text, nil) } | ||
| 201 | show((error as? Attachments.Failure)?.description ?? error.localizedDescription) | ||
| 202 | } | ||
| 203 | } | ||
| 204 | |||
| 205 | /// `yank-media` with an image: `data` saved as `org-yank-image-save-method` says, with | ||
| 206 | /// extension `ext`, and its link at the caret. `prefix` replaces "clipboard" in the name. | ||
| 207 | public func yankImage(_ data: Data, ext: String, prefix: String = "clipboard") { | ||
| 208 | let method = ImageYank.SaveMethod(OrgPreferences.yankImageSaveMethod()) | ||
| 209 | insert { entry in [try ImageYank.save(data, ext: ext, method: method, in: &entry, prefix: prefix)] } | ||
| 210 | } | ||
| 211 | |||
| 212 | /// Files dropped or pasted, as `org-yank-dnd-method` says: attached with `attachMethod`, | ||
| 213 | /// opened, or linked; their links at the caret. | ||
| 214 | public func drop(_ files: [URL], method: ImageYank.DropMethod = OrgPreferences.yankDndMethod(), attachMethod: Attachments.Method = .cp) { | ||
| 215 | guard !files.isEmpty else { return } | ||
| 216 | switch method { | ||
| 217 | case .ask: | ||
| 218 | ask(Prompt(key: "dnd", message: "What to do with file?", choices: ["attach", "open", "insert file: link"])) { answer in | ||
| 219 | switch answer { | ||
| 220 | case "attach": drop(files, method: .attach, attachMethod: attachMethod) | ||
| 221 | case "open": drop(files, method: .open, attachMethod: attachMethod) | ||
| 222 | case "insert file: link": drop(files, method: .fileLink, attachMethod: attachMethod) | ||
| 223 | default: break | ||
| 224 | } | ||
| 225 | } | ||
| 226 | case .open: | ||
| 227 | for file in files { open(file.path) } | ||
| 228 | case .attach, .fileLink: | ||
| 229 | let saveMethod = ImageYank.SaveMethod(OrgPreferences.yankImageSaveMethod()) | ||
| 230 | insert { entry in | ||
| 231 | let scoped = files.map { $0.startAccessingSecurityScopedResource() } | ||
| 232 | defer { for (file, on) in zip(files, scoped) where on { file.stopAccessingSecurityScopedResource() } } | ||
| 233 | return try ImageYank.drop(files, method: method, attachMethod: attachMethod, saveMethod: saveMethod, in: &entry) | ||
| 234 | } | ||
| 235 | } | ||
| 236 | } | ||
| 237 | |||
| 187 | static func attached(_ names: [String]) -> String? { | 238 | static func attached(_ names: [String]) -> String? { |
| 188 | switch names.count { | 239 | switch names.count { |
| 189 | case 0: nil | 240 | case 0: nil |
Sources/OrgApp/EmacsImport.swift +5
| @@ -575,6 +575,11 @@ public struct EmacsImport: Sendable { | |||
| 575 | add(name, .string(dir)) | 575 | add(name, .string(dir)) |
| 576 | case "org-attach-use-inheritance": | 576 | case "org-attach-use-inheritance": |
| 577 | if value.symbol == "selective" { add(name, .string("selective")) } else { add(name, .string(truthy ? "t" : "nil")) } | 577 | if value.symbol == "selective" { add(name, .string("selective")) } else { add(name, .string(truthy ? "t" : "nil")) } |
| 578 | case "org-yank-image-save-method": | ||
| 579 | if value.symbol == "attach" { add(name, .string("attach")) } else if let dir = value.string { add(name, .string(dir)) } else { note("not attach or a folder") } | ||
| 580 | case "org-yank-dnd-method": | ||
| 581 | guard let method = value.symbol, ["ask", "attach", "open", "file-link"].contains(method) else { return note("not ask, attach, open or file-link") } | ||
| 582 | add(name, .string(method)) | ||
| 578 | case "org-crypt-tag-matcher": | 583 | case "org-crypt-tag-matcher": |
| 579 | guard let tag = value.string, tag.range(of: "^[\\w@#%]+$", options: .regularExpression) != nil else { return note("not a single tag") } | 584 | guard let tag = value.string, tag.range(of: "^[\\w@#%]+$", options: .regularExpression) != nil else { return note("not a single tag") } |
| 580 | add(name, .string(tag)) | 585 | add(name, .string(tag)) |
Sources/OrgApp/ImageYank.swift added +134
| @@ -0,0 +1,134 @@ | |||
| 1 | import Foundation | ||
| 2 | import OrgCore | ||
| 3 | |||
| 4 | /// Org 9.7's `yank-media` and drag-and-drop handlers (org.el, Org 9.8.7): a pasted image saved | ||
| 5 | /// as `org-yank-image-save-method` says, dropped files handled as `org-yank-dnd-method` says, | ||
| 6 | /// and their links inserted at the caret. Two differences from Org: links have no | ||
| 7 | /// description, and each goes on a line of its own, so they show as inline images. | ||
| 8 | public enum ImageYank { | ||
| 9 | /// `org-yank-image-save-method`: an attachment of the entry, or a file in a folder, | ||
| 10 | /// relative to the org file's folder unless absolute. | ||
| 11 | public enum SaveMethod: Equatable, Sendable { | ||
| 12 | case attach | ||
| 13 | case directory(String) | ||
| 14 | |||
| 15 | public init(_ value: String) { | ||
| 16 | self = value.isEmpty || value == "attach" ? .attach : .directory(value) | ||
| 17 | } | ||
| 18 | } | ||
| 19 | |||
| 20 | /// `org-yank-dnd-method`. | ||
| 21 | public enum DropMethod: String, Sendable { | ||
| 22 | case attach, open, fileLink = "file-link", ask | ||
| 23 | } | ||
| 24 | |||
| 25 | /// `org-yank-image-autogen-filename` with the extension: `clipboard-20261011T232238.png`. | ||
| 26 | /// Org's `.%6N` is the part `file-name-with-extension` replaces, so it never shows. | ||
| 27 | public static func fileName(ext: String, date: Date = Date(), prefix: String = "clipboard") -> String { | ||
| 28 | let format = DateFormatter() | ||
| 29 | format.locale = Locale(identifier: "en_US_POSIX") | ||
| 30 | format.dateFormat = "yyyyMMdd'T'HHmmss" | ||
| 31 | return "\(prefix)-\(format.string(from: date)).\(ext)" | ||
| 32 | } | ||
| 33 | |||
| 34 | /// `name`, or `name-2`, `name-3`… before the extension, whichever `dir` doesn't have yet. | ||
| 35 | static func unused(_ name: String, in dir: String) -> String { | ||
| 36 | let base = (name as NSString).deletingPathExtension | ||
| 37 | let ext = (name as NSString).pathExtension | ||
| 38 | var candidate = name | ||
| 39 | var n = 2 | ||
| 40 | while FileManager.default.fileExists(atPath: (dir as NSString).appendingPathComponent(candidate)) { | ||
| 41 | candidate = "\(base)-\(n)" + (ext.isEmpty ? "" : "." + ext) | ||
| 42 | n += 1 | ||
| 43 | } | ||
| 44 | return candidate | ||
| 45 | } | ||
| 46 | |||
| 47 | /// A `file:` link to `path` from the org file at `orgPath`: relative when it's under the | ||
| 48 | /// file's folder, else absolute with `~` for the home folder. | ||
| 49 | static func fileLink(_ path: String, from orgPath: String) -> String { | ||
| 50 | let folder = (orgPath as NSString).deletingLastPathComponent + "/" | ||
| 51 | let target = path.hasPrefix(folder) ? String(path.dropFirst(folder.count)) : (path as NSString).abbreviatingWithTildeInPath | ||
| 52 | return "[[file:\(target)]]" | ||
| 53 | } | ||
| 54 | |||
| 55 | /// The folder a `directory` method names, made if missing. | ||
| 56 | static func folder(_ dir: String, for entry: Attachments.Entry) throws -> String { | ||
| 57 | let folder = OrgAttach.expand((dir as NSString).expandingTildeInPath, in: (entry.path as NSString).deletingLastPathComponent) | ||
| 58 | try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) | ||
| 59 | return folder | ||
| 60 | } | ||
| 61 | |||
| 62 | /// `org--image-yank-media-handler`: `data` saved with extension `ext`; the link to it. | ||
| 63 | public static func save(_ data: Data, ext: String, method: SaveMethod, in entry: inout Attachments.Entry, | ||
| 64 | date: Date = Date(), prefix: String = "clipboard") throws -> String { | ||
| 65 | switch method { | ||
| 66 | case .attach: | ||
| 67 | let dir = try Attachments.directoryCreating(&entry) | ||
| 68 | let name = unused(fileName(ext: ext, date: date, prefix: prefix), in: dir) | ||
| 69 | try Attachments.attach(data, named: name, to: &entry) | ||
| 70 | return "[[attachment:\(name)]]" | ||
| 71 | case .directory(let dir): | ||
| 72 | let folder = try folder(dir, for: entry) | ||
| 73 | let file = (folder as NSString).appendingPathComponent(unused(fileName(ext: ext, date: date, prefix: prefix), in: folder)) | ||
| 74 | try data.write(to: URL(fileURLWithPath: file)) | ||
| 75 | return fileLink(file, from: entry.path) | ||
| 76 | } | ||
| 77 | } | ||
| 78 | |||
| 79 | static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "svg", "webp", "tif", "tiff", "bmp", "heic", "avif"] | ||
| 80 | |||
| 81 | /// `org--dnd-attach-file` and the `file-link` case of `org--dnd-local-file-handler` for | ||
| 82 | /// each file; `.open` and `.ask` are the caller's. With `attach`, an image goes to the | ||
| 83 | /// save method's folder when that is a directory, as Org does. The links, in order. | ||
| 84 | public static func drop(_ files: [URL], method: DropMethod, attachMethod: Attachments.Method, saveMethod: SaveMethod, | ||
| 85 | in entry: inout Attachments.Entry) throws -> [String] { | ||
| 86 | try files.map { file in | ||
| 87 | switch method { | ||
| 88 | case .fileLink, .open, .ask: | ||
| 89 | return fileLink(file.standardizedFileURL.path, from: entry.path) | ||
| 90 | case .attach: | ||
| 91 | if case .directory(let dir) = saveMethod, imageExtensions.contains(file.pathExtension.lowercased()) { | ||
| 92 | let folder = try folder(dir, for: entry) | ||
| 93 | let target = (folder as NSString).appendingPathComponent(file.lastPathComponent) | ||
| 94 | let files = FileManager.default | ||
| 95 | switch attachMethod { | ||
| 96 | case .mv: try files.moveItem(atPath: file.path, toPath: target) | ||
| 97 | case .cp: try files.copyItem(atPath: file.path, toPath: target) | ||
| 98 | case .ln: try files.linkItem(atPath: file.path, toPath: target) | ||
| 99 | case .lns: try files.createSymbolicLink(atPath: target, withDestinationPath: file.path) | ||
| 100 | } | ||
| 101 | return fileLink(target, from: entry.path) | ||
| 102 | } | ||
| 103 | return "[[\(try Attachments.attach(file, method: attachMethod, to: &entry).link)]]" | ||
| 104 | } | ||
| 105 | } | ||
| 106 | } | ||
| 107 | |||
| 108 | /// `text` with `links` inserted at `offset`, one per line: a line break goes before them | ||
| 109 | /// when the line has text before the caret, and after them when it has text after. The | ||
| 110 | /// caret after the last link. | ||
| 111 | public static func inserting(_ links: [String], into text: String, at offset: Int) -> (text: String, caret: Int) { | ||
| 112 | let ns = text as NSString | ||
| 113 | let offset = min(max(offset, 0), ns.length) | ||
| 114 | let line = ns.lineRange(for: NSRange(location: offset, length: 0)) | ||
| 115 | var contentEnd = NSMaxRange(line) | ||
| 116 | while contentEnd > line.location, [0x0A, 0x0D].contains(ns.character(at: contentEnd - 1)) { contentEnd -= 1 } | ||
| 117 | let before = ns.substring(with: NSRange(location: line.location, length: offset - line.location)) | ||
| 118 | let after = offset < contentEnd ? ns.substring(with: NSRange(location: offset, length: contentEnd - offset)) : "" | ||
| 119 | let lead = before.trimmingCharacters(in: .whitespaces).isEmpty ? "" : "\n" | ||
| 120 | let trail = after.trimmingCharacters(in: .whitespaces).isEmpty ? "" : "\n" | ||
| 121 | let body = lead + links.joined(separator: "\n") | ||
| 122 | let new = ns.replacingCharacters(in: NSRange(location: offset, length: 0), with: body + trail) | ||
| 123 | return (new, offset + (body as NSString).length) | ||
| 124 | } | ||
| 125 | |||
| 126 | /// `offset` in `old` moved to where it is in `new`, for a change that touched one span; | ||
| 127 | /// text inserted at `offset`, such as a property drawer, ends up before it. | ||
| 128 | public static func map(_ offset: Int, from old: String, to new: String) -> Int { | ||
| 129 | guard let edit = TextEdit.between(old, new).first else { return offset } | ||
| 130 | if offset < edit.range.lowerBound { return offset } | ||
| 131 | let delta = (new as NSString).length - (old as NSString).length | ||
| 132 | return max(offset, edit.range.upperBound) + delta | ||
| 133 | } | ||
| 134 | } | ||
Sources/OrgApp/OrgPreferences.swift +8
| @@ -175,6 +175,14 @@ public enum OrgPreferences { | |||
| 175 | default: nil | 175 | default: nil |
| 176 | } | 176 | } |
| 177 | } | 177 | } |
| 178 | /// `org-yank-image-save-method`: "attach", or the folder pasted images go in. | ||
| 179 | public static func yankImageSaveMethod(_ defaults: UserDefaults = .standard) -> String { | ||
| 180 | string("yankImageSaveMethod", defaults).nonEmpty ?? "attach" | ||
| 181 | } | ||
| 182 | /// `org-yank-dnd-method`. | ||
| 183 | public static func yankDndMethod(_ defaults: UserDefaults = .standard) -> ImageYank.DropMethod { | ||
| 184 | ImageYank.DropMethod(rawValue: string("yankDndMethod", defaults)) ?? .ask | ||
| 185 | } | ||
| 178 | /// `org-crypt-tag-matcher`, a tag. | 186 | /// `org-crypt-tag-matcher`, a tag. |
| 179 | public static func cryptTag(_ defaults: UserDefaults = .standard) -> String { | 187 | public static func cryptTag(_ defaults: UserDefaults = .standard) -> String { |
| 180 | let tag = string("cryptTagMatcher", defaults).trimmingCharacters(in: .whitespaces) | 188 | let tag = string("cryptTagMatcher", defaults).trimmingCharacters(in: .whitespaces) |
Sources/OrgApp/UserConfig.swift +5
| @@ -173,6 +173,11 @@ public enum UserConfig { | |||
| 173 | Setting(section: "", key: "org-attach-use-inheritance", defaultsKey: "attachUseInheritance", | 173 | Setting(section: "", key: "org-attach-use-inheritance", defaultsKey: "attachUseInheritance", |
| 174 | kind: .choice([("selective", "selective"), ("t", "t"), ("nil", "nil")]), fallback: .string("selective"), | 174 | kind: .choice([("selective", "selective"), ("t", "t"), ("nil", "nil")]), fallback: .string("selective"), |
| 175 | comment: "whether DIR and ID inherit for attachments: selective (as org-use-property-inheritance), t or nil", legacy: ""), | 175 | comment: "whether DIR and ID inherit for attachments: selective (as org-use-property-inheritance), t or nil", legacy: ""), |
| 176 | Setting(section: "", key: "org-yank-image-save-method", defaultsKey: "yankImageSaveMethod", kind: .string, fallback: .string("attach"), | ||
| 177 | comment: "where pasted images go: attach (the entry's attachments) or a folder, relative to the org file's folder unless absolute", legacy: ""), | ||
| 178 | Setting(section: "", key: "org-yank-dnd-method", defaultsKey: "yankDndMethod", | ||
| 179 | kind: .choice([("ask", "ask"), ("attach", "attach"), ("open", "open"), ("file-link", "file-link")]), fallback: .string("ask"), | ||
| 180 | comment: "files dropped on the editor: ask, attach, open or file-link", legacy: ""), | ||
| 176 | Setting(section: "", key: "org-crypt-tag-matcher", defaultsKey: "cryptTagMatcher", kind: .string, fallback: .string("crypt"), | 181 | Setting(section: "", key: "org-crypt-tag-matcher", defaultsKey: "cryptTagMatcher", kind: .string, fallback: .string("crypt"), |
| 177 | comment: "the tag of entries Encrypt Tagged Entries encrypts", legacy: ""), | 182 | comment: "the tag of entries Encrypt Tagged Entries encrypts", legacy: ""), |
| 178 | Setting(section: "", key: "org-display-remote-inline-images", defaultsKey: "remoteInlineImages", | 183 | Setting(section: "", key: "org-display-remote-inline-images", defaultsKey: "remoteInlineImages", |
Sources/OrgEditorAppKit/EditorCommands.swift +1
| @@ -181,6 +181,7 @@ public enum EditorCommands { | |||
| 181 | edit("backward-kill-word", "Kill Word Backward", "deleteWordBackward:"), | 181 | edit("backward-kill-word", "Kill Word Backward", "deleteWordBackward:"), |
| 182 | edit("kill-line", "Kill Line", "deleteToEndOfParagraph:"), | 182 | edit("kill-line", "Kill Line", "deleteToEndOfParagraph:"), |
| 183 | edit("yank", "Yank", "yank:"), | 183 | edit("yank", "Yank", "yank:"), |
| 184 | edit("yank-media", "Yank Media", "paste:"), | ||
| 184 | edit("select-all", "Select All", "selectAll:"), | 185 | edit("select-all", "Select All", "selectAll:"), |
| 185 | edit("kill-region", "Kill Region", "cut:"), | 186 | edit("kill-region", "Kill Region", "cut:"), |
| 186 | edit("copy-region", "Copy Region", "copy:"), | 187 | edit("copy-region", "Copy Region", "copy:"), |
Sources/OrgEditorAppKit/Fragments.swift +5 −2
| @@ -114,9 +114,12 @@ final class LatexFragment: NSTextLayoutFragment, @unchecked Sendable { | |||
| 114 | final class InlineImageBox: NSObject, @unchecked Sendable { | 114 | final class InlineImageBox: NSObject, @unchecked Sendable { |
| 115 | let image: NSImage | 115 | let image: NSImage |
| 116 | let size: CGSize | 116 | let size: CGSize |
| 117 | init(image: NSImage, size: CGSize) { | 117 | /// Drawn under the line's text, which shows while the caret is on it. |
| 118 | let below: Bool | ||
| 119 | init(image: NSImage, size: CGSize, below: Bool = false) { | ||
| 118 | self.image = image | 120 | self.image = image |
| 119 | self.size = size | 121 | self.size = size |
| 122 | self.below = below | ||
| 120 | } | 123 | } |
| 121 | } | 124 | } |
| 122 | 125 | ||
| @@ -133,7 +136,7 @@ final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable { | |||
| 133 | 136 | ||
| 134 | private var frame: CGRect? { | 137 | private var frame: CGRect? { |
| 135 | guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil } | 138 | guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil } |
| 136 | return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: box.size.width, height: box.size.height) | 139 | return CGRect(x: line.typographicBounds.minX, y: (box.below ? line.typographicBounds.maxY : line.typographicBounds.minY) + 2, width: box.size.width, height: box.size.height) |
| 137 | } | 140 | } |
| 138 | 141 | ||
| 139 | override var renderingSurfaceBounds: CGRect { | 142 | override var renderingSurfaceBounds: CGRect { |
Sources/OrgEditorAppKit/Keys.swift +3
| @@ -17,6 +17,9 @@ final class OrgTextView: NSTextView { | |||
| 17 | /// The text as shown, for accessibility. | 17 | /// The text as shown, for accessibility. |
| 18 | var accessibleText: (() -> AccessibleText)? | 18 | var accessibleText: (() -> AccessibleText)? |
| 19 | var onMouseDown: (() -> Void)? | 19 | var onMouseDown: (() -> Void)? |
| 20 | /// Files and an image pasted or dropped; each returns whether it took them. | ||
| 21 | var onFiles: (([URL]) -> Bool)? | ||
| 22 | var onImage: ((Data, String) -> Bool)? | ||
| 20 | /// The view gained or lost focus, or its window key status: the selection's color changes. | 23 | /// The view gained or lost focus, or its window key status: the selection's color changes. |
| 21 | var onFocusChange: (() -> Void)? | 24 | var onFocusChange: (() -> Void)? |
| 22 | private var keyObservers: [NSObjectProtocol] = [] | 25 | private var keyObservers: [NSObjectProtocol] = [] |
Sources/OrgEditorAppKit/OrgEditor+Images.swift +7 −5
| @@ -65,7 +65,7 @@ extension OrgEditor { | |||
| 65 | } | 65 | } |
| 66 | 66 | ||
| 67 | /// Image lines in `range` show the image over the link, which is hidden unless the caret is | 67 | /// Image lines in `range` show the image over the link, which is hidden unless the caret is |
| 68 | /// on the line. | 68 | /// on the line; then the image goes under it. |
| 69 | func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) { | 69 | func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) { |
| 70 | guard showsImages, isOrg else { return } | 70 | guard showsImages, isOrg else { return } |
| 71 | let text = storage.string as NSString | 71 | let text = storage.string as NSString |
| @@ -80,13 +80,15 @@ extension OrgEditor { | |||
| 80 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 | 80 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 |
| 81 | let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0)) | 81 | let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0)) |
| 82 | // Invisible, keeping the line's height, so line numbers stay apart. | 82 | // Invisible, keeping the line's height, so line numbers stay apart. |
| 83 | if line.location != revealed.location, content.length > 0 { | 83 | let shown = line.location == revealed.location && content.length > 0 |
| 84 | if !shown, content.length > 0 { | ||
| 84 | storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content) | 85 | storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content) |
| 85 | } | 86 | } |
| 86 | storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length))) | 87 | storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height), below: shown), range: NSRange(location: line.location, length: max(1, content.length))) |
| 87 | let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() | 88 | let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() |
| 88 | // The image sits where the line is; the spacing makes room for the rest of it. | 89 | // The image sits where the line is, or under it while the link shows; the spacing |
| 89 | style.paragraphSpacing = max(0, height + 4 - theme.font.boundingRectForFont.height) | 90 | // makes room for the rest of it. |
| 91 | style.paragraphSpacing = shown ? height + 4 : max(0, height + 4 - theme.font.boundingRectForFont.height) | ||
| 90 | storage.addAttribute(.paragraphStyle, value: style, range: line) | 92 | storage.addAttribute(.paragraphStyle, value: style, range: line) |
| 91 | } | 93 | } |
| 92 | } | 94 | } |
Sources/OrgEditorAppKit/OrgEditor.swift +18
| @@ -172,6 +172,18 @@ public final class OrgEditor: NSObject { | |||
| 172 | self.accessibleCache = (self.storageGeneration, text) | 172 | self.accessibleCache = (self.storageGeneration, text) |
| 173 | return text | 173 | return text |
| 174 | } | 174 | } |
| 175 | view.onFiles = { [weak self, unowned view] files in | ||
| 176 | guard let self, let onFiles = self.onFiles, self.isOrg else { return false } | ||
| 177 | self.active = view | ||
| 178 | onFiles(files) | ||
| 179 | return true | ||
| 180 | } | ||
| 181 | view.onImage = { [weak self, unowned view] data, ext in | ||
| 182 | guard let self, let onImage = self.onImage, self.isOrg else { return false } | ||
| 183 | self.active = view | ||
| 184 | onImage(data, ext) | ||
| 185 | return true | ||
| 186 | } | ||
| 175 | view.onMouseDown = { [weak self, unowned view] in | 187 | view.onMouseDown = { [weak self, unowned view] in |
| 176 | self?.active = view | 188 | self?.active = view |
| 177 | self?.markActive = false | 189 | self?.markActive = false |
| @@ -364,6 +376,12 @@ public final class OrgEditor: NSObject { | |||
| 364 | public var knownTags: @Sendable () -> [String] = { [] } | 376 | public var knownTags: @Sendable () -> [String] = { [] } |
| 365 | /// Effects other than messages, for the app to carry out. | 377 | /// Effects other than messages, for the app to carry out. |
| 366 | public var onEffect: ((Effect) -> Void)? | 378 | public var onEffect: ((Effect) -> Void)? |
| 379 | /// Where paste looks for images and files; scripts checking the app set another. | ||
| 380 | public static var pasteboard = NSPasteboard.general | ||
| 381 | /// Files pasted or dropped at the caret; nil leaves them to the text view. | ||
| 382 | public var onFiles: (([URL]) -> Void)? | ||
| 383 | /// An image pasted or dropped at the caret, with its extension (`yank-media`). | ||
| 384 | public var onImage: ((Data, String) -> Void)? | ||
| 367 | 385 | ||
| 368 | public var keymap: Keymap { | 386 | public var keymap: Keymap { |
| 369 | get { dispatcher.keymap } | 387 | get { dispatcher.keymap } |
Sources/OrgEditorAppKit/OrgTextView+Media.swift added +60
| @@ -0,0 +1,60 @@ | |||
| 1 | #if os(macOS) | ||
| 2 | import AppKit | ||
| 3 | |||
| 4 | /// Images and files pasted or dropped on the text view, for `yank-media` and Org's | ||
| 5 | /// drag-and-drop handlers. Text goes to the text system as before. | ||
| 6 | extension OrgTextView { | ||
| 7 | static let jpeg = NSPasteboard.PasteboardType("public.jpeg") | ||
| 8 | static let gif = NSPasteboard.PasteboardType("com.compuserve.gif") | ||
| 9 | |||
| 10 | /// The files on `pasteboard`, if it has any. | ||
| 11 | static func files(on pasteboard: NSPasteboard) -> [URL]? { | ||
| 12 | let urls = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? [] | ||
| 13 | return urls.isEmpty ? nil : urls | ||
| 14 | } | ||
| 15 | |||
| 16 | /// The image on `pasteboard` and the extension for it, when there is no text: PNG, JPEG | ||
| 17 | /// and GIF as they are, anything else AppKit reads as PNG. | ||
| 18 | static func image(on pasteboard: NSPasteboard) -> (data: Data, ext: String)? { | ||
| 19 | guard pasteboard.availableType(from: [.string]) == nil else { return nil } | ||
| 20 | if let data = pasteboard.data(forType: .png) { return (data, "png") } | ||
| 21 | if let data = pasteboard.data(forType: jpeg) { return (data, "jpeg") } | ||
| 22 | if let data = pasteboard.data(forType: gif) { return (data, "gif") } | ||
| 23 | guard let image = NSImage(pasteboard: pasteboard), let tiff = image.tiffRepresentation, | ||
| 24 | let png = NSBitmapImageRep(data: tiff)?.representation(using: .png, properties: [:]) else { return nil } | ||
| 25 | return (png, "png") | ||
| 26 | } | ||
| 27 | |||
| 28 | /// Hands files or an image to the editor; false when it doesn't take them. | ||
| 29 | func takeMedia(from pasteboard: NSPasteboard) -> Bool { | ||
| 30 | guard isEditable else { return false } | ||
| 31 | if let files = Self.files(on: pasteboard) { return onFiles?(files) ?? false } | ||
| 32 | if let image = Self.image(on: pasteboard) { return onImage?(image.data, image.ext) ?? false } | ||
| 33 | return false | ||
| 34 | } | ||
| 35 | |||
| 36 | override func paste(_ sender: Any?) { | ||
| 37 | if !takeMedia(from: OrgEditor.pasteboard) { super.paste(sender) } | ||
| 38 | } | ||
| 39 | |||
| 40 | override var acceptableDragTypes: [NSPasteboard.PasteboardType] { | ||
| 41 | super.acceptableDragTypes + [.fileURL, .png, .tiff, Self.jpeg, Self.gif] | ||
| 42 | } | ||
| 43 | |||
| 44 | override func dragOperation(for dragInfo: any NSDraggingInfo, type: NSPasteboard.PasteboardType) -> NSDragOperation { | ||
| 45 | if isEditable, Self.files(on: dragInfo.draggingPasteboard) != nil || Self.image(on: dragInfo.draggingPasteboard) != nil { return .copy } | ||
| 46 | return super.dragOperation(for: dragInfo, type: type) | ||
| 47 | } | ||
| 48 | |||
| 49 | override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool { | ||
| 50 | let pasteboard = sender.draggingPasteboard | ||
| 51 | guard isEditable, Self.files(on: pasteboard) != nil || Self.image(on: pasteboard) != nil else { | ||
| 52 | return super.performDragOperation(sender) | ||
| 53 | } | ||
| 54 | window?.makeFirstResponder(self) | ||
| 55 | let index = characterIndexForInsertion(at: convert(sender.draggingLocation, from: nil)) | ||
| 56 | setSelectedRange(NSRange(location: index, length: 0)) | ||
| 57 | return takeMedia(from: pasteboard) | ||
| 58 | } | ||
| 59 | } | ||
| 60 | #endif | ||
Sources/Orgstar/ContentView.swift +8 −6
| @@ -295,6 +295,8 @@ struct ContentView: View { | |||
| 295 | .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings } | 295 | .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings } |
| 296 | .onAppear { | 296 | .onAppear { |
| 297 | commands.externalHandler = runExternal | 297 | commands.externalHandler = runExternal |
| 298 | commands.filesHandler = { attachActions.drop($0) } | ||
| 299 | commands.imageHandler = { attachActions.yankImage($0, ext: $1) } | ||
| 298 | // `org-clock-out-when-done`, and the notification when the Effort runs out. | 300 | // `org-clock-out-when-done`, and the notification when the Effort runs out. |
| 299 | clock.notifications = SystemReminderCenter.isAvailable ? SystemReminderCenter() : nil | 301 | clock.notifications = SystemReminderCenter.isAvailable ? SystemReminderCenter() : nil |
| 300 | session.textChanged = { [weak session, weak clock, weak commands] path in | 302 | session.textChanged = { [weak session, weak clock, weak commands] path in |
| @@ -704,7 +706,7 @@ struct ContentView: View { | |||
| 704 | let context = editor.context() | 706 | let context = editor.context() |
| 705 | return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options) | 707 | return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options) |
| 706 | }, | 708 | }, |
| 707 | apply: applyText, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) }, | 709 | apply: { applyText($0, caret: $1) }, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) }, |
| 708 | storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) }, | 710 | storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) }, |
| 709 | open: { [session, workspace, commands] file in | 711 | open: { [session, workspace, commands] file in |
| 710 | if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace) { commands.show(message) } | 712 | if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace) { commands.show(message) } |
| @@ -737,7 +739,7 @@ struct ContentView: View { | |||
| 737 | case .plotImage(_, let url): | 739 | case .plotImage(_, let url): |
| 738 | PlotSheet(content: .image(url)) | 740 | PlotSheet(content: .image(url)) |
| 739 | case .crypt(_, let request): | 741 | case .crypt(_, let request): |
| 740 | CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: applyText) { message in | 742 | CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: { applyText($0) }) { message in |
| 741 | self.panel = nil | 743 | self.panel = nil |
| 742 | if let message { commands.show(message) } | 744 | if let message { commands.show(message) } |
| 743 | } | 745 | } |
| @@ -750,12 +752,12 @@ struct ContentView: View { | |||
| 750 | } | 752 | } |
| 751 | } | 753 | } |
| 752 | 754 | ||
| 753 | /// `new` in place of the buffer's text, as one edit. | 755 | /// `new` in place of the buffer's text, as one edit, with the caret at `caret` or where it was. |
| 754 | private func applyText(_ new: String) { | 756 | private func applyText(_ new: String, caret: Int? = nil) { |
| 755 | guard let editor = commands.editor else { return } | 757 | guard let editor = commands.editor else { return } |
| 756 | let context = editor.context() | 758 | let context = editor.context() |
| 757 | editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), | 759 | let caret = min(caret ?? context.caret, (new as NSString).length) |
| 758 | selection: [min(context.caret, (new as NSString).length)..<min(context.caret, (new as NSString).length)]))) | 760 | editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret]))) |
| 759 | } | 761 | } |
| 760 | 762 | ||
| 761 | /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as | 763 | /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as |
Sources/Orgstar/DevelopmentHooks.swift +4
| @@ -1,4 +1,5 @@ | |||
| 1 | import AppKit | 1 | import AppKit |
| 2 | import OrgEditorAppKit | ||
| 2 | 3 | ||
| 3 | /// Switches for checking the app from scripts, read from the environment: | 4 | /// Switches for checking the app from scripts, read from the environment: |
| 4 | /// - `ORGSTAR_DATA_DIR`: where the index and roots live (see `WorkspaceModel.defaultDirectory`). | 5 | /// - `ORGSTAR_DATA_DIR`: where the index and roots live (see `WorkspaceModel.defaultDirectory`). |
| @@ -9,6 +10,8 @@ import AppKit | |||
| 9 | /// sheet or prompt they open is what the snapshot renders. | 10 | /// sheet or prompt they open is what the snapshot renders. |
| 10 | /// - `ORGSTAR_ANSWERS`: answers to the prompts those commands ask, in order, separated by commas. | 11 | /// - `ORGSTAR_ANSWERS`: answers to the prompts those commands ask, in order, separated by commas. |
| 11 | /// - `ORGSTAR_URL`: an `org-protocol://` link to handle at launch, as if opened from a browser. | 12 | /// - `ORGSTAR_URL`: an `org-protocol://` link to handle at launch, as if opened from a browser. |
| 13 | /// - `ORGSTAR_PASTEBOARD`: the name of a pasteboard to paste images and files from, instead of | ||
| 14 | /// the clipboard. | ||
| 12 | /// - `ORGSTAR_APPEARANCE`: `dark` or `light`, instead of the system's. | 15 | /// - `ORGSTAR_APPEARANCE`: `dark` or `light`, instead of the system's. |
| 13 | /// - `ORGSTAR_SNAPSHOT`: after `ORGSTAR_SNAPSHOT_DELAY` seconds (default 3), render the main | 16 | /// - `ORGSTAR_SNAPSHOT`: after `ORGSTAR_SNAPSHOT_DELAY` seconds (default 3), render the main |
| 14 | /// window to this PNG path and quit. Rendering from inside the app needs no screen-recording | 17 | /// window to this PNG path and quit. Rendering from inside the app needs no screen-recording |
| @@ -24,6 +27,7 @@ enum DevelopmentHooks { | |||
| 24 | @MainActor | 27 | @MainActor |
| 25 | static func scheduleSnapshot() { | 28 | static func scheduleSnapshot() { |
| 26 | let environment = ProcessInfo.processInfo.environment | 29 | let environment = ProcessInfo.processInfo.environment |
| 30 | if let name = environment["ORGSTAR_PASTEBOARD"] { OrgEditor.pasteboard = NSPasteboard(name: NSPasteboard.Name(name)) } | ||
| 27 | if let appearance = environment["ORGSTAR_APPEARANCE"] { | 31 | if let appearance = environment["ORGSTAR_APPEARANCE"] { |
| 28 | NSApp.appearance = NSAppearance(named: appearance == "dark" ? .darkAqua : .aqua) | 32 | NSApp.appearance = NSAppearance(named: appearance == "dark" ? .darkAqua : .aqua) |
| 29 | } | 33 | } |
Sources/Orgstar/OrgstarApp.swift +3
| @@ -31,6 +31,9 @@ final class AppCommands { | |||
| 31 | var editorSettings = EditorSettings() | 31 | var editorSettings = EditorSettings() |
| 32 | /// Runs work outside the text (a table recalculation in Emacs); the main window sets it. | 32 | /// Runs work outside the text (a table recalculation in Emacs); the main window sets it. |
| 33 | var externalHandler: ((ExternalRequest) -> Void)? | 33 | var externalHandler: ((ExternalRequest) -> Void)? |
| 34 | /// Files and images pasted or dropped on an editor; the main window sets them. | ||
| 35 | var filesHandler: (([URL]) -> Void)? | ||
| 36 | var imageHandler: ((Data, String) -> Void)? | ||
| 34 | /// Tags used across the workspace, for tag completion; the main window sets it. | 37 | /// Tags used across the workspace, for tag completion; the main window sets it. |
| 35 | var knownTags: () -> [String] = { [] } | 38 | var knownTags: () -> [String] = { [] } |
| 36 | /// The pending key prefix, and what can follow it. | 39 | /// The pending key prefix, and what can follow it. |
Sources/Orgstar/PaneView.swift +2
| @@ -124,6 +124,8 @@ struct PaneView: NSViewRepresentable { | |||
| 124 | session.reveal(offset) | 124 | session.reveal(offset) |
| 125 | } | 125 | } |
| 126 | editor.onExternal = { [weak commands] request in commands?.externalHandler?(request) } | 126 | editor.onExternal = { [weak commands] request in commands?.externalHandler?(request) } |
| 127 | editor.onFiles = { [weak commands] in commands?.filesHandler?($0) } | ||
| 128 | editor.onImage = { [weak commands] in commands?.imageHandler?($0, $1) } | ||
| 127 | editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } } | 129 | editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } } |
| 128 | editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) } | 130 | editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) } |
| 129 | editor.onEffect = { [weak commands, weak session] effect in | 131 | editor.onEffect = { [weak commands, weak session] effect in |
Sources/OrgstarMobile/EditorScreen.swift +2 −2
| @@ -491,10 +491,10 @@ extension EditorScreen { | |||
| 491 | let context = editor.editContext() | 491 | let context = editor.editContext() |
| 492 | return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options) | 492 | return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options) |
| 493 | }, | 493 | }, |
| 494 | apply: { new in | 494 | apply: { new, caret in |
| 495 | guard let editor else { return } | 495 | guard let editor else { return } |
| 496 | let context = editor.editContext() | 496 | let context = editor.editContext() |
| 497 | let caret = min(context.caret, (new as NSString).length) | 497 | let caret = min(caret ?? context.caret, (new as NSString).length) |
| 498 | _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret]))) | 498 | _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret]))) |
| 499 | }, | 499 | }, |
| 500 | show: { message = $0 }, | 500 | show: { message = $0 }, |
Sources/OrgstarMobile/MobileEditor+Display.swift +7 −5
| @@ -111,7 +111,7 @@ extension MobileEditor { | |||
| 111 | } | 111 | } |
| 112 | 112 | ||
| 113 | /// Image lines in `range` show the image over the link, which is hidden unless the caret is | 113 | /// Image lines in `range` show the image over the link, which is hidden unless the caret is |
| 114 | /// on the line. | 114 | /// on the line; then the image goes under it. |
| 115 | func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) { | 115 | func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) { |
| 116 | guard showsImages else { return } | 116 | guard showsImages else { return } |
| 117 | let text = storage.string as NSString | 117 | let text = storage.string as NSString |
| @@ -127,13 +127,15 @@ extension MobileEditor { | |||
| 127 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 | 127 | let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 |
| 128 | let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0)) | 128 | let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0)) |
| 129 | // Invisible, keeping the line's height. | 129 | // Invisible, keeping the line's height. |
| 130 | if line.location != revealed.location, content.length > 0 { | 130 | let shown = line.location == revealed.location && content.length > 0 |
| 131 | if !shown, content.length > 0 { | ||
| 131 | storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content) | 132 | storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content) |
| 132 | } | 133 | } |
| 133 | storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length))) | 134 | storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height), below: shown), range: NSRange(location: line.location, length: max(1, content.length))) |
| 134 | let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() | 135 | let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() |
| 135 | // The image sits where the line is; the spacing makes room for the rest of it. | 136 | // The image sits where the line is, or under it while the link shows; the spacing |
| 136 | style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight) | 137 | // makes room for the rest of it. |
| 138 | style.paragraphSpacing = shown ? height + 4 : max(0, height + 4 - theme.font.lineHeight) | ||
| 137 | storage.addAttribute(.paragraphStyle, value: style, range: line) | 139 | storage.addAttribute(.paragraphStyle, value: style, range: line) |
| 138 | } | 140 | } |
| 139 | } | 141 | } |
Sources/OrgstarMobile/MobileFragments.swift +5 −2
| @@ -121,9 +121,12 @@ final class LatexBox: NSObject, @unchecked Sendable { | |||
| 121 | final class InlineImageBox: NSObject, @unchecked Sendable { | 121 | final class InlineImageBox: NSObject, @unchecked Sendable { |
| 122 | let image: UIImage | 122 | let image: UIImage |
| 123 | let size: CGSize | 123 | let size: CGSize |
| 124 | init(image: UIImage, size: CGSize) { | 124 | /// Drawn under the line's text, which shows while the caret is on it. |
| 125 | let below: Bool | ||
| 126 | init(image: UIImage, size: CGSize, below: Bool = false) { | ||
| 125 | self.image = image | 127 | self.image = image |
| 126 | self.size = size | 128 | self.size = size |
| 129 | self.below = below | ||
| 127 | } | 130 | } |
| 128 | } | 131 | } |
| 129 | 132 | ||
| @@ -217,7 +220,7 @@ final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable { | |||
| 217 | 220 | ||
| 218 | private var imageRect: CGRect? { | 221 | private var imageRect: CGRect? { |
| 219 | guard let image, let line = textLineFragments.first else { return nil } | 222 | guard let image, let line = textLineFragments.first else { return nil } |
| 220 | return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: image.size.width, height: image.size.height) | 223 | return CGRect(x: line.typographicBounds.minX, y: (image.below ? line.typographicBounds.maxY : line.typographicBounds.minY) + 2, width: image.size.width, height: image.size.height) |
| 221 | } | 224 | } |
| 222 | 225 | ||
| 223 | override var renderingSurfaceBounds: CGRect { | 226 | override var renderingSurfaceBounds: CGRect { |
Tests/OrgAppTests/ImageYankTests.swift added +162
| @@ -0,0 +1,162 @@ | |||
| 1 | import Foundation | ||
| 2 | import OrgCore | ||
| 3 | import Testing | ||
| 4 | @testable import OrgApp | ||
| 5 | |||
| 6 | struct ImageYankTests { | ||
| 7 | /// An ID per file, ending in its name's letter. | ||
| 8 | static let id = "6a1b2c3d-0000-4000-8000-00000000000" | ||
| 9 | static let notes = """ | ||
| 10 | #+title: Notes | ||
| 11 | Free text. | ||
| 12 | * Task | ||
| 13 | Body. | ||
| 14 | |||
| 15 | """ | ||
| 16 | static var noon: Date { | ||
| 17 | DateComponents(calendar: Calendar.current, year: 2024, month: 1, day: 1, hour: 12).date! | ||
| 18 | } | ||
| 19 | |||
| 20 | static func folder() throws -> URL { | ||
| 21 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-yank-\(UUID().uuidString)").resolvingSymlinksInPath() | ||
| 22 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) | ||
| 23 | return folder | ||
| 24 | } | ||
| 25 | |||
| 26 | @Test func fileNameIsOrgsAutogeneratedName() { | ||
| 27 | #expect(ImageYank.fileName(ext: "png", date: Self.noon) == "clipboard-20240101T120000.png") | ||
| 28 | #expect(ImageYank.fileName(ext: "jpg", date: Self.noon, prefix: "photo") == "photo-20240101T120000.jpg") | ||
| 29 | } | ||
| 30 | |||
| 31 | /// The text and files `org--image-yank-media-handler` leaves, without the link it inserts: | ||
| 32 | /// in an entry, before the first heading (a file-level ID), and into a folder. | ||
| 33 | @Test func savingMatchesEmacs() throws { | ||
| 34 | let folder = try Self.folder() | ||
| 35 | defer { try? FileManager.default.removeItem(at: folder) } | ||
| 36 | let dir = folder.path | ||
| 37 | for name in ["a", "b", "c"] { try Self.notes.write(toFile: "\(dir)/\(name).org", atomically: true, encoding: .utf8) } | ||
| 38 | let form = #""" | ||
| 39 | (progn | ||
| 40 | (require 'org) (require 'org-attach) (require 'json) | ||
| 41 | (let ((out nil) | ||
| 42 | (org-yank-image-file-name-function (lambda () "clipboard-20240101T120000.000000"))) | ||
| 43 | (cl-letf (((symbol-function 'org-id-new) (lambda (&rest _) (concat "\#(Self.id)" (file-name-base (buffer-file-name)))))) | ||
| 44 | (cl-flet ((yank (file where method) | ||
| 45 | (with-current-buffer (find-file-noselect (concat "\#(dir)/" file)) | ||
| 46 | (goto-char (point-min)) (search-forward where) | ||
| 47 | (let ((org-yank-image-save-method method) (start (copy-marker (point)))) | ||
| 48 | (org--image-yank-media-handler 'image/png "PNG") | ||
| 49 | (push (buffer-substring-no-properties start (point)) out) | ||
| 50 | (delete-region start (point))) | ||
| 51 | (push (buffer-substring-no-properties (point-min) (point-max)) out)))) | ||
| 52 | (yank "a.org" "Body." 'attach) | ||
| 53 | (yank "b.org" "Free text." 'attach) | ||
| 54 | (yank "c.org" "Body." "img/"))) | ||
| 55 | (with-temp-file "\#(dir)/out.json" (insert (json-encode (vconcat (nreverse out))))))) | ||
| 56 | """# | ||
| 57 | let process = Process() | ||
| 58 | process.executableURL = URL(fileURLWithPath: "/usr/bin/env") | ||
| 59 | process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form] | ||
| 60 | process.currentDirectoryURL = folder | ||
| 61 | let pipe = Pipe() | ||
| 62 | process.standardOutput = pipe | ||
| 63 | process.standardError = pipe | ||
| 64 | try process.run() | ||
| 65 | let log = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) | ||
| 66 | process.waitUntilExit() | ||
| 67 | try #require(FileManager.default.fileExists(atPath: folder.appendingPathComponent("out.json").path), "\(log)") | ||
| 68 | let emacs = try JSONDecoder().decode([String].self, from: Data(contentsOf: folder.appendingPathComponent("out.json"))) | ||
| 69 | try FileManager.default.removeItem(at: folder.appendingPathComponent("out.json")) | ||
| 70 | let emacsFiles = AttachmentsTests.listing(folder).filter { !$0.hasSuffix(".org") } | ||
| 71 | for name in ["data", "img"] { try? FileManager.default.removeItem(atPath: "\(dir)/\(name)") } | ||
| 72 | |||
| 73 | var ours: [String] = [] | ||
| 74 | for (file, at, method) in [("a.org", "Body.", ImageYank.SaveMethod.attach), ("b.org", "Free text.", .attach), ("c.org", "Body.", .directory("img/"))] { | ||
| 75 | let ns = Self.notes as NSString | ||
| 76 | var entry = Attachments.Entry(text: Self.notes, offset: NSMaxRange(ns.range(of: at)), path: "\(dir)/\(file)", idDir: "data/") | ||
| 77 | if method == .attach { _ = try Attachments.directoryCreating(&entry, newID: { Self.id + (file as NSString).deletingPathExtension }) } | ||
| 78 | ours.append(try ImageYank.save(Data("PNG".utf8), ext: "png", method: method, in: &entry, date: Self.noon)) | ||
| 79 | ours.append(entry.text) | ||
| 80 | } | ||
| 81 | |||
| 82 | #expect(emacs.count == 6, "\(log)") | ||
| 83 | // Org's links carry the file name as their description; ours have none. | ||
| 84 | #expect(ours[0] == "[[attachment:clipboard-20240101T120000.png]]") | ||
| 85 | #expect(emacs[0] == "[[attachment:clipboard-20240101T120000.png][clipboard-20240101T120000.png]]") | ||
| 86 | #expect(ours[2] == "[[attachment:clipboard-20240101T120000.png]]") | ||
| 87 | #expect(ours[4] == emacs[4]) | ||
| 88 | for index in [1, 3, 5] { #expect(ours[index] == emacs[index], "step \(index)") } | ||
| 89 | #expect(AttachmentsTests.listing(folder).filter { !$0.hasSuffix(".org") } == emacsFiles) | ||
| 90 | |||
| 91 | // The link before the first heading shows as an image: the file-level ID's folder. | ||
| 92 | let (text, caret) = ImageYank.inserting([ours[2]], into: ours[3], at: NSMaxRange((ours[3] as NSString).range(of: "Free text."))) | ||
| 93 | #expect(DocumentSession.attachmentPath("clipboard-20240101T120000.png", at: caret, tree: OrgParser.parse(text), path: "\(dir)/b.org") | ||
| 94 | == "\(dir)/data/6a/1b2c3d-0000-4000-8000-00000000000b/clipboard-20240101T120000.png") | ||
| 95 | #expect(InlineImages.image(atLine: caret - 1, in: text as NSString, attachment: { name, _ in name })?.path == "clipboard-20240101T120000.png") | ||
| 96 | } | ||
| 97 | |||
| 98 | @Test func aSecondPasteInTheSameSecondGetsANewName() throws { | ||
| 99 | let folder = try Self.folder() | ||
| 100 | defer { try? FileManager.default.removeItem(at: folder) } | ||
| 101 | var entry = Attachments.Entry(text: Self.notes, offset: 0, path: folder.appendingPathComponent("n.org").path) | ||
| 102 | let first = try ImageYank.save(Data(), ext: "png", method: .directory("img"), in: &entry, date: Self.noon) | ||
| 103 | let second = try ImageYank.save(Data(), ext: "png", method: .directory("img"), in: &entry, date: Self.noon) | ||
| 104 | #expect(first == "[[file:img/clipboard-20240101T120000.png]]") | ||
| 105 | #expect(second == "[[file:img/clipboard-20240101T120000-2.png]]") | ||
| 106 | } | ||
| 107 | |||
| 108 | @Test func droppedFiles() throws { | ||
| 109 | let folder = try Self.folder() | ||
| 110 | defer { try? FileManager.default.removeItem(at: folder) } | ||
| 111 | let elsewhere = try Self.folder() | ||
| 112 | defer { try? FileManager.default.removeItem(at: elsewhere) } | ||
| 113 | let photo = elsewhere.appendingPathComponent("photo.jpg") | ||
| 114 | let doc = elsewhere.appendingPathComponent("doc.pdf") | ||
| 115 | try Data("j".utf8).write(to: photo) | ||
| 116 | try Data("p".utf8).write(to: doc) | ||
| 117 | let path = folder.appendingPathComponent("n.org").path | ||
| 118 | var entry = Attachments.Entry(text: "* Task\n", offset: 7, path: path, idDir: "data/") | ||
| 119 | |||
| 120 | let linked = try ImageYank.drop([folder.appendingPathComponent("sub/x.png"), doc], method: .fileLink, attachMethod: .cp, saveMethod: .attach, in: &entry) | ||
| 121 | #expect(linked == ["[[file:sub/x.png]]", "[[file:\((doc.path as NSString).abbreviatingWithTildeInPath)]]"]) | ||
| 122 | |||
| 123 | let attached = try ImageYank.drop([photo, doc], method: .attach, attachMethod: .cp, saveMethod: .attach, in: &entry) | ||
| 124 | #expect(attached == ["[[attachment:photo.jpg]]", "[[attachment:doc.pdf]]"]) | ||
| 125 | let dir = try #require(Attachments.directory(entry)) | ||
| 126 | #expect(Attachments.files(in: dir) == ["doc.pdf", "photo.jpg"]) | ||
| 127 | #expect(entry.text.hasPrefix("* Task") && entry.text.contains(":ATTACH:")) | ||
| 128 | |||
| 129 | // An image goes to the save method's folder when it is one; other files are attached. | ||
| 130 | let moved = try ImageYank.drop([photo], method: .attach, attachMethod: .mv, saveMethod: .directory("img"), in: &entry) | ||
| 131 | #expect(moved == ["[[file:img/photo.jpg]]"]) | ||
| 132 | #expect(FileManager.default.fileExists(atPath: folder.appendingPathComponent("img/photo.jpg").path)) | ||
| 133 | #expect(!FileManager.default.fileExists(atPath: photo.path)) | ||
| 134 | } | ||
| 135 | |||
| 136 | @Test func linksGoOnLinesOfTheirOwn() { | ||
| 137 | let link = "[[attachment:a.png]]" | ||
| 138 | #expect(ImageYank.inserting([link], into: "a\n\nb\n", at: 2) == ("a\n\(link)\nb\n", 2 + 20)) | ||
| 139 | #expect(ImageYank.inserting([link], into: "one two\n", at: 3) == ("one\n\(link)\n two\n", 4 + 20)) | ||
| 140 | #expect(ImageYank.inserting([link], into: "one\n", at: 3) == ("one\n\(link)\n", 4 + 20)) | ||
| 141 | #expect(ImageYank.inserting([link], into: "one", at: 3) == ("one\n\(link)", 4 + 20)) | ||
| 142 | #expect(ImageYank.inserting([link], into: "two\n", at: 0) == ("\(link)\ntwo\n", 20)) | ||
| 143 | #expect(ImageYank.inserting([link, link], into: "", at: 0) == ("\(link)\n\(link)", 41)) | ||
| 144 | #expect(ImageYank.inserting([link], into: " - item\n ", at: 11) == (" - item\n \(link)", 31)) | ||
| 145 | } | ||
| 146 | |||
| 147 | @Test func caretFollowsTheChangeAboveIt() { | ||
| 148 | let old = "* Task\nBody." | ||
| 149 | let new = "* Task\n:PROPERTIES:\n:ID: x\n:END:\nBody." | ||
| 150 | #expect(ImageYank.map(12, from: old, to: new) == (new as NSString).length) | ||
| 151 | #expect(ImageYank.map(3, from: old, to: new) == 3) | ||
| 152 | #expect(ImageYank.map(7, from: old, to: new) == 7 + 26) | ||
| 153 | let drawer = ":PROPERTIES:\n:ID: x\n:END:\n" | ||
| 154 | #expect(ImageYank.map(0, from: "#+title: a\n", to: drawer + "#+title: a\n") == (drawer as NSString).length) | ||
| 155 | } | ||
| 156 | |||
| 157 | @Test func settings() { | ||
| 158 | #expect(ImageYank.SaveMethod("attach") == .attach) | ||
| 159 | #expect(ImageYank.SaveMethod("") == .attach) | ||
| 160 | #expect(ImageYank.SaveMethod("~/img/") == .directory("~/img/")) | ||
| 161 | } | ||
| 162 | } | ||
Tests/OrgEditorAppKitTests/PasteMediaTests.swift added +64
| @@ -0,0 +1,64 @@ | |||
| 1 | import AppKit | ||
| 2 | import OrgDocument | ||
| 3 | import Testing | ||
| 4 | @testable import OrgEditorAppKit | ||
| 5 | |||
| 6 | @MainActor | ||
| 7 | struct PasteMediaTests { | ||
| 8 | static func pasteboard() -> NSPasteboard { | ||
| 9 | let pasteboard = NSPasteboard(name: NSPasteboard.Name("orgstar-test-\(UUID().uuidString)")) | ||
| 10 | pasteboard.clearContents() | ||
| 11 | return pasteboard | ||
| 12 | } | ||
| 13 | |||
| 14 | static var tiff: Data { | ||
| 15 | let image = NSImage(size: NSSize(width: 2, height: 2)) | ||
| 16 | image.lockFocus() | ||
| 17 | NSColor.red.setFill() | ||
| 18 | NSRect(x: 0, y: 0, width: 2, height: 2).fill() | ||
| 19 | image.unlockFocus() | ||
| 20 | return image.tiffRepresentation! | ||
| 21 | } | ||
| 22 | |||
| 23 | @Test func imagesWithoutTextArePastedAsImages() { | ||
| 24 | let png = Self.pasteboard() | ||
| 25 | png.setData(Data("PNG".utf8), forType: .png) | ||
| 26 | #expect(OrgTextView.image(on: png)?.ext == "png") | ||
| 27 | #expect(OrgTextView.image(on: png)?.data == Data("PNG".utf8)) | ||
| 28 | |||
| 29 | let tiff = Self.pasteboard() | ||
| 30 | tiff.setData(Self.tiff, forType: .tiff) | ||
| 31 | let converted = OrgTextView.image(on: tiff) | ||
| 32 | #expect(converted?.ext == "png") | ||
| 33 | #expect((converted.flatMap { NSBitmapImageRep(data: $0.data) }?.pixelsWide ?? 0) >= 2) | ||
| 34 | |||
| 35 | let text = Self.pasteboard() | ||
| 36 | text.setData(Data("PNG".utf8), forType: .png) | ||
| 37 | text.setString("caption", forType: .string) | ||
| 38 | #expect(OrgTextView.image(on: text) == nil) | ||
| 39 | } | ||
| 40 | |||
| 41 | @Test func filesAreFiles() { | ||
| 42 | let pasteboard = Self.pasteboard() | ||
| 43 | let url = URL(fileURLWithPath: "/tmp/a.png") | ||
| 44 | pasteboard.writeObjects([url as NSURL]) | ||
| 45 | #expect(OrgTextView.files(on: pasteboard) == [url]) | ||
| 46 | #expect(OrgTextView.files(on: Self.pasteboard()) == nil) | ||
| 47 | } | ||
| 48 | |||
| 49 | @Test func theEditorTakesMediaOnlyInOrgWithAHandler() { | ||
| 50 | let harness = Harness("* a\n") | ||
| 51 | let view = harness.editor.textView as! OrgTextView | ||
| 52 | let pasteboard = Self.pasteboard() | ||
| 53 | pasteboard.setData(Data("PNG".utf8), forType: .png) | ||
| 54 | #expect(!view.takeMedia(from: pasteboard)) | ||
| 55 | var got: (Data, String)? | ||
| 56 | harness.editor.onImage = { got = ($0, $1) } | ||
| 57 | #expect(view.takeMedia(from: pasteboard)) | ||
| 58 | #expect(got?.1 == "png") | ||
| 59 | |||
| 60 | let plain = Harness(DocumentState(bytes: Array("x\n".utf8)), mode: .plain(language: nil)) | ||
| 61 | plain.editor.onImage = { _, _ in Issue.record("a plain buffer took an image") } | ||
| 62 | #expect(!(plain.editor.textView as! OrgTextView).takeMedia(from: pasteboard)) | ||
| 63 | } | ||
| 64 | } | ||