Sources/OrgEditorAppKit/Fragments.swift

211 lines · 10779 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    /// Drawn under the line's text, which shows while the caret is on it.
118    let below: Bool
119    init(image: NSImage, size: CGSize, below: Bool = false) {
120        self.image = image
121        self.size = size
122        self.below = below
123    }
124}
125
126/// An image link's line drawn as the image, with the paragraph spacing making room for its
127/// height.
128final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable {
129    static func image(_ string: NSAttributedString) -> InlineImageBox? {
130        var found: InlineImageBox?
131        string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
132            if let box = value as? InlineImageBox { found = box; stop.pointee = true }
133        }
134        return found
135    }
136
137    private var frame: CGRect? {
138        guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil }
139        return CGRect(x: line.typographicBounds.minX, y: (box.below ? line.typographicBounds.maxY : line.typographicBounds.minY) + 2, width: box.size.width, height: box.size.height)
140    }
141
142    override var renderingSurfaceBounds: CGRect {
143        frame.map { super.renderingSurfaceBounds.union($0) } ?? super.renderingSurfaceBounds
144    }
145
146    override func draw(at point: CGPoint, in context: CGContext) {
147        super.draw(at: point, in: context)
148        guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let frame else { return }
149        NSGraphicsContext.saveGraphicsState()
150        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
151        box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
152        NSGraphicsContext.restoreGraphicsState()
153    }
154}
155
156/// A paragraph with pretty entities: each is drawn as its character where the entity's last
157/// (now invisible) character sits, so it takes one column as in Emacs.
158final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
159    static func hasEntities(_ string: NSAttributedString) -> Bool {
160        var found = false
161        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
162            if value != nil { found = true; stop.pointee = true }
163        }
164        return found
165    }
166
167    override func draw(at point: CGPoint, in context: CGContext) {
168        super.draw(at: point, in: context)
169        Self.drawEntities(of: self, at: point, in: context)
170    }
171
172    static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
173        guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
174        NSGraphicsContext.saveGraphicsState()
175        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
176        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
177            guard let display = value as? String,
178                  let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
179            var attributes = string.attributes(at: range.location, effectiveRange: nil)
180            attributes[.foregroundColor] = NSColor.textColor
181            attributes[.orgEntityDisplay] = nil
182            let x = line.locationForCharacter(at: range.location).x
183            let bounds = line.typographicBounds
184            NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
185        }
186        NSGraphicsContext.restoreGraphicsState()
187    }
188}
189
190/// A heading line drawn with an ellipsis after it, like org's folded headings.
191final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
192    override func draw(at point: CGPoint, in context: CGContext) {
193        super.draw(at: point, in: context)
194        EntityFragment.drawEntities(of: self, at: point, in: context)
195        guard let line = textLineFragments.first else { return }
196        let bounds = line.typographicBounds
197        let ellipsis = NSAttributedString(string: " …", attributes: [
198            .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
199            .foregroundColor: NSColor.secondaryLabelColor,
200        ])
201        NSGraphicsContext.saveGraphicsState()
202        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
203        ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
204        NSGraphicsContext.restoreGraphicsState()
205    }
206
207    override var renderingSurfaceBounds: CGRect {
208        super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
209    }
210}
211#endif