Sources/OrgEditorAppKit/Fragments.swift
241 lines · 12634 bytes
18 symbols in this file
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 /// An image link's image, on the link's line or on its first character.
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.
66class 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 /// Drawn under the text, which shows while the caret is on the line.
118 let below: Bool
119 /// In the line's text where the link is, on a character as wide and as tall as the image;
120 /// otherwise the link is all the line holds.
121 let inText: Bool
122 init(image: NSImage, size: CGSize, below: Bool = false, inText: Bool = false) {
123 self.image = image
124 self.size = size
125 self.below = below
126 self.inText = inText
127 }
128}
129
130/// A paragraph with image links drawn as their images: a line's image with the paragraph
131/// spacing making room for its height, an image in the text on its hidden link.
132final class ImageFragment: LatexFragment, @unchecked Sendable {
133 static func hasImages(_ string: NSAttributedString) -> Bool {
134 var found = false
135 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
136 if value != nil { found = true; stop.pointee = true }
137 }
138 return found
139 }
140
141 /// Each image and where it goes, in the fragment's coordinates.
142 static func frames(of fragment: NSTextLayoutFragment) -> [(box: InlineImageBox, frame: CGRect)] {
143 guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString, let first = fragment.textLineFragments.first else { return [] }
144 let last = fragment.textLineFragments.last { $0.characterRange.length > 0 } ?? first
145 var out: [(InlineImageBox, CGRect)] = []
146 // Images under the paragraph stand side by side.
147 var under = first.typographicBounds.minX
148 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, range, _ in
149 guard let box = value as? InlineImageBox else { return }
150 if !box.inText {
151 out.append((box, CGRect(origin: CGPoint(x: first.typographicBounds.minX, y: (box.below ? first.typographicBounds.maxY : first.typographicBounds.minY) + 2), size: box.size)))
152 } else if box.below {
153 out.append((box, CGRect(origin: CGPoint(x: under, y: last.typographicBounds.maxY + 2), size: box.size)))
154 under += box.size.width + 4
155 } else if let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) {
156 let bounds = line.typographicBounds
157 let ascender = (string.attribute(.font, at: range.location, effectiveRange: nil) as? NSFont)?.ascender ?? box.size.height
158 out.append((box, CGRect(origin: CGPoint(x: bounds.minX + line.locationForCharacter(at: range.location).x, y: bounds.minY + line.glyphOrigin.y - ascender), size: box.size)))
159 }
160 }
161 return out
162 }
163
164 static func drawImages(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
165 let frames = frames(of: fragment)
166 guard !frames.isEmpty else { return }
167 NSGraphicsContext.saveGraphicsState()
168 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
169 for (box, frame) in frames {
170 box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
171 }
172 NSGraphicsContext.restoreGraphicsState()
173 }
174
175 override var renderingSurfaceBounds: CGRect {
176 Self.frames(of: self).reduce(super.renderingSurfaceBounds) { $0.union($1.frame) }
177 }
178
179 override func draw(at point: CGPoint, in context: CGContext) {
180 super.draw(at: point, in: context)
181 Self.drawImages(of: self, at: point, in: context)
182 }
183}
184
185/// A paragraph with pretty entities: each is drawn as its character where the entity's last
186/// (now invisible) character sits, so it takes one column as in Emacs.
187final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
188 static func hasEntities(_ string: NSAttributedString) -> Bool {
189 var found = false
190 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
191 if value != nil { found = true; stop.pointee = true }
192 }
193 return found
194 }
195
196 override func draw(at point: CGPoint, in context: CGContext) {
197 super.draw(at: point, in: context)
198 Self.drawEntities(of: self, at: point, in: context)
199 }
200
201 static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
202 guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
203 NSGraphicsContext.saveGraphicsState()
204 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
205 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
206 guard let display = value as? String,
207 let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
208 var attributes = string.attributes(at: range.location, effectiveRange: nil)
209 attributes[.foregroundColor] = NSColor.textColor
210 attributes[.orgEntityDisplay] = nil
211 let x = line.locationForCharacter(at: range.location).x
212 let bounds = line.typographicBounds
213 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
214 }
215 NSGraphicsContext.restoreGraphicsState()
216 }
217}
218
219/// A heading line drawn with an ellipsis after it, like org's folded headings.
220final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
221 override func draw(at point: CGPoint, in context: CGContext) {
222 super.draw(at: point, in: context)
223 EntityFragment.drawEntities(of: self, at: point, in: context)
224 ImageFragment.drawImages(of: self, at: point, in: context)
225 guard let line = textLineFragments.first else { return }
226 let bounds = line.typographicBounds
227 let ellipsis = NSAttributedString(string: " …", attributes: [
228 .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
229 .foregroundColor: NSColor.secondaryLabelColor,
230 ])
231 NSGraphicsContext.saveGraphicsState()
232 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
233 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
234 NSGraphicsContext.restoreGraphicsState()
235 }
236
237 override var renderingSurfaceBounds: CGRect {
238 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
239 }
240}
241#endif