Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocMath/MathRenderer.swift3// Description: LaTeX math typesetting through SwiftMath: measured, cached layouts that draw as vector glyphs into any Core Graphics context.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import AppKit9import CoreGraphics10import DocModel11import SwiftMath1213/// The OpenType math fonts bundled with SwiftMath (all under the SIL Open Font License or the GUST Font License).14public enum MathTypeface: String, Sendable, CaseIterable {15 case latinModern, termes, xits, libertinus, fira, notoSans, garamond1617 var font: MathFont {18 switch self {19 case .latinModern: return .latinModernFont20 case .termes: return .termesFont21 case .xits: return .xitsFont22 case .libertinus: return .libertinusFont23 case .fira: return .firaFont24 case .notoSans: return .notoSansFont25 case .garamond: return .garamondFont26 }27 }2829 /// The math face that sits best next to a text family.30 public static func matching(textFamily: String) -> MathTypeface {31 let f = textFamily.lowercased()32 if f.contains("times") { return .termes }33 if f.contains("garamond") { return .garamond }34 if f.contains("helvetica") || f.contains("avenir") || f.contains("sf pro") || f.contains("arial") { return .fira }35 if f.contains("charter") || f.contains("georgia") || f.contains("palatino") { return .libertinus }36 return .latinModern37 }38}3940/// A typeset formula. Immutable once built; the wrapped image only replays vector drawing commands.41public final class MathLayout: @unchecked Sendable {42 public let latex: String43 public let width: CGFloat44 public let ascent: CGFloat45 public let descent: CGFloat46 /// Parse error reported by the typesetter; the formula then renders as its source text so the problem stays visible.47 public let error: String?48 private let image: NSImage?49 private let baselineInImage: CGFloat50 private let fallback: NSAttributedString?51 private static let drawLock = NSRecursiveLock()5253 init(latex: String, width: CGFloat, ascent: CGFloat, descent: CGFloat, image: NSImage?, baselineInImage: CGFloat, error: String?, fallback: NSAttributedString?) {54 self.latex = latex; self.width = width; self.ascent = ascent; self.descent = descent55 self.image = image; self.baselineInImage = baselineInImage; self.error = error; self.fallback = fallback56 }5758 /// Draws with the baseline starting at `origin`, in a context whose y axis points DOWN (page coordinates).59 public func draw(in ctx: CGContext, at origin: CGPoint) {60 // A layout is cached and shared; its image replays drawing commands that are not safe to run from two threads at once.61 MathLayout.drawLock.lock()62 defer { MathLayout.drawLock.unlock() }63 ctx.saveGState()64 ctx.translateBy(x: origin.x, y: origin.y)65 ctx.scaleBy(x: 1, y: -1)66 if let image {67 let ns = NSGraphicsContext(cgContext: ctx, flipped: false)68 NSGraphicsContext.saveGraphicsState()69 NSGraphicsContext.current = ns70 image.draw(in: CGRect(x: 0, y: -baselineInImage, width: image.size.width, height: image.size.height))71 NSGraphicsContext.restoreGraphicsState()72 } else if let fallback {73 let line = CTLineCreateWithAttributedString(fallback)74 ctx.textMatrix = .identity75 ctx.textPosition = .zero76 CTLineDraw(line, ctx)77 }78 ctx.restoreGState()79 }80}8182public enum MathRenderer {83 private final class Box: NSObject { let layout: MathLayout; init(_ l: MathLayout) { layout = l } }84 nonisolated(unsafe) private static let cache: NSCache<NSString, Box> = { let c = NSCache<NSString, Box>(); c.countLimit = 4000; return c }()85 private static let lock = NSLock()8687 /// Typesets `latex`. Results are cached per (source, size, style, colour, typeface).88 public static func layout(latex: String, fontSize: CGFloat, display: Bool, color: RGBA = .black, typeface: MathTypeface = .latinModern) -> MathLayout {89 let key = "\(typeface.rawValue)|\(fontSize)|\(display)|\(color.hexString)\(color.a)|\(latex)" as NSString90 if let hit = cache.object(forKey: key) { return hit.layout }91 // SwiftMath's font tables are loaded lazily; serialise the first loads.92 lock.lock()93 defer { lock.unlock() }94 if let hit = cache.object(forKey: key) { return hit.layout }95 let nsColor = NSColor(srgbRed: color.r, green: color.g, blue: color.b, alpha: color.a)96 var error: NSError?97 var image: NSImage?98 var info: MathImage.LayoutInfo?99 if let refusal = MathGuard.refusal(latex) {100 error = NSError(domain: "ai.spboucher.orix.docs.math", code: 1, userInfo: [NSLocalizedDescriptionKey: refusal])101 } else {102 var math = MathImage(latex: latex, fontSize: fontSize, textColor: nsColor, labelMode: display ? .display : .text, textAlignment: .left)103 math.font = typeface.font104 (error, image, info) = math.asImage()105 }106 let result: MathLayout107 if let image, let info, error == nil {108 let height = max(info.ascent + info.descent, fontSize / 2)109 let baseline = (image.size.height - height) / 2 + info.descent110 // SwiftMath reports the image size rounded up; the advance width used for layout is that size.111 result = MathLayout(latex: latex, width: image.size.width, ascent: info.ascent + 1, descent: info.descent + 1, image: image, baselineInImage: baseline, error: nil, fallback: nil)112 } else {113 let font = NSFont.monospacedSystemFont(ofSize: fontSize * 0.85, weight: .regular)114 let text = NSAttributedString(string: latex.isEmpty ? "□" : latex, attributes: [.font: font, .foregroundColor: NSColor.systemRed])115 let line = CTLineCreateWithAttributedString(text)116 var a: CGFloat = 0, d: CGFloat = 0, l: CGFloat = 0117 let w = CGFloat(CTLineGetTypographicBounds(line, &a, &d, &l))118 result = MathLayout(latex: latex, width: w, ascent: a, descent: d, image: nil, baselineInImage: 0,119 error: latex.isEmpty ? "Empty equation" : (error?.localizedDescription ?? "The LaTeX expression could not be parsed."), fallback: text)120 }121 cache.setObject(Box(result), forKey: key)122 return result123 }124125 /// nil when `latex` parses; otherwise the parser's message.126 public static func validate(_ latex: String) -> String? {127 if latex.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return "Empty equation" }128 if let refusal = MathGuard.refusal(latex) { return refusal }129 var error: NSError?130 let list = MTMathListBuilder.build(fromString: latex, error: &error)131 if let error { return error.localizedDescription }132 return list == nil ? "The LaTeX expression could not be parsed." : nil133 }134}135136/// Equations arrive from untrusted files. The typesetting library recurses on nesting and traps on some malformed input,137/// so expressions outside these bounds are refused before they reach it and shown as their source text instead.138public enum MathGuard {139 public static let maxLength = 4000140 public static let maxDepth = 24141 public static let maxCells = 400142143 /// nil when the expression may be typeset; otherwise the reason it is refused.144 public static func refusal(_ latex: String) -> String? {145 if latex.utf16.count > maxLength { return "The equation is too long to typeset (over \(maxLength) characters)." }146 if latex.unicodeScalars.contains(where: { $0.value < 0x20 && $0 != "\n" && $0 != "\t" || $0.value == 0xFFFC }) { return "The equation contains control characters." }147 var depth = 0, deepest = 0, cells = 0, scripts = 0, deepestScripts = 0148 var previous: Character = " "149 var escaped = false150 let chars = Array(latex)151 var i = 0152 while i < chars.count {153 let ch = chars[i]154 if escaped {155 escaped = false156 if ch == "\\" { cells += 1 }157 // \left and \begin open a level; \right and \end close one.158 if ch.isLetter {159 var word = ""160 var j = i161 while j < chars.count, chars[j].isLetter { word.append(chars[j]); j += 1 }162 if word == "left" || word == "begin" { depth += 1; deepest = max(deepest, depth) }163 if word == "right" || word == "end" { depth -= 1 }164 if ["frac", "sqrt", "binom", "over", "choose", "atop"].contains(word) { scripts += 1; deepestScripts = max(deepestScripts, scripts) }165 i = j166 previous = "a"167 continue168 }169 } else if ch == "\\" {170 escaped = true171 } else if ch == "{" {172 depth += 1; deepest = max(deepest, depth)173 } else if ch == "}" {174 depth -= 1175 if depth < 0 { return "The equation has an unmatched closing brace." }176 } else if ch == "&" {177 cells += 1178 } else if ch == "^" || ch == "_" {179 if previous == "^" || previous == "_" { return "The equation has two script operators in a row." }180 }181 if !ch.isWhitespace { previous = ch }182 i += 1183 }184 if escaped { return "The equation ends with an incomplete command." }185 if depth > 0 { return "The equation has an unclosed group." }186 if depth < 0 { return "The equation closes more groups than it opens." }187 if deepest > maxDepth { return "The equation is nested too deeply to typeset (more than \(maxDepth) levels)." }188 if deepestScripts > 60 { return "The equation has too many stacked fractions or roots." }189 if cells > maxCells { return "The equation's table is too large to typeset." }190 return nil191 }192}193