Repository Public
1// ORIX Docs2// File: App/Sources/Sheets/MathView.swift3// Description: A view that typesets LaTeX with the document's math renderer and draws it as vector glyphs (equation preview, palette keys).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import AppKit9import DocModel10import DocMath1112struct MathView: NSViewRepresentable {13 let latex: String14 var fontSize: CGFloat = 2015 var display = true16 var typeface: MathTypeface = .latinModern17 var padding: CGFloat = 41819 func makeNSView(context: Context) -> MathCanvas { MathCanvas() }2021 func updateNSView(_ view: MathCanvas, context: Context) {22 guard view.latex != latex || view.fontSize != fontSize || view.display != display || view.typeface != typeface || view.padding != padding else { return }23 view.latex = latex; view.fontSize = fontSize; view.display = display; view.typeface = typeface; view.padding = padding24 view.needsDisplay = true25 }26}2728final class MathCanvas: NSView {29 var latex = ""30 var fontSize: CGFloat = 2031 var display = true32 var typeface: MathTypeface = .latinModern33 var padding: CGFloat = 43435 override var isFlipped: Bool { true }36 override func hitTest(_ point: NSPoint) -> NSView? { nil }37 override func viewDidChangeEffectiveAppearance() { needsDisplay = true }3839 override func draw(_ dirtyRect: NSRect) {40 guard !latex.isEmpty, let ctx = NSGraphicsContext.current?.cgContext else { return }41 let dark = effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua42 let layout = MathRenderer.layout(latex: latex, fontSize: fontSize, display: display, color: RGBA(hex: dark ? 0xECEDF3 : 0x16181D), typeface: typeface)43 guard layout.error == nil, layout.width > 0 else { return }44 let height = layout.ascent + layout.descent45 let scale = min(1, max(0.1, (bounds.width - 2 * padding) / layout.width), max(0.1, (bounds.height - 2 * padding) / max(1, height)))46 ctx.saveGState()47 ctx.translateBy(x: (bounds.width - layout.width * scale) / 2, y: (bounds.height - height * scale) / 2 + layout.ascent * scale)48 ctx.scaleBy(x: scale, y: scale)49 layout.draw(in: ctx, at: .zero)50 ctx.restoreGState()51 }52}5354/// Lets SwiftUI controls insert text at the insertion point of a `LatexEditor`.55final class LatexEditorController {56 weak var textView: NSTextView?5758 /// Inserts a snippet. `‸` marks the places to fill: the first one receives the selected text (if any) and the caret lands on the next one.59 func insert(_ snippet: String) {60 guard let tv = textView else { return }61 let marker = MathSnippet.marker62 let selection = tv.selectedRange()63 let selected = (tv.string as NSString).substring(with: selection)64 var s = snippet65 if !selected.isEmpty, let r = s.range(of: marker) { s.replaceSubrange(r, with: selected) }66 let caret = (s as NSString).range(of: marker)67 var clean = s.replacingOccurrences(of: marker, with: "")68 // A command name must not run into the letters that follow it ("\alpha" + "x").69 if clean.range(of: #"\\[A-Za-z]+$"#, options: .regularExpression) != nil { clean += " " }70 tv.insertText(clean, replacementRange: selection)71 let offset = caret.location == NSNotFound ? (clean as NSString).length : caret.location72 tv.setSelectedRange(NSRange(location: selection.location + offset, length: 0))73 tv.window?.makeFirstResponder(tv)74 }7576 func focus() { if let tv = textView { tv.window?.makeFirstResponder(tv) } }77}7879/// A multi-line monospaced source editor without any automatic substitution (quotes, dashes and spelling would corrupt LaTeX).80struct LatexEditor: NSViewRepresentable {81 @Binding var text: String82 let controller: LatexEditorController8384 func makeCoordinator() -> Coordinator { Coordinator(text: $text) }8586 func makeNSView(context: Context) -> NSScrollView {87 let scroll = NSTextView.scrollableTextView()88 scroll.hasVerticalScroller = true89 scroll.autohidesScrollers = true90 scroll.drawsBackground = false91 scroll.borderType = .noBorder92 guard let tv = scroll.documentView as? NSTextView else { return scroll }93 tv.delegate = context.coordinator94 tv.font = .monospacedSystemFont(ofSize: 13, weight: .regular)95 tv.textColor = .labelColor96 tv.drawsBackground = false97 tv.isRichText = false98 tv.allowsUndo = true99 tv.isAutomaticQuoteSubstitutionEnabled = false100 tv.isAutomaticDashSubstitutionEnabled = false101 tv.isAutomaticTextReplacementEnabled = false102 tv.isAutomaticSpellingCorrectionEnabled = false103 tv.isContinuousSpellCheckingEnabled = false104 tv.isGrammarCheckingEnabled = false105 tv.isAutomaticTextCompletionEnabled = false106 tv.textContainerInset = NSSize(width: 6, height: 7)107 tv.string = text108 tv.setAccessibilityLabel(String(localized: "LaTeX source"))109 tv.setAccessibilityIdentifier("equation-source")110 controller.textView = tv111 DispatchQueue.main.async { tv.window?.makeFirstResponder(tv); tv.setSelectedRange(NSRange(location: (tv.string as NSString).length, length: 0)) }112 return scroll113 }114115 func updateNSView(_ scroll: NSScrollView, context: Context) {116 guard let tv = scroll.documentView as? NSTextView else { return }117 context.coordinator.text = $text118 if tv.string != text { tv.string = text }119 }120121 final class Coordinator: NSObject, NSTextViewDelegate {122 var text: Binding<String>123 init(text: Binding<String>) { self.text = text }124 func textDidChange(_ notification: Notification) {125 guard let tv = notification.object as? NSTextView else { return }126 if text.wrappedValue != tv.string { text.wrappedValue = tv.string }127 }128 }129}130