Sources/OrgEditorAppKit/Fragments.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgEditorAppKit/Fragments.swift history · blame · raw

145 lines · 7546 bytes

  1#if os(macOS)
  2import AppKit
  3
  4/// A line of a block, on a band across the whole width of the view, as Emacs extends the
  5/// `org-block` face.
  6final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
  7    private var band: CGRect {
  8        let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
  9        // Not under the empty line TextKit adds after a final newline.
 10        let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
 11        return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height)
 12    }
 13
 14    override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
 15
 16    override func draw(at point: CGPoint, in context: CGContext) {
 17        context.saveGState()
 18        context.setFillColor(Theme.blockBackground.cgColor)
 19        context.fill(band.offsetBy(dx: point.x, dy: point.y))
 20        // The band covers the view's selection highlight, so the selected text is drawn on it,
 21        // in the color the view uses: the theme's when focused, the system's muted one when not.
 22        if let manager = textLayoutManager {
 23            let active = Theme.focusedLayouts.contains(ObjectIdentifier(manager))
 24            context.setFillColor((active ? Theme.selection : NSColor.unemphasizedSelectedTextBackgroundColor).cgColor)
 25            let single = textLineFragments.count == 1
 26            for selection in manager.textSelections {
 27                for range in selection.textRanges where !range.isEmpty {
 28                    guard let part = range.intersection(rangeInElement), !part.isEmpty else { continue }
 29                    manager.enumerateTextSegments(in: part, type: .selection, options: [.rangeNotRequired]) { _, frame, _, _ in
 30                        var rect = frame.offsetBy(dx: point.x - self.layoutFragmentFrame.minX, dy: point.y - self.layoutFragmentFrame.minY)
 31                        // A one-line fragment's selection covers its band, leaving no gap to the next line.
 32                        if single { rect = CGRect(x: rect.minX, y: point.y, width: rect.width, height: self.band.height) }
 33                        context.fill(rect)
 34                        return true
 35                    }
 36                }
 37            }
 38        }
 39        context.restoreGState()
 40        super.draw(at: point, in: context)
 41    }
 42}
 43
 44extension NSAttributedString.Key {
 45    /// The character an entity shows as, on the entity's last character.
 46    static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
 47    /// The image an image link's line shows under it.
 48    static let orgImage = NSAttributedString.Key("OrgImage")
 49}
 50
 51final class InlineImageBox: NSObject, @unchecked Sendable {
 52    let image: NSImage
 53    let size: CGSize
 54    init(image: NSImage, size: CGSize) {
 55        self.image = image
 56        self.size = size
 57    }
 58}
 59
 60/// An image link's line drawn as the image, with the paragraph spacing making room for its
 61/// height.
 62final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable {
 63    static func image(_ string: NSAttributedString) -> InlineImageBox? {
 64        var found: InlineImageBox?
 65        string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
 66            if let box = value as? InlineImageBox { found = box; stop.pointee = true }
 67        }
 68        return found
 69    }
 70
 71    private var frame: CGRect? {
 72        guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil }
 73        return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: box.size.width, height: box.size.height)
 74    }
 75
 76    override var renderingSurfaceBounds: CGRect {
 77        frame.map { super.renderingSurfaceBounds.union($0) } ?? super.renderingSurfaceBounds
 78    }
 79
 80    override func draw(at point: CGPoint, in context: CGContext) {
 81        super.draw(at: point, in: context)
 82        guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let frame else { return }
 83        NSGraphicsContext.saveGraphicsState()
 84        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
 85        box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
 86        NSGraphicsContext.restoreGraphicsState()
 87    }
 88}
 89
 90/// A paragraph with pretty entities: each is drawn as its character where the entity's last
 91/// (now invisible) character sits, so it takes one column as in Emacs.
 92final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
 93    static func hasEntities(_ string: NSAttributedString) -> Bool {
 94        var found = false
 95        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
 96            if value != nil { found = true; stop.pointee = true }
 97        }
 98        return found
 99    }
100
101    override func draw(at point: CGPoint, in context: CGContext) {
102        super.draw(at: point, in: context)
103        Self.drawEntities(of: self, at: point, in: context)
104    }
105
106    static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
107        guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
108        NSGraphicsContext.saveGraphicsState()
109        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
110        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
111            guard let display = value as? String,
112                  let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
113            var attributes = string.attributes(at: range.location, effectiveRange: nil)
114            attributes[.foregroundColor] = NSColor.textColor
115            attributes[.orgEntityDisplay] = nil
116            let x = line.locationForCharacter(at: range.location).x
117            let bounds = line.typographicBounds
118            NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
119        }
120        NSGraphicsContext.restoreGraphicsState()
121    }
122}
123
124/// A heading line drawn with an ellipsis after it, like org's folded headings.
125final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
126    override func draw(at point: CGPoint, in context: CGContext) {
127        super.draw(at: point, in: context)
128        EntityFragment.drawEntities(of: self, at: point, in: context)
129        guard let line = textLineFragments.first else { return }
130        let bounds = line.typographicBounds
131        let ellipsis = NSAttributedString(string: " …", attributes: [
132            .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
133            .foregroundColor: NSColor.secondaryLabelColor,
134        ])
135        NSGraphicsContext.saveGraphicsState()
136        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
137        ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
138        NSGraphicsContext.restoreGraphicsState()
139    }
140
141    override var renderingSurfaceBounds: CGRect {
142        super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
143    }
144}
145#endif