Sources/OrgEditorAppKit/OrgEditor+Images.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgEditorAppKit/OrgEditor+Images.swift history · blame · raw

125 lines · 6770 bytes

5 symbols in this file
  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    /// The widest an image shows: the text's width, less a margin.
 35    private var imageMaxWidth: CGFloat { max(80, (textView.textContainer?.size.width ?? 600) - 40) }
 36
 37    /// Sizes images again once the view's width has changed, after the layout pass that changed it.
 38    func fitImages() {
 39        guard showsImages, !fittingImages else { return }
 40        fittingImages = true
 41        DispatchQueue.main.async { [weak self] in
 42            guard let self else { return }
 43            self.fittingImages = false
 44            if self.showsImages, self.imageWidth != self.imageMaxWidth { self.refreshImages() }
 45        }
 46    }
 47
 48    /// `attachment:` links' files, for inline images.
 49    private var attachment: ((String, Int) -> String?)? {
 50        guard let attachmentPath else { return nil }
 51        let tree = document.tree
 52        return { attachmentPath($0, $1, tree) }
 53    }
 54
 55    /// Whether http(s) links show, as `org-display-remote-inline-images` says.
 56    private var remote: Bool { options.remoteInlineImages != "skip" }
 57
 58    private func loadImage(_ path: String) -> NSImage? {
 59        if path.contains("://") {
 60            guard let url = URL(string: path) else { return nil }
 61            let mode = RemoteImages.Mode(rawValue: options.remoteInlineImages) ?? .skip
 62            let data = RemoteImages.shared.data(for: url, mode: mode) { [weak self] in
 63                guard let self, self.showsImages else { return }
 64                self.refreshImages()
 65            }
 66            return data.flatMap(NSImage.init(data:))
 67        }
 68        let expanded = OrgPaths.expandingTilde(path)
 69        let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
 70        let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
 71        let key = "\(url.path)|\(modified)" as NSString
 72        if let cached = Self.imageCache.object(forKey: key) { return cached }
 73        guard let image = NSImage(contentsOf: url) else { return nil }
 74        Self.imageCache.setObject(image, forKey: key)
 75        return image
 76    }
 77
 78    /// Image links in `range` show their image, and the link is hidden unless the caret is on
 79    /// its line. A link that is all its line holds keeps the line, with the image over it, or
 80    /// under it while the link shows. A link in a line's text is as wide and as tall as its
 81    /// image, which goes under the paragraph while the link shows.
 82    func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
 83        guard showsImages, isOrg else { return }
 84        let text = storage.string as NSString
 85        let maxWidth = imageMaxWidth
 86        imageWidth = maxWidth
 87        let links = InlineImages.links(document.tree, in: range, includeLinked: imagesIncludeLinked, remote: remote, attachment: attachment)
 88        for placement in Presentation.imagePlacements(links, in: text) {
 89            guard let picture = loadImage(placement.link.image.path) else { continue }
 90            let size = Presentation.imageSize(natural: picture.size, width: placement.link.image.width, maxWidth: maxWidth)
 91            let link = NSRange(placement.link.range)
 92            let line = text.lineRange(for: link)
 93            let shown = NSLocationInRange(revealed.location, line)
 94            let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
 95            defer { storage.addAttribute(.paragraphStyle, value: style, range: line) }
 96            guard placement.ownLine else {
 97                let first = NSRange(location: link.location, length: 1)
 98                storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: size, below: shown, inText: true), range: first)
 99                if shown {
100                    style.paragraphSpacing = max(style.paragraphSpacing, size.height + 4)
101                    continue
102                }
103                // Pretty entities in the link would draw over the image.
104                storage.removeAttribute(.orgEntityDisplay, range: link)
105                storage.addAttributes(theme.hidden, range: link)
106                storage.addAttribute(.underlineStyle, value: 0, range: link)
107                let lineHeight = theme.font.ascender - theme.font.descender + theme.font.leading
108                let font = NSFont(descriptor: theme.font.fontDescriptor, size: Presentation.imageFontSize(height: size.height, pointSize: theme.font.pointSize, lineHeight: lineHeight)) ?? theme.font
109                let advance = text.substring(with: first).size(withAttributes: [.font: font]).width
110                storage.addAttributes([.font: font, .kern: size.width - advance], range: first)
111                continue
112            }
113            let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
114            // Invisible, keeping the line's height, so line numbers stay apart.
115            if !shown {
116                storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content)
117            }
118            storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: size, below: shown), range: content)
119            // The image sits where the line is, or under it while the link shows; the spacing
120            // makes room for the rest of it.
121            style.paragraphSpacing = shown ? size.height + 4 : max(0, size.height + 4 - theme.font.boundingRectForFont.height)
122        }
123    }
124}
125#endif