SPB Git

Repository Public MIT

MathView.swift 8.8 KB 193 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/Markdown/MathView.swift10// Module           : Markdown11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import SwiftMath90#if canImport(UIKit)91import UIKit92typealias PlatformImage = UIImage93#else94import AppKit95typealias PlatformImage = NSImage96#endif9798struct RenderedMath: @unchecked Sendable {99    let image: PlatformImage100    let descent: CGFloat101    let size: CGSize102    var swiftUIImage: Image {103        #if canImport(UIKit)104        Image(uiImage: image)105        #else106        Image(nsImage: image)107        #endif108    }109}110111/// Typesets TeX once per (source, size, mode). Images are templates: they take the colour of the surrounding text.112@MainActor enum MathRenderer {113    private static let cache: NSCache<NSString, Box> = { let c = NSCache<NSString, Box>(); c.countLimit = 600; return c }()114    private final class Box { let value: RenderedMath?; init(_ v: RenderedMath?) { value = v } }115116    static func render(_ tex: String, fontSize: CGFloat, display: Bool) -> RenderedMath? {117        let key = "\(display ? "D" : "I")|\(fontSize)|\(tex)" as NSString118        if let hit = cache.object(forKey: key) { return hit.value }119        let value = typeset(tex, fontSize: fontSize, display: display)120        cache.setObject(Box(value), forKey: key)121        return value122    }123124    private static func typeset(_ tex: String, fontSize: CGFloat, display: Bool) -> RenderedMath? {125        guard tex.count < 4000 else { return nil }126        let label = MTMathUILabel()127        label.displayErrorInline = false128        label.fontSize = fontSize; label.labelMode = display ? .display : .text; label.textColor = .black; label.textAlignment = .left129        label.latex = tex130        guard label.error == nil else { return nil }131        #if canImport(UIKit)132        // MTMathUILabel implements only intrinsicContentSize on iOS; UIView.sizeThatFits would return the (zero) bounds.133        let fit = label.intrinsicContentSize134        guard fit.width > 0, fit.height > 0, fit.width < 20_000 else { return nil }135        let size = CGSize(width: ceil(fit.width) + 2, height: ceil(fit.height) + 2)136        label.frame = CGRect(origin: .zero, size: size)137        label.backgroundColor = .clear138        label.layoutIfNeeded()139        guard let list = label.displayList else { return nil }140        let format = UIGraphicsImageRendererFormat(); format.scale = 3; format.opaque = false141        let image = UIGraphicsImageRenderer(size: size, format: format).image { ctx in142            // the display list draws in Core Graphics coordinates (origin bottom-left)143            ctx.cgContext.translateBy(x: 0, y: size.height); ctx.cgContext.scaleBy(x: 1, y: -1)144            list.draw(ctx.cgContext)145        }.withRenderingMode(.alwaysTemplate)146        let lineHeight = max(list.ascent + list.descent, fontSize / 2)147        return RenderedMath(image: image, descent: (size.height - lineHeight) / 2 + list.descent, size: size)148        #else149        let fit = label.fittingSize150        guard fit.width > 0, fit.height > 0, fit.width < 20_000 else { return nil }151        let size = CGSize(width: ceil(fit.width) + 2, height: ceil(fit.height) + 2)152        label.frame = CGRect(origin: .zero, size: size)153        label.layout()154        guard let list = label.displayList else { return nil }155        let scale: CGFloat = 2156        guard let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width * scale), pixelsHigh: Int(size.height * scale), bitsPerSample: 8,157                                         samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0) else { return nil }158        rep.size = size // set before creating the context: it gives the context its 2× scale159        guard let ctx = NSGraphicsContext(bitmapImageRep: rep) else { return nil }160        NSGraphicsContext.saveGraphicsState(); NSGraphicsContext.current = ctx161        list.draw(ctx.cgContext)162        NSGraphicsContext.restoreGraphicsState()163        let image = NSImage(size: size); image.addRepresentation(rep); image.isTemplate = true164        let lineHeight = max(list.ascent + list.descent, fontSize / 2)165        return RenderedMath(image: image, descent: (size.height - lineHeight) / 2 + list.descent, size: size)166        #endif167    }168}169170/// Display formula (its own line, centred, scrolls horizontally when wider than the column).171struct MathBlockView: View {172    let tex: String173    @Environment(\.transcriptFontSize) private var fontSize174    var body: some View {175        if let m = MathRenderer.render(tex, fontSize: fontSize * 1.15, display: true) {176            ViewThatFits(in: .horizontal) {177                m.swiftUIImage.renderingMode(.template).foregroundStyle(.primary).frame(maxWidth: .infinity).padding(.vertical, 4)178                ScrollView(.horizontal) { m.swiftUIImage.renderingMode(.template).foregroundStyle(.primary).padding(.vertical, 4) }179            }180            .accessibilityLabel("Formula: \(tex)")181            .contextMenu { Button("Copy LaTeX") { Pasteboard.copy(tex) } }182        } else {183            // TeX that cannot be typeset is shown as written, never hidden184            Text(tex).font(.system(size: fontSize * 0.92, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled)185        }186    }187}188189private struct TranscriptFontSizeKey: EnvironmentKey { static let defaultValue: CGFloat = 17 }190extension EnvironmentValues {191    var transcriptFontSize: CGFloat { get { self[TranscriptFontSizeKey.self] } set { self[TranscriptFontSizeKey.self] = newValue } }192}193
Files main
Menu

Theme