SPB Git

Repository Public

MathView.swift 4.9 KB 86 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Components/MathView.swift3// Description: Native LaTeX rendering (CoreText via SwiftMath) to template images with baseline metrics, for inline and display formulas.4import SwiftUI5import SwiftMath67struct RenderedMath {8    let image: NSImage9    let descent: CGFloat10    let size: CGSize11}1213/// Typesets TeX once per (source, size, mode) and caches the bitmap. Images are templates: they take the colour of the14/// surrounding text, so one rendering serves light and dark appearances.15enum MathRenderer {16    private static let cache: NSCache<NSString, Box> = { let c = NSCache<NSString, Box>(); c.countLimit = 600; return c }()17    private final class Box { let value: RenderedMath?; init(_ v: RenderedMath?) { value = v } }1819    static func render(_ tex: String, fontSize: CGFloat, display: Bool) -> RenderedMath? {20        let key = "\(display ? "D" : "I")|\(fontSize)|\(tex)" as NSString21        if let hit = cache.object(forKey: key) { return hit.value }22        let value = typeset(tex, fontSize: fontSize, display: display)23        cache.setObject(Box(value), forKey: key)24        return value25    }2627    private static func typeset(_ tex: String, fontSize: CGFloat, display: Bool) -> RenderedMath? {28        guard tex.count < 4000 else { return nil }29        let label = MTMathUILabel()30        label.displayErrorInline = false31        label.fontSize = fontSize; label.labelMode = display ? .display : .text; label.textColor = .black; label.textAlignment = .left32        label.latex = tex33        guard label.error == nil else { return nil }34        let fit = label.fittingSize35        guard fit.width > 0, fit.height > 0, fit.width < 20_000 else { return nil }36        let size = CGSize(width: ceil(fit.width) + 2, height: ceil(fit.height) + 2)37        label.frame = CGRect(origin: .zero, size: size); label.layout()38        guard let list = label.displayList else { return nil }39        let scale: CGFloat = 240        guard let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width * scale), pixelsHigh: Int(size.height * scale), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,41                                         colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0) else { return nil }42        rep.size = size // set before creating the context: it gives the context its 2× scale43        guard let ctx = NSGraphicsContext(bitmapImageRep: rep) else { return nil }44        NSGraphicsContext.saveGraphicsState(); NSGraphicsContext.current = ctx45        list.draw(ctx.cgContext)46        NSGraphicsContext.restoreGraphicsState()47        let image = NSImage(size: size); image.addRepresentation(rep); image.isTemplate = true48        // the label centres the line vertically: the baseline sits `position.y` above the bottom edge49        let lineHeight = max(list.ascent + list.descent, fontSize / 2)50        return RenderedMath(image: image, descent: (size.height - lineHeight) / 2 + list.descent, size: size)51    }52}5354/// Display formula (its own line, centred, scrolls horizontally when wider than the column).55struct MathBlockView: View {56    let tex: String57    @Environment(\.transcriptFontSize) private var fontSize58    var body: some View {59        if let m = MathRenderer.render(tex, fontSize: fontSize * 1.15, display: true) {60            ViewThatFits(in: .horizontal) {61                Image(nsImage: m.image).renderingMode(.template).foregroundStyle(.primary).frame(maxWidth: .infinity).padding(.vertical, 4)62                ScrollView(.horizontal) { Image(nsImage: m.image).renderingMode(.template).foregroundStyle(.primary).padding(.vertical, 4) }63            }64            .accessibilityLabel("Formule : \(tex)")65            .contextMenu { Button("Copier le LaTeX") { Pasteboard.copy(tex) } }66        } else {67            // TeX that cannot be typeset is shown as written, never hidden68            Text(tex).font(.system(size: fontSize * 0.92, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled)69        }70    }71}7273private struct TranscriptFontSizeKey: EnvironmentKey { static let defaultValue: CGFloat = 14 }74extension EnvironmentValues {75    var transcriptFontSize: CGFloat { get { self[TranscriptFontSizeKey.self] } set { self[TranscriptFontSizeKey.self] = newValue } }76}7778enum Pasteboard {79    static func copy(_ string: String) { let pb = NSPasteboard.general; pb.clearContents(); pb.setString(string, forType: .string) }80    /// Rich copy: Markdown source as plain text plus RTF, so that Pages / Mail / Notes paste formatted text.81    static func copy(plain: String, rich: NSAttributedString) {82        let pb = NSPasteboard.general; pb.clearContents(); pb.setString(plain, forType: .string)83        if let rtf = try? rich.data(from: NSRange(location: 0, length: rich.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf]) { pb.setData(rtf, forType: .rtf) }84    }85}86
Files main
Menu

Theme