Sources/OrgEditorAppKit/OrgEditor+Images.swift

09c5ecd551a0ae8f5078cb88c33958c92428d71f
orgstar/Sources/OrgEditorAppKit/OrgEditor+Images.swift

110 lines · 6158 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    /// `includeLinked` as `org-toggle-inline-images` with a prefix argument: links with a
 12    /// description show their image too.
 13    func toggleImages(includeLinked: Bool = false) {
 14        showsImages.toggle()
 15        imagesIncludeLinked = showsImages && includeLinked
 16        refreshImages()
 17        if showsImages {
 18            let count = InlineImages.links(document.tree, in: 0..<utf16Length, includeLinked: imagesIncludeLinked, remote: remote, attachment: attachment)
 19                .count { loadImage($0.image.path) != nil }
 20            onMessage?("\(count) images displayed inline")
 21        } else {
 22            onMessage?("Inline image display turned off")
 23        }
 24    }
 25
 26    public func refreshImages() {
 27        keepingTopLine {
 28            restyleOutsideEditing(0..<utf16Length)
 29            invalidateAllLayout()
 30        }
 31        redrawViews()
 32    }
 33
 34    /// `attachment:` links' files, for inline images.
 35    private var attachment: ((String, Int) -> String?)? {
 36        guard let attachmentPath else { return nil }
 37        let tree = document.tree
 38        return { attachmentPath($0, $1, tree) }
 39    }
 40
 41    /// Whether http(s) links show, as `org-display-remote-inline-images` says.
 42    private var remote: Bool { options.remoteInlineImages != "skip" }
 43
 44    private func loadImage(_ path: String) -> NSImage? {
 45        if path.contains("://") {
 46            guard let url = URL(string: path) else { return nil }
 47            let mode = RemoteImages.Mode(rawValue: options.remoteInlineImages) ?? .skip
 48            let data = RemoteImages.shared.data(for: url, mode: mode) { [weak self] in
 49                guard let self, self.showsImages else { return }
 50                self.refreshImages()
 51            }
 52            return data.flatMap(NSImage.init(data:))
 53        }
 54        let expanded = OrgPaths.expandingTilde(path)
 55        let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
 56        let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
 57        let key = "\(url.path)|\(modified)" as NSString
 58        if let cached = Self.imageCache.object(forKey: key) { return cached }
 59        guard let image = NSImage(contentsOf: url) else { return nil }
 60        Self.imageCache.setObject(image, forKey: key)
 61        return image
 62    }
 63
 64    /// Image links in `range` show their image, and the link is hidden unless the caret is on
 65    /// its line. A link that is all its line holds keeps the line, with the image over it, or
 66    /// under it while the link shows. A link in a line's text is as wide and as tall as its
 67    /// image, which goes under the paragraph while the link shows.
 68    func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
 69        guard showsImages, isOrg else { return }
 70        let text = storage.string as NSString
 71        let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40)
 72        let links = InlineImages.links(document.tree, in: range, includeLinked: imagesIncludeLinked, remote: remote, attachment: attachment)
 73        for placement in Presentation.imagePlacements(links, in: text) {
 74            guard let picture = loadImage(placement.link.image.path) else { continue }
 75            let size = Presentation.imageSize(natural: picture.size, width: placement.link.image.width, maxWidth: maxWidth)
 76            let link = NSRange(placement.link.range)
 77            let line = text.lineRange(for: link)
 78            let shown = NSLocationInRange(revealed.location, line)
 79            let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
 80            defer { storage.addAttribute(.paragraphStyle, value: style, range: line) }
 81            guard placement.ownLine else {
 82                let first = NSRange(location: link.location, length: 1)
 83                storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: size, below: shown, inText: true), range: first)
 84                if shown {
 85                    style.paragraphSpacing = max(style.paragraphSpacing, size.height + 4)
 86                    continue
 87                }
 88                // Pretty entities in the link would draw over the image.
 89                storage.removeAttribute(.orgEntityDisplay, range: link)
 90                storage.addAttributes(theme.hidden, range: link)
 91                storage.addAttribute(.underlineStyle, value: 0, range: link)
 92                let lineHeight = theme.font.ascender - theme.font.descender + theme.font.leading
 93                let font = NSFont(descriptor: theme.font.fontDescriptor, size: Presentation.imageFontSize(height: size.height, pointSize: theme.font.pointSize, lineHeight: lineHeight)) ?? theme.font
 94                let advance = text.substring(with: first).size(withAttributes: [.font: font]).width
 95                storage.addAttributes([.font: font, .kern: size.width - advance], range: first)
 96                continue
 97            }
 98            let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
 99            // Invisible, keeping the line's height, so line numbers stay apart.
100            if !shown {
101                storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content)
102            }
103            storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: size, below: shown), range: content)
104            // The image sits where the line is, or under it while the link shows; the spacing
105            // makes room for the rest of it.
106            style.paragraphSpacing = shown ? size.height + 4 : max(0, size.height + 4 - theme.font.boundingRectForFont.height)
107        }
108    }
109}
110#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form