diff --git a/README.md b/README.md index 15e4433..17c85d3 100644 --- a/README.md +++ b/README.md @@ -346,6 +346,30 @@ selection ends, and its range is nil. The selection stays when the person opens In UIKit, use `onSelectionChange`, `selectedRange` and `selectsAllWhenShown` on `TranscriptTextView`. +### Waiting for the final content + +The view lays out plain text at once only when it shows no layout yet. A style or a renderer that the app sets before +the document, on a view that has a width, makes the view lay out the empty text first. The text of the document then +shows on a later turn of the main run loop, as in the example below. Layouts of later updates, images, formulas and +code colors also come back on later turns. A snapshot or a test that does not wait for them can show no text, or the +text without them. +`contentSettled()` on `TranscriptTextView` returns when the view shows its final content. Then no layout, stream +parse, image load, formula or code colors are pending, the last layout is on screen, and its tiles are drawn: + +```swift +let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 320, height: 600)) +view.mathRenderer = myMathRenderer +view.document = document +await view.contentSettled() +let image = UIGraphicsImageRenderer(bounds: view.bounds).image { view.layer.render(in: $0.cgContext) } +``` + +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 +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. + ## In this repository | Folder | Contents | diff --git a/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift b/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift new file mode 100644 index 0000000..afa6470 --- /dev/null +++ b/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift @@ -0,0 +1,103 @@ +import Foundation + +/// The tasks that wait for a view to show its final content (see +/// `TranscriptTextView.contentSettled()`), and when to let them go: when +/// nothing is in flight in `work`, the stream has no text left to parse, +/// and the view has laid out and drawn on main. +@MainActor +final class ContentSettledWaiters { + private let work: PendingWork + /// The stream that the view shows, if any. + var stream: () -> TranscriptStream? = { nil } + /// Lays out on main what cannot wait, such as a new width. It can start + /// work, such as image loads. + var layOut: () -> Void = {} + /// Draws what the last layout needs, once nothing is in flight. + var draw: () -> Void = {} + + private var waiters: [Int: CheckedContinuation] = [:] + private var nextID = 0 + private weak var watchedStream: TranscriptStream? + + init(work: PendingWork) { + self.work = work + } + + /// How many tasks wait. + var count: Int { waiters.count } + + /// Returns when the content has settled, or at once if the task is cancelled. + func wait() async { + guard !Task.isCancelled else { return } + let id = nextID + nextID += 1 + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + waiters[id] = continuation + if waiters.count == 1 { watchWork(true) } + check() + } + } onCancel: { [self] in + DispatchQueue.main.async { + MainActor.assumeIsolated { self.resume(id) } + } + } + } + + /// Lets every waiting task go if the content has settled. + func check() { + guard !waiters.isEmpty, isSettled() else { return } + let resumed = waiters + waiters = [:] + watchWork(false) + resumed.values.forEach { $0.resume() } + } + + private func resume(_ id: Int) { + guard let continuation = waiters.removeValue(forKey: id) else { return } + if waiters.isEmpty { watchWork(false) } + continuation.resume() + } + + /// Checks again each time the work runs out, while a task waits. + private func watchWork(_ watches: Bool) { + guard watches else { + work.setOnIdle(nil) + return + } + work.setOnIdle { [weak self] in + DispatchQueue.main.async { + MainActor.assumeIsolated { self?.check() } + } + } + } + + private func isSettled() -> Bool { + guard work.isIdle, streamIsIdle() else { return false } + layOut() + // A callback of the layout, such as `onSelectionChange`, can append + // to the stream, and an append starts no work. + guard work.isIdle, streamIsIdle() else { return false } + draw() + return true + } + + /// The stream has no text left to parse. If it has, checks again when + /// it becomes idle. + private func streamIsIdle() -> Bool { + guard let stream = stream(), !stream.isIdle else { return true } + if watchedStream !== stream { + watchedStream = stream + // `flush()` runs this inline, so the check must not lay out + // or draw inside the caller's call. + stream.whenIdle { [weak self, weak stream] in + guard let self else { return } + if self.watchedStream === stream { self.watchedStream = nil } + DispatchQueue.main.async { [weak self] in + MainActor.assumeIsolated { self?.check() } + } + } + } + return false + } +} diff --git a/Sources/TranscriptKit/Layout/ImageStore.swift b/Sources/TranscriptKit/Layout/ImageStore.swift index 71a3e14..fa8c675 100644 --- a/Sources/TranscriptKit/Layout/ImageStore.swift +++ b/Sources/TranscriptKit/Layout/ImageStore.swift @@ -10,6 +10,8 @@ import Foundation final class TranscriptImageStore: @unchecked Sendable { typealias Loader = @Sendable (TranscriptImage) async -> CGImage? + /// Counts the loads, formulas and highlights in flight. + let work: PendingWork private let lock = NSLock() private var pictures: [String: CGImage] = [:] private var requested: Set = [] @@ -27,6 +29,10 @@ 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 } } @@ -46,6 +52,7 @@ 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. func setOnChange(_ onChange: (@Sendable () -> Void)?) { lock.withLock { self.onChange = onChange } } @@ -90,9 +97,12 @@ final class TranscriptImageStore: @unchecked Sendable { private func highlight(_ block: String, text: String, language: String?, with highlighter: @escaping TranscriptCodeHighlighter, generation: Int) { + let work = work + work.begin() Task.detached { [weak self] in let marks = await highlighter(text, language) self?.finishHighlight(block, text: text, language: language, marks: marks, generation: generation) + work.end() } } @@ -150,9 +160,12 @@ final class TranscriptImageStore: @unchecked Sendable { return (nil, mathRenderer, mathGeneration) } if let render { + 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) + work.end() } } return formula @@ -177,9 +190,12 @@ final class TranscriptImageStore: @unchecked Sendable { return (nil, loader, self.generation) } if let load { + let work = work + work.begin() Task.detached { [weak self] in let box = PictureBox(picture: await load(image)) self?.finish(image.source, box, generation: generation) + work.end() } } return picture diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index 4cf780d..644d75d 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -77,8 +77,16 @@ final class LayoutEngine: @unchecked Sendable { } let queue = DispatchQueue(label: "TranscriptKit.layout", qos: .userInitiated) + /// The work in flight: drains that are scheduled or running, a result + /// 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. - let images = TranscriptImageStore() + let images: TranscriptImageStore + + init() { + work = PendingWork() + images = TranscriptImageStore(work: work) + } // Guarded by `lock`. private let lock = NSLock() @@ -243,10 +251,11 @@ final class LayoutEngine: @unchecked Sendable { return max(lastDrain + frameInterval - CACurrentMediaTime(), 0) } if let delay { + work.begin() if delay > 0 { - queue.asyncAfter(deadline: .now() + delay) { self.drain() } + queue.asyncAfter(deadline: .now() + delay) { self.drain(); self.work.end() } } else { - queue.async { self.drain() } + queue.async { self.drain(); self.work.end() } } } return accepted @@ -398,7 +407,9 @@ final class LayoutEngine: @unchecked Sendable { /// update that adds no text, for when updates have stopped. The tail /// stays in use. Any thread; the result comes like any other. func settleFinishedFades() { + work.begin() queue.async { [self] in + defer { work.end() } guard let layout = base, width > 0, layout.width == width else { return } let (fading, band) = updateFades(layout: layout, appendedTo: layout, tagsStarted: false) guard let band else { return } @@ -458,6 +469,7 @@ final class LayoutEngine: @unchecked Sendable { } guard !wakeScheduled else { return nil } wakeScheduled = true + work.begin() return onOutput } handler?() @@ -465,13 +477,16 @@ final class LayoutEngine: @unchecked Sendable { /// The merged result waiting to be installed, if any. Main thread. func takeOutput() -> Output? { - lock.withLock { () -> Output? in + let (output, woke): (Output?, Bool) = lock.withLock { defer { mailbox = nil wakeScheduled = false } - return mailbox + return (mailbox, wakeScheduled) } + // The caller installs the output before main can see the work idle. + if woke { work.end() } + return output } // MARK: Synchronous layout (main thread) diff --git a/Sources/TranscriptKit/Layout/PendingWork.swift b/Sources/TranscriptKit/Layout/PendingWork.swift new file mode 100644 index 0000000..4c4cf15 --- /dev/null +++ b/Sources/TranscriptKit/Layout/PendingWork.swift @@ -0,0 +1,39 @@ +import Foundation + +/// Counts one view's work in flight on other threads and queues: layouts +/// that are waiting or running, results that main has not installed yet, +/// and pictures, formulas and code colors that are loading. Any thread. +/// +/// Each piece of work calls `begin()` before it hands off and `end()` once +/// it is done, after it has begun whatever it leads to. The count therefore +/// reaches zero only when nothing is left to do. +final class PendingWork: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + private var onIdle: (@Sendable () -> Void)? + + /// Nothing is in flight. + var isIdle: Bool { lock.withLock { count == 0 } } + + /// Sets what to call, on the thread that ends the last piece of work, + /// when the count drops to zero. Nil to call nothing. + func setOnIdle(_ onIdle: (@Sendable () -> Void)?) { + lock.withLock { self.onIdle = onIdle } + } + + func begin() { + lock.withLock { count += 1 } + } + + func end() { + let handler: (@Sendable () -> Void)? = lock.withLock { + guard count > 0 else { + assertionFailure("PendingWork.end() without a begin()") + return nil + } + count -= 1 + return count == 0 ? onIdle : nil + } + handler?() + } +} diff --git a/Sources/TranscriptKit/Stream/TranscriptStream.swift b/Sources/TranscriptKit/Stream/TranscriptStream.swift index 4124486..7d9d1bd 100644 --- a/Sources/TranscriptKit/Stream/TranscriptStream.swift +++ b/Sources/TranscriptKit/Stream/TranscriptStream.swift @@ -48,6 +48,7 @@ public final class TranscriptStream { private var pending = "" private var finishPending = false private var jobInFlight = false + private var idleActions: [() -> Void] = [] /// - Parameters: /// - markdown: text that is already complete, such as earlier @@ -93,6 +94,7 @@ public final class TranscriptStream { return worker.latest } receive(latest) + runIdleActions() } private func receive(_ update: StreamUpdate) { @@ -115,6 +117,24 @@ public final class TranscriptStream { worker.detach(id) } + // MARK: Pending work + + /// No appended text waits to be parsed, and no parse is running. The + /// sinks have had every version by then. + var isIdle: Bool { !jobInFlight && pending.isEmpty && !finishPending } + + /// Calls `action` once, the next time the stream becomes idle. + func whenIdle(_ action: @escaping () -> Void) { + idleActions.append(action) + } + + private func runIdleActions() { + guard isIdle, !idleActions.isEmpty else { return } + let actions = idleActions + idleActions = [] + actions.forEach { $0() } + } + // MARK: Frame timing /// Starts parsing what has been appended, unless a parse is running. @@ -135,6 +155,7 @@ public final class TranscriptStream { self.jobInFlight = false if let update { self.receive(update) } if !self.pending.isEmpty || self.finishPending { self.scheduleFrame() } + self.runIdleActions() } } } diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index fdb641f..beff65c 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -149,11 +149,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// Fetch only from sources you trust. public var imageLoader: (@Sendable (TranscriptImage) async -> CGImage?)? { didSet { - engine.images.setLoader(imageLoader) { [weak self] in - DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } - } - } + engine.images.setLoader(imageLoader, onChange: imagesChanged) relayoutNow() } } @@ -165,11 +161,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// arrive. Not set by default. public var codeHighlighter: TranscriptCodeHighlighter? { didSet { - engine.images.setOnChange { [weak self] in - DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } - } - } + engine.images.setOnChange(imagesChanged) engine.images.setHighlighter(codeHighlighter) relayoutNow() } @@ -183,17 +175,55 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// default. public var mathRenderer: TranscriptMathRenderer? { didSet { - engine.images.setOnChange { [weak self] in - DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } - } - } + engine.images.setOnChange(imagesChanged) engine.images.setMathRenderer(mathRenderer) 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 + /// snapshot, or in a test. + /// + /// 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 + /// 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`. + /// + /// Give the view its size before the call. A view with no width lays + /// out nothing, so it settles at once with no content. + public func contentSettled() async { + await settledWaiters.wait() + } + private let engine = LayoutEngine() + private lazy var settledWaiters = makeSettledWaiters() + + private func makeSettledWaiters() -> ContentSettledWaiters { + let waiters = ContentSettledWaiters(work: engine.work) + waiters.stream = { [weak self] in self?.stream } + waiters.layOut = { [weak self] in self?.layoutIfNeeded() } + waiters.draw = { [weak self] in self?.drawTilesNow() } + return waiters + } + + /// Lays out again on main when a picture, a formula or code colors + /// arrive. Any thread. + 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() + } + } + } /// Holds the tiles, and the tail layer above them, below the system's /// selection views. @@ -593,6 +623,14 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD trimSpareTiles() } + /// Draws now the tiles that wait for the next commit. They take back + /// the tail first, so that they hold all of the text. + private func drawTilesNow() { + handTailToTiles() + if canvasCheckScheduled { updateCanvas() } + for tile in tiles.values { tile.layer.displayIfNeeded() } + } + private func makeTile() -> CanvasView { let tile = CanvasView() tile.owner = self diff --git a/Tests/TranscriptKitTests/ContentSettledTests.swift b/Tests/TranscriptKitTests/ContentSettledTests.swift new file mode 100644 index 0000000..9318729 --- /dev/null +++ b/Tests/TranscriptKitTests/ContentSettledTests.swift @@ -0,0 +1,450 @@ +import CoreGraphics +import Foundation +import Testing +@testable import TranscriptKit + +/// Holds back async work until the test opens it. +private final class Gate: @unchecked Sendable { + private let lock = NSLock() + private var isOpen = false + private var waiting: [CheckedContinuation] = [] + + func wait() async { + await withCheckedContinuation { continuation in + let open = lock.withLock { + if !isOpen { waiting.append(continuation) } + return isOpen + } + if open { continuation.resume() } + } + } + + func open() { + let resumed = lock.withLock { + isOpen = true + defer { waiting = [] } + return waiting + } + resumed.forEach { $0.resume() } + } +} + +private final class Flag: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + func raise() { lock.withLock { count += 1 } } + var raised: Int { lock.withLock { count } } +} + +/// Waits until `condition` holds, for at most two seconds. +private func waitUntil(_ condition: () -> Bool) async { + for _ in 0..<200 where !condition() { + try? await Task.sleep(for: .milliseconds(10)) + } +} + +private let image = TranscriptImage(source: "https://x.y/c.png", alt: "a chart") + +@Test func pendingWorkCallsItsHandlerWhenTheLastPieceEnds() { + let work = PendingWork() + let idle = Flag() + work.setOnIdle { idle.raise() } + #expect(work.isIdle) + work.begin() + work.begin() + work.end() + #expect(!work.isIdle) + #expect(idle.raised == 0) + work.end() + #expect(work.isIdle) + #expect(idle.raised == 1) +} + +@Test func aLayoutIsPendingUntilTheViewTakesIt() async { + let engine = LayoutEngine() + let posted = Flag() + engine.setOutputHandler { posted.raise() } + _ = engine.relayout(width: 300, style: TranscriptStyle()) + #expect(engine.work.isIdle) + + engine.submit(.init(document: MarkdownStreamParser.document(from: "Some text"), source: 1, sequence: 1)) + #expect(!engine.work.isIdle) + await waitUntil { posted.raised > 0 } + // Laid out, and waiting in the mailbox until the test takes it. + #expect(!engine.work.isIdle) + + #expect(engine.takeOutput() != nil) + await waitUntil { engine.work.isIdle } + #expect(engine.work.isIdle) +} + +@Test func aRequestThatLaysOutNothingEndsItsWork() async { + let engine = LayoutEngine() + // No width yet: the drain keeps the document and posts nothing. + engine.submit(.init(document: MarkdownStreamParser.document(from: "Some text"), source: 1, sequence: 1)) + await waitUntil { engine.work.isIdle } + #expect(engine.work.isIdle) + #expect(engine.takeOutput() == nil) +} + +@Test func aPictureThatDoesNotLoadStillEndsItsWork() async { + let store = TranscriptImageStore() + let gate = Gate() + let changes = Flag() + store.setLoader({ _ in + await gate.wait() + return nil + }, onChange: { changes.raise() }) + #expect(store.picture(for: image) == nil) + #expect(!store.work.isIdle) + gate.open() + await waitUntil { store.work.isIdle } + #expect(store.work.isIdle) + #expect(changes.raised == 0) +} + +@Test func workThatAChangeStartsKeepsTheStoreBusy() async { + let store = TranscriptImageStore() + let work = store.work + 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: { + // As the view does: the relayout on main is work too. + work.begin() + changes.raise() + }) + _ = store.picture(for: image) + await waitUntil { changes.raised > 0 } + // Busy until the test ends the work that the change began. + #expect(!work.isIdle) + work.end() + #expect(work.isIdle) +} + +@Test func settlingFadesIsPendingWork() async { + let engine = LayoutEngine() + let release = DispatchSemaphore(value: 0) + engine.queue.async { release.wait() } + engine.settleFinishedFades() + #expect(!engine.work.isIdle) + release.signal() + await waitUntil { engine.work.isIdle } + #expect(engine.work.isIdle) +} + +@Test func formulasAndCodeColorsArePendingUntilTheyArrive() async { + let store = TranscriptImageStore() + let gate = Gate() + store.setMathRenderer { _, _ in + await gate.wait() + return nil + } + store.setHighlighter { code, _ in + await gate.wait() + return [TranscriptCodeHighlight(range: 0.. CGImage?) { + let work = engine.work + engine.images.setLoader(loader) { [weak self] in + work.begin() + DispatchQueue.main.async { + MainActor.assumeIsolated { self?.relayout() } + work.end() + } + } + } + + func show(_ stream: TranscriptStream) { + self.stream = stream + source += 1 + let source = source + let engine = engine + let attachment = stream.attachSink { update in + engine.submit(.init(document: update.document, source: source, sequence: update.sequence, isFinished: update.isFinished)) + } + engine.submit(.init(document: attachment.latest.document, source: source, sequence: attachment.latest.sequence, + isFinished: attachment.latest.isFinished)) + } +} + +/// Waits on main until `condition` holds, for at most two seconds. +@MainActor +private func waitOnMain(_ condition: () -> Bool) async { + for _ in 0..<200 where !condition() { + try? await Task.sleep(for: .milliseconds(10)) + } +} + +private func picture() -> CGImage? { + CGContext(data: nil, width: 40, height: 20, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)?.makeImage() +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func contentWithNothingPendingSettlesAtOnce() async { + let host = Host() + await host.waiters.wait() + #expect(host.draws == 1) + #expect(host.waiters.count == 0) +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func contentSettlesOnceTheStreamAndThePicturesAreIn() async throws { + let host = Host() + let gate = Gate() + host.setLoader { _ in + await gate.wait() + return picture() + } + let stream = TranscriptStream() + host.show(stream) + stream.append("see ![a chart](https://x.y/c.png) here") + stream.finish() + + var settled = false + let waiting = Task { @MainActor in + await host.waiters.wait() + settled = true + } + await waitOnMain { host.text.hasPrefix("see") } + try await Task.sleep(for: .milliseconds(100)) + #expect(!settled) + #expect(host.draws == 0) + #expect(try #require(host.installed).entry(at: 0).layout.attachments.first?.attachment.picture == nil) + + gate.open() + await waiting.value + #expect(settled) + #expect(host.draws == 1) + #expect(host.engine.work.isIdle) + #expect(stream.isIdle) + #expect(try #require(host.installed).entry(at: 0).layout.attachments.first?.attachment.picture != nil) +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func anUnfinishedStreamSettlesBetweenItsChunks() async { + let host = Host() + let stream = TranscriptStream() + host.show(stream) + stream.append("One two") + await host.waiters.wait() + #expect(host.text == "One two") + + stream.append(" three") + await host.waiters.wait() + #expect(host.text == "One two three") + + // Text that the parser holds back makes no new version, and still settles. + stream.append("\n\n#") + await host.waiters.wait() + #expect(stream.isIdle) + #expect(host.text == "One two three") +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func aCancelledWaitReturnsAtOnce() async { + let host = Host() + let gate = Gate() + host.setLoader { _ in + await gate.wait() + return nil + } + let stream = TranscriptStream() + host.show(stream) + stream.append("see ![a chart](https://x.y/c.png) here") + stream.flush() + await waitOnMain { host.text.hasPrefix("see") } + + let first = Task { @MainActor in await host.waiters.wait() } + let second = Task { @MainActor in await host.waiters.wait() } + await waitOnMain { host.waiters.count == 2 } + first.cancel() + await first.value + #expect(host.waiters.count == 1) + #expect(host.draws == 0) + + // Already cancelled: it does not wait at all. + let third = Task { @MainActor in + withUnsafeCurrentTask { $0?.cancel() } + await host.waiters.wait() + } + await third.value + #expect(host.waiters.count == 1) + + // The image loads nothing, and that counts as done. + gate.open() + await second.value + #expect(host.waiters.count == 0) + #expect(host.draws == 1) +} + +@MainActor +private final class FlushRecord { + var waitersBefore = -1 + var drawsAfter = -1 +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func aFlushDoesNotSettleInsideTheCall() async { + let host = Host() + let stream = TranscriptStream() + host.show(stream) + stream.append("One two") + await host.waiters.wait() + let draws = host.draws + + let flush = FlushRecord() + // In the main queue before the append starts the frame timer, so the + // frame cannot parse the text before the flush. + DispatchQueue.main.async { + MainActor.assumeIsolated { + flush.waitersBefore = host.waiters.count + stream.flush() + flush.drawsAfter = host.draws + } + } + // Text that the parser holds back starts no layout work. + stream.append("\n\n#") + await host.waiters.wait() + #expect(flush.waitersBefore == 1) + #expect(flush.drawsAfter == draws) + #expect(host.draws == draws + 1) +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func workThatTheLayoutStartsHoldsTheWaitBack() async throws { + let host = Host(width: 0) + let gate = Gate() + host.setLoader { _ in + await gate.wait() + return picture() + } + host.engine.submit(.init(document: MarkdownStreamParser.document(from: "see ![a chart](https://x.y/c.png) here"), + source: 1, sequence: 1, isFinished: true)) + // No width yet: the drain keeps the document and lays out nothing. + await waitOnMain { host.engine.work.isIdle } + #expect(host.installed == nil) + + // As a view does when it gets its width: the layout asks for the picture. + host.waiters.layOut = { [weak host] in + guard let host, host.width == 0 else { return } + host.width = 300 + host.relayout() + } + var settled = false + let waiting = Task { @MainActor in + await host.waiters.wait() + settled = true + } + await waitOnMain { host.installed != nil } + try await Task.sleep(for: .milliseconds(100)) + #expect(!settled) + #expect(host.draws == 0) + #expect(try #require(host.installed).entry(at: 0).layout.attachments.first?.attachment.picture == nil) + + gate.open() + await waiting.value + #expect(host.draws == 1) + #expect(try #require(host.installed).entry(at: 0).layout.attachments.first?.attachment.picture != nil) +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func aStreamThatChangesWhileATaskWaitsSettlesOnTheNewStream() async { + let host = Host() + let gate = Gate() + host.setLoader { _ in + await gate.wait() + return nil + } + let first = TranscriptStream() + host.show(first) + first.append("see ![a chart](https://x.y/c.png) here") + first.flush() + await waitOnMain { host.text.hasPrefix("see") } + + let waiting = Task { @MainActor in await host.waiters.wait() } + await waitOnMain { host.waiters.count == 1 } + let second = TranscriptStream() + host.show(second) + second.append("Other text") + gate.open() + await waiting.value + #expect(second.isIdle) + #expect(host.text == "Other text") +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func textThatTheLayoutAppendsHoldsTheWaitBack() async { + let host = Host() + let stream = TranscriptStream() + host.show(stream) + stream.append("One two") + await host.waiters.wait() + + // As an app does that appends from a callback of the layout, such as + // `onSelectionChange`. + var appended = false + host.waiters.layOut = { + guard !appended else { return } + appended = true + stream.append(" three") + } + await host.waiters.wait() + #expect(appended) + #expect(stream.isIdle) + #expect(host.text == "One two three") +} diff --git a/Tests/TranscriptKitTests/StreamTests.swift b/Tests/TranscriptKitTests/StreamTests.swift index 0d8ae37..3dd3a0f 100644 --- a/Tests/TranscriptKitTests/StreamTests.swift +++ b/Tests/TranscriptKitTests/StreamTests.swift @@ -265,3 +265,30 @@ private final class Flag: @unchecked Sendable { #expect(changed.isRaised) #expect(stream.unplacedHeight.revision == before &+ 1) } + +@MainActor +@Test func aStreamIsIdleOnceItsTextIsParsed() async { + let stream = TranscriptStream() + #expect(stream.isIdle) + var idle = 0 + stream.whenIdle { idle += 1 } + stream.append("Some **text") + #expect(!stream.isIdle) + for _ in 0..<200 where idle == 0 { try? await Task.sleep(for: .milliseconds(10)) } + #expect(idle == 1) + #expect(stream.isIdle) + #expect(stream.document.block(at: 0).text.hasPrefix("Some")) + + // Held-back text changes nothing visible, and still ends. + stream.whenIdle { idle += 1 } + stream.append("\n\n#") + for _ in 0..<200 where idle == 1 { try? await Task.sleep(for: .milliseconds(10)) } + #expect(idle == 2) + + stream.whenIdle { idle += 1 } + stream.finish() + #expect(!stream.isIdle) + stream.flush() + #expect(stream.isIdle) + #expect(idle == 3) +}