Sources/OrgEditorAppKit/OrgEditor+Images.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgEditorAppKit/OrgEditor+Images.swift history · blame · raw

87 lines · 4474 bytes

 1#if os(macOS)
 2import AppKit
 3import OrgCore
 4import OrgPresentation
 5
 6extension OrgEditor {
 7    // MARK: - Inline images
 8
 9    private static let imageCache = NSCache<NSString, NSImage>()
10
11    func toggleImages() {
12        showsImages.toggle()
13        refreshImages()
14        if showsImages {
15            let ns = textView.string as NSString
16            var count = 0
17            var offset = 0
18            while offset < ns.length {
19                let line = ns.lineRange(for: NSRange(location: offset, length: 0))
20                if let image = InlineImages.image(atLine: line.location, in: ns, remote: remote), loadImage(image.path) != nil { count += 1 }
21                offset = NSMaxRange(line)
22            }
23            onMessage?("\(count) images displayed inline")
24        } else {
25            onMessage?("Inline image display turned off")
26        }
27    }
28
29    public func refreshImages() {
30        keepingTopLine {
31            restyleOutsideEditing(0..<utf16Length)
32            invalidateAllLayout()
33        }
34        redrawViews()
35    }
36
37    /// Whether http(s) links show, as `org-display-remote-inline-images` says.
38    private var remote: Bool { options.remoteInlineImages != "skip" }
39
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        }
50        let expanded = (path as NSString).expandingTildeInPath
51        let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
52        let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
53        let key = "\(url.path)|\(modified)" as NSString
54        if let cached = Self.imageCache.object(forKey: key) { return cached }
55        guard let image = NSImage(contentsOf: url) else { return nil }
56        Self.imageCache.setObject(image, forKey: key)
57        return image
58    }
59
60    /// Image lines in `range` show the image over the link, which is hidden unless the caret is
61    /// on the line.
62    func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
63        guard showsImages, isOrg else { return }
64        let text = storage.string as NSString
65        let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40)
66        var location = range.lowerBound
67        while location < range.upperBound, location < text.length {
68            let line = text.lineRange(for: NSRange(location: location, length: 0))
69            location = NSMaxRange(line)
70            guard let image = InlineImages.image(atLine: line.location, in: text, remote: remote), let picture = loadImage(image.path) else { continue }
71            var width = image.width.map(CGFloat.init) ?? picture.size.width
72            width = min(width, maxWidth)
73            let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
74            let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
75            // Invisible, keeping the line's height, so line numbers stay apart.
76            if line.location != revealed.location, content.length > 0 {
77                storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content)
78            }
79            storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
80            let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
81            // The image sits where the line is; the spacing makes room for the rest of it.
82            style.paragraphSpacing = max(0, height + 4 - theme.font.boundingRectForFont.height)
83            storage.addAttribute(.paragraphStyle, value: style, range: line)
84        }
85    }
86}
87#endif