Skip to content
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
103 changes: 103 additions & 0 deletions Sources/TranscriptKit/Layout/ContentSettledWaiters.swift
Original file line number Diff line number Diff line change
@@ -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<Void, Never>] = [:]
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
}
}
16 changes: 16 additions & 0 deletions Sources/TranscriptKit/Layout/ImageStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = []
Expand All @@ -27,6 +29,10 @@ final class TranscriptImageStore: @unchecked Sendable {
private var highlighting: Set<String> = []
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 } }
Expand All @@ -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 }
}
Expand Down Expand Up @@ -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()
}
}

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
25 changes: 20 additions & 5 deletions Sources/TranscriptKit/Layout/LayoutEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -458,20 +469,24 @@ final class LayoutEngine: @unchecked Sendable {
}
guard !wakeScheduled else { return nil }
wakeScheduled = true
work.begin()
return onOutput
}
handler?()
}

/// 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)
Expand Down
39 changes: 39 additions & 0 deletions Sources/TranscriptKit/Layout/PendingWork.swift
Original file line number Diff line number Diff line change
@@ -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?()
}
}
21 changes: 21 additions & 0 deletions Sources/TranscriptKit/Stream/TranscriptStream.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -93,6 +94,7 @@ public final class TranscriptStream {
return worker.latest
}
receive(latest)
runIdleActions()
}

private func receive(_ update: StreamUpdate) {
Expand All @@ -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.
Expand All @@ -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()
}
}
}
Expand Down
Loading
Loading