Files
plak/Sources/PlakUI/Page/CodeAttachment.swift
T
2026-10-17 17:33:13 +02:00

165 lines
6.7 KiB
Swift

import AppKit
import PlakCore
/// The look of code: the mono font in ink, with a colour for each kind of token.
enum CodeStyle {
static func attributes(_ font: NSFont) -> [NSAttributedString.Key: Any] {
[.font: font, .foregroundColor: Theme.ink]
}
static func color(_ kind: CodeTokenKind) -> NSColor {
switch kind {
case .keyword: Theme.codeKeyword
case .string: Theme.codeString
case .number: Theme.codeNumber
case .comment: Theme.codeComment
case .variable: Theme.codeVariable
case .tag: Theme.codeTag
case .attribute: Theme.codeAttribute
}
}
/// Gives all of `text` the code look, then the colours of its tokens.
static func highlight(_ text: NSMutableAttributedString, kind: FenceKind, font: NSFont) {
let all = NSRange(location: 0, length: text.length)
text.beginEditing()
text.setAttributes(attributes(font), range: all)
for token in CodeHighlighter.tokens(text.string, kind: kind) where token.range.upperBound <= text.length {
text.addAttribute(.foregroundColor, value: color(token.kind), range: NSRange(token.range))
}
text.endEditing()
}
/// Colours the tokens as temporary attributes, which change the drawing and never the layout.
static func colorize(_ layoutManager: NSLayoutManager, text: String, kind: FenceKind) {
let length = (text as NSString).length
layoutManager.removeTemporaryAttribute(.foregroundColor, forCharacterRange: NSRange(location: 0, length: length))
for token in CodeHighlighter.tokens(text, kind: kind) where token.range.upperBound <= length {
layoutManager.addTemporaryAttribute(.foregroundColor, value: color(token.kind), forCharacterRange: NSRange(token.range))
}
}
}
/// The part of `frame` the current drawing paints, in the coordinates of the view being drawn; nil when none.
/// An empty clip gives a null box, whose origin is infinite.
@MainActor
func drawingClip(within frame: NSRect) -> NSRect? {
guard let box = NSGraphicsContext.current?.cgContext.boundingBoxOfClipPath else { return frame }
let visible = frame.intersection(box)
return visible.isFiniteArea ? visible : nil
}
extension NSRect {
/// Not null, not empty, and with finite edges: safe to turn into row and glyph numbers.
var isFiniteArea: Bool {
!isNull && !isEmpty && minX.isFinite && minY.isFinite && maxX.isFinite && maxY.isFinite
}
}
/// Code laid out at a width the way the code editor lays it out, for the height and the drawing of a code block.
final class CodeLayout {
private let storage = NSTextStorage()
private let layoutManager = NSLayoutManager()
private let container = NSTextContainer(size: NSSize(width: 100, height: CGFloat.greatestFiniteMagnitude))
init() {
storage.addLayoutManager(layoutManager)
container.lineFragmentPadding = 0
layoutManager.addTextContainer(container)
}
func set(_ body: String, kind: FenceKind, font: NSFont) {
storage.setAttributedString(NSAttributedString(string: body))
CodeStyle.highlight(storage, kind: kind, font: font)
}
/// The height of the whole block: the wrapped code and the padding around it.
func blockHeight(width: CGFloat) -> CGFloat {
let padding = PageMetrics.codePadding
let textWidth = max(1, width - padding * 2)
if container.size.width != textWidth { container.size = NSSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude) }
layoutManager.ensureLayout(for: container)
return ceil(layoutManager.usedRect(for: container).height) + padding * 2
}
/// Draws the lines of the block that lie in `clip`.
func draw(in block: NSRect, clip: NSRect) {
_ = blockHeight(width: block.width)
let origin = NSPoint(x: block.minX + PageMetrics.codePadding, y: block.minY + PageMetrics.codePadding)
let visible = clip.intersection(block)
guard visible.isFiniteArea else { return }
let range = layoutManager.glyphRange(forBoundingRect: visible.offsetBy(dx: -origin.x, dy: -origin.y), in: container)
layoutManager.drawGlyphs(forGlyphRange: range, at: origin)
}
}
/// A code block in the page: one character that knows its kind and its body.
final class CodeAttachment: NSTextAttachment {
let kind: FenceKind
let body: String
init(kind: FenceKind, body: String, font: NSFont) {
self.kind = kind
self.body = body
super.init(data: nil, ofType: nil)
attachmentCell = CodeBlockCell(kind: kind, body: body, font: font)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
}
/// Highlighted code on the code paper, over the full width of the column.
final class CodeBlockCell: NSTextAttachmentCell, ObjectCell {
private let kind: FenceKind
private let body: String
private let layout = CodeLayout()
private var size = NSSize.zero
/// AppKit reads it in `cellFrame`, which it does not mark main-actor; the page lays out on the main thread only.
nonisolated(unsafe) var editingHeight: CGFloat?
init(kind: FenceKind, body: String, font: NSFont) {
self.kind = kind
self.body = body
super.init(textCell: "")
layout.set(body, kind: kind, font: font)
}
@available(*, unavailable)
required init(coder: NSCoder) { fatalError("init(coder:) is not supported") }
func setFont(_ font: NSFont) {
layout.set(body, kind: kind, font: font)
}
override func cellSize() -> NSSize {
size
}
override func cellBaselineOffset() -> NSPoint {
.zero
}
override func cellFrame(for textContainer: NSTextContainer, proposedLineFragment lineFrag: NSRect,
glyphPosition position: NSPoint, characterIndex charIndex: Int) -> NSRect {
let width = floor(lineFrag.width - max(0, position.x))
size = NSSize(width: width, height: editingHeight ?? layout.blockHeight(width: width))
return NSRect(origin: .zero, size: size)
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?) {
Theme.codePaper.setFill()
NSBezierPath(roundedRect: cellFrame, xRadius: PageMetrics.codeCornerRadius, yRadius: PageMetrics.codeCornerRadius).fill()
guard editingHeight == nil, let clip = drawingClip(within: cellFrame) else { return }
layout.draw(in: cellFrame, clip: clip)
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?, characterIndex charIndex: Int, layoutManager: NSLayoutManager) {
draw(withFrame: cellFrame, in: controlView)
}
override func wantsToTrackMouse() -> Bool {
false
}
}