Sources/OrgEditorAppKit/OrgEditor+Images.swift
94 lines · 4776 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, attachment: attachment), 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 /// `attachment:` links' files, for inline images.
38 private var attachment: ((String, Int) -> String?)? {
39 guard let attachmentPath else { return nil }
40 let tree = document.tree
41 return { attachmentPath($0, $1, tree) }
42 }
43
44 /// Whether http(s) links show, as `org-display-remote-inline-images` says.
45 private var remote: Bool { options.remoteInlineImages != "skip" }
46
47 private func loadImage(_ path: String) -> NSImage? {
48 if path.contains("://") {
49 guard let url = URL(string: path) else { return nil }
50 let mode = RemoteImages.Mode(rawValue: options.remoteInlineImages) ?? .skip
51 let data = RemoteImages.shared.data(for: url, mode: mode) { [weak self] in
52 guard let self, self.showsImages else { return }
53 self.refreshImages()
54 }
55 return data.flatMap(NSImage.init(data:))
56 }
57 let expanded = (path as NSString).expandingTildeInPath
58 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
59 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
60 let key = "\(url.path)|\(modified)" as NSString
61 if let cached = Self.imageCache.object(forKey: key) { return cached }
62 guard let image = NSImage(contentsOf: url) else { return nil }
63 Self.imageCache.setObject(image, forKey: key)
64 return image
65 }
66
67 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
68 /// on the line.
69 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
70 guard showsImages, isOrg else { return }
71 let text = storage.string as NSString
72 let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40)
73 var location = range.lowerBound
74 while location < range.upperBound, location < text.length {
75 let line = text.lineRange(for: NSRange(location: location, length: 0))
76 location = NSMaxRange(line)
77 guard let image = InlineImages.image(atLine: line.location, in: text, remote: remote, attachment: attachment), let picture = loadImage(image.path) else { continue }
78 var width = image.width.map(CGFloat.init) ?? picture.size.width
79 width = min(width, maxWidth)
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))
82 // Invisible, keeping the line's height, so line numbers stay apart.
83 if line.location != revealed.location, content.length > 0 {
84 storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content)
85 }
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 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 style.paragraphSpacing = max(0, height + 4 - theme.font.boundingRectForFont.height)
90 storage.addAttribute(.paragraphStyle, value: style, range: line)
91 }
92 }
93}
94#endif