diff --git a/README.md b/README.md index 2a2666d..09af85c 100644 --- a/README.md +++ b/README.md @@ -253,7 +253,9 @@ 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 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) @@ -271,6 +273,28 @@ 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. 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. 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) + +TranscriptText(stream: stream) + .mathRenderer(myRenderer, cache: cache) +``` + +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 The text is selectable by default. Turn selection off for text inside a view that reacts to taps, such as a card or a @@ -408,8 +432,9 @@ let image = UIGraphicsImageRenderer(bounds: view.bounds).image { view.layer.rend ``` While a stream that has not finished goes on, `contentSettled()` returns at the first moment when nothing is pending. -A cancelled task returns at once. An image or a formula that comes back as nil counts as done. A load, a formula or -a highlight that never ends holds back `contentSettled()`, so use a timeout or cancel the task. Give the view its size +A cancelled task returns at once. An image that comes back as nil counts as done. A formula that comes back as nil +counts as done when it shows its LaTeX as written, about a second later. A load, a formula or a highlight that never +ends holds back `contentSettled()`, so use a timeout or cancel the task. Give the view its size before the call: a view with no width lays out nothing and settles at once. Fades and tag animations that play are not waited for, so turn off `textFadeInDuration` and `animatesTags` to compare pixels. diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index 0aa8840..5167e77 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 @@ -718,11 +719,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/ImageStore.swift b/Sources/TranscriptKit/Layout/ImageStore.swift index fa8c675..e5d6d41 100644 --- a/Sources/TranscriptKit/Layout/ImageStore.swift +++ b/Sources/TranscriptKit/Layout/ImageStore.swift @@ -17,6 +17,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 @@ -29,16 +33,33 @@ final class TranscriptImageStore: @unchecked Sendable { private var highlighting: Set = [] private var waitingCode: [String: (text: String, language: String?)] = [:] - init(work: PendingWork = PendingWork()) { - self.work = work - } - /// Goes up each time a picture arrives; layouts made at an older /// 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. + /// - work: counts the loads, formulas and highlights in flight, and + /// each change until `onChange` has run for it. + /// - 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(), + work: PendingWork = PendingWork(), + 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.work = work + self.deliver = deliver + self.settle = settle + mathCache.add(self) + } + + /// 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 { @@ -51,8 +72,10 @@ final class TranscriptImageStore: @unchecked Sendable { } } - /// Sets what to call (on any thread) when a picture or colors arrive. - /// Work that the call starts must begin on `work` before it returns. + /// 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. Work that the call starts must begin on + /// `work` before it returns. func setOnChange(_ onChange: (@Sendable () -> Void)?) { lock.withLock { self.onChange = onChange } } @@ -107,78 +130,251 @@ 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 - private struct FormulaKey: Hashable { - let math: TranscriptMath - /// The font size, to half a point. - let size: Int + /// 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 + } + + /// 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 - private var formulas: [FormulaKey: TranscriptMathImage] = [:] - private var formulasRequested: Set = [] + 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 } } - /// 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 = [] + resetFormulas() + } + } + + /// Sets where drawn formulas are kept, and lays them out again. + func setMathCache(_ cache: TranscriptMathCache) { + let changed: Bool = lock.withLock { + guard cache !== mathCache else { return false } + mathCache = cache + resetFormulas() + return true } + if changed { cache.add(self) } } - /// The drawn formula if it has arrived. Starts drawing it if not. - func formula(for math: TranscriptMath, fontSize: CGFloat) -> TranscriptMathImage? { - let key = FormulaKey(math: math, size: Int((fontSize * 2).rounded())) - let (formula, render, generation): (TranscriptMathImage?, TranscriptMathRenderer?, Int) = lock.withLock { - if let formula = formulas[key] { return (formula, nil, mathGeneration) } - guard let mathRenderer, !formulasRequested.contains(key) else { return (nil, nil, mathGeneration) } - formulasRequested.insert(key) - return (nil, mathRenderer, mathGeneration) + /// 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 + 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) } + 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) + } + 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 = 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) + } + state.drawing = key + return (meanwhile, (mathRenderer, mathCache, mathGeneration)) } - if let render { + if let (renderer, cache, generation) = start { + draw(key, in: slot, with: renderer, cache: cache, generation: generation) + } + return formula + } + + /// 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) { + let work = work + work.begin() + cache.draw(key, with: renderer) { [weak self] result in + self?.finishFormula(key, in: slot, result, generation: generation) + work.end() + } + } + + private func finishFormula(_ key: TranscriptMathCache.Key, in slot: MathSlot, _ result: TranscriptMathCache.Result, + generation: Int) { + 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 + } + } + 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 { let work = work work.begin() - Task.detached { [weak self] in - let drawn = await render(math, CGFloat(key.size) / 2)?.withAlphaAsMask() - self?.finishFormula(key, drawn, generation: generation) + settle { [weak self] in + self?.settleFailure(key, in: slot, generation: generation) work.end() } } - return formula + if changed { notifyChange() } } - private func finishFormula(_ key: FormulaKey, _ formula: TranscriptMathImage?, generation: Int) { - let handler: (@Sendable () -> Void)? = lock.withLock { - guard generation == mathGeneration, let formula else { return nil } - formulas[key] = formula + /// 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 onChange + return true } - handler?() + if changed { notifyChange() } } /// The picture for `image` if it has arrived. Starts loading it if not. @@ -202,13 +398,35 @@ 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 } + let work = work + work.begin() + deliver { [weak self] in + defer { work.end() } + guard let self else { return } + let handler = lock.withLock { + changeScheduled = false + return onChange + } + handler?() } - handler?() } } diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index 644d75d..bf3a32b 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -81,11 +81,12 @@ final class LayoutEngine: @unchecked Sendable { /// that the view has not taken yet, and the image store's loads. let work: PendingWork /// Pictures for the documents' images, if the view was given a loader. + /// Formulas are kept in the cache that views share. let images: TranscriptImageStore init() { work = PendingWork() - images = TranscriptImageStore(work: work) + images = TranscriptImageStore(mathCache: .shared, work: work) } // Guarded by `lock`. 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..631bad9 --- /dev/null +++ b/Sources/TranscriptKit/Layout/MathCache.swift @@ -0,0 +1,141 @@ +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. 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() + + /// 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. + case failed + } + + /// 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 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) { + images = LeastRecentlyUsed(costLimit: byteLimit) + } + + /// 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() { + let stores: [TranscriptImageStore] = lock.withLock { + generation += 1 + images.removeAll() + return self.stores.values.compactMap(\.store) + } + for store in stores { store.mathCacheWasEmptied(self) } + } + + /// 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 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(TranscriptMathImage), wait, start(Draw) } + let step: Step = lock.withLock { + 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[draw] = [done] + draws += 1 + return .start(draw) + } + switch step { + case .known(let image): + done(.drawn(image)) + case .wait: + break + case .start(let draw): + Task.detached { + let drawn = await renderer(key.math, key.fontSize)?.withAlphaAsMask() + self.finish(draw, drawn.map(Result.drawn) ?? .failed) + } + } + } + + private func finish(_ draw: Draw, _ result: Result) { + let waiters: [@Sendable (Result) -> Void] = lock.withLock { + 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 { (images.totalCost, images.count) } } +} diff --git a/Sources/TranscriptKit/Layout/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index cb80992..f148919 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -362,11 +362,12 @@ 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 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? @@ -374,7 +375,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 } @@ -400,8 +401,11 @@ public struct TranscriptStyle: Equatable, Sendable { } 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 { 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) } @@ -415,6 +419,30 @@ 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 { + 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() + } +} + /// What layout needs to know to size images: the loaded ones, and the width /// they must fit in. struct ImageSizing { @@ -423,7 +451,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? @@ -436,19 +465,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). - init(math: TranscriptMath, sizing: ImageSizing?, font: CTFont, style: TranscriptStyle) { + /// 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 let formula = sizing?.store?.formula(for: math, fontSize: CTFontGetSize(font)) { + 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)! @@ -471,6 +506,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 @@ -519,3 +571,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/Sources/TranscriptKit/Model/TranscriptMathImage.swift b/Sources/TranscriptKit/Model/TranscriptMathImage.swift index e9ae1d2..be619ec 100644 --- a/Sources/TranscriptKit/Model/TranscriptMathImage.swift +++ b/Sources/TranscriptKit/Model/TranscriptMathImage.swift @@ -21,7 +21,10 @@ 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, 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 1a8d959..653b324 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,15 @@ public struct TranscriptText: UIViewRepresentable { return copy } - /// Draws LaTeX formulas; see `TranscriptTextView.mathRenderer`. Read once, + /// Draws LaTeX formulas; see `TranscriptTextView.mathRenderer`. The + /// 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) -> TranscriptText { + public func mathRenderer(_ renderer: @escaping TranscriptMathRenderer, cache: TranscriptMathCache = .shared) -> TranscriptText { var copy = self copy.mathRenderer = renderer + copy.mathCache = cache return copy } @@ -165,7 +170,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 beff65c..192965a 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -169,10 +169,22 @@ 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. 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(imagesChanged) @@ -181,6 +193,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() + } + } + /// Waits until the view shows its final content: no layout, stream /// parse, image load, formula or code colors are pending, the last /// layout is on screen, and its tiles are drawn. Use it before a @@ -189,8 +212,9 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// Work that keeps arriving, such as a stream that has not finished, /// does not hold it back: it returns at the first moment when nothing /// is pending. A cancelled task returns at once. An image that the - /// loader returns nil for, and a formula that the renderer returns nil - /// for, count as done. A load, a formula or a highlight that never ends + /// loader returns nil for counts as done. A formula that the renderer + /// returns nil for counts as done when it shows its LaTeX as written, + /// about a second later. A load, a formula or a highlight that never ends /// holds it back: use a timeout, or cancel the task. Fades and tag /// animations that play are not waited for: to compare pixels, turn off /// `textFadeInDuration` and `animatesTags`. @@ -212,16 +236,11 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD return waiters } - /// Lays out again on main when a picture, a formula or code colors - /// arrive. Any thread. + /// Lays out again when pictures, formulas or code colors arrive. The + /// image store calls it on main. private var imagesChanged: @Sendable () -> Void { - let work = engine.work - return { [weak self] in - work.begin() - DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } - work.end() - } + { [weak self] in + MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } } } diff --git a/Tests/TranscriptKitTests/ContentSettledTests.swift b/Tests/TranscriptKitTests/ContentSettledTests.swift index 9318729..bef9cd3 100644 --- a/Tests/TranscriptKitTests/ContentSettledTests.swift +++ b/Tests/TranscriptKitTests/ContentSettledTests.swift @@ -135,7 +135,7 @@ private let image = TranscriptImage(source: "https://x.y/c.png", alt: "a chart") } @Test func formulasAndCodeColorsArePendingUntilTheyArrive() async { - let store = TranscriptImageStore() + let store = TranscriptImageStore(settle: { $0() }) let gate = Gate() store.setMathRenderer { _, _ in await gate.wait() @@ -145,7 +145,7 @@ private let image = TranscriptImage(source: "https://x.y/c.png", alt: "a chart") await gate.wait() return [TranscriptCodeHighlight(range: 0.. 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() } + } +} + +@Test func aChangeIsPendingUntilOnChangeRuns() async { + let deliveries = HeldWork() + let store = TranscriptImageStore(deliver: { deliveries.add($0) }) + let changes = Flag() + store.setLoader({ _ in + CGContext(data: nil, width: 4, height: 4, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)?.makeImage() + }, onChange: { changes.raise() }) + _ = store.picture(for: image) + await waitUntil { deliveries.count > 0 } + // The picture has arrived, but the view has not laid out for it yet. + #expect(deliveries.count == 1) + #expect(!store.work.isIdle) + deliveries.runAll() + #expect(changes.raised == 1) + #expect(store.work.isIdle) +} + +@Test func aFormulaThatFailsIsPendingUntilItShowsItsLatex() async { + let settles = HeldWork() + let store = TranscriptImageStore(deliver: { $0() }, settle: { settles.add($0) }) + let changes = Flag() + store.setOnChange { changes.raise() } + store.setMathRenderer { _, _ in nil } + let math = TranscriptMath(tex: "\\frac{a", isDisplay: true) + let slot = TranscriptImageStore.MathSlot(block: "m", index: 0) + _ = store.formula(for: math, fontSize: 17, in: slot) + await waitUntil { settles.count > 0 } + // The renderer is done, but the formula still shows empty space. + #expect(settles.count == 1) + #expect(!store.work.isIdle) + settles.runAll() + #expect(store.work.isIdle) + #expect(changes.raised == 1) + guard case .asWritten = store.formula(for: math, fontSize: 17, in: slot) else { + Issue.record("The formula does not show its LaTeX") + return + } +} + // MARK: Waiting for the content to settle /// A layout engine wired as `TranscriptTextView` wires it, without UIKit: diff --git a/Tests/TranscriptKitTests/MathCacheTests.swift b/Tests/TranscriptKitTests/MathCacheTests.swift new file mode 100644 index 0000000..f871c7e --- /dev/null +++ b/Tests/TranscriptKitTests/MathCacheTests.swift @@ -0,0 +1,471 @@ +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)) + } +} + +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() + 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.drawnImage(math) == 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.drawnImage(math) != nil) + // Another font size is another formula. + #expect(later.drawnImage(math, fontSize: 20, slot: "larger") == nil) + await waitFor { calls.all.count == 2 } + #expect(cache.drawCount == 2) +} + +@Test func aFormulaThatFailsIsNotDrawnAgain() async { + let cache = TranscriptMathCache() + let store = TranscriptImageStore(mathCache: cache) + let calls = RenderCalls() + store.setMathRenderer { math, _ in + calls.add(math.tex) + return nil + } + let math = TranscriptMath(tex: "\\frac{", isDisplay: true) + #expect(store.drawnImage(math) == nil) + await waitFor { calls.all.count == 1 } + try? await Task.sleep(for: .milliseconds(50)) + #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 { + // 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.drawnImage(math) + await waitFor { store.drawnImage(math) != nil } + // The first formula is used again each time, so it stays. + #expect(store.drawnImage(formulas[0]) != nil) + } + #expect(cache.usage.count == 3) + #expect(cache.usage.bytes <= 256 * 3) + #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) +} + +@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]) +} + +/// 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) +} + +/// 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? { 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) @@ -263,3 +266,117 @@ 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) +} + +@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(settle: { $0() }) + 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) +} + +@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 } } +}