Sources/OrgEditorAppKit/Fragments.swift
208 lines · 10592 bytes
1#if os(macOS)
2import AppKit
3import OrgPresentation
4
5/// A line of a block, on a band across the whole width of the view, as Emacs extends the
6/// `org-block` face.
7final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
8 private var band: CGRect {
9 let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
10 // Not under the empty line TextKit adds after a final newline.
11 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
12 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height)
13 }
14
15 override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
16
17 override func draw(at point: CGPoint, in context: CGContext) {
18 context.saveGState()
19 context.setFillColor(Theme.blockBackground.cgColor)
20 context.fill(band.offsetBy(dx: point.x, dy: point.y))
21 // The band covers the view's selection highlight, so the selected text is drawn on it,
22 // in the color the view uses: the theme's when focused, the system's muted one when not.
23 if let manager = textLayoutManager {
24 let active = Theme.focusedLayouts.contains(ObjectIdentifier(manager))
25 context.setFillColor((active ? Theme.selection : NSColor.unemphasizedSelectedTextBackgroundColor).cgColor)
26 let single = textLineFragments.count == 1
27 for selection in manager.textSelections {
28 for range in selection.textRanges where !range.isEmpty {
29 guard let part = range.intersection(rangeInElement), !part.isEmpty else { continue }
30 manager.enumerateTextSegments(in: part, type: .selection, options: [.rangeNotRequired]) { _, frame, _, _ in
31 var rect = frame.offsetBy(dx: point.x - self.layoutFragmentFrame.minX, dy: point.y - self.layoutFragmentFrame.minY)
32 // A one-line fragment's selection covers its band, leaving no gap to the next line.
33 if single { rect = CGRect(x: rect.minX, y: point.y, width: rect.width, height: self.band.height) }
34 context.fill(rect)
35 return true
36 }
37 }
38 }
39 }
40 context.restoreGState()
41 super.draw(at: point, in: context)
42 }
43}
44
45extension NSAttributedString.Key {
46 /// The character an entity shows as, on the entity's last character.
47 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
48 /// The image an image link's line shows under it.
49 static let orgImage = NSAttributedString.Key("OrgImage")
50 /// A LaTeX fragment's typeset math, on its first character.
51 static let orgLatex = NSAttributedString.Key("OrgLatex")
52}
53
54final class LatexBox: NSObject, @unchecked Sendable {
55 let rendering: LatexPreview.Rendering
56 /// An environment's image sits at the start of its first line, under the line's top.
57 let environment: Bool
58 init(_ rendering: LatexPreview.Rendering, environment: Bool) {
59 self.rendering = rendering
60 self.environment = environment
61 }
62}
63
64/// A paragraph with LaTeX previews: each drawn where its hidden fragment starts, on the line's
65/// baseline, or at the top of an environment's first line.
66final class LatexFragment: NSTextLayoutFragment, @unchecked Sendable {
67 static func hasLatex(_ string: NSAttributedString) -> Bool {
68 var found = false
69 string.enumerateAttribute(.orgLatex, in: NSRange(location: 0, length: string.length)) { value, _, stop in
70 if value != nil { found = true; stop.pointee = true }
71 }
72 return found
73 }
74
75 /// Each preview and where it goes, in the fragment's coordinates.
76 private var boxes: [(box: LatexBox, frame: CGRect)] {
77 guard let string = (textElement as? NSTextParagraph)?.attributedString else { return [] }
78 var out: [(LatexBox, CGRect)] = []
79 string.enumerateAttribute(.orgLatex, in: NSRange(location: 0, length: string.length)) { value, range, _ in
80 guard let box = value as? LatexBox,
81 let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
82 let bounds = line.typographicBounds
83 let size = box.rendering.size
84 if box.environment {
85 out.append((box, CGRect(x: bounds.minX + line.locationForCharacter(at: range.location).x, y: bounds.minY + 2, width: size.width, height: size.height)))
86 } else {
87 let baseline = bounds.minY + line.glyphOrigin.y
88 let top = max(bounds.minY, baseline - (size.height - box.rendering.descent))
89 out.append((box, CGRect(x: bounds.minX + line.locationForCharacter(at: range.location).x, y: top, width: size.width, height: size.height)))
90 }
91 }
92 return out
93 }
94
95 override var renderingSurfaceBounds: CGRect {
96 boxes.reduce(super.renderingSurfaceBounds) { $0.union($1.frame) }
97 }
98
99 override func draw(at point: CGPoint, in context: CGContext) {
100 super.draw(at: point, in: context)
101 EntityFragment.drawEntities(of: self, at: point, in: context)
102 for (box, frame) in boxes {
103 let rect = frame.offsetBy(dx: point.x, dy: point.y)
104 context.saveGState()
105 // The context is flipped; the image is drawn upright.
106 context.translateBy(x: rect.minX, y: rect.maxY)
107 context.scaleBy(x: 1, y: -1)
108 context.draw(box.rendering.image, in: CGRect(origin: .zero, size: rect.size))
109 context.restoreGState()
110 }
111 }
112}
113
114final class InlineImageBox: NSObject, @unchecked Sendable {
115 let image: NSImage
116 let size: CGSize
117 init(image: NSImage, size: CGSize) {
118 self.image = image
119 self.size = size
120 }
121}
122
123/// An image link's line drawn as the image, with the paragraph spacing making room for its
124/// height.
125final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable {
126 static func image(_ string: NSAttributedString) -> InlineImageBox? {
127 var found: InlineImageBox?
128 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
129 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
130 }
131 return found
132 }
133
134 private var frame: CGRect? {
135 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil }
136 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: box.size.width, height: box.size.height)
137 }
138
139 override var renderingSurfaceBounds: CGRect {
140 frame.map { super.renderingSurfaceBounds.union($0) } ?? super.renderingSurfaceBounds
141 }
142
143 override func draw(at point: CGPoint, in context: CGContext) {
144 super.draw(at: point, in: context)
145 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let frame else { return }
146 NSGraphicsContext.saveGraphicsState()
147 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
148 box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
149 NSGraphicsContext.restoreGraphicsState()
150 }
151}
152
153/// A paragraph with pretty entities: each is drawn as its character where the entity's last
154/// (now invisible) character sits, so it takes one column as in Emacs.
155final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
156 static func hasEntities(_ string: NSAttributedString) -> Bool {
157 var found = false
158 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
159 if value != nil { found = true; stop.pointee = true }
160 }
161 return found
162 }
163
164 override func draw(at point: CGPoint, in context: CGContext) {
165 super.draw(at: point, in: context)
166 Self.drawEntities(of: self, at: point, in: context)
167 }
168
169 static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
170 guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
171 NSGraphicsContext.saveGraphicsState()
172 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
173 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
174 guard let display = value as? String,
175 let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
176 var attributes = string.attributes(at: range.location, effectiveRange: nil)
177 attributes[.foregroundColor] = NSColor.textColor
178 attributes[.orgEntityDisplay] = nil
179 let x = line.locationForCharacter(at: range.location).x
180 let bounds = line.typographicBounds
181 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
182 }
183 NSGraphicsContext.restoreGraphicsState()
184 }
185}
186
187/// A heading line drawn with an ellipsis after it, like org's folded headings.
188final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
189 override func draw(at point: CGPoint, in context: CGContext) {
190 super.draw(at: point, in: context)
191 EntityFragment.drawEntities(of: self, at: point, in: context)
192 guard let line = textLineFragments.first else { return }
193 let bounds = line.typographicBounds
194 let ellipsis = NSAttributedString(string: " …", attributes: [
195 .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
196 .foregroundColor: NSColor.secondaryLabelColor,
197 ])
198 NSGraphicsContext.saveGraphicsState()
199 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
200 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
201 NSGraphicsContext.restoreGraphicsState()
202 }
203
204 override var renderingSurfaceBounds: CGRect {
205 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
206 }
207}
208#endif