From 22ad2714a57a38898f136f65dd0429810f7be7e9 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:10:37 -0800 Subject: [PATCH 1/7] Keep drawn formulas in a cache with a size limit The image store kept every formula that the math renderer drew, and never removed one. A long conversation with many formulas used more memory over time. Now a TranscriptMathCache keeps the drawn formulas. It removes the least recently used formulas when they use more than a byte limit (16 MB by default). A cache calls the renderer once for each formula and font size. Stores that wait for the same formula get the same result. A formula that the renderer cannot draw is kept as a failure, so that the renderer is not called for it again. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/Layout/ImageStore.swift | 62 ++++++---- .../TranscriptKit/Layout/LayoutEngine.swift | 3 +- .../Layout/LeastRecentlyUsed.swift | 67 ++++++++++ Sources/TranscriptKit/Layout/MathCache.swift | 109 ++++++++++++++++ Tests/TranscriptKitTests/MathCacheTests.swift | 116 ++++++++++++++++++ 5 files changed, 333 insertions(+), 24 deletions(-) create mode 100644 Sources/TranscriptKit/Layout/LeastRecentlyUsed.swift create mode 100644 Sources/TranscriptKit/Layout/MathCache.swift create mode 100644 Tests/TranscriptKitTests/MathCacheTests.swift diff --git a/Sources/TranscriptKit/Layout/ImageStore.swift b/Sources/TranscriptKit/Layout/ImageStore.swift index 71a3e14..07f43a9 100644 --- a/Sources/TranscriptKit/Layout/ImageStore.swift +++ b/Sources/TranscriptKit/Layout/ImageStore.swift @@ -115,53 +115,69 @@ final class TranscriptImageStore: @unchecked Sendable { // 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 mathCache: TranscriptMathCache private var mathGeneration = 0 - private var formulas: [FormulaKey: TranscriptMathImage] = [:] - private var formulasRequested: Set = [] + private var formulasRequested: Set = [] + + /// - Parameter mathCache: where drawn formulas are kept. A store has a + /// cache of its own unless it is given one that views share. + init(mathCache: TranscriptMathCache = TranscriptMathCache()) { + self.mathCache = mathCache + } 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. + /// Sets the math renderer. Formulas are asked for again, and the revision + /// goes up so that they are laid out again. The cache keeps what it has, + /// because views that share it set their renderers one by one. func setMathRenderer(_ renderer: TranscriptMathRenderer?) { lock.withLock { mathRenderer = renderer mathGeneration += 1 _revision += 1 - formulas = [:] + formulasRequested = [] + } + } + + /// Sets where drawn formulas are kept, and lays them out again. + func setMathCache(_ cache: TranscriptMathCache) { + lock.withLock { + guard cache !== mathCache else { return } + mathCache = cache + mathGeneration += 1 + _revision += 1 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) } + let key = TranscriptMathCache.Key(math: math, fontSize: fontSize) + let (formula, start): (TranscriptMathImage?, (TranscriptMathRenderer, TranscriptMathCache, Int)?) = lock.withLock { + guard let mathRenderer else { return (nil, nil) } + switch mathCache.result(for: key) { + case .drawn(let formula)?: return (formula, nil) + case .failed?: return (nil, nil) + case nil: break + } + guard !formulasRequested.contains(key) else { return (nil, nil) } formulasRequested.insert(key) - return (nil, mathRenderer, mathGeneration) + return (nil, (mathRenderer, mathCache, 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) + if let (renderer, cache, generation) = start { + cache.draw(key, with: renderer) { [weak self] result in + self?.finishFormula(key, result, generation: generation) } } return formula } - private func finishFormula(_ key: FormulaKey, _ formula: TranscriptMathImage?, generation: Int) { + private func finishFormula(_ key: TranscriptMathCache.Key, _ result: TranscriptMathCache.Result, generation: Int) { let handler: (@Sendable () -> Void)? = lock.withLock { - guard generation == mathGeneration, let formula else { return nil } - formulas[key] = formula + guard generation == mathGeneration else { return nil } + formulasRequested.remove(key) + guard case .drawn = result else { return nil } _revision += 1 return onChange } diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index 4cf780d..dff7c11 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -78,7 +78,8 @@ final class LayoutEngine: @unchecked Sendable { let queue = DispatchQueue(label: "TranscriptKit.layout", qos: .userInitiated) /// Pictures for the documents' images, if the view was given a loader. - let images = TranscriptImageStore() + /// Formulas are kept in the cache that views share. + let images = TranscriptImageStore(mathCache: .shared) // Guarded by `lock`. private let lock = NSLock() diff --git a/Sources/TranscriptKit/Layout/LeastRecentlyUsed.swift b/Sources/TranscriptKit/Layout/LeastRecentlyUsed.swift new file mode 100644 index 0000000..7e89210 --- /dev/null +++ b/Sources/TranscriptKit/Layout/LeastRecentlyUsed.swift @@ -0,0 +1,67 @@ +/// Values with a cost each, of which it keeps the most recently used, up to +/// a total cost. The newest value always stays, even when it alone costs more. +struct LeastRecentlyUsed { + private struct Node { + var value: Value + var cost: Int + var older: Key? + var newer: Key? + } + + let costLimit: Int + private var nodes: [Key: Node] = [:] + private var oldest: Key? + private var newest: Key? + private(set) var totalCost = 0 + + init(costLimit: Int) { + self.costLimit = max(costLimit, 0) + } + + var count: Int { nodes.count } + + /// The value for `key`, which becomes the most recently used. + mutating func value(for key: Key) -> Value? { + guard let node = unlink(key) else { return nil } + link(key, node) + return node.value + } + + /// Whether `key` has a value, without using it. + func contains(_ key: Key) -> Bool { nodes[key] != nil } + + /// Keeps `value` as the most recently used, and removes the least + /// recently used values while the total cost is over the limit. + mutating func set(_ value: Value, for key: Key, cost: Int) { + if let old = unlink(key) { totalCost -= old.cost } + let cost = max(cost, 0) + link(key, Node(value: value, cost: cost)) + totalCost += cost + while totalCost > costLimit, let oldest, oldest != key, let removed = unlink(oldest) { + totalCost -= removed.cost + } + } + + mutating func removeAll() { + nodes = [:] + oldest = nil + newest = nil + totalCost = 0 + } + + private mutating func unlink(_ key: Key) -> Node? { + guard let node = nodes.removeValue(forKey: key) else { return nil } + if let older = node.older { nodes[older]?.newer = node.newer } else { oldest = node.newer } + if let newer = node.newer { nodes[newer]?.older = node.older } else { newest = node.older } + return Node(value: node.value, cost: node.cost) + } + + private mutating func link(_ key: Key, _ node: Node) { + var node = node + node.older = newest + node.newer = nil + if let newest { nodes[newest]?.newer = key } else { oldest = key } + newest = key + nodes[key] = node + } +} diff --git a/Sources/TranscriptKit/Layout/MathCache.swift b/Sources/TranscriptKit/Layout/MathCache.swift new file mode 100644 index 0000000..1fedaed --- /dev/null +++ b/Sources/TranscriptKit/Layout/MathCache.swift @@ -0,0 +1,109 @@ +import CoreGraphics +import Foundation + +/// Keeps the formulas that a math renderer drew, so that views that share +/// the cache draw each formula once. Any thread. +/// +/// Each `TranscriptTextView` uses `shared` unless the app gives it another +/// cache. A cache keeps the formulas of one renderer: give views whose +/// renderers draw a formula differently a cache each. +public final class TranscriptMathCache: @unchecked Sendable { + /// The cache that views use unless the app gives them another. + public static let shared = TranscriptMathCache() + + /// A formula at a font size, to half a point. + struct Key: Hashable, Sendable { + let math: TranscriptMath + let size: Int + + init(math: TranscriptMath, fontSize: CGFloat) { + self.math = math + self.size = Int((fontSize * 2).rounded()) + } + + var fontSize: CGFloat { CGFloat(size) / 2 } + } + + /// What the renderer gave for a formula. + enum Result: Sendable { + case drawn(TranscriptMathImage) + /// The renderer returned nil: the formula shows its LaTeX as written. + case failed + + /// Bytes. A formula that failed costs a little too, so that the + /// number of formulas kept has a limit. + var cost: Int { + guard case .drawn(let formula) = self else { return 256 } + return max(formula.image.bytesPerRow * formula.image.height, 256) + } + } + + private let lock = NSLock() + private var results: LeastRecentlyUsed + /// For each formula that is being drawn: what to call with its result. + private var waiting: [Key: [@Sendable (Result) -> Void]] = [:] + private var generation = 0 + private var draws = 0 + + /// - Parameter byteLimit: how much memory the drawn formulas can use. + /// When they use more, the formulas used least recently are removed. + public init(byteLimit: Int = 16 * 1024 * 1024) { + results = LeastRecentlyUsed(costLimit: byteLimit) + } + + /// Removes all the formulas. Views draw a formula again the next time + /// they lay it out. Use this when the renderer changes how it draws. + public func removeAll() { + lock.withLock { + generation += 1 + results.removeAll() + } + } + + /// The result for `key`, if the renderer has given it. + func result(for key: Key) -> Result? { + lock.withLock { results.value(for: key) } + } + + /// Calls `done` with the result for `key`: right away if the renderer + /// has given it, or else once it has drawn the formula. The renderer is + /// not called again for a formula that it is drawing. + func draw(_ key: Key, with renderer: @escaping TranscriptMathRenderer, then done: @escaping @Sendable (Result) -> Void) { + enum Step { case known(Result), wait, start(Int) } + let step: Step = lock.withLock { + if let known = results.value(for: key) { return .known(known) } + if waiting[key] != nil { + waiting[key]!.append(done) + return .wait + } + waiting[key] = [done] + draws += 1 + return .start(generation) + } + switch step { + case .known(let result): + done(result) + case .wait: + break + case .start(let generation): + Task.detached { + let drawn = await renderer(key.math, key.fontSize)?.withAlphaAsMask() + self.finish(key, drawn.map(Result.drawn) ?? .failed, generation: generation) + } + } + } + + private func finish(_ key: Key, _ result: Result, generation: Int) { + let waiters: [@Sendable (Result) -> Void] = lock.withLock { + if generation == self.generation { results.set(result, for: key, cost: result.cost) } + return waiting.removeValue(forKey: key) ?? [] + } + for done in waiters { done(result) } + } + + /// How many times the renderer was called. For tests. + var drawCount: Int { lock.withLock { draws } } + + /// How much memory the formulas use, in bytes, and how many there are. For tests. + var usage: (bytes: Int, count: Int) { lock.withLock { (results.totalCost, results.count) } } +} diff --git a/Tests/TranscriptKitTests/MathCacheTests.swift b/Tests/TranscriptKitTests/MathCacheTests.swift new file mode 100644 index 0000000..855b93e --- /dev/null +++ b/Tests/TranscriptKitTests/MathCacheTests.swift @@ -0,0 +1,116 @@ +import CoreGraphics +import Foundation +import Testing +@testable import TranscriptKit + +@Test func leastRecentlyUsedRemovesTheOldestOverItsLimit() { + var cache = LeastRecentlyUsed(costLimit: 30) + cache.set(1, for: "a", cost: 10) + cache.set(2, for: "b", cost: 10) + cache.set(3, for: "c", cost: 10) + // Using "a" makes "b" the oldest. + #expect(cache.value(for: "a") == 1) + cache.set(4, for: "d", cost: 10) + #expect(!cache.contains("b")) + #expect(cache.contains("a") && cache.contains("c") && cache.contains("d")) + #expect(cache.totalCost == 30) + // A new value for a key replaces its cost. + cache.set(5, for: "c", cost: 20) + #expect(cache.totalCost == 30) + #expect(cache.count == 2) + #expect(cache.value(for: "c") == 5) + // The newest value stays, even when it alone is over the limit. + cache.set(6, for: "e", cost: 50) + #expect(cache.count == 1) + #expect(cache.value(for: "e") == 6) + cache.removeAll() + #expect(cache.count == 0 && cache.totalCost == 0) +} + +/// A drawn formula: an opaque box `width` by `height` pixels. +func solidFormula(width: Int, height: Int) -> TranscriptMathImage { + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.setFillColor(CGColor(gray: 0, alpha: 1)) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + return TranscriptMathImage(image: context.makeImage()!, size: CGSize(width: width, height: height), baseline: 2) +} + +/// Waits until `condition` holds, for at most two seconds. +func waitFor(_ condition: () -> Bool) async { + for _ in 0..<200 where !condition() { + try? await Task.sleep(for: .milliseconds(10)) + } +} + +/// Records which formulas a renderer was asked to draw. +final class RenderCalls: @unchecked Sendable { + private let lock = NSLock() + private var items: [String] = [] + func add(_ tex: String) { lock.withLock { items.append(tex) } } + var all: [String] { lock.withLock { items } } +} + +@Test func storesThatShareACacheDrawAFormulaOnce() async { + let cache = TranscriptMathCache() + let calls = RenderCalls() + let renderer: TranscriptMathRenderer = { math, _ in + calls.add(math.tex) + try? await Task.sleep(for: .milliseconds(50)) + return solidFormula(width: 20, height: 10) + } + let stores = (0..<3).map { _ in TranscriptImageStore(mathCache: cache) } + let math = TranscriptMath(tex: "x^2", isDisplay: false) + for store in stores { + store.setMathRenderer(renderer) + #expect(store.formula(for: math, fontSize: 17) == nil) + } + await waitFor { stores.allSatisfy { $0.formula(for: math, fontSize: 17) != nil } } + #expect(stores.allSatisfy { $0.formula(for: math, fontSize: 17) != nil }) + #expect(calls.all == ["x^2"]) + // A store that comes later finds it drawn. + let later = TranscriptImageStore(mathCache: cache) + later.setMathRenderer(renderer) + #expect(later.formula(for: math, fontSize: 17) != nil) + // Another font size is another formula. + #expect(later.formula(for: math, fontSize: 20) == nil) + await waitFor { calls.all.count == 2 } + #expect(cache.drawCount == 2) +} + +@Test func aFormulaThatFailsIsNotDrawnAgain() async { + let store = TranscriptImageStore() + let calls = RenderCalls() + store.setMathRenderer { math, _ in + calls.add(math.tex) + return nil + } + let math = TranscriptMath(tex: "\\frac{", isDisplay: true) + #expect(store.formula(for: math, fontSize: 17) == nil) + await waitFor { calls.all.count == 1 } + try? await Task.sleep(for: .milliseconds(50)) + #expect(store.formula(for: math, fontSize: 17) == nil) + try? await Task.sleep(for: .milliseconds(50)) + #expect(calls.all.count == 1) +} + +@Test func theCacheRemovesTheLeastRecentlyUsedFormulasOverItsLimit() async { + // Each formula is 10 by 10 pixels: 100 bytes as a mask, which costs 256. + let cache = TranscriptMathCache(byteLimit: 256 * 3) + let store = TranscriptImageStore(mathCache: cache) + store.setMathRenderer { _, _ in solidFormula(width: 10, height: 10) } + let formulas = (0..<5).map { TranscriptMath(tex: "x_\($0)", isDisplay: false) } + for math in formulas { + _ = store.formula(for: math, fontSize: 17) + await waitFor { store.formula(for: math, fontSize: 17) != nil } + // The first formula is used again each time, so it stays. + #expect(store.formula(for: formulas[0], fontSize: 17) != nil) + } + #expect(cache.usage.count == 3) + #expect(cache.usage.bytes <= 256 * 3) + #expect(cache.result(for: .init(math: formulas[0], fontSize: 17)) != nil) + #expect(cache.result(for: .init(math: formulas[1], fontSize: 17)) == nil) + #expect(cache.result(for: .init(math: formulas[4], fontSize: 17)) != nil) + cache.removeAll() + #expect(cache.usage.count == 0) +} From bf3b0940f0af8826ed8d70073cd6088ef9291183 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:12:31 -0800 Subject: [PATCH 2/7] Keep a formula's last image while its LaTeX changes An app can close an open display formula on each snapshot, so the LaTeX of one formula changes on each update. Each change started a new render, and the formula showed its LaTeX until the new image arrived. Now the store knows each formula by its slot: the block's id, and how many formulas come before it in the block. This works like the code highlighter, which keeps the last colors of a block while its code grows: - While the new LaTeX is drawn, the slot shows its last image. - A slot draws one formula at a time. Newer LaTeX replaces the LaTeX that waits for its turn. - The last image is shown only for LaTeX that can be an earlier version of the new LaTeX: the same kind of formula, and a shared start of at least half of it. Documents that are parsed with the same id prefix have the same block ids, so a view can get another document's formula in a slot. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/Layout/ImageStore.swift | 115 ++++++++++++++---- .../Layout/TranscriptStyle.swift | 22 +++- Tests/TranscriptKitTests/MathCacheTests.swift | 82 +++++++++++-- Tests/TranscriptKitTests/MathTests.swift | 25 ++++ 4 files changed, 202 insertions(+), 42 deletions(-) diff --git a/Sources/TranscriptKit/Layout/ImageStore.swift b/Sources/TranscriptKit/Layout/ImageStore.swift index 07f43a9..881cbf9 100644 --- a/Sources/TranscriptKit/Layout/ImageStore.swift +++ b/Sources/TranscriptKit/Layout/ImageStore.swift @@ -115,10 +115,32 @@ final class TranscriptImageStore: @unchecked Sendable { // MARK: Formulas + /// Which formula of a block: the block's id, and how many formulas come + /// before it in the block. While a formula streams in, its LaTeX changes + /// and its slot stays the same. + struct MathSlot: Hashable, Sendable { + let block: String + let index: Int + } + + /// What to show for a formula. + enum Formula { + /// Its image, or while it is drawn, the last image of its slot. + case drawn(TranscriptMathImage) + /// It is being drawn, and its slot has no image yet. + case pending + /// Its LaTeX as written: there is no renderer, or it returned nil. + case asWritten + } + private var mathRenderer: TranscriptMathRenderer? private var mathCache: TranscriptMathCache private var mathGeneration = 0 - private var formulasRequested: Set = [] + /// For each slot, as for code blocks: the formula it last showed drawn, + /// the one being drawn, and the newest one waiting for its turn. + private var shownFormulas: [MathSlot: TranscriptMathCache.Key] = [:] + private var drawingFormulas: [MathSlot: TranscriptMathCache.Key] = [:] + private var waitingFormulas: [MathSlot: TranscriptMathCache.Key] = [:] /// - Parameter mathCache: where drawn formulas are kept. A store has a /// cache of its own unless it is given one that views share. @@ -134,9 +156,7 @@ final class TranscriptImageStore: @unchecked Sendable { func setMathRenderer(_ renderer: TranscriptMathRenderer?) { lock.withLock { mathRenderer = renderer - mathGeneration += 1 - _revision += 1 - formulasRequested = [] + resetFormulas() } } @@ -145,41 +165,84 @@ final class TranscriptImageStore: @unchecked Sendable { lock.withLock { guard cache !== mathCache else { return } mathCache = cache - mathGeneration += 1 - _revision += 1 - formulasRequested = [] + resetFormulas() } } - /// The drawn formula if it has arrived. Starts drawing it if not. - func formula(for math: TranscriptMath, fontSize: CGFloat) -> TranscriptMathImage? { + private func resetFormulas() { + mathGeneration += 1 + _revision += 1 + shownFormulas = [:] + drawingFormulas = [:] + waitingFormulas = [:] + } + + /// What to show for `math` in `slot`. When it is not drawn yet, drawing + /// starts (or waits for the slot's current one to end), and the slot's + /// last image is given meanwhile: while a formula streams in, its last + /// image is closer to the new one than empty space is. + func formula(for math: TranscriptMath, fontSize: CGFloat, in slot: MathSlot) -> Formula { let key = TranscriptMathCache.Key(math: math, fontSize: fontSize) - let (formula, start): (TranscriptMathImage?, (TranscriptMathRenderer, TranscriptMathCache, Int)?) = lock.withLock { - guard let mathRenderer else { return (nil, nil) } + let (formula, start): (Formula, (TranscriptMathRenderer, TranscriptMathCache, Int)?) = lock.withLock { + guard let mathRenderer else { return (.asWritten, nil) } switch mathCache.result(for: key) { - case .drawn(let formula)?: return (formula, nil) - case .failed?: return (nil, nil) - case nil: break + case .drawn(let image)?: + shownFormulas[slot] = key + return (.drawn(image), nil) + case .failed?: + return (.asWritten, nil) + case nil: + break + } + var meanwhile = Formula.pending + if let shown = shownFormulas[slot], Self.mayBeEarlierVersion(shown.math, of: math), + case .drawn(let image)? = mathCache.result(for: shown) { + meanwhile = .drawn(image) } - guard !formulasRequested.contains(key) else { return (nil, nil) } - formulasRequested.insert(key) - return (nil, (mathRenderer, mathCache, mathGeneration)) + if let drawing = drawingFormulas[slot] { + waitingFormulas[slot] = drawing == key ? nil : key + return (meanwhile, nil) + } + drawingFormulas[slot] = key + return (meanwhile, (mathRenderer, mathCache, mathGeneration)) } if let (renderer, cache, generation) = start { - cache.draw(key, with: renderer) { [weak self] result in - self?.finishFormula(key, result, generation: generation) - } + draw(key, in: slot, with: renderer, cache: cache, generation: generation) } return formula } - private func finishFormula(_ key: TranscriptMathCache.Key, _ result: TranscriptMathCache.Result, generation: Int) { - let handler: (@Sendable () -> Void)? = lock.withLock { - guard generation == mathGeneration else { return nil } - formulasRequested.remove(key) - guard case .drawn = result else { return nil } + /// Whether `earlier` can be the same formula as `later` before more of + /// it arrived. Block ids repeat in documents parsed with the same id + /// prefix, so a slot can hold another document's formula. + static func mayBeEarlierVersion(_ earlier: TranscriptMath, of later: TranscriptMath) -> Bool { + guard earlier.isDisplay == later.isDisplay else { return false } + let shared = zip(earlier.tex, later.tex).prefix { $0 == $1 }.count + return shared > 0 && shared * 2 >= earlier.tex.count + } + + private func draw(_ key: TranscriptMathCache.Key, in slot: MathSlot, with renderer: @escaping TranscriptMathRenderer, + cache: TranscriptMathCache, generation: Int) { + cache.draw(key, with: renderer) { [weak self] result in + self?.finishFormula(key, in: slot, result, generation: generation) + } + } + + private func finishFormula(_ key: TranscriptMathCache.Key, in slot: MathSlot, _ result: TranscriptMathCache.Result, + generation: Int) { + let (handler, next): ((@Sendable () -> Void)?, (TranscriptMathCache.Key, TranscriptMathRenderer, TranscriptMathCache)?) = lock.withLock { + guard generation == mathGeneration else { return (nil, nil) } + if case .drawn = result { shownFormulas[slot] = key } _revision += 1 - return onChange + if let waiting = waitingFormulas.removeValue(forKey: slot), waiting != key, let mathRenderer { + drawingFormulas[slot] = waiting + return (onChange, (waiting, mathRenderer, mathCache)) + } + drawingFormulas[slot] = nil + return (onChange, nil) + } + if let (waiting, renderer, cache) = next { + draw(waiting, in: slot, with: renderer, cache: cache, generation: generation) } handler?() } diff --git a/Sources/TranscriptKit/Layout/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index 69af107..75a4953 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -257,7 +257,7 @@ public struct TranscriptStyle: Equatable, Sendable { var traits = extraTraits var isLink = false var image: TranscriptImage? - var math: TranscriptMath? + var math: (math: TranscriptMath, start: Int)? // Spans are sorted with outer ones first, so an inner tag's colors win. var foreground: TranscriptColor? var background: TranscriptColor? @@ -265,7 +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 spanMath = span.math { math = (spanMath, span.range.lowerBound + start) } if let decoration = span.customTag?.decoration { if let color = decoration.foreground { foreground = color } if let color = decoration.background { background = color } @@ -287,8 +287,9 @@ public struct TranscriptStyle: Equatable, Sendable { if let background { result.addAttribute(Self.backgroundKey, value: background, range: range) } 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 = math.map { ImageAttachment(math: $0, sizing: images, font: font, style: self) } - ?? ImageAttachment(image: image!, sizing: images, font: font, style: self) + let attachment = math.map { + ImageAttachment(math: $0.math, slot: Self.mathSlot(in: block, at: $0.start), 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) } @@ -302,6 +303,15 @@ public struct TranscriptStyle: Equatable, Sendable { } } +extension TranscriptStyle { + /// The slot of the formula that starts at UTF-16 offset `start` of + /// `block`: it is the same whichever part of the block is laid out. + static func mathSlot(in block: TranscriptBlock, at start: Int) -> TranscriptImageStore.MathSlot { + let before = block.spans.reduce(0) { $0 + ($1.math != nil && $1.range.lowerBound < start ? 1 : 0) } + return TranscriptImageStore.MathSlot(block: block.id, index: before) + } +} + /// What layout needs to know to size images: the loaded ones, and the width /// they must fit in. struct ImageSizing { @@ -325,11 +335,11 @@ final class ImageAttachment: @unchecked Sendable { /// 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) { + init(math: TranscriptMath, slot: TranscriptImageStore.MathSlot, 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)) { + if case .drawn(let formula)? = sizing?.store?.formula(for: math, fontSize: CTFontGetSize(font), in: slot) { 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 diff --git a/Tests/TranscriptKitTests/MathCacheTests.swift b/Tests/TranscriptKitTests/MathCacheTests.swift index 855b93e..36a79e1 100644 --- a/Tests/TranscriptKitTests/MathCacheTests.swift +++ b/Tests/TranscriptKitTests/MathCacheTests.swift @@ -43,6 +43,16 @@ func waitFor(_ condition: () -> Bool) async { } } +extension TranscriptImageStore { + /// The image given for `math` in `slot` (by default, a slot of its own), if any. + func drawnImage(_ math: TranscriptMath, fontSize: CGFloat = 17, slot: String? = nil) -> TranscriptMathImage? { + guard case .drawn(let image) = formula(for: math, fontSize: fontSize, in: MathSlot(block: slot ?? math.tex, index: 0)) else { + return nil + } + return image + } +} + /// Records which formulas a renderer was asked to draw. final class RenderCalls: @unchecked Sendable { private let lock = NSLock() @@ -63,17 +73,17 @@ final class RenderCalls: @unchecked Sendable { let math = TranscriptMath(tex: "x^2", isDisplay: false) for store in stores { store.setMathRenderer(renderer) - #expect(store.formula(for: math, fontSize: 17) == nil) + #expect(store.drawnImage(math) == nil) } - await waitFor { stores.allSatisfy { $0.formula(for: math, fontSize: 17) != nil } } - #expect(stores.allSatisfy { $0.formula(for: math, fontSize: 17) != nil }) + await waitFor { stores.allSatisfy { $0.drawnImage(math) != nil } } + #expect(stores.allSatisfy { $0.drawnImage(math) != nil }) #expect(calls.all == ["x^2"]) // A store that comes later finds it drawn. let later = TranscriptImageStore(mathCache: cache) later.setMathRenderer(renderer) - #expect(later.formula(for: math, fontSize: 17) != nil) + #expect(later.drawnImage(math) != nil) // Another font size is another formula. - #expect(later.formula(for: math, fontSize: 20) == nil) + #expect(later.drawnImage(math, fontSize: 20, slot: "larger") == nil) await waitFor { calls.all.count == 2 } #expect(cache.drawCount == 2) } @@ -86,10 +96,10 @@ final class RenderCalls: @unchecked Sendable { return nil } let math = TranscriptMath(tex: "\\frac{", isDisplay: true) - #expect(store.formula(for: math, fontSize: 17) == nil) + #expect(store.drawnImage(math) == nil) await waitFor { calls.all.count == 1 } try? await Task.sleep(for: .milliseconds(50)) - #expect(store.formula(for: math, fontSize: 17) == nil) + #expect(store.drawnImage(math) == nil) try? await Task.sleep(for: .milliseconds(50)) #expect(calls.all.count == 1) } @@ -101,10 +111,10 @@ final class RenderCalls: @unchecked Sendable { store.setMathRenderer { _, _ in solidFormula(width: 10, height: 10) } let formulas = (0..<5).map { TranscriptMath(tex: "x_\($0)", isDisplay: false) } for math in formulas { - _ = store.formula(for: math, fontSize: 17) - await waitFor { store.formula(for: math, fontSize: 17) != nil } + _ = store.drawnImage(math) + await waitFor { store.drawnImage(math) != nil } // The first formula is used again each time, so it stays. - #expect(store.formula(for: formulas[0], fontSize: 17) != nil) + #expect(store.drawnImage(formulas[0]) != nil) } #expect(cache.usage.count == 3) #expect(cache.usage.bytes <= 256 * 3) @@ -114,3 +124,55 @@ final class RenderCalls: @unchecked Sendable { cache.removeAll() #expect(cache.usage.count == 0) } + +@Test func aStreamedFormulaKeepsItsLastImageAndIsDrawnOneLatexAtATime() async { + let store = TranscriptImageStore() + let calls = RenderCalls() + store.setMathRenderer { math, _ in + calls.add(math.tex) + try? await Task.sleep(for: .milliseconds(100)) + return solidFormula(width: 10 * math.tex.count, height: 10) + } + let slot = TranscriptImageStore.MathSlot(block: "md-0", index: 0) + func ask(_ tex: String) -> TranscriptImageStore.Formula { + store.formula(for: TranscriptMath(tex: tex, isDisplay: true), fontSize: 17, in: slot) + } + func width(_ formula: TranscriptImageStore.Formula) -> CGFloat? { + guard case .drawn(let image) = formula else { return nil } + return image.size.width + } + // The same formula as its LaTeX grows. + #expect(width(ask("x")) == nil) + #expect(width(ask("x^2 +")) == nil) + #expect(width(ask("x^2 + y")) == nil) + await waitFor { width(ask("x^2 + y")) == 70 } + // The middle LaTeX was replaced by the newest while the first was drawn. + #expect(calls.all == ["x", "x^2 + y"]) + // While newer LaTeX is drawn, the last image is given for it. + #expect(width(ask("x^2 + y^2")) == 70) + // Not for another formula in the same slot. + #expect(width(ask("\\sum_i i")) == nil) + await waitFor { calls.all.count == 4 } + #expect(calls.all.suffix(2) == ["x^2 + y^2", "\\sum_i i"]) +} + +@Test func onlyAFormulaThatCanGrowIntoTheNewOneIsShownMeanwhile() { + func earlier(_ a: String, _ b: String, display: Bool = true) -> Bool { + TranscriptImageStore.mayBeEarlierVersion(TranscriptMath(tex: a, isDisplay: true), of: TranscriptMath(tex: b, isDisplay: display)) + } + #expect(earlier("x", "x^2")) + #expect(earlier("\\frac{a}{}", "\\frac{a}{b}")) + #expect(earlier("a + b", "a + c")) + #expect(!earlier("x^2", "y^2")) + #expect(!earlier("a + b + c + d", "a + x")) + #expect(!earlier("x", "x^2", display: false)) +} + +@Test func aFormulasSlotIsTheSameInAnyPartOfItsBlock() { + let block = MarkdownStreamParser.document(from: "| \\(a\\) | \\(b\\) |\n|---|---|\n| \\(c\\) | d |").blocks[0] + let starts = block.spans.filter { $0.math != nil }.map(\.range.lowerBound) + #expect(starts.count == 3) + let slots = starts.map { TranscriptStyle.mathSlot(in: block, at: $0) } + #expect(slots.map(\.index) == [0, 1, 2]) + #expect(Set(slots.map(\.block)) == [block.id]) +} diff --git a/Tests/TranscriptKitTests/MathTests.swift b/Tests/TranscriptKitTests/MathTests.swift index 5e043da..5c347dd 100644 --- a/Tests/TranscriptKitTests/MathTests.swift +++ b/Tests/TranscriptKitTests/MathTests.swift @@ -263,3 +263,28 @@ private func attachment(in layout: DocumentLayout) -> ImageAttachment? { let side = pixel(line.frame.midX - 25) #expect(side.0 > 200 && side.1 > 200 && side.2 > 200) } + +@Test func aFormulaWhoseLatexChangesKeepsItsImageUntilTheNewOneIsDrawn() async { + let store = TranscriptImageStore() + store.setMathRenderer { math, _ in + try? await Task.sleep(for: .milliseconds(50)) + return boxFormula(width: 20 * math.tex.count, height: 20, baseline: 4) + } + let style = TranscriptStyle() + let first = MarkdownStreamParser.document(from: "$$x$$") + var revision = store.revision + _ = DocumentLayout(document: first, width: 300, style: style, reusing: nil, images: store) + await waitUntil { store.revision > revision } + let drawn = DocumentLayout(document: first, width: 300, style: style, reusing: nil, images: store) + #expect(attachment(in: drawn)?.size.width == 20) + // The same block, as when an app parses each new snapshot of the text. + let grown = MarkdownStreamParser.document(from: "$$x+y$$") + #expect(grown.blocks[0].id == first.blocks[0].id) + revision = store.revision + let meanwhile = DocumentLayout(document: grown, width: 300, style: style, reusing: drawn, images: store) + #expect(attachment(in: meanwhile)?.isMask == true) + #expect(attachment(in: meanwhile)?.size.width == 20) + await waitUntil { store.revision > revision } + let after = DocumentLayout(document: grown, width: 300, style: style, reusing: meanwhile, images: store) + #expect(attachment(in: after)?.size.width == 60) +} From 61ca19b0d10af1f1b5a88f6fe161c29e6f509f97 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:14:22 -0800 Subject: [PATCH 3/7] Leave empty space for a formula until it is drawn A formula showed its LaTeX in the code font until the renderer drew it. Then the image replaced the LaTeX, and the text moved. Now a formula that is being drawn, and has no last image, is empty space. Its size comes from its LaTeX: about 0.55 em for each symbol, one line tall for inline math, and for display math one line for each row, two lines when it has a fraction, a sum or an integral. Nothing is drawn in the space. Copy and VoiceOver still give the LaTeX. A formula shows its LaTeX as written only when there is no renderer, or when the renderer returned nil for it. A nil result now lays the formula out again, so that its LaTeX replaces the empty space. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/DocumentLayout.swift | 4 +- .../Layout/TranscriptStyle.swift | 81 ++++++++++++++++++- Tests/TranscriptKitTests/MathTests.swift | 65 ++++++++++++++- 3 files changed, 142 insertions(+), 8 deletions(-) diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index 73f623e..e129548 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -705,11 +705,11 @@ public final class DocumentLayout: @unchecked Sendable { } return } - // No picture: a chip with the alt text. + // No picture: a chip with the alt text, or for a formula being drawn, nothing. + guard let label = attachment.label else { return } context.setFillColor(background) context.addPath(CGPath(roundedRect: rect.insetBy(dx: 0, dy: 1), cornerWidth: 5, cornerHeight: 5, transform: nil)) context.fillPath() - guard let label = attachment.label else { return } var ascent: CGFloat = 0 var descent: CGFloat = 0 CTLineGetTypographicBounds(label, &ascent, &descent, nil) diff --git a/Sources/TranscriptKit/Layout/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index 75a4953..d818b01 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -320,7 +320,8 @@ struct ImageSizing { } /// An image in laid-out text: the loaded picture, or a placeholder showing -/// the alt text when there is none. +/// the alt text when there is none. A formula that is being drawn has +/// neither: it is empty space. final class ImageAttachment: @unchecked Sendable { let image: TranscriptImage let picture: CGImage? @@ -333,19 +334,25 @@ final class ImageAttachment: @unchecked Sendable { 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). + /// A formula, drawn by the store's math renderer. Until it is, it is empty + /// space of about its size. Without a renderer, or if the renderer cannot + /// draw it, it is its LaTeX as written. init(math: TranscriptMath, slot: TranscriptImageStore.MathSlot, sizing: ImageSizing?, font: CTFont, style: TranscriptStyle) { self.image = TranscriptImage(source: "", alt: math.tex) self.math = math let maximumWidth = max(sizing?.maximumWidth ?? 320, 20) - if case .drawn(let formula)? = sizing?.store?.formula(for: math, fontSize: CTFontGetSize(font), in: slot) { + let formula = sizing?.store?.formula(for: math, fontSize: CTFontGetSize(font), in: slot) ?? .asWritten + if case .drawn(let formula) = formula { 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 if case .pending = formula { + self.picture = nil + self.label = nil + (self.size, self.ascent) = Self.reservedSpace(for: math, font: font, maximumWidth: maximumWidth) } else { let size = CTFontGetSize(font) * 0.85 let code = style.codeFont?.makeFont(size: size) ?? CTFontCreateUIFontForLanguage(.userFixedPitch, size, nil)! @@ -368,6 +375,23 @@ final class ImageAttachment: @unchecked Sendable { } } + /// Room for a formula that is not drawn yet, so that the text around it + /// moves less when it is: about as wide as its symbols, and one line + /// tall for inline math. Display math gets a line for each of its rows, + /// and two when it has a fraction, a sum or an integral. + static func reservedSpace(for math: TranscriptMath, font: CTFont, maximumWidth: CGFloat) -> (size: CGSize, ascent: CGFloat) { + let fontSize = CTFontGetSize(font) + let ascent = ceil(CTFontGetAscent(font)) + let lineHeight = ceil(CTFontGetAscent(font) + CTFontGetDescent(font)) + let shape = LatexShape(math.tex) + let rows = math.isDisplay ? shape.rows : 1 + let symbolsInARow = (shape.symbols + rows - 1) / rows + let width = min(max(CGFloat(symbolsInARow) * fontSize * 0.55, fontSize).rounded(), maximumWidth) + guard math.isDisplay else { return (CGSize(width: width, height: lineHeight), ascent) } + let height = lineHeight * CGFloat(rows) * (shape.isTall ? 2 : 1) + return (CGSize(width: width, height: height), height - (lineHeight - ascent)) + } + init(image: TranscriptImage, sizing: ImageSizing?, font: CTFont, style: TranscriptStyle) { self.image = image self.math = nil @@ -416,3 +440,52 @@ final class ImageAttachment: @unchecked Sendable { return CTRunDelegateCreate(&callbacks, Unmanaged.passRetained(self).toOpaque())! } } + +/// A rough count of what a formula draws, read from its LaTeX. +struct LatexShape: Equatable { + /// Letters, digits, operators and symbol commands such as `\alpha`. + var symbols = 0 + /// Rows, which `\\` separates. + var rows = 1 + /// It has a fraction, a sum, an integral or a product, which are about + /// twice as tall as a line. + var isTall = false + + private static let layoutCommands: Set = [ + "frac", "dfrac", "tfrac", "left", "right", "mathrm", "mathbf", "mathit", "mathsf", "text", "textrm", + "operatorname", "displaystyle", "textstyle", "limits", + ] + private static let tallCommands: Set = ["frac", "dfrac", "sum", "int", "iint", "oint", "prod", "coprod", "binom"] + + init(_ tex: String) { + let units = Substring(tex) + var index = units.startIndex + while index < units.endIndex { + let character = units[index] + index = units.index(after: index) + guard character == "\\" else { + if !(character.isWhitespace || "{}^_&~".contains(character)) { symbols += 1 } + continue + } + let name = units[index...].prefix { $0.isLetter } + guard !name.isEmpty else { + // An escaped character, `\\` between rows, or a space such as `\,`. + guard index < units.endIndex else { break } + let escaped = units[index] + if escaped == "\\" { rows += 1 } else if "{}|%$#".contains(escaped) { symbols += 1 } + index = units.index(after: index) + continue + } + index = name.endIndex + if Self.tallCommands.contains(name) { isTall = true } + if name == "begin" || name == "end" { + // The environment's name is not drawn. + if index < units.endIndex, units[index] == "{", let close = units[index...].firstIndex(of: "}") { + index = units.index(after: close) + } + } else if !Self.layoutCommands.contains(name) { + symbols += 1 + } + } + } +} diff --git a/Tests/TranscriptKitTests/MathTests.swift b/Tests/TranscriptKitTests/MathTests.swift index 5c347dd..db9ca0a 100644 --- a/Tests/TranscriptKitTests/MathTests.swift +++ b/Tests/TranscriptKitTests/MathTests.swift @@ -211,7 +211,7 @@ private func attachment(in layout: DocumentLayout) -> ImageAttachment? { return nil } -@Test func aFormulaShowsItsLatexUntilTheRendererDrawsIt() async { +@Test func aFormulaIsEmptySpaceUntilTheRendererDrawsIt() async { let store = TranscriptImageStore() store.setMathRenderer { _, fontSize in boxFormula(width: 40, height: Int(fontSize), baseline: 5) @@ -220,7 +220,10 @@ private func attachment(in layout: DocumentLayout) -> ImageAttachment? { 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) + #expect(attachment(in: first)?.label == nil) + #expect((attachment(in: first)?.size.width ?? 0) > 0) + // Copy still gives the LaTeX. + #expect(document.copyText(in: 0.. revision } let second = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: first, images: store) let drawn = attachment(in: second) @@ -288,3 +291,61 @@ private func attachment(in layout: DocumentLayout) -> ImageAttachment? { let after = DocumentLayout(document: grown, width: 300, style: style, reusing: meanwhile, images: store) #expect(attachment(in: after)?.size.width == 60) } + +@Test func aFormulaShowsItsLatexWithoutARendererOrWhenTheRendererFails() async { + let document = MarkdownStreamParser.document(from: "So \\(x\\) here") + let plain = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: nil, images: TranscriptImageStore()) + #expect(attachment(in: plain)?.label != nil) + + let store = TranscriptImageStore() + store.setMathRenderer { _, _ in nil } + let revision = store.revision + let first = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: nil, images: store) + #expect(attachment(in: first)?.label == nil) + await waitUntil { store.revision > revision } + let failed = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: first, images: store) + #expect(attachment(in: failed)?.label != nil) +} + +@Test func aFormulaBeingDrawnDrawsNothing() { + let store = TranscriptImageStore() + store.setMathRenderer { _, _ in + try? await Task.sleep(for: .seconds(5)) + return nil + } + let layout = DocumentLayout(document: MarkdownStreamParser.document(from: "$$\\frac{a}{b}$$"), width: 200, + style: TranscriptStyle(), reusing: nil, images: store) + #expect(attachment(in: layout)?.label == nil) + let width = 200 + let height = Int(layout.height.rounded(.up)) + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + layout.draw(in: context, dirtyRect: CGRect(x: 0, y: 0, width: width, height: 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) + #expect(bytes.allSatisfy { $0 == 0 }) +} + +@Test func theSpaceForAFormulaFollowsItsLatex() { + func shape(_ tex: String) -> (Int, Int, Bool) { + let shape = LatexShape(tex) + return (shape.symbols, shape.rows, shape.isTall) + } + #expect(shape("x^2 + y^2") == (5, 1, false)) + #expect(shape("\\frac{a}{\\alpha}") == (2, 1, true)) + #expect(shape("\\begin{aligned} a &= b \\\\ c &= d \\end{aligned}") == (6, 2, false)) + #expect(shape("\\{ x \\, y \\}") == (4, 1, false)) + + let font = CTFontCreateWithName("Helvetica" as CFString, 20, nil) + let line = ceil(CTFontGetAscent(font) + CTFontGetDescent(font)) + let inline = ImageAttachment.reservedSpace(for: TranscriptMath(tex: "x^2 + y^2", isDisplay: false), font: font, maximumWidth: 300) + #expect(inline.size == CGSize(width: 55, height: line)) + #expect(inline.ascent == ceil(CTFontGetAscent(font))) + let fraction = ImageAttachment.reservedSpace(for: TranscriptMath(tex: "\\frac{a}{b}", isDisplay: true), font: font, maximumWidth: 300) + #expect(fraction.size.height == line * 2) + #expect(fraction.size.width == 22) + let wide = ImageAttachment.reservedSpace(for: TranscriptMath(tex: String(repeating: "x+", count: 100), isDisplay: true), + font: font, maximumWidth: 300) + #expect(wide.size.width == 300) +} From bc5d5324a95dc629ee0e407c529bbe4b888fe960 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:15:24 -0800 Subject: [PATCH 4/7] Lay out once for images that arrive together Each picture, code color or formula that arrived called the view's change handler. The view then laid out the whole document on the main thread, one time for each arrival. A message with ten formulas laid out ten times when they arrived. Now the store calls the handler on the main queue. Arrivals before the call runs share it, so the view lays out once for all of them. An arrival after the call starts gets a call of its own. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/Layout/ImageStore.swift | 75 +++++++++++++------ .../iOS/TranscriptTextView.swift | 12 +-- Tests/TranscriptKitTests/MathCacheTests.swift | 37 +++++++++ 3 files changed, 92 insertions(+), 32 deletions(-) diff --git a/Sources/TranscriptKit/Layout/ImageStore.swift b/Sources/TranscriptKit/Layout/ImageStore.swift index 881cbf9..2e0dec3 100644 --- a/Sources/TranscriptKit/Layout/ImageStore.swift +++ b/Sources/TranscriptKit/Layout/ImageStore.swift @@ -15,6 +15,10 @@ final class TranscriptImageStore: @unchecked Sendable { private var requested: Set = [] private var loader: Loader? private var onChange: (@Sendable () -> Void)? + /// Runs `onChange`: on the main queue, unless a test gives its own. + private let deliver: @Sendable (@escaping @Sendable () -> Void) -> Void + /// `onChange` is waiting to run, and changes until then need no call of their own. + private var changeScheduled = false private var generation = 0 private var _revision = 0 @@ -31,8 +35,18 @@ final class TranscriptImageStore: @unchecked Sendable { /// revision may show placeholders where pictures now are. var revision: Int { lock.withLock { _revision } } - /// Sets the loader and what to call (on any thread) when a picture has - /// arrived. Pictures loaded with an earlier loader are dropped, and the + /// - Parameters: + /// - mathCache: where drawn formulas are kept. A store has a cache of + /// its own unless it is given one that views share. + /// - deliver: runs `onChange`. + init(mathCache: TranscriptMathCache = TranscriptMathCache(), + deliver: @escaping @Sendable (@escaping @Sendable () -> Void) -> Void = { DispatchQueue.main.async(execute: $0) }) { + self.mathCache = mathCache + self.deliver = deliver + } + + /// Sets the loader and what to call when a picture has arrived; see + /// `setOnChange`. Pictures loaded with an earlier loader are dropped, and the /// revision goes up so that images already laid out are asked for again. func setLoader(_ loader: Loader?, onChange: (@Sendable () -> Void)?) { lock.withLock { @@ -45,7 +59,9 @@ final class TranscriptImageStore: @unchecked Sendable { } } - /// Sets what to call (on any thread) when a picture or colors arrive. + /// Sets what to call on the main queue when pictures, colors or formulas + /// arrive. Those that arrive before it runs share one call, so that the + /// view lays out once for them. func setOnChange(_ onChange: (@Sendable () -> Void)?) { lock.withLock { self.onChange = onChange } } @@ -97,20 +113,20 @@ final class TranscriptImageStore: @unchecked Sendable { } private func finishHighlight(_ block: String, text: String, language: String?, marks: [TranscriptCodeHighlight], generation: Int) { - let (handler, next): ((@Sendable () -> Void)?, (TranscriptCodeHighlighter, String, String?)?) = lock.withLock { - guard generation == highlightGeneration else { return (nil, nil) } + let (changed, next): (Bool, (TranscriptCodeHighlighter, String, String?)?) = lock.withLock { + guard generation == highlightGeneration else { return (false, nil) } highlights[block] = (text, language, marks) _revision += 1 if let waiting = waitingCode.removeValue(forKey: block), let highlighter, waiting.text != text || waiting.language != language { - return (onChange, (highlighter, waiting.text, waiting.language)) + return (true, (highlighter, waiting.text, waiting.language)) } highlighting.remove(block) - return (onChange, nil) + return (true, nil) } if let (highlighter, text, language) = next { highlight(block, text: text, language: language, with: highlighter, generation: generation) } - handler?() + if changed { notifyChange() } } // MARK: Formulas @@ -142,12 +158,6 @@ final class TranscriptImageStore: @unchecked Sendable { private var drawingFormulas: [MathSlot: TranscriptMathCache.Key] = [:] private var waitingFormulas: [MathSlot: TranscriptMathCache.Key] = [:] - /// - Parameter mathCache: where drawn formulas are kept. A store has a - /// cache of its own unless it is given one that views share. - init(mathCache: TranscriptMathCache = TranscriptMathCache()) { - self.mathCache = mathCache - } - var hasMathRenderer: Bool { lock.withLock { mathRenderer != nil } } /// Sets the math renderer. Formulas are asked for again, and the revision @@ -230,21 +240,21 @@ final class TranscriptImageStore: @unchecked Sendable { private func finishFormula(_ key: TranscriptMathCache.Key, in slot: MathSlot, _ result: TranscriptMathCache.Result, generation: Int) { - let (handler, next): ((@Sendable () -> Void)?, (TranscriptMathCache.Key, TranscriptMathRenderer, TranscriptMathCache)?) = lock.withLock { - guard generation == mathGeneration else { return (nil, nil) } + let (changed, next): (Bool, (TranscriptMathCache.Key, TranscriptMathRenderer, TranscriptMathCache)?) = lock.withLock { + guard generation == mathGeneration else { return (false, nil) } if case .drawn = result { shownFormulas[slot] = key } _revision += 1 if let waiting = waitingFormulas.removeValue(forKey: slot), waiting != key, let mathRenderer { drawingFormulas[slot] = waiting - return (onChange, (waiting, mathRenderer, mathCache)) + return (true, (waiting, mathRenderer, mathCache)) } drawingFormulas[slot] = nil - return (onChange, nil) + return (true, nil) } if let (waiting, renderer, cache) = next { draw(waiting, in: slot, with: renderer, cache: cache, generation: generation) } - handler?() + if changed { notifyChange() } } /// The picture for `image` if it has arrived. Starts loading it if not. @@ -265,13 +275,32 @@ final class TranscriptImageStore: @unchecked Sendable { } private func finish(_ source: String, _ box: PictureBox, generation: Int) { - let handler: (@Sendable () -> Void)? = lock.withLock { - guard generation == self.generation, let picture = box.picture else { return nil } + let changed: Bool = lock.withLock { + guard generation == self.generation, let picture = box.picture else { return false } pictures[source] = picture _revision += 1 - return onChange + return true + } + if changed { notifyChange() } + } + + /// Calls `onChange` with `deliver`, once for all the changes that come + /// before it runs. + private func notifyChange() { + let schedule: Bool = lock.withLock { + guard onChange != nil, !changeScheduled else { return false } + changeScheduled = true + return true + } + guard schedule else { return } + deliver { [weak self] in + guard let self else { return } + let handler = lock.withLock { + changeScheduled = false + return onChange + } + handler?() } - handler?() } } diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index fdb641f..be7c15d 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -150,9 +150,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD public var imageLoader: (@Sendable (TranscriptImage) async -> CGImage?)? { didSet { engine.images.setLoader(imageLoader) { [weak self] in - DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } - } + MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } } relayoutNow() } @@ -166,9 +164,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD public var codeHighlighter: TranscriptCodeHighlighter? { didSet { engine.images.setOnChange { [weak self] in - DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } - } + MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } } engine.images.setHighlighter(codeHighlighter) relayoutNow() @@ -184,9 +180,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD public var mathRenderer: TranscriptMathRenderer? { didSet { engine.images.setOnChange { [weak self] in - DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } - } + MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } } engine.images.setMathRenderer(mathRenderer) relayoutNow() diff --git a/Tests/TranscriptKitTests/MathCacheTests.swift b/Tests/TranscriptKitTests/MathCacheTests.swift index 36a79e1..58b5927 100644 --- a/Tests/TranscriptKitTests/MathCacheTests.swift +++ b/Tests/TranscriptKitTests/MathCacheTests.swift @@ -176,3 +176,40 @@ final class RenderCalls: @unchecked Sendable { #expect(slots.map(\.index) == [0, 1, 2]) #expect(Set(slots.map(\.block)) == [block.id]) } + +/// Keeps what the store gives to run on the main queue, until the test runs it. +private final class Deliveries: @unchecked Sendable { + private let lock = NSLock() + private var waiting: [@Sendable () -> Void] = [] + private var calls = 0 + func add(_ work: @escaping @Sendable () -> Void) { lock.withLock { waiting.append(work) } } + var count: Int { lock.withLock { waiting.count } } + func runAll() { + let work = lock.withLock { + defer { waiting = [] } + return waiting + } + work.forEach { $0() } + } + func called() { lock.withLock { calls += 1 } } + var callCount: Int { lock.withLock { calls } } +} + +@Test func formulasThatArriveTogetherCallOnChangeOnce() async { + let deliveries = Deliveries() + let store = TranscriptImageStore(deliver: { deliveries.add($0) }) + store.setOnChange { deliveries.called() } + store.setMathRenderer { _, _ in solidFormula(width: 10, height: 10) } + let revision = store.revision + for index in 0..<5 { _ = store.drawnImage(TranscriptMath(tex: "x_\(index)", isDisplay: false)) } + await waitFor { store.revision == revision + 5 } + #expect(store.revision == revision + 5) + #expect(deliveries.count == 1) + deliveries.runAll() + #expect(deliveries.callCount == 1) + // A formula that arrives after the call gets a call of its own. + _ = store.drawnImage(TranscriptMath(tex: "y", isDisplay: false)) + await waitFor { deliveries.count == 1 } + deliveries.runAll() + #expect(deliveries.callCount == 2) +} From 73823d539f7cbd578c19fe3a6e27615afbf18490 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:16:18 -0800 Subject: [PATCH 5/7] Let views share a math cache A page with many message views can show the same formula in many of them. Each view had its own formulas, so each view drew the formula again. Now each TranscriptTextView keeps its formulas in TranscriptMathCache.shared by default, and draws a formula only if no view that shares the cache has drawn it. An app can give a view its own cache with `mathCache`, or in SwiftUI with `.mathRenderer(_:cache:)`. Views that share a cache must have renderers that draw a formula the same way. The README and the doc comments of the renderer now describe the empty space, the last image while LaTeX changes, and the cache. Co-Authored-By: Claude Opus 5.5 --- README.md | 22 +++++++++++++++++- .../Model/TranscriptMathImage.swift | 3 ++- .../TranscriptKit/iOS/TranscriptText.swift | 14 +++++++---- .../iOS/TranscriptTextView.swift | 23 +++++++++++++++---- 4 files changed, 52 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 15e4433..461a9fa 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,8 @@ A single `$` is text, so prices stay as written. TranscriptKit does not read Mar 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. +up to the baseline. TranscriptKit calls it off the main thread, once for each formula and font size. If it returns +nil, the formula shows its LaTeX as written. ```swift TranscriptText(stream: stream) @@ -256,6 +257,25 @@ scaled down to fit. A paragraph that holds only display math is centered. While nothing until it closes, so the text on screen only grows. Copy gives the LaTeX with its delimiters, and VoiceOver reads the LaTeX. +Until the renderer draws a formula, the formula is empty space of about its size. The LaTeX of a formula can change +from one update to the next, for example when your app closes an open formula in each new snapshot of the text. Then +the formula keeps its last image until the new one is drawn. Each formula has at most one drawing in progress, and +newer LaTeX replaces the LaTeX that waits for its turn. Images that arrive together cause one layout. + +Drawn formulas are kept in a `TranscriptMathCache`. All views share `TranscriptMathCache.shared` by default, so a +formula that shows in many messages is drawn once. The cache removes the least recently used formulas when they use +more than its byte limit, 16 MB by default. Give views whose renderers draw a formula differently a cache each: + +```swift +let cache = TranscriptMathCache(byteLimit: 8 * 1024 * 1024) + +TranscriptText(stream: stream) + .mathRenderer(myRenderer, cache: cache) +``` + +In UIKit, set `mathCache` on `TranscriptTextView`. Call `removeAll()` on a cache after your renderer changes how it +draws. + ### 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/Model/TranscriptMathImage.swift b/Sources/TranscriptKit/Model/TranscriptMathImage.swift index e9ae1d2..aa4d839 100644 --- a/Sources/TranscriptKit/Model/TranscriptMathImage.swift +++ b/Sources/TranscriptKit/Model/TranscriptMathImage.swift @@ -21,7 +21,8 @@ public struct TranscriptMathImage: @unchecked Sendable { /// 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. +/// for each formula and size in a `TranscriptMathCache`, and again only if +/// the cache removed the formula. Nil shows the LaTeX as written. public typealias TranscriptMathRenderer = @Sendable (_ math: TranscriptMath, _ fontSize: CGFloat) async -> TranscriptMathImage? extension TranscriptMathImage { diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index 1a8d959..c34be7d 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -21,6 +21,7 @@ public struct TranscriptText: UIViewRepresentable { private var loader: (@Sendable (TranscriptImage) async -> CGImage?)? private var highlighter: TranscriptCodeHighlighter? private var mathRenderer: TranscriptMathRenderer? + private var mathCache: TranscriptMathCache = .shared private var animatesTags = true private var textFadeInDuration: TimeInterval? private var animationTiming: TranscriptAnimationTiming = .immediately @@ -78,11 +79,13 @@ 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 { + /// Draws LaTeX formulas; see `TranscriptTextView.mathRenderer`. The + /// drawn formulas are kept in `cache`, which views share by default; see + /// `TranscriptTextView.mathCache`. Read once, when the view is created. + public func mathRenderer(_ renderer: @escaping TranscriptMathRenderer, cache: TranscriptMathCache = .shared) -> TranscriptText { var copy = self copy.mathRenderer = renderer + copy.mathCache = cache return copy } @@ -165,7 +168,10 @@ 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 } + if let mathRenderer { + view.mathCache = mathCache + view.mathRenderer = mathRenderer + } return view } diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index be7c15d..977d731 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -173,10 +173,14 @@ 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. + /// and font size in `mathCache`. Only the alpha of the image it returns is + /// used: the formula is drawn in the text color. Not set by default. + /// + /// Until a formula is drawn, it is empty space of about its size. While + /// the LaTeX of a formula changes, as when an app closes an open formula + /// in each new snapshot of the text, the formula keeps its last image + /// until the new one is drawn, and only its newest LaTeX waits to be + /// drawn. A formula shows its LaTeX as written if the renderer returns nil. public var mathRenderer: TranscriptMathRenderer? { didSet { engine.images.setOnChange { [weak self] in @@ -187,6 +191,17 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } } + /// Keeps the formulas that `mathRenderer` draws, so that views that share + /// a cache draw each formula once. `TranscriptMathCache.shared` by default. + /// Give views whose renderers draw a formula differently a cache each. + public var mathCache: TranscriptMathCache = .shared { + didSet { + guard mathCache !== oldValue else { return } + engine.images.setMathCache(mathCache) + relayoutNow() + } + } + private let engine = LayoutEngine() /// Holds the tiles, and the tail layer above them, below the system's From d8d80bd38d8ce33920e4fd46dab4ec5281151608 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:25:40 -0800 Subject: [PATCH 6/7] Keep the images of formulas on screen when the cache removes them A slot kept only the key of its last formula. When the cache removed a formula that was on screen, the next layout found no image, showed empty space and drew the formula again. With more formulas on screen than the cache holds, each arrival removed another formula, and the view never settled. Now each slot keeps its last image too. A formula that the cache removed shows that image, and is not drawn again. The store keeps the 1024 slots that it used last, so that a view that shows one document after another does not keep all of their formulas. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/Layout/ImageStore.swift | 19 +++++++----- Tests/TranscriptKitTests/MathTests.swift | 31 +++++++++++++++++++ 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/Sources/TranscriptKit/Layout/ImageStore.swift b/Sources/TranscriptKit/Layout/ImageStore.swift index 2e0dec3..9fd9f82 100644 --- a/Sources/TranscriptKit/Layout/ImageStore.swift +++ b/Sources/TranscriptKit/Layout/ImageStore.swift @@ -154,7 +154,11 @@ final class TranscriptImageStore: @unchecked Sendable { private var mathGeneration = 0 /// For each slot, as for code blocks: the formula it last showed drawn, /// the one being drawn, and the newest one waiting for its turn. - private var shownFormulas: [MathSlot: TranscriptMathCache.Key] = [:] + /// The last images are kept here too: a formula on screen that the cache + /// removed is then not drawn again, which would remove another one. Only + /// the slots used last are kept, so that a view that shows one document + /// after another does not keep all their formulas. + private var shownFormulas = LeastRecentlyUsed(costLimit: 1024) private var drawingFormulas: [MathSlot: TranscriptMathCache.Key] = [:] private var waitingFormulas: [MathSlot: TranscriptMathCache.Key] = [:] @@ -182,7 +186,7 @@ final class TranscriptImageStore: @unchecked Sendable { private func resetFormulas() { mathGeneration += 1 _revision += 1 - shownFormulas = [:] + shownFormulas.removeAll() drawingFormulas = [:] waitingFormulas = [:] } @@ -197,18 +201,17 @@ final class TranscriptImageStore: @unchecked Sendable { guard let mathRenderer else { return (.asWritten, nil) } switch mathCache.result(for: key) { case .drawn(let image)?: - shownFormulas[slot] = key + shownFormulas.set((key, image), for: slot, cost: 1) return (.drawn(image), nil) case .failed?: return (.asWritten, nil) case nil: break } + let shown = shownFormulas.value(for: slot) + if let shown, shown.key == key { return (.drawn(shown.image), nil) } var meanwhile = Formula.pending - if let shown = shownFormulas[slot], Self.mayBeEarlierVersion(shown.math, of: math), - case .drawn(let image)? = mathCache.result(for: shown) { - meanwhile = .drawn(image) - } + if let shown, Self.mayBeEarlierVersion(shown.key.math, of: math) { meanwhile = .drawn(shown.image) } if let drawing = drawingFormulas[slot] { waitingFormulas[slot] = drawing == key ? nil : key return (meanwhile, nil) @@ -242,7 +245,7 @@ final class TranscriptImageStore: @unchecked Sendable { generation: Int) { let (changed, next): (Bool, (TranscriptMathCache.Key, TranscriptMathRenderer, TranscriptMathCache)?) = lock.withLock { guard generation == mathGeneration else { return (false, nil) } - if case .drawn = result { shownFormulas[slot] = key } + if case .drawn(let image) = result { shownFormulas.set((key, image), for: slot, cost: 1) } _revision += 1 if let waiting = waitingFormulas.removeValue(forKey: slot), waiting != key, let mathRenderer { drawingFormulas[slot] = waiting diff --git a/Tests/TranscriptKitTests/MathTests.swift b/Tests/TranscriptKitTests/MathTests.swift index db9ca0a..c1caf6c 100644 --- a/Tests/TranscriptKitTests/MathTests.swift +++ b/Tests/TranscriptKitTests/MathTests.swift @@ -349,3 +349,34 @@ private func attachment(in layout: DocumentLayout) -> ImageAttachment? { font: font, maximumWidth: 300) #expect(wide.size.width == 300) } + +@Test func formulasOnScreenAreNotDrawnAgainWhenTheCacheRemovesThem() async { + // Room for 3 of the 5 formulas, which are 4 by 4 pixels: 16 bytes as a mask, which costs 256. + let cache = TranscriptMathCache(byteLimit: 256 * 3) + let store = TranscriptImageStore(mathCache: cache) + let calls = RenderCount() + store.setMathRenderer { _, _ in + calls.add() + return boxFormula(width: 2, height: 2, baseline: 0) + } + let document = MarkdownStreamParser.document(from: "\\(a\\) \\(b\\) \\(c\\) \\(d\\) \\(e\\)") + var layout = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: nil, images: store) + for _ in 0..<20 { + let revision = store.revision + await waitUntil { store.revision > revision } + if store.revision == revision { break } + layout = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: layout, images: store) + } + let attachments = layout.entry(at: 0).layout.attachments + #expect(attachments.count == 5) + #expect(attachments.allSatisfy { $0.attachment.picture != nil }) + #expect(calls.value == 5) + #expect(cache.usage.count == 3) +} + +private final class RenderCount: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + func add() { lock.withLock { count += 1 } } + var value: Int { lock.withLock { count } } +} From 240c042274e377167d334cddadb756365884d493 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:48:16 -0800 Subject: [PATCH 7/7] Keep a formula's image when its renderer fails or the cache is emptied A renderer can return nil for LaTeX that is not complete yet. The formula now keeps its last image or its empty space. It shows its LaTeX only when that LaTeX stays the same for one second after the failure. The cache keeps only images. Each view keeps its failures per formula. removeAll() now lays out the views that use the cache again, and a draw from before removeAll() is not kept or joined. A store keeps the slots of the document that it lays out, with no fixed count. Older draws do not replace newer images, and newer LaTeX that is already drawn drops the LaTeX that waits. The slot of a formula is found with a binary search. Co-Authored-By: Claude Opus 5.5 --- README.md | 14 +- .../TranscriptKit/Layout/DocumentLayout.swift | 1 + Sources/TranscriptKit/Layout/ImageStore.swift | 173 +++++++++--- Sources/TranscriptKit/Layout/MathCache.swift | 102 ++++--- .../Layout/TranscriptStyle.swift | 26 +- .../Model/TranscriptMathImage.swift | 4 +- .../TranscriptKit/iOS/TranscriptText.swift | 6 +- .../iOS/TranscriptTextView.swift | 10 +- Tests/TranscriptKitTests/MathCacheTests.swift | 264 +++++++++++++++++- Tests/TranscriptKitTests/MathTests.swift | 2 +- 10 files changed, 512 insertions(+), 90 deletions(-) diff --git a/README.md b/README.md index 461a9fa..7e00878 100644 --- a/README.md +++ b/README.md @@ -239,7 +239,8 @@ A single `$` is text, so prices stay as written. TranscriptKit does not read Mar 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. If it returns -nil, the formula shows its LaTeX as written. +nil, the formula shows its LaTeX as written once that LaTeX stays the same for a second. LaTeX that is not complete yet +can fail while it streams in, and the formula then keeps what it showed. ```swift TranscriptText(stream: stream) @@ -260,11 +261,14 @@ reads the LaTeX. Until the renderer draws a formula, the formula is empty space of about its size. The LaTeX of a formula can change from one update to the next, for example when your app closes an open formula in each new snapshot of the text. Then the formula keeps its last image until the new one is drawn. Each formula has at most one drawing in progress, and -newer LaTeX replaces the LaTeX that waits for its turn. Images that arrive together cause one layout. +newer LaTeX replaces the LaTeX that waits for its turn. Images that arrive together cause one layout. A view keeps +the images of the formulas in the document it shows, also when the cache removes them, so it does not draw them again. Drawn formulas are kept in a `TranscriptMathCache`. All views share `TranscriptMathCache.shared` by default, so a formula that shows in many messages is drawn once. The cache removes the least recently used formulas when they use -more than its byte limit, 16 MB by default. Give views whose renderers draw a formula differently a cache each: +more than its byte limit, 16 MB by default. The cache does not keep a nil result: each view keeps it for the formulas +it shows. A view shows the formulas that any renderer of its cache drew, so give views whose renderers draw a formula +differently a cache each: ```swift let cache = TranscriptMathCache(byteLimit: 8 * 1024 * 1024) @@ -273,8 +277,8 @@ TranscriptText(stream: stream) .mathRenderer(myRenderer, cache: cache) ``` -In UIKit, set `mathCache` on `TranscriptTextView`. Call `removeAll()` on a cache after your renderer changes how it -draws. +In UIKit, set `mathCache` on `TranscriptTextView`. Setting a renderer does not empty the cache. Call `removeAll()` on +a cache after your renderer changes how it draws: the views that use the cache then draw their formulas again. ### Selection diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index e129548..93b80c3 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -67,6 +67,7 @@ public final class DocumentLayout: @unchecked Sendable { self.document = document let imageRevision = images?.revision ?? 0 self.imageRevision = imageRevision + images?.keepFormulas(of: document) // A line-limited layout may hold a block cut short, so it is not reused. let previous = style.lineLimit == nil ? previous.flatMap { $0.width == width && $0.style == style ? $0 : nil } : nil diff --git a/Sources/TranscriptKit/Layout/ImageStore.swift b/Sources/TranscriptKit/Layout/ImageStore.swift index 9fd9f82..a503929 100644 --- a/Sources/TranscriptKit/Layout/ImageStore.swift +++ b/Sources/TranscriptKit/Layout/ImageStore.swift @@ -39,10 +39,17 @@ final class TranscriptImageStore: @unchecked Sendable { /// - mathCache: where drawn formulas are kept. A store has a cache of /// its own unless it is given one that views share. /// - deliver: runs `onChange`. + /// - settle: runs its work once the LaTeX of a formula that the + /// renderer could not draw may have stopped changing. init(mathCache: TranscriptMathCache = TranscriptMathCache(), - deliver: @escaping @Sendable (@escaping @Sendable () -> Void) -> Void = { DispatchQueue.main.async(execute: $0) }) { + deliver: @escaping @Sendable (@escaping @Sendable () -> Void) -> Void = { DispatchQueue.main.async(execute: $0) }, + settle: @escaping @Sendable (@escaping @Sendable () -> Void) -> Void = { + DispatchQueue.global().asyncAfter(deadline: .now() + 1, execute: $0) + }) { self.mathCache = mathCache self.deliver = deliver + self.settle = settle + mathCache.add(self) } /// Sets the loader and what to call when a picture has arrived; see @@ -149,18 +156,35 @@ final class TranscriptImageStore: @unchecked Sendable { case asWritten } + /// A slot, as for code blocks: what it shows and what is drawn for it. + private struct SlotState { + /// The formula the slot was asked for last. + var asked: TranscriptMathCache.Key? + /// The slot's last image, and its formula. The image is kept here + /// too, so that a formula on screen that the cache removed is not + /// drawn again, which would remove another one. + var shown: (key: TranscriptMathCache.Key, image: TranscriptMathImage)? + /// The last formula that the renderer could not draw, and whether + /// its LaTeX stayed the same long enough after that to show it. + var failed: TranscriptMathCache.Key? + var failureSettled = false + /// The formula being drawn, and the newest one waiting for its turn. + var drawing: TranscriptMathCache.Key? + var waiting: TranscriptMathCache.Key? + /// The slot showed a newer formula than the one being drawn, which + /// then must not replace it. + var drawingIsOutdated = false + } + private var mathRenderer: TranscriptMathRenderer? private var mathCache: TranscriptMathCache private var mathGeneration = 0 - /// For each slot, as for code blocks: the formula it last showed drawn, - /// the one being drawn, and the newest one waiting for its turn. - /// The last images are kept here too: a formula on screen that the cache - /// removed is then not drawn again, which would remove another one. Only - /// the slots used last are kept, so that a view that shows one document - /// after another does not keep all their formulas. - private var shownFormulas = LeastRecentlyUsed(costLimit: 1024) - private var drawingFormulas: [MathSlot: TranscriptMathCache.Key] = [:] - private var waitingFormulas: [MathSlot: TranscriptMathCache.Key] = [:] + private var mathSlots: [MathSlot: SlotState] = [:] + /// How many slots were kept when slots of other documents were last removed. + private var keptMathSlots = 0 + /// Runs its work once the LaTeX of a formula that failed may have + /// stopped changing. + private let settle: @Sendable (@escaping @Sendable () -> Void) -> Void var hasMathRenderer: Bool { lock.withLock { mathRenderer != nil } } @@ -176,47 +200,81 @@ final class TranscriptImageStore: @unchecked Sendable { /// Sets where drawn formulas are kept, and lays them out again. func setMathCache(_ cache: TranscriptMathCache) { - lock.withLock { - guard cache !== mathCache else { return } + let changed: Bool = lock.withLock { + guard cache !== mathCache else { return false } mathCache = cache resetFormulas() + return true } + if changed { cache.add(self) } + } + + /// The cache removed all its formulas: they are drawn again. + func mathCacheWasEmptied(_ cache: TranscriptMathCache) { + let changed: Bool = lock.withLock { + guard cache === mathCache else { return false } + resetFormulas() + return mathRenderer != nil + } + if changed { notifyChange() } } private func resetFormulas() { mathGeneration += 1 _revision += 1 - shownFormulas.removeAll() - drawingFormulas = [:] - waitingFormulas = [:] + mathSlots = [:] + keptMathSlots = 0 + } + + /// Removes the slots of blocks that are not in `document`, so that a + /// view that shows one document after another does not keep all their + /// formulas. The slots of `document` all stay, however many there are. + func keepFormulas(of document: TranscriptDocument) { + lock.withLock { + guard mathSlots.count > keptMathSlots * 2 + 64 else { return } + let blocks = Set(document.blocks.map(\.id)) + mathSlots = mathSlots.filter { blocks.contains($0.key.block) || $0.value.drawing != nil } + keptMathSlots = mathSlots.count + } } /// What to show for `math` in `slot`. When it is not drawn yet, drawing /// starts (or waits for the slot's current one to end), and the slot's /// last image is given meanwhile: while a formula streams in, its last /// image is closer to the new one than empty space is. + /// + /// A renderer can return nil for LaTeX that is not complete yet. Then the + /// slot shows the same until its LaTeX stays the same for a moment, and + /// only after that shows the LaTeX as written. func formula(for math: TranscriptMath, fontSize: CGFloat, in slot: MathSlot) -> Formula { let key = TranscriptMathCache.Key(math: math, fontSize: fontSize) let (formula, start): (Formula, (TranscriptMathRenderer, TranscriptMathCache, Int)?) = lock.withLock { guard let mathRenderer else { return (.asWritten, nil) } - switch mathCache.result(for: key) { - case .drawn(let image)?: - shownFormulas.set((key, image), for: slot, cost: 1) + var state = mathSlots[slot] ?? SlotState() + defer { mathSlots[slot] = state } + state.asked = key + if let image = mathCache.image(for: key) { + state.shown = (key, image) + state.waiting = nil + state.drawingIsOutdated = state.drawing != nil return (.drawn(image), nil) - case .failed?: - return (.asWritten, nil) - case nil: - break } - let shown = shownFormulas.value(for: slot) - if let shown, shown.key == key { return (.drawn(shown.image), nil) } + if let shown = state.shown, shown.key == key { + state.waiting = nil + state.drawingIsOutdated = state.drawing != nil + return (.drawn(shown.image), nil) + } var meanwhile = Formula.pending - if let shown, Self.mayBeEarlierVersion(shown.key.math, of: math) { meanwhile = .drawn(shown.image) } - if let drawing = drawingFormulas[slot] { - waitingFormulas[slot] = drawing == key ? nil : key + if let shown = state.shown, Self.mayBeEarlierVersion(shown.key.math, of: math) { meanwhile = .drawn(shown.image) } + if state.failed == key { + state.waiting = nil + return (state.failureSettled ? .asWritten : meanwhile, nil) + } + if let drawing = state.drawing { + state.waiting = drawing == key ? nil : key return (meanwhile, nil) } - drawingFormulas[slot] = key + state.drawing = key return (meanwhile, (mathRenderer, mathCache, mathGeneration)) } if let (renderer, cache, generation) = start { @@ -243,20 +301,61 @@ final class TranscriptImageStore: @unchecked Sendable { private func finishFormula(_ key: TranscriptMathCache.Key, in slot: MathSlot, _ result: TranscriptMathCache.Result, generation: Int) { - let (changed, next): (Bool, (TranscriptMathCache.Key, TranscriptMathRenderer, TranscriptMathCache)?) = lock.withLock { - guard generation == mathGeneration else { return (false, nil) } - if case .drawn(let image) = result { shownFormulas.set((key, image), for: slot, cost: 1) } - _revision += 1 - if let waiting = waitingFormulas.removeValue(forKey: slot), waiting != key, let mathRenderer { - drawingFormulas[slot] = waiting - return (true, (waiting, mathRenderer, mathCache)) + let (changed, failed, next): (Bool, Bool, (TranscriptMathCache.Key, TranscriptMathRenderer, TranscriptMathCache)?) = lock.withLock { + guard generation == mathGeneration, var state = mathSlots[slot] else { return (false, false, nil) } + defer { mathSlots[slot] = state } + let isNewest = key == state.asked + var changed = false + var failed = false + switch result { + case .drawn(let image): + // An older formula's image stands in for the newest until that is drawn. + let standsIn = !state.drawingIsOutdated && state.asked.map { Self.mayBeEarlierVersion(key.math, of: $0.math) } == true + if isNewest || standsIn { + state.shown = (key, image) + changed = true + } + case .failed: + if isNewest { + state.failed = key + state.failureSettled = false + failed = true + } } - drawingFormulas[slot] = nil - return (true, nil) + if changed { _revision += 1 } + state.drawingIsOutdated = false + if let waiting = state.waiting, let mathRenderer { + state.waiting = nil + state.drawing = waiting + return (changed, failed, (waiting, mathRenderer, mathCache)) + } + state.waiting = nil + state.drawing = nil + return (changed, failed, nil) } if let (waiting, renderer, cache) = next { draw(waiting, in: slot, with: renderer, cache: cache, generation: generation) } + if failed { + settle { [weak self] in self?.settleFailure(key, in: slot, generation: generation) } + } + if changed { notifyChange() } + } + + /// How many slots the store keeps. For tests. + var mathSlotCount: Int { lock.withLock { mathSlots.count } } + + /// Shows the LaTeX of a formula that failed, if the slot was not asked + /// for other LaTeX since. + private func settleFailure(_ key: TranscriptMathCache.Key, in slot: MathSlot, generation: Int) { + let changed: Bool = lock.withLock { + guard generation == mathGeneration, var state = mathSlots[slot], state.failed == key, state.asked == key, + !state.failureSettled else { return false } + state.failureSettled = true + mathSlots[slot] = state + _revision += 1 + return true + } if changed { notifyChange() } } diff --git a/Sources/TranscriptKit/Layout/MathCache.swift b/Sources/TranscriptKit/Layout/MathCache.swift index 1fedaed..631bad9 100644 --- a/Sources/TranscriptKit/Layout/MathCache.swift +++ b/Sources/TranscriptKit/Layout/MathCache.swift @@ -6,7 +6,9 @@ import Foundation /// /// Each `TranscriptTextView` uses `shared` unless the app gives it another /// cache. A cache keeps the formulas of one renderer: give views whose -/// renderers draw a formula differently a cache each. +/// renderers draw a formula differently a cache each. The cache keeps only +/// images: when the renderer returns nil, each view keeps that result for +/// the formulas it shows, until its renderer is set again. public final class TranscriptMathCache: @unchecked Sendable { /// The cache that views use unless the app gives them another. public static let shared = TranscriptMathCache() @@ -27,83 +29,113 @@ public final class TranscriptMathCache: @unchecked Sendable { /// What the renderer gave for a formula. enum Result: Sendable { case drawn(TranscriptMathImage) - /// The renderer returned nil: the formula shows its LaTeX as written. + /// The renderer returned nil. case failed + } - /// Bytes. A formula that failed costs a little too, so that the - /// number of formulas kept has a limit. - var cost: Int { - guard case .drawn(let formula) = self else { return 256 } - return max(formula.image.bytesPerRow * formula.image.height, 256) - } + /// A draw of `key` that started after the cache was emptied `generation` times. + private struct Draw: Hashable { + let key: Key + let generation: Int + } + + private struct WeakStore { + weak var store: TranscriptImageStore? } private let lock = NSLock() - private var results: LeastRecentlyUsed - /// For each formula that is being drawn: what to call with its result. - private var waiting: [Key: [@Sendable (Result) -> Void]] = [:] + private var images: LeastRecentlyUsed + /// For each draw in progress: what to call with its result. + private var waiting: [Draw: [@Sendable (Result) -> Void]] = [:] + private var stores: [ObjectIdentifier: WeakStore] = [:] + /// How many stores were alive when the dead ones were last removed. + private var liveStores = 0 private var generation = 0 private var draws = 0 /// - Parameter byteLimit: how much memory the drawn formulas can use. /// When they use more, the formulas used least recently are removed. public init(byteLimit: Int = 16 * 1024 * 1024) { - results = LeastRecentlyUsed(costLimit: byteLimit) + images = LeastRecentlyUsed(costLimit: byteLimit) } - /// Removes all the formulas. Views draw a formula again the next time - /// they lay it out. Use this when the renderer changes how it draws. + /// Removes all the formulas, and lays out again the views that use the + /// cache, so that they draw their formulas again. Use this when the + /// renderer changes how it draws. Formulas that are being drawn now are + /// not kept, and are drawn again when a view asks for them. public func removeAll() { - lock.withLock { + let stores: [TranscriptImageStore] = lock.withLock { generation += 1 - results.removeAll() + images.removeAll() + return self.stores.values.compactMap(\.store) } + for store in stores { store.mathCacheWasEmptied(self) } } - /// The result for `key`, if the renderer has given it. - func result(for key: Key) -> Result? { - lock.withLock { results.value(for: key) } + /// Tells `store` when the cache is emptied. + func add(_ store: TranscriptImageStore) { + lock.withLock { + stores[ObjectIdentifier(store)] = WeakStore(store: store) + if stores.count > liveStores * 2 + 64 { + stores = stores.filter { $0.value.store != nil } + liveStores = stores.count + } + } + } + + /// The image for `key`, if the renderer has drawn it. + func image(for key: Key) -> TranscriptMathImage? { + lock.withLock { images.value(for: key) } } /// Calls `done` with the result for `key`: right away if the renderer - /// has given it, or else once it has drawn the formula. The renderer is - /// not called again for a formula that it is drawing. + /// has drawn it, or else once the renderer has given its result. The + /// renderer is not called again for a formula that it is drawing. func draw(_ key: Key, with renderer: @escaping TranscriptMathRenderer, then done: @escaping @Sendable (Result) -> Void) { - enum Step { case known(Result), wait, start(Int) } + enum Step { case known(TranscriptMathImage), wait, start(Draw) } let step: Step = lock.withLock { - if let known = results.value(for: key) { return .known(known) } - if waiting[key] != nil { - waiting[key]!.append(done) + if let known = images.value(for: key) { return .known(known) } + let draw = Draw(key: key, generation: generation) + if waiting[draw] != nil { + waiting[draw]!.append(done) return .wait } - waiting[key] = [done] + waiting[draw] = [done] draws += 1 - return .start(generation) + return .start(draw) } switch step { - case .known(let result): - done(result) + case .known(let image): + done(.drawn(image)) case .wait: break - case .start(let generation): + case .start(let draw): Task.detached { let drawn = await renderer(key.math, key.fontSize)?.withAlphaAsMask() - self.finish(key, drawn.map(Result.drawn) ?? .failed, generation: generation) + self.finish(draw, drawn.map(Result.drawn) ?? .failed) } } } - private func finish(_ key: Key, _ result: Result, generation: Int) { + private func finish(_ draw: Draw, _ result: Result) { let waiters: [@Sendable (Result) -> Void] = lock.withLock { - if generation == self.generation { results.set(result, for: key, cost: result.cost) } - return waiting.removeValue(forKey: key) ?? [] + if draw.generation == generation, case .drawn(let image) = result { + images.set(image, for: draw.key, cost: Self.cost(of: image)) + } + return waiting.removeValue(forKey: draw) ?? [] } for done in waiters { done(result) } } + /// Bytes, and at least a little for each formula, so that the number of + /// formulas kept has a limit. + static func cost(of formula: TranscriptMathImage) -> Int { + max(formula.image.bytesPerRow * formula.image.height, 256) + } + /// How many times the renderer was called. For tests. var drawCount: Int { lock.withLock { draws } } /// How much memory the formulas use, in bytes, and how many there are. For tests. - var usage: (bytes: Int, count: Int) { lock.withLock { (results.totalCost, results.count) } } + var usage: (bytes: Int, count: Int) { lock.withLock { (images.totalCost, images.count) } } } diff --git a/Sources/TranscriptKit/Layout/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index d818b01..7519660 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -253,6 +253,7 @@ public struct TranscriptStyle: Equatable, Sendable { cuts.insert(span.range.upperBound) } let sorted = cuts.sorted() + var mathStarts: [Int]? for (lower, upper) in zip(sorted, sorted.dropFirst()) { var traits = extraTraits var isLink = false @@ -287,8 +288,10 @@ public struct TranscriptStyle: Equatable, Sendable { if let background { result.addAttribute(Self.backgroundKey, value: background, range: range) } 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 = math.map { - ImageAttachment(math: $0.math, slot: Self.mathSlot(in: block, at: $0.start), sizing: images, font: font, style: self) + let attachment = math.map { math -> ImageAttachment in + if mathStarts == nil { mathStarts = Self.mathStarts(in: block) } + let slot = Self.mathSlot(in: block, at: math.start, starts: mathStarts!) + return ImageAttachment(math: math.math, slot: slot, 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) @@ -307,8 +310,23 @@ extension TranscriptStyle { /// The slot of the formula that starts at UTF-16 offset `start` of /// `block`: it is the same whichever part of the block is laid out. static func mathSlot(in block: TranscriptBlock, at start: Int) -> TranscriptImageStore.MathSlot { - let before = block.spans.reduce(0) { $0 + ($1.math != nil && $1.range.lowerBound < start ? 1 : 0) } - return TranscriptImageStore.MathSlot(block: block.id, index: before) + mathSlot(in: block, at: start, starts: mathStarts(in: block)) + } + + /// The same, with the block's `mathStarts`. + static func mathSlot(in block: TranscriptBlock, at start: Int, starts: [Int]) -> TranscriptImageStore.MathSlot { + var low = 0 + var high = starts.count + while low < high { + let middle = (low + high) / 2 + if starts[middle] < start { low = middle + 1 } else { high = middle } + } + return TranscriptImageStore.MathSlot(block: block.id, index: low) + } + + /// Where the block's formulas start, in order. + static func mathStarts(in block: TranscriptBlock) -> [Int] { + block.spans.compactMap { $0.math != nil ? $0.range.lowerBound : nil }.sorted() } } diff --git a/Sources/TranscriptKit/Model/TranscriptMathImage.swift b/Sources/TranscriptKit/Model/TranscriptMathImage.swift index aa4d839..be619ec 100644 --- a/Sources/TranscriptKit/Model/TranscriptMathImage.swift +++ b/Sources/TranscriptKit/Model/TranscriptMathImage.swift @@ -22,7 +22,9 @@ public struct TranscriptMathImage: @unchecked Sendable { /// 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 in a `TranscriptMathCache`, and again only if -/// the cache removed the formula. Nil shows the LaTeX as written. +/// the cache removed the formula. Nil shows the LaTeX as written, once it +/// stays the same for a second. The cache does not keep nil: each view +/// keeps it for the formulas it shows, until its renderer is set again. public typealias TranscriptMathRenderer = @Sendable (_ math: TranscriptMath, _ fontSize: CGFloat) async -> TranscriptMathImage? extension TranscriptMathImage { diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index c34be7d..653b324 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -80,8 +80,10 @@ public struct TranscriptText: UIViewRepresentable { } /// Draws LaTeX formulas; see `TranscriptTextView.mathRenderer`. The - /// drawn formulas are kept in `cache`, which views share by default; see - /// `TranscriptTextView.mathCache`. Read once, when the view is created. + /// drawn formulas are kept in `cache`, which is `TranscriptMathCache.shared` + /// by default: views that share a cache show the formulas that any of + /// their renderers drew. See `TranscriptTextView.mathCache`. Read once, + /// when the view is created. public func mathRenderer(_ renderer: @escaping TranscriptMathRenderer, cache: TranscriptMathCache = .shared) -> TranscriptText { var copy = self copy.mathRenderer = renderer diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 977d731..501ae79 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -180,7 +180,15 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// the LaTeX of a formula changes, as when an app closes an open formula /// in each new snapshot of the text, the formula keeps its last image /// until the new one is drawn, and only its newest LaTeX waits to be - /// drawn. A formula shows its LaTeX as written if the renderer returns nil. + /// drawn. If the renderer returns nil, the formula shows its LaTeX as + /// written once that LaTeX stays the same for a second: LaTeX that is + /// not complete yet can fail while it streams in. + /// + /// Views share `TranscriptMathCache.shared` by default, and a formula + /// that one view drew shows in the others without a call to their + /// renderers. Setting this property does not empty the cache. Give views + /// whose renderers draw a formula differently a `mathCache` each, and + /// call `removeAll()` on the cache when the renderer changes how it draws. public var mathRenderer: TranscriptMathRenderer? { didSet { engine.images.setOnChange { [weak self] in diff --git a/Tests/TranscriptKitTests/MathCacheTests.swift b/Tests/TranscriptKitTests/MathCacheTests.swift index 58b5927..f871c7e 100644 --- a/Tests/TranscriptKitTests/MathCacheTests.swift +++ b/Tests/TranscriptKitTests/MathCacheTests.swift @@ -89,7 +89,8 @@ final class RenderCalls: @unchecked Sendable { } @Test func aFormulaThatFailsIsNotDrawnAgain() async { - let store = TranscriptImageStore() + let cache = TranscriptMathCache() + let store = TranscriptImageStore(mathCache: cache) let calls = RenderCalls() store.setMathRenderer { math, _ in calls.add(math.tex) @@ -102,6 +103,8 @@ final class RenderCalls: @unchecked Sendable { #expect(store.drawnImage(math) == nil) try? await Task.sleep(for: .milliseconds(50)) #expect(calls.all.count == 1) + // The cache keeps only images: a view that comes later asks the renderer again. + #expect(cache.usage.count == 0) } @Test func theCacheRemovesTheLeastRecentlyUsedFormulasOverItsLimit() async { @@ -118,9 +121,9 @@ final class RenderCalls: @unchecked Sendable { } #expect(cache.usage.count == 3) #expect(cache.usage.bytes <= 256 * 3) - #expect(cache.result(for: .init(math: formulas[0], fontSize: 17)) != nil) - #expect(cache.result(for: .init(math: formulas[1], fontSize: 17)) == nil) - #expect(cache.result(for: .init(math: formulas[4], fontSize: 17)) != nil) + #expect(cache.image(for: .init(math: formulas[0], fontSize: 17)) != nil) + #expect(cache.image(for: .init(math: formulas[1], fontSize: 17)) == nil) + #expect(cache.image(for: .init(math: formulas[4], fontSize: 17)) != nil) cache.removeAll() #expect(cache.usage.count == 0) } @@ -213,3 +216,256 @@ private final class Deliveries: @unchecked Sendable { deliveries.runAll() #expect(deliveries.callCount == 2) } + +/// Holds a renderer until the test lets it go on. +private final class Gate: @unchecked Sendable { + private let lock = NSLock() + private var isOpen = false + private var waiters: [CheckedContinuation] = [] + + func wait() async { + await withCheckedContinuation { continuation in + let resume: Bool = lock.withLock { + if isOpen { return true } + waiters.append(continuation) + return false + } + if resume { continuation.resume() } + } + } + + func open() { + let waiters: [CheckedContinuation] = lock.withLock { + isOpen = true + defer { self.waiters = [] } + return self.waiters + } + waiters.forEach { $0.resume() } + } +} + +/// Keeps the work that the store runs once a failed formula may have settled. +private final class Settles: @unchecked Sendable { + private let lock = NSLock() + private var waiting: [@Sendable () -> Void] = [] + func add(_ work: @escaping @Sendable () -> Void) { lock.withLock { waiting.append(work) } } + var count: Int { lock.withLock { waiting.count } } + func runAll() { + let work = lock.withLock { + defer { waiting = [] } + return waiting + } + work.forEach { $0() } + } +} + +private func width(_ formula: TranscriptImageStore.Formula) -> CGFloat? { + guard case .drawn(let image) = formula else { return nil } + return image.size.width +} + +private func isAsWritten(_ formula: TranscriptImageStore.Formula) -> Bool { + if case .asWritten = formula { return true } + return false +} + +@Test func aFormulaThatFailsWhileItStreamsInDoesNotShowItsLatex() async { + let settles = Settles() + let store = TranscriptImageStore(settle: { settles.add($0) }) + let calls = RenderCalls() + // Like a real renderer: LaTeX with an open brace cannot be drawn. + store.setMathRenderer { math, _ in + calls.add(math.tex) + let open = math.tex.filter { $0 == "{" }.count + let closed = math.tex.filter { $0 == "}" }.count + return open == closed ? solidFormula(width: 10 * math.tex.count, height: 10) : nil + } + let slot = TranscriptImageStore.MathSlot(block: "md-0", index: 0) + func ask(_ tex: String) -> TranscriptImageStore.Formula { + store.formula(for: TranscriptMath(tex: tex, isDisplay: true), fontSize: 17, in: slot) + } + let full = "x = \\frac{a}{b}" + for count in 1...full.count { + let tex = String(full.prefix(count)) + #expect(!isAsWritten(ask(tex))) + await waitFor { calls.all.last == tex } + #expect(calls.all.last == tex) + try? await Task.sleep(for: .milliseconds(5)) + #expect(!isAsWritten(ask(tex))) + } + // The failures of LaTeX that changed since settle to nothing. + settles.runAll() + #expect(width(ask(full)) == CGFloat(10 * full.count)) + + // LaTeX that fails and then stays the same shows as written: it is not a prefix of a drawn formula forever. + let broken = full + " + \\frac{c}{" + #expect(width(ask(broken)) == CGFloat(10 * full.count)) + await waitFor { settles.count == 1 } + #expect(width(ask(broken)) == CGFloat(10 * full.count)) + settles.runAll() + #expect(isAsWritten(ask(broken))) +} + +@Test func removingAllFormulasDrawsThemAgainInTheStoresThatShowThem() async { + let cache = TranscriptMathCache() + let deliveries = Deliveries() + let store = TranscriptImageStore(mathCache: cache, deliver: { deliveries.add($0) }) + store.setOnChange { deliveries.called() } + let calls = RenderCalls() + store.setMathRenderer { math, _ in + calls.add(math.tex) + return solidFormula(width: 10 * calls.all.count, height: 10) + } + let math = TranscriptMath(tex: "x", isDisplay: false) + _ = store.drawnImage(math) + await waitFor { store.drawnImage(math) != nil } + #expect(store.drawnImage(math)?.size.width == 10) + deliveries.runAll() + let revision = store.revision + cache.removeAll() + #expect(store.revision > revision) + #expect(deliveries.count == 1) + deliveries.runAll() + #expect(store.drawnImage(math) == nil) + await waitFor { store.drawnImage(math) != nil } + #expect(store.drawnImage(math)?.size.width == 20) + #expect(calls.all == ["x", "x"]) +} + +@Test func aDrawThatStartedBeforeRemoveAllIsNotKept() async { + let cache = TranscriptMathCache() + let store = TranscriptImageStore(mathCache: cache) + let gates = [Gate(), Gate()] + let calls = RenderCalls() + store.setMathRenderer { math, _ in + let call = calls.all.count + calls.add(math.tex) + await gates[call].wait() + return solidFormula(width: 10 * (call + 1), height: 10) + } + let math = TranscriptMath(tex: "x", isDisplay: false) + #expect(store.drawnImage(math) == nil) + await waitFor { calls.all.count == 1 } + cache.removeAll() + // The new request does not wait for the draw from before. + #expect(store.drawnImage(math) == nil) + await waitFor { calls.all.count == 2 } + #expect(calls.all.count == 2) + gates[0].open() + try? await Task.sleep(for: .milliseconds(50)) + #expect(cache.usage.count == 0) + #expect(store.drawnImage(math) == nil) + gates[1].open() + await waitFor { store.drawnImage(math) != nil } + #expect(store.drawnImage(math)?.size.width == 20) + #expect(cache.image(for: .init(math: math, fontSize: 17))?.size.width == 20) +} + +@Test func aStoreGivenAnotherCacheDrawsIntoIt() async { + let first = TranscriptMathCache() + let second = TranscriptMathCache() + let store = TranscriptImageStore(mathCache: first) + store.setMathRenderer { _, _ in solidFormula(width: 10, height: 10) } + let math = TranscriptMath(tex: "x", isDisplay: false) + _ = store.drawnImage(math) + await waitFor { store.drawnImage(math) != nil } + var revision = store.revision + store.setMathCache(second) + #expect(store.revision > revision) + #expect(store.drawnImage(math) == nil) + await waitFor { store.drawnImage(math) != nil } + #expect(second.drawCount == 1) + // The cache it used before no longer lays it out again. + revision = store.revision + first.removeAll() + #expect(store.revision == revision) + #expect(store.drawnImage(math) != nil) +} + +@Test func newerLatexThatIsAlreadyDrawnReplacesTheWaitingLatex() async { + // Room for one formula only. + let cache = TranscriptMathCache(byteLimit: 256) + let gate = Gate() + let calls = RenderCalls() + let renderer: TranscriptMathRenderer = { math, _ in + calls.add(math.tex) + if math.tex == "x" { await gate.wait() } + return solidFormula(width: 10 * math.tex.count, height: 10) + } + let store = TranscriptImageStore(mathCache: cache) + let other = TranscriptImageStore(mathCache: cache) + store.setMathRenderer(renderer) + other.setMathRenderer(renderer) + let slot = TranscriptImageStore.MathSlot(block: "md-0", index: 0) + func ask(_ tex: String) -> TranscriptImageStore.Formula { + store.formula(for: TranscriptMath(tex: tex, isDisplay: true), fontSize: 17, in: slot) + } + _ = ask("x") + await waitFor { calls.all == ["x"] } + _ = ask("x+") + // Another view draws the newest LaTeX first. + let newest = TranscriptMath(tex: "x+y", isDisplay: true) + _ = other.drawnImage(newest) + await waitFor { other.drawnImage(newest) != nil } + #expect(width(ask("x+y")) == 30) + gate.open() + await waitFor { cache.image(for: .init(math: TranscriptMath(tex: "x", isDisplay: true), fontSize: 17)) != nil } + try? await Task.sleep(for: .milliseconds(50)) + // "x+" was not drawn, and the late image of "x" did not replace the newer one. + #expect(calls.all == ["x", "x+y"]) + #expect(width(ask("x+y")) == 30) + #expect(calls.all == ["x", "x+y"]) +} + +@Test func picturesColorsAndFormulasThatArriveTogetherCallOnChangeOnce() async { + let deliveries = Deliveries() + let store = TranscriptImageStore(deliver: { deliveries.add($0) }) + let picture = solidFormula(width: 4, height: 4).image + store.setLoader({ _ in picture }, onChange: { deliveries.called() }) + store.setHighlighter { code, _ in [TranscriptCodeHighlight(range: 0.. ImageAttachment? { let plain = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: nil, images: TranscriptImageStore()) #expect(attachment(in: plain)?.label != nil) - let store = TranscriptImageStore() + let store = TranscriptImageStore(settle: { $0() }) store.setMathRenderer { _, _ in nil } let revision = store.revision let first = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: nil, images: store)