Sources/OrgApp/ImageYank.swift

135 lines · 7575 bytes

11 symbols in this file
  1import Foundation
  2import 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.
  8public 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)) : OrgPaths.abbreviatingWithTilde(path)
 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(OrgPaths.expandingTilde(dir), 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        // On a heading's line they go under it, in the entry the files were attached to.
114        let offset = OrgAttach.belowHeading(text, at: min(max(offset, 0), ns.length))
115        let line = ns.lineRange(for: NSRange(location: offset, length: 0))
116        var contentEnd = NSMaxRange(line)
117        while contentEnd > line.location, [0x0A, 0x0D].contains(ns.character(at: contentEnd - 1)) { contentEnd -= 1 }
118        let before = ns.substring(with: NSRange(location: line.location, length: offset - line.location))
119        let after = offset < contentEnd ? ns.substring(with: NSRange(location: offset, length: contentEnd - offset)) : ""
120        let lead = before.trimmingCharacters(in: .whitespaces).isEmpty ? "" : "\n"
121        let trail = after.trimmingCharacters(in: .whitespaces).isEmpty ? "" : "\n"
122        let body = lead + links.joined(separator: "\n")
123        let new = ns.replacingCharacters(in: NSRange(location: offset, length: 0), with: body + trail)
124        return (new, offset + (body as NSString).length)
125    }
126
127    /// `offset` in `old` moved to where it is in `new`, for a change that touched one span;
128    /// text inserted at `offset`, such as a property drawer, ends up before it.
129    public static func map(_ offset: Int, from old: String, to new: String) -> Int {
130        guard let edit = TextEdit.between(old, new).first else { return offset }
131        if offset < edit.range.lowerBound { return offset }
132        let delta = (new as NSString).length - (old as NSString).length
133        return max(offset, edit.range.upperBound) + delta
134    }
135}