diff --git a/README.md b/README.md index 8e4dbf6..87f545a 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut - fenced and indented code blocks, colored by a highlighter your app provides, and tables; - links, bare URLs and email addresses, and reference links; - images, drawn by a loader your app provides; + - LaTeX math, drawn by a renderer your app provides; - HTML entities and a few HTML tags. - **Custom tags.** Define tags such as `@Ana` and how they look: font traits, colours, a link, padding, and shapes drawn behind or over the text. Pills and underlines (solid, dashed, dotted, wavy, @@ -205,6 +206,34 @@ TranscriptText(stream: stream) In UIKit, set `codeHighlighter` on `TranscriptTextView`. Colors are `TranscriptColor`s, so give them a light and a dark value when the theme has both. +### Math + +LaTeX between `\(` and `\)` is inline math. A line that starts with `\[` or `$$` starts display math, which ends at +`\]` or `$$`. Display math is a block of its own and can span lines: TranscriptKit keeps its lines as written, even a +line that starts with `-` or `#`. If a blank line comes before the closer, it is not a formula, and its lines show as +text. `$$ … $$` inside a line is display math too. A `\[` inside a line is a Markdown escape, so `\[1\]` shows `[1]`. +A single `$` is text, so prices stay as written. TranscriptKit does not read Markdown inside a formula. + +Without a renderer, a formula shows its LaTeX in the code font. A renderer gets the formula and the font size of the +text around it. It returns an image, the image's size in points, and its baseline: the distance from the bottom edge +up to the baseline. TranscriptKit calls it off the main thread, once for each formula and font size. + +```swift +TranscriptText(stream: stream) + .mathRenderer { math, fontSize in + guard let drawn = await myMathRenderer.draw(math.tex, display: math.isDisplay, fontSize: fontSize) else { + return nil + } + return TranscriptMathImage(image: drawn.cgImage, size: drawn.size, baseline: drawn.descent) + } +``` + +In UIKit, set `mathRenderer` on `TranscriptTextView`. TranscriptKit uses only the alpha of the image, and draws the +formula in the text color, so it follows light and dark appearance. A formula that is wider than the text column is +scaled down to fit. A paragraph that holds only display math is centered. While a formula streams in, it shows +nothing until it closes, so the text on screen only grows. Copy gives the LaTeX with its delimiters, and VoiceOver +reads the LaTeX. + ### Selection The text is selectable by default. Turn selection off for text inside a view that reacts to taps, such as a card or a diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index 80c09a4..bc0291d 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -110,7 +110,7 @@ final class BlockLayout: @unchecked Sendable { let insets = style.insets(for: block) let available = max(width - insets.leading - insets.trailing, 1) - let hasImages = block.spans.contains { $0.image != nil } + let hasImages = block.spans.contains { $0.image != nil || $0.math != nil } // Laid out again when the store's pictures or code colors change. let usesStore = hasImages || (block.kind.isCode && images?.hasHighlighter == true) let revision = usesStore ? (images?.revision ?? 0) : nil @@ -182,9 +182,13 @@ final class BlockLayout: @unchecked Sendable { let fixedHeight = style.lineHeight(for: block.kind) let gap = fixedHeight == nil ? style.lineSpacing : 0 + let isDisplayMath = block.spans.count == 1 && block.spans[0].math?.isDisplay == true + && block.text.trimmingCharacters(in: .whitespacesAndNewlines) == "\u{FFFC}" func add(_ ctLine: CTLine, range: Range, indexBase: Int, leading: CGFloat = 0, text: NSAttributedString? = nil) { let metrics = fitted(lineMetrics(ctLine, isEmpty: range.isEmpty, font: font), to: fixedHeight) - let x = insets.leading + leading + alignmentOffset(block, style: style, width: metrics.width, room: available - leading) + let x = insets.leading + leading + (isDisplayMath + ? max(((available - leading - metrics.width) / 2).rounded(.down), 0) + : alignmentOffset(block, style: style, width: metrics.width, room: available - leading)) var decorations: LineDecorations? if let decorated, let text { decorations = LineDecorations.make(line: ctLine, range: range, indexBase: indexBase, visibleWidth: metrics.width, diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index a77356c..63c5408 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -650,7 +650,14 @@ public final class DocumentLayout: @unchecked Sendable { context.translateBy(x: rect.minX, y: rect.maxY) context.scaleBy(x: 1, y: -1) context.interpolationQuality = .high - context.draw(picture, in: CGRect(origin: .zero, size: rect.size)) + let box = CGRect(origin: .zero, size: rect.size) + if attachment.isMask { + context.clip(to: box, mask: picture) + context.setFillColor(text) + context.fill(box) + } else { + context.draw(picture, in: box) + } return } // No picture: a chip with the alt text. diff --git a/Sources/TranscriptKit/Layout/ImageStore.swift b/Sources/TranscriptKit/Layout/ImageStore.swift index 9c21cd3..71a3e14 100644 --- a/Sources/TranscriptKit/Layout/ImageStore.swift +++ b/Sources/TranscriptKit/Layout/ImageStore.swift @@ -113,6 +113,61 @@ final class TranscriptImageStore: @unchecked Sendable { handler?() } + // MARK: Formulas + + private struct FormulaKey: Hashable { + let math: TranscriptMath + /// The font size, to half a point. + let size: Int + } + + private var mathRenderer: TranscriptMathRenderer? + private var mathGeneration = 0 + private var formulas: [FormulaKey: TranscriptMathImage] = [:] + private var formulasRequested: Set = [] + + var hasMathRenderer: Bool { lock.withLock { mathRenderer != nil } } + + /// Sets the math renderer. Formulas drawn by an earlier one are dropped, + /// and the revision goes up so that they are laid out again. + func setMathRenderer(_ renderer: TranscriptMathRenderer?) { + lock.withLock { + mathRenderer = renderer + mathGeneration += 1 + _revision += 1 + formulas = [:] + formulasRequested = [] + } + } + + /// The drawn formula if it has arrived. Starts drawing it if not. + func formula(for math: TranscriptMath, fontSize: CGFloat) -> TranscriptMathImage? { + let key = FormulaKey(math: math, size: Int((fontSize * 2).rounded())) + let (formula, render, generation): (TranscriptMathImage?, TranscriptMathRenderer?, Int) = lock.withLock { + if let formula = formulas[key] { return (formula, nil, mathGeneration) } + guard let mathRenderer, !formulasRequested.contains(key) else { return (nil, nil, mathGeneration) } + formulasRequested.insert(key) + return (nil, mathRenderer, mathGeneration) + } + if let render { + Task.detached { [weak self] in + let drawn = await render(math, CGFloat(key.size) / 2)?.withAlphaAsMask() + self?.finishFormula(key, drawn, generation: generation) + } + } + return formula + } + + private func finishFormula(_ key: FormulaKey, _ formula: TranscriptMathImage?, generation: Int) { + let handler: (@Sendable () -> Void)? = lock.withLock { + guard generation == mathGeneration, let formula else { return nil } + formulas[key] = formula + _revision += 1 + return onChange + } + handler?() + } + /// The picture for `image` if it has arrived. Starts loading it if not. func picture(for image: TranscriptImage) -> CGImage? { let (picture, load, generation): (CGImage?, Loader?, Int) = lock.withLock { diff --git a/Sources/TranscriptKit/Layout/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index 3340e36..69af107 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -257,6 +257,7 @@ public struct TranscriptStyle: Equatable, Sendable { var traits = extraTraits var isLink = false var image: TranscriptImage? + var math: TranscriptMath? // Spans are sorted with outer ones first, so an inner tag's colors win. var foreground: TranscriptColor? var background: TranscriptColor? @@ -264,6 +265,7 @@ public struct TranscriptStyle: Equatable, Sendable { traits.formUnion(span.traits) if span.link != nil || span.reference.map({ definitions[$0] != nil }) == true { isLink = true } if let spanImage = span.image { image = spanImage } + if let spanMath = span.math { math = spanMath } if let decoration = span.customTag?.decoration { if let color = decoration.foreground { foreground = color } if let color = decoration.background { background = color } @@ -283,9 +285,10 @@ public struct TranscriptStyle: Equatable, Sendable { result.addAttribute(Self.foregroundKey, value: linkColor, range: range) } if let background { result.addAttribute(Self.backgroundKey, value: background, range: range) } - if let image, range.length == 1 { + if image != nil || math != nil, range.length == 1 { let font = result.attribute(Self.fontKey, at: lower, effectiveRange: nil).map { $0 as! CTFont } ?? self.font(for: block.kind) - let attachment = ImageAttachment(image: image, sizing: images, font: font, style: self) + let attachment = math.map { ImageAttachment(math: $0, sizing: images, font: font, style: self) } + ?? ImageAttachment(image: image!, sizing: images, font: font, style: self) result.addAttribute(Self.imageKey, value: attachment, range: range) result.addAttribute(Self.runDelegateKey, value: attachment.makeRunDelegate(), range: range) } @@ -316,9 +319,48 @@ final class ImageAttachment: @unchecked Sendable { let size: CGSize /// Above the baseline; the rest of `size.height` is below it. let ascent: CGFloat + /// For a formula: it, and its picture is a mask drawn in the text color. + let math: TranscriptMath? + var isMask: Bool { math != nil && picture != nil } + + /// A formula, drawn by the store's math renderer, or its LaTeX as written + /// until it is (or if it is not). + init(math: TranscriptMath, sizing: ImageSizing?, font: CTFont, style: TranscriptStyle) { + self.image = TranscriptImage(source: "", alt: math.tex) + self.math = math + let maximumWidth = max(sizing?.maximumWidth ?? 320, 20) + if let formula = sizing?.store?.formula(for: math, fontSize: CTFontGetSize(font)) { + let natural = CGSize(width: max(formula.size.width, 1), height: max(formula.size.height, 1)) + let scale = min(1, maximumWidth / natural.width) + self.picture = formula.image + self.label = nil + self.size = CGSize(width: ceil(natural.width * scale), height: ceil(natural.height * scale)) + self.ascent = size.height - formula.baseline * scale + } else { + let size = CTFontGetSize(font) * 0.85 + let code = style.codeFont?.makeFont(size: size) ?? CTFontCreateUIFontForLanguage(.userFixedPitch, size, nil)! + let attributes: [NSAttributedString.Key: Any] = [ + TranscriptStyle.fontKey: code, + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true, + ] + var line = CTLineCreateWithAttributedString(NSAttributedString(string: math.source, attributes: attributes)) + let padding: CGFloat = 6 + let available = maximumWidth - padding * 2 + if CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil)) > available { + let ellipsis = CTLineCreateWithAttributedString(NSAttributedString(string: "…", attributes: attributes)) + line = CTLineCreateTruncatedLine(line, Double(available), .end, ellipsis) ?? line + } + self.picture = nil + self.label = line + let width = ceil(CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))) + padding * 2 + self.size = CGSize(width: min(width, maximumWidth), height: ceil(CTFontGetAscent(font) + CTFontGetDescent(font)) + 4) + self.ascent = ceil(CTFontGetAscent(font)) + 2 + } + } init(image: TranscriptImage, sizing: ImageSizing?, font: CTFont, style: TranscriptStyle) { self.image = image + self.math = nil let maximumWidth = max(sizing?.maximumWidth ?? 320, 20) if let picture = sizing?.store?.picture(for: image) { let natural = CGSize(width: max(CGFloat(picture.width), 1), height: max(CGFloat(picture.height), 1)) diff --git a/Sources/TranscriptKit/Markdown/BlockParser.swift b/Sources/TranscriptKit/Markdown/BlockParser.swift index 58d1b19..4ef128f 100644 --- a/Sources/TranscriptKit/Markdown/BlockParser.swift +++ b/Sources/TranscriptKit/Markdown/BlockParser.swift @@ -4,7 +4,8 @@ import Foundation /// /// Follows CommonMark's two-level structure: container blocks (block quotes /// and list items, nested in any order) hold leaf blocks (paragraphs, ATX and -/// setext headings, fenced and indented code, GFM tables, thematic breaks). +/// setext headings, fenced and indented code, GFM tables, thematic breaks, +/// and display math: a line that starts with `\[` or `$$`). /// Each leaf becomes one block that records the containers it sits in. /// HTML comment blocks are dropped. Not supported: other raw HTML blocks /// (they read as paragraphs) and link reference definitions. @@ -16,6 +17,9 @@ enum BlockParser { case code(language: String?, fence: Character?, fenceLength: Int, indent: Int, closed: Bool) case rule case table(alignments: [TranscriptTable.Alignment]) + /// Display math that a line starting with `\[` or `$$` opened, until + /// `closer` ends it. Its lines are kept as written. + case math(closer: String, closed: Bool) } /// A block's content, kept in the form that is cheapest to extend. @@ -37,6 +41,8 @@ enum BlockParser { /// `lastLine` trimmed, as UTF-16: converted once when the line is /// added, not again on every update while it stays the last line. private var lastLineUnits: [UInt16] = [] + /// Display math: its lines as written, from the opener to the closer. + private(set) var mathLines: [String] = [] /// Tables: each row's cells, as source. private(set) var rows: [[String]] = [] /// Tables: the parsed cells of complete rows, filled in as they are parsed. @@ -69,6 +75,8 @@ enum BlockParser { lineCount += 1 case .rule: break + case .math: + mathLines.append(line) case .table: rows.append(BlockParser.tableCells(line)) lineCount += 1 @@ -82,6 +90,17 @@ enum BlockParser { } } + /// Display math that never closed: its lines become a paragraph, as written. + mutating func becomeParagraph() { + let lines = mathLines + kind = .paragraph + mathLines = [] + lineCount = 0 + for line in lines { + addLine(String(BlockParser.trimmingSpaceAndTab(Substring(line)))) + } + } + /// Turns a one-line paragraph into a table with that line as its header. mutating func becomeTable(alignments: [TranscriptTable.Alignment]) { let header = lastLine ?? "" @@ -171,6 +190,11 @@ enum BlockParser { return true } + private var lastBlockIsOpenMath: Bool { + guard case .math(_, false)? = blocks.last?.kind else { return false } + return true + } + private var lastBlockIsOpenIndentedCode: Bool { guard case .code(_, nil, _, _, false)? = blocks.last?.kind else { return false } return true @@ -181,6 +205,7 @@ enum BlockParser { private mutating func endLastBlock() { canContinue = false tableOpen = false + if lastBlockIsOpenMath { blocks[blocks.count - 1].becomeParagraph() } guard let last = blocks.indices.last, case .code(let language, let fence, let length, let indent, false) = blocks[last].kind else { return } blocks[last].kind = .code(language: language, fence: fence, fenceLength: length, indent: indent, closed: true) @@ -255,6 +280,29 @@ enum BlockParser { } return } + // An open formula takes its containers' lines as written, up to + // the closer. A blank line cannot be inside one: then it was not + // a formula, and its lines are text. + if lastBlockIsOpenMath, allMatched, case .math(let closer, _) = blocks[blocks.count - 1].kind { + let rest = scanner.rest + if BlockParser.trimmingSpaceAndTab(rest).isEmpty { + blocks[blocks.count - 1].becomeParagraph() + canContinue = false + return + } + guard let close = BlockParser.mathCloser(in: rest, closer: closer) else { + blocks[blocks.count - 1].addLine(String(rest)) + return + } + blocks[blocks.count - 1].addLine(String(rest[..") { inComment = false } return @@ -389,6 +437,20 @@ enum BlockParser { endLists(from: containers.count) return } + if let closer = BlockParser.mathOpener(leaf) { + let body = leaf.dropFirst(2) + if let close = BlockParser.mathCloser(in: body, closer: closer) { + // On one line, and alone on it: a block. With text after it, + // it is part of the paragraph. + if BlockParser.trimmingSpaceAndTab(body[close.upperBound...]).isEmpty { + start(.math(closer: closer, closed: true), line: String(leaf[.. String? { + if content.hasPrefix("\\[") { return "\\]" } + if content.hasPrefix("$$") { return "$$" } + return nil + } + + /// Where `closer` is in `text`. A backslash escapes the character after + /// it, so the "\]" in "\\]" (a line break, then "]") does not close. + static func mathCloser(in text: Substring, closer: String) -> Range? { + var index = text.startIndex + while index < text.endIndex { + let next = text.index(after: index) + guard next < text.endIndex else { return nil } + if text[index] == "\\" { + if closer == "\\]", text[next] == "]" { return index.. (character: Character, length: Int, language: String?)? { guard let first = content.first, first == "`" || first == "~" else { return nil } let length = content.prefix { $0 == first }.count diff --git a/Sources/TranscriptKit/Markdown/InlineParser.swift b/Sources/TranscriptKit/Markdown/InlineParser.swift index 739366c..2be9189 100644 --- a/Sources/TranscriptKit/Markdown/InlineParser.swift +++ b/Sources/TranscriptKit/Markdown/InlineParser.swift @@ -78,6 +78,11 @@ enum InlineParser { /// literal "[1]" changes text already shown. A longer one shows as written. private static let openBracketReach = 64 + /// While streaming, an open formula hides what follows it for this many + /// units, so that the text only grows. A longer one shows as plain text, + /// as it does if it never closes. + private static let openMathReach = 512 + fileprivate struct Tag { let name: String let traits: InlineSpan.Traits @@ -114,12 +119,12 @@ enum InlineParser { let extras: InlineSpan.Extras? init(from: Int, to: Int, traits: InlineSpan.Traits, link: String?, image: TranscriptImage? = nil, - reference: String? = nil, customTag: InlineSpan.CustomTag? = nil) { + reference: String? = nil, customTag: InlineSpan.CustomTag? = nil, math: TranscriptMath? = nil) { self.from = from self.to = to self.traits = traits self.link = link - self.extras = InlineSpan.Extras.make(image: image, reference: reference, customTag: customTag) + self.extras = InlineSpan.Extras.make(image: image, reference: reference, customTag: customTag, math: math) } func span(_ range: Range) -> InlineSpan { @@ -203,10 +208,11 @@ enum InlineParser { private static let objectReplacement: UInt16 = 0xFFFC private static let atSign = UInt16(UInt8(ascii: "@")) private static let dot = UInt16(UInt8(ascii: ".")) + private static let dollar = UInt16(UInt8(ascii: "$")) private static func isSpecial(_ unit: UInt16) -> Bool { switch unit { - case backslash, backtick, star, underscore, tilde, bang, openBracket, closeBracket, lessThan, ampersand: return true + case backslash, backtick, star, underscore, tilde, bang, openBracket, closeBracket, lessThan, ampersand, dollar: return true default: return false } } @@ -214,7 +220,7 @@ enum InlineParser { private static let escapable = Set("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".utf16) /// Trailing units that are held back in open mode: each could be the /// start of markup that the next characters decide. - private static let heldBackWhenTrailing = Set("*_~`\\[]!".utf16) + private static let heldBackWhenTrailing = Set("*_~`\\[]!$".utf16) private static var longestEntityName: Int { HTMLEntities.longestName } @@ -384,6 +390,23 @@ enum InlineParser { switch unit { case backslash: + // "\(" … "\)" is inline math. "\[" … "\]" is display math only + // at the start of a line, where the block parser finds it; in a + // line, "\[" is an escaped "[". + if i + 1 < count, units[i + 1] == openParen { + if let close = mathClose(from: i + 2, in: units, count: count, closer: closeParen) { + guard allowed(close + 1) else { return false } + takeMath(&state, units, opener: i, close: close, display: false) + state.position = close + 2 + return true + } + // Whether it closes later depends on text that may still come. + guard allowed(count) else { return false } + if open, count - i <= openMathReach { + state.position = count + return true + } + } guard i + 1 < count else { guard allowed(count) else { return false } state.appendText(units[i..<(i + 1)]) @@ -764,6 +787,34 @@ enum InlineParser { state.position = i + 1 } + case dollar: + // "$$" … "$$" is display math. A single "$", as in a price, is text. + guard i + 1 < count else { + guard allowed(count) else { return false } + state.appendText(units[i..<(i + 1)]) + state.position = i + 1 + return true + } + guard allowed(i + 1) else { return false } + guard units[i + 1] == dollar else { + state.appendText(units[i..<(i + 1)]) + state.position = i + 1 + return true + } + if let close = mathClose(from: i + 2, in: units, count: count, closer: nil) { + guard allowed(close + 1) else { return false } + takeMath(&state, units, opener: i, close: close, display: true) + state.position = close + 2 + return true + } + guard allowed(count) else { return false } + if open, count - i <= openMathReach { + state.position = count + } else { + state.appendText(units[i..<(i + 2)]) + state.position = i + 2 + } + case ampersand: let scan = scanEntity(at: i, in: units, count: count) if case .incomplete = scan { @@ -851,6 +902,37 @@ enum InlineParser { return true } + // MARK: Math + + /// Where the closing delimiter starts after `start`: `\` then `closer`, or + /// "$$" when `closer` is nil. A backslash escapes the unit after it, so + /// "\\)" (a LaTeX line break, then ")") does not close. + private static func mathClose(from start: Int, in units: [UInt16], count: Int, closer: UInt16?) -> Int? { + var k = start + while k + 1 < count { + if units[k] == backslash { + if let closer, units[k + 1] == closer { return k } + k += 2 + continue + } + if closer == nil, units[k] == dollar, units[k + 1] == dollar { return k } + k += 1 + } + return nil + } + + /// A formula, kept whole: its LaTeX is not parsed as Markdown. An empty + /// one shows as written. + private static func takeMath(_ state: inout Checkpoint, _ units: [UInt16], opener: Int, close: Int, display: Bool) { + let tex = String(decoding: units[(opener + 2).., traits: Traits = [], link: String? = nil, image: TranscriptImage? = nil, - reference: String? = nil, customTag: CustomTag? = nil) { + reference: String? = nil, customTag: CustomTag? = nil, math: TranscriptMath? = nil) { self.range = range self.traits = traits self.link = link - self.extras = Extras.make(image: image, reference: reference, customTag: customTag) + self.extras = Extras.make(image: image, reference: reference, customTag: customTag, math: math) } init(range: Range, traits: Traits, link: String?, extras: Extras?) { @@ -64,24 +70,45 @@ public struct InlineSpan: Equatable, Sendable { let image: TranscriptImage? let reference: String? let customTag: CustomTag? + let math: TranscriptMath? - private init(image: TranscriptImage?, reference: String?, customTag: CustomTag?) { + private init(image: TranscriptImage?, reference: String?, customTag: CustomTag?, math: TranscriptMath?) { self.image = image self.reference = reference self.customTag = customTag + self.math = math } /// Nil when there is nothing to keep. - static func make(image: TranscriptImage?, reference: String?, customTag: CustomTag?) -> Extras? { - image == nil && reference == nil && customTag == nil ? nil : Extras(image: image, reference: reference, customTag: customTag) + static func make(image: TranscriptImage?, reference: String?, customTag: CustomTag?, math: TranscriptMath? = nil) -> Extras? { + image == nil && reference == nil && customTag == nil && math == nil + ? nil : Extras(image: image, reference: reference, customTag: customTag, math: math) } static func == (a: Extras, b: Extras) -> Bool { - a === b || (a.image == b.image && a.reference == b.reference && a.customTag == b.customTag) + a === b || (a.image == b.image && a.reference == b.reference && a.customTag == b.customTag && a.math == b.math) } } } +/// A LaTeX formula in the text: `\( … \)` inline, or display math, which is +/// `$$ … $$` or a block that starts with `\[` or `$$` at the start of a line. +/// It is drawn by the app's renderer; see `TranscriptTextView.mathRenderer`. +public struct TranscriptMath: Equatable, Hashable, Sendable { + /// The formula's LaTeX, without its delimiters. + public var tex: String + /// Display math, set on its own, rather than math in a line of text. + public var isDisplay: Bool + + public init(tex: String, isDisplay: Bool) { + self.tex = tex + self.isDisplay = isDisplay + } + + /// The formula as written, with delimiters: what copying gives. + public var source: String { isDisplay ? "\\[" + tex + "\\]" : "\\(" + tex + "\\)" } +} + /// An image in the text, `![alt](source)` in Markdown. public struct TranscriptImage: Equatable, Hashable, Sendable { public var source: String @@ -403,10 +430,11 @@ public struct TranscriptDocument: Equatable, Sendable { guard lower < upper else { continue } let local = NSRange(location: lower - start, length: upper - lower) let text = NSMutableString(string: (block.text as NSString).substring(with: local)) - // Images by their alt text, last first so offsets stay valid. - for span in block.spans.reversed() { - guard let image = span.image, local.contains(span.range.lowerBound) else { continue } - text.replaceCharacters(in: NSRange(location: span.range.lowerBound - local.location, length: 1), with: image.alt) + // Images by their alt text and formulas by their LaTeX, last + // first so offsets stay valid. + for span in block.spans.reversed() where local.contains(span.range.lowerBound) { + guard let replacement = span.image?.alt ?? span.math?.source else { continue } + text.replaceCharacters(in: NSRange(location: span.range.lowerBound - local.location, length: 1), with: replacement) } piece = text as String } diff --git a/Sources/TranscriptKit/Model/TranscriptMathImage.swift b/Sources/TranscriptKit/Model/TranscriptMathImage.swift new file mode 100644 index 0000000..e9ae1d2 --- /dev/null +++ b/Sources/TranscriptKit/Model/TranscriptMathImage.swift @@ -0,0 +1,44 @@ +import CoreGraphics +import Foundation + +/// A formula drawn by the app's renderer; see `TranscriptTextView.mathRenderer`. +public struct TranscriptMathImage: @unchecked Sendable { + /// A mask: only its alpha is used, and it is drawn in the text color, so + /// the formula follows light and dark appearance. + public var image: CGImage + /// Its size, in points. A formula wider than the text column is scaled down to fit. + public var size: CGSize + /// How far the formula's baseline is above its bottom edge, in points: + /// its depth. The baseline sits on the line's baseline. + public var baseline: CGFloat + + public init(image: CGImage, size: CGSize, baseline: CGFloat) { + self.image = image + self.size = size + self.baseline = max(baseline, 0) + } +} + +/// Draws a formula at a font size: the size of the text around inline math, +/// or of the paragraph for display math. Called off the main thread, once +/// for each formula and size. Nil keeps the LaTeX shown as written. +public typealias TranscriptMathRenderer = @Sendable (_ math: TranscriptMath, _ fontSize: CGFloat) async -> TranscriptMathImage? + +extension TranscriptMathImage { + /// The formula with its image's alpha as a DeviceGray image without + /// alpha: the only kind of image that `CGContext.clip(to:mask:)` takes. + func withAlphaAsMask() -> TranscriptMathImage? { + let width = image.width + let height = image.height + guard width > 0, height > 0, + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width, + space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue), + let data = context.data else { return nil } + context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height)) + guard let provider = CGDataProvider(data: Data(bytes: data, count: context.bytesPerRow * height) as CFData), + let mask = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8, bytesPerRow: context.bytesPerRow, + space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), + provider: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent) else { return nil } + return TranscriptMathImage(image: mask, size: size, baseline: baseline) + } +} diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index 8fb270e..6157488 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -20,6 +20,7 @@ public struct TranscriptText: UIViewRepresentable { private let style: TranscriptStyle private var loader: (@Sendable (TranscriptImage) async -> CGImage?)? private var highlighter: TranscriptCodeHighlighter? + private var mathRenderer: TranscriptMathRenderer? private var animatesTags = true private var animationTiming: TranscriptAnimationTiming = .immediately private var isSelectable = true @@ -63,6 +64,14 @@ public struct TranscriptText: UIViewRepresentable { return copy } + /// Draws LaTeX formulas; see `TranscriptTextView.mathRenderer`. Read once, + /// when the view is created. + public func mathRenderer(_ renderer: @escaping TranscriptMathRenderer) -> TranscriptText { + var copy = self + copy.mathRenderer = renderer + return copy + } + /// Whether custom tags with an animation play it when they finish /// arriving; see `TranscriptTextView.animatesTags`. On by default. public func animatesTags(_ animates: Bool) -> TranscriptText { @@ -127,6 +136,7 @@ public struct TranscriptText: UIViewRepresentable { view.setContentHuggingPriority(.required, for: .vertical) if let loader { view.imageLoader = loader } if let highlighter { view.codeHighlighter = highlighter } + if let mathRenderer { view.mathRenderer = mathRenderer } return view } diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift index c808c71..6fa1e84 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView+Accessibility.swift @@ -12,7 +12,7 @@ extension TranscriptTextView { for index in 0.. String { + let text = NSMutableString(string: (block.text as NSString).substring(to: end)) + for span in block.spans.reversed() where span.range.lowerBound < end && span.range.count == 1 { + guard let replacement = span.image?.alt ?? span.math?.tex else { continue } + text.replaceCharacters(in: NSRange(location: span.range.lowerBound, length: 1), with: replacement) + } + return text as String + } + /// What VoiceOver says for a block: its list marker, then its text. static func spokenText(_ text: String, of block: TranscriptBlock) -> String { switch block.marker { diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index baae8bc..643e7d7 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -163,6 +163,24 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } } + /// Draws LaTeX formulas: `\( … \)` inline, and `\[ … \]` and `$$ … $$` + /// as display math. It is called off the main thread, once for each formula + /// and font size. Only the alpha of the image it returns is used: the + /// formula is drawn in the text color. A formula shows its LaTeX as + /// written until it is drawn, or if the renderer returns nil. Not set by + /// default. + public var mathRenderer: TranscriptMathRenderer? { + didSet { + engine.images.setOnChange { [weak self] in + DispatchQueue.main.async { + MainActor.assumeIsolated { self?.relayoutNow() } + } + } + engine.images.setMathRenderer(mathRenderer) + relayoutNow() + } + } + private let engine = LayoutEngine() /// Holds the tiles, and the tail layer above them, below the system's diff --git a/Tests/TranscriptKitTests/MarkdownElementsTests.swift b/Tests/TranscriptKitTests/MarkdownElementsTests.swift index 205615a..d238810 100644 --- a/Tests/TranscriptKitTests/MarkdownElementsTests.swift +++ b/Tests/TranscriptKitTests/MarkdownElementsTests.swift @@ -127,6 +127,7 @@ private func characterSteps(_ markdown: String) -> [TranscriptDocument] { "- [ ] task one\n- [x] task *two*\n - nested ~~old~~ new\n\n> quote\n>\n> > deeper & deeper\n\n1. step\n\n ```\n code\n ```\n", "A bold and it
next © © ![pic](https://x.y/p.png) www.example.com.\n", "Write to first_last@example.co.uk or , not @handle.\n\n1. a\n1. b\n\n3) c\n3) d\n", + "Euler \\(e^{i\\pi} + 1 = 0\\) costs $5, not $$\\sum_{k=1}^{n} k$$, and\n\\[\n\\frac{a}{b} \\\\ c\n\\]\n\nNot math: \\(x and $$y\n", "See [the docs][d] and [d][], as in [1] and [2].\n\n[d]: https://docs.example.com \"Docs\"\n[1]: \n\nAfter, [a long bracket that is not a link at all, just an aside in the text] and [x](https://x.y).\n", ]) func newElementsOnlyGrowWhileStreaming(markdown: String) { diff --git a/Tests/TranscriptKitTests/MathTests.swift b/Tests/TranscriptKitTests/MathTests.swift new file mode 100644 index 0000000..5e043da --- /dev/null +++ b/Tests/TranscriptKitTests/MathTests.swift @@ -0,0 +1,265 @@ +import CoreGraphics +import CoreText +import Foundation +import Testing +@testable import TranscriptKit + +private func firstBlock(_ markdown: String) -> TranscriptBlock { + MarkdownStreamParser.document(from: markdown).blocks[0] +} + +private func formulas(_ block: TranscriptBlock) -> [TranscriptMath] { + block.spans.compactMap(\.math) +} + +@Test func inlineAndDisplayMathAreParsed() { + let inline = firstBlock("Euler: \\(e^{i\\pi} + 1 = 0\\) holds.") + #expect(formulas(inline) == [TranscriptMath(tex: "e^{i\\pi} + 1 = 0", isDisplay: false)]) + #expect(inline.text == "Euler: \u{FFFC} holds.") + #expect(formulas(firstBlock("\\[ x^2 \\]")) == [TranscriptMath(tex: "x^2", isDisplay: true)]) + #expect(firstBlock("\\[ x^2 \\]").text == "\u{FFFC}") + #expect(formulas(firstBlock("$$a + b$$")) == [TranscriptMath(tex: "a + b", isDisplay: true)]) + // Display math on lines of its own, in one paragraph. + #expect(formulas(firstBlock("$$\nx = 1\n$$")) == [TranscriptMath(tex: "x = 1", isDisplay: true)]) +} + +@Test func latexIsKeptWholeAndNotReadAsMarkdown() { + let block = firstBlock("\\(a_1 * b_2 * c_3\\) and \\(\\begin{pmatrix} a \\\\) b \\end{pmatrix}\\)") + #expect(formulas(block).map(\.tex) == ["a_1 * b_2 * c_3", "\\begin{pmatrix} a \\\\) b \\end{pmatrix}"]) + #expect(!block.spans.contains { $0.traits.contains(.italic) }) +} + +@Test func dollarsInTextAreNotMath() { + let prices = firstBlock("It costs $5 now and $10 later.") + #expect(formulas(prices).isEmpty) + #expect(prices.text == "It costs $5 now and $10 later.") + let unclosed = firstBlock("Only $$ here.") + #expect(formulas(unclosed).isEmpty) + #expect(unclosed.text == "Only $$ here.") +} + +@Test func anUnclosedOpenerInFinishedTextIsAnEscape() { + let block = firstBlock("Not math: \\(x") + #expect(formulas(block).isEmpty) + #expect(block.text == "Not math: (x") +} + +@Test func streamedMathMatchesParsingAtOnceAndShowsNothingUntilItCloses() { + let source = "Before \\(x^2 + y^2\\) after, and $$\\sum_i i$$ too." + var parser = MarkdownStreamParser(idPrefix: "md") + var shownSource: [String] = [] + for character in source { + parser.append(String(character)) + let text = parser.document.blocks.last?.text ?? "" + if text.contains("\\") || text.contains("$") { shownSource.append(text) } + } + parser.finish() + #expect(shownSource.isEmpty) + #expect(parser.document == MarkdownStreamParser.document(from: source)) + #expect(formulas(parser.document.blocks[0]).count == 2) +} + +@Test func aStrayOpenerShowsAsTextOnceItIsFarBehind() { + let tail = String(repeating: "word ", count: 120) + var parser = MarkdownStreamParser(idPrefix: "md") + parser.append("Before \\( " + tail) + #expect(parser.document.blocks[0].text == "Before ( " + tail.dropLast()) + var dollars = MarkdownStreamParser(idPrefix: "md") + dollars.append("Only $$ " + tail) + #expect(dollars.document.blocks[0].text == "Only $$ " + tail.dropLast()) +} + +@Test func anEmptyFormulaShowsAsWritten() { + #expect(firstBlock("a $$ $$ b").text == "a $$ $$ b") + #expect(firstBlock("a \\(\\) b").text == "a \\(\\) b") +} + +private let mathSamples = [ + "Euler \\(e^{i\\pi} + 1 = 0\\) costs $5, not $$\\sum_{k=1}^{n} k$$, and \\[\\frac{a}{b} \\\\ c\\] **bold \\(x_1\\) here**.", + "Not math: \\(x and $$y, then *it* " + String(repeating: "word ", count: 120), + "$$ $$ and \\(\\) and \\\\(x\\) and $ $ and \\[a \\$ b\\]", +] + +/// The resumable path, with every unit before the end promised stable, as +/// for a long line that keeps growing. +@Test func checkpointedMathParsesOnlyGrowAndMatchAParseFromScratch() { + for source in mathSamples { + let units = Array(source.utf16) + var checkpoint = InlineParser.Checkpoint() + var previous = "" + var shrank: [String] = [] + for end in 1...units.count { + let result = InlineParser.parse(Array(units[.. " + result.text) } + previous = result.text + } + #expect(shrank.isEmpty, "\(shrank)") + let resumed = InlineParser.parse(units, open: false, stableLength: units.count, resumingFrom: &checkpoint, tags: [:]) + #expect(resumed == InlineParser.parse(source, open: false, tags: [:]), "\(source)") + } +} + +@Test func everySplitPointGivesTheSameMath() { + for source in mathSamples + displaySamples { + let whole = MarkdownStreamParser.document(from: source, idPrefix: "m") + var mismatches: [Int] = [] + for split in 1.. [(text: String, tex: [String])] { + MarkdownStreamParser.document(from: markdown).blocks.map { ($0.text, formulas($0).map(\.tex)) } +} + +@Test func displayMathIsABlockThatKeepsItsLines() { + let list = blocks("\\[\nx = a\n- b\n# c\n\\]") + #expect(list.count == 1) + #expect(list.first?.tex == ["x = a\n- b\n# c"]) + let split = blocks("Text\n$$\nx^2\n$$\nmore text") + #expect(split.map(\.text) == ["Text", "\u{FFFC}", "more text"]) + #expect(split[1].tex == ["x^2"]) + // In a list item and in a quote. + #expect(blocks("1. Item\n2. \\[\n y = 2\n \\]").last?.tex == ["y = 2"]) + #expect(blocks("> \\[\n> a \\\\\n> b\n> \\]").first?.tex == ["a \\\\\nb"]) +} + +@Test func textAfterTheCloserStartsAParagraph() { + let result = blocks("\\[\nx = 1\n\\] Then more.") + #expect(result.map(\.text) == ["\u{FFFC}", "Then more."]) + // On its opening line, text after the closer makes it part of the paragraph. + let inline = firstBlock("$$x$$ and more") + #expect(inline.text == "\u{FFFC} and more") + #expect(formulas(inline) == [TranscriptMath(tex: "x", isDisplay: true)]) +} + +@Test func withABlankLineBeforeTheCloserItIsNotAFormula() { + let result = blocks("$$\nx = a\n- b\n\nAfter.") + #expect(result.map(\.text) == ["$$ x = a - b", "After."]) + #expect(result.allSatisfy { $0.tex.isEmpty }) + // Never closed: its lines show as written. + #expect(blocks("\\[\nx = a\n- b").map(\.text) == ["[ x = a - b"]) +} + +private let displaySamples = [ + "Roots:\n\\[\nx = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}\n\\]\nand then\n\n$$\n\\begin{aligned}\na &= b \\\\\n- c &= d\n\\end{aligned}\n$$\n\n- item \\(x\\)\n \\[\n y\n \\] after\n", + "$$\nnever closed\n# not a heading\n\nNext paragraph with $5.\n\\[1\\] Smith.\n$$x$$\n", +] + +@Test func streamedDisplayMathOnlyGrowsAndMatchesParsingAtOnce() { + for source in displaySamples { + var parser = MarkdownStreamParser(idPrefix: "md") + var previous = parser.document + var shrank: [String] = [] + for character in source { + parser.append(String(character)) + if !parser.document.extends(previous), shrank.count < 3 { + shrank.append("\(previous.blocks.last?.text.debugDescription ?? "-") -> \(parser.document.blocks.last?.text.debugDescription ?? "-")") + } + previous = parser.document + } + parser.finish() + #expect(shrank.isEmpty, "\(shrank)") + #expect(parser.document == MarkdownStreamParser.document(from: source)) + } +} + +/// A formula image as a renderer makes one: RGBA, transparent, with an +/// opaque black box in its middle third. `width` by `height` points, its +/// baseline `baseline` above the bottom. +private func boxFormula(width: Int, height: Int, baseline: CGFloat) -> TranscriptMathImage { + let scale = 2 + let context = CGContext(data: nil, width: width * scale, height: height * scale, bitsPerComponent: 8, bytesPerRow: 0, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.setFillColor(CGColor(gray: 0, alpha: 1)) + context.fill(CGRect(x: width * scale / 3, y: 0, width: width * scale / 3, height: height * scale)) + return TranscriptMathImage(image: context.makeImage()!, size: CGSize(width: width, height: height), baseline: baseline) +} + +private func waitUntil(_ condition: () -> Bool) async { + for _ in 0..<200 where !condition() { + try? await Task.sleep(for: .milliseconds(10)) + } +} + +private func attachment(in layout: DocumentLayout) -> ImageAttachment? { + let line = layout.entry(at: 0).layout.lines[0] + for run in CTLineGetGlyphRuns(line.ctLine) as! [CTRun] { + let attributes = CTRunGetAttributes(run) as NSDictionary + if let attachment = attributes[TranscriptStyle.imageKey.rawValue] as? ImageAttachment { return attachment } + } + return nil +} + +@Test func aFormulaShowsItsLatexUntilTheRendererDrawsIt() async { + let store = TranscriptImageStore() + store.setMathRenderer { _, fontSize in + boxFormula(width: 40, height: Int(fontSize), baseline: 5) + } + let document = MarkdownStreamParser.document(from: "So \\(x\\) here") + let revision = store.revision + let first = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: nil, images: store) + #expect(attachment(in: first)?.picture == nil) + #expect(attachment(in: first)?.label != nil) + await waitUntil { store.revision > revision } + let second = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: first, images: store) + let drawn = attachment(in: second) + #expect(drawn?.isMask == true) + #expect(drawn?.size == CGSize(width: 40, height: 17)) + #expect(drawn?.ascent == 12) +} + +@Test func displayMathIsCentredAndDrawnInTheTextColor() async { + let store = TranscriptImageStore() + store.setMathRenderer { _, _ in boxFormula(width: 60, height: 20, baseline: 4) } + let document = MarkdownStreamParser.document(from: "$$x$$") + let revision = store.revision + _ = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: nil, images: store) + await waitUntil { store.revision > revision } + let layout = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: nil, images: store) + let line = layout.entry(at: 0).layout.lines[0] + #expect(abs(line.frame.midX - 150) <= 1) + + let scale: CGFloat = 2 + let width = Int(layout.width * scale) + let height = Int((layout.height * scale).rounded()) + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.setFillColor(CGColor(gray: 1, alpha: 1)) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + context.translateBy(x: 0, y: CGFloat(height)) + context.scaleBy(x: scale, y: -scale) + layout.draw(in: context, dirtyRect: CGRect(x: 0, y: 0, width: layout.width, height: layout.height), + text: CGColor(red: 1, green: 0, blue: 0, alpha: 1), codeBackground: CGColor(gray: 0.9, alpha: 1), + accent: CGColor(gray: 0.6, alpha: 1), dark: false) + let bytes = UnsafeRawBufferPointer(start: context.data!, count: width * height * 4) + func pixel(_ x: CGFloat) -> (UInt8, UInt8, UInt8) { + let index = (Int(((line.baseline - 6) * scale).rounded()) * width + Int((x * scale).rounded())) * 4 + return (bytes[index], bytes[index + 1], bytes[index + 2]) + } + // The box is drawn in the text color, and the transparent sides are not drawn. + let middle = pixel(line.frame.midX) + #expect(middle.0 > 200 && middle.1 < 60 && middle.2 < 60) + let side = pixel(line.frame.midX - 25) + #expect(side.0 > 200 && side.1 > 200 && side.2 > 200) +}