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