Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/MathRenderer.swift3// Description: Native LaTeX typesetting (CoreText via SwiftMath) to template images with baseline metrics, for inline and display formulas.4import AppKit5import SwiftMath67/// Typesets TeX once per (source, size, mode) and caches the bitmap. Images are templates: they take the colour of the8/// surrounding text, so one rendering serves light and dark appearances.9@MainActor enum MathRenderer {10 private static let cache: NSCache<NSString, Box> = { let c = NSCache<NSString, Box>(); c.countLimit = 600; return c }()11 private final class Box { let value: RenderedMath?; init(_ v: RenderedMath?) { value = v } }1213 static func render(_ tex: String, fontSize: CGFloat, display: Bool) -> RenderedMath? {14 let key = "\(display ? "D" : "I")|\(fontSize)|\(tex)" as NSString15 if let hit = cache.object(forKey: key) { return hit.value }16 let value = typeset(tex, fontSize: fontSize, display: display)17 cache.setObject(Box(value), forKey: key)18 return value19 }2021 private static func typeset(_ tex: String, fontSize: CGFloat, display: Bool) -> RenderedMath? {22 guard tex.count < 4000 else { return nil }23 let label = MTMathUILabel()24 label.displayErrorInline = false25 label.fontSize = fontSize; label.labelMode = display ? .display : .text; label.textColor = .black; label.textAlignment = .left26 label.latex = tex27 guard label.error == nil else { return nil }28 let fit = label.fittingSize29 guard fit.width > 0, fit.height > 0, fit.width < 20_000 else { return nil }30 let size = CGSize(width: ceil(fit.width) + 2, height: ceil(fit.height) + 2)31 label.frame = CGRect(origin: .zero, size: size); label.layout()32 guard let list = label.displayList else { return nil }33 let scale: CGFloat = 234 guard let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width * scale), pixelsHigh: Int(size.height * scale), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,35 colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0) else { return nil }36 rep.size = size // set before creating the context: it gives the context its 2× scale37 guard let ctx = NSGraphicsContext(bitmapImageRep: rep) else { return nil }38 NSGraphicsContext.saveGraphicsState(); NSGraphicsContext.current = ctx39 list.draw(ctx.cgContext)40 NSGraphicsContext.restoreGraphicsState()41 let image = NSImage(size: size); image.addRepresentation(rep); image.isTemplate = true42 // the label centres the line vertically: the baseline sits `position.y` above the bottom edge43 let lineHeight = max(list.ascent + list.descent, fontSize / 2)44 return RenderedMath(image: image, descent: (size.height - lineHeight) / 2 + list.descent, size: size)45 }46}47