@quran.ws/qvp-react-native 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +86 -32
- package/android/build.gradle +16 -8
- package/android/src/main/java/ws/quran/qvp/rn/Codes.kt +34 -0
- package/android/src/main/java/ws/quran/qvp/rn/Marshal.kt +78 -30
- package/android/src/main/java/ws/quran/qvp/rn/QvpModule.kt +105 -50
- package/android/src/main/java/ws/quran/qvp/rn/QvpPageViewManager.kt +1 -0
- package/android/src/main/java/ws/quran/qvp/rn/QvpRnPageView.kt +55 -14
- package/android/src/main/java/ws/quran/qvp/rn/QvpRnWords.kt +26 -0
- package/ios/QvpModule.m +167 -0
- package/ios/QvpModule.swift +508 -0
- package/ios/QvpRnBytes.swift +66 -0
- package/ios/QvpRnCodes.swift +33 -0
- package/ios/QvpRnMarshal.swift +360 -0
- package/ios/QvpRnPageView.swift +467 -0
- package/ios/QvpRnPassageView.swift +160 -0
- package/ios/vendor/QvpEngine.json +4 -0
- package/ios/vendor/QvpKit/QvpDress.swift +390 -0
- package/ios/vendor/QvpKit/QvpEngine.swift +55 -0
- package/ios/vendor/QvpKit/QvpPage.swift +469 -0
- package/ios/vendor/QvpKit/QvpPageCache.swift +176 -0
- package/ios/vendor/QvpKit/QvpPageCanvas.swift +1031 -0
- package/ios/vendor/QvpKit/QvpPageView.swift +711 -0
- package/ios/vendor/QvpKit/QvpPassage.swift +240 -0
- package/ios/vendor/QvpKit/QvpViewPolicy.swift +26 -0
- package/ios/vendor/QvpKit/QvpZoom.swift +200 -0
- package/ios/vendor/QvpKit/QvpZoomSpring.swift +22 -0
- package/ios/vendor/QvpKit/Types.swift +440 -0
- package/ios/vendor-qvpkit.sh +36 -0
- package/package.json +10 -3
- package/qvp-react-native.podspec +97 -0
- package/src/codes.ts +33 -0
- package/src/index.tsx +171 -55
|
@@ -0,0 +1,1031 @@
|
|
|
1
|
+
// SwiftUI renderer for a `QvpPage` — the same frame as QvpPageView (UIKit), drawn with
|
|
2
|
+
// `Canvas`: paper → a dress's ornament layer (a CGImage cached per dress revision, view
|
|
3
|
+
// transform and band, shared with QvpPageView) → highlight bands → cached base ink (a CGImage of every non-styled path at the
|
|
4
|
+
// current per-line transform, rebuilt only when the styled set / layout / transform changes)
|
|
5
|
+
// → styled ink from `styledPaths()` → mask boxes. A `TimelineView(.animation)` runs frames only
|
|
6
|
+
// while `page.tick(now)` reports a transition in flight.
|
|
7
|
+
//
|
|
8
|
+
// SwiftUI has no `setNeedsDisplay()`, so the mutable surface lives on `QvpCanvasController`
|
|
9
|
+
// (`@Observable`): set the page and the layout knobs there, call `invalidate()` after engine
|
|
10
|
+
// calls the controller cannot see (`highlight`, `style`, `mask`, …), and pass the controller
|
|
11
|
+
// to `QvpPageCanvas`. Gestures mirror QvpPageView and every one is a callback: tap →
|
|
12
|
+
// gap-aware hit-test → `onWordTap` / `onDecorationTap` / `onEmptyTap`; double-tap → `onDoubleTap`
|
|
13
|
+
// (nil resets the view); long-press + drag → whole-word selection; pinch / pan on top of the
|
|
14
|
+
// engine layout, with a horizontal swipe at the fitted size reported through `onSwipe`.
|
|
15
|
+
// When the page is not zoomed and `onSwipe` is nil the drag gesture is detached entirely,
|
|
16
|
+
// so an enclosing pager (`TabView`, `ScrollView`) keeps its own swipe.
|
|
17
|
+
//
|
|
18
|
+
// After `page.dress(...)` or `page.undress()`, call `resetView()`: the engine lays the page out
|
|
19
|
+
// again for the dress, and `resetView()` takes that layout up and fits the page with its
|
|
20
|
+
// border. A host that scrolls the page itself (`hostScrolls`) gives the canvas the size of
|
|
21
|
+
// `hostPageSize`, the engine's dressed box fitted to the canvas width, so the whole border is
|
|
22
|
+
// on it, and plans its box with `printedHeight(forWidth:)`, which holds the border too.
|
|
23
|
+
#if canImport(SwiftUI)
|
|
24
|
+
import SwiftUI
|
|
25
|
+
import CoreGraphics
|
|
26
|
+
#if canImport(UIKit)
|
|
27
|
+
import UIKit
|
|
28
|
+
#endif
|
|
29
|
+
|
|
30
|
+
/// Engine state + view state for one `QvpPageCanvas`. Create one per displayed page slot,
|
|
31
|
+
/// assign `page`, and call `invalidate()` after engine calls that change what is drawn.
|
|
32
|
+
@available(iOS 17.0, macOS 14.0, *)
|
|
33
|
+
@MainActor @Observable
|
|
34
|
+
public final class QvpCanvasController {
|
|
35
|
+
public var page: QvpPage? {
|
|
36
|
+
didSet { cache.clear(); ornaments.clear(); selectionHandle = 0; relayout(); resetView(); applyPendingCarry() }
|
|
37
|
+
}
|
|
38
|
+
// layout knobs (viewport size comes from the canvas)
|
|
39
|
+
public var padTop: CGFloat = 0 { didSet { relayout() } }
|
|
40
|
+
public var padBottom: CGFloat = 0 { didSet { relayout() } }
|
|
41
|
+
public var padSide: CGFloat = 0 { didSet { relayout() } }
|
|
42
|
+
/// Crop the printed page's own horizontal margins (page units, ≥ 0): the
|
|
43
|
+
/// INK spans the padded viewport instead of the full viewBox — for hosts
|
|
44
|
+
/// replacing ink-cropped raster pages. Feed from `page.cropBounds("page")`:
|
|
45
|
+
/// left = box.x0, right = page.width − box.x1.
|
|
46
|
+
public var cropLeft: Float = 0 { didSet { relayout() } }
|
|
47
|
+
public var cropRight: Float = 0 { didSet { relayout() } }
|
|
48
|
+
/// Line spacing only opens up; the engine clamps values below 1 to the printed lineSpacing.
|
|
49
|
+
public var lineSpacing: Float = 1 { didSet { relayout() } }
|
|
50
|
+
public var fillHeight = false { didSet { relayout() } }
|
|
51
|
+
/// How big a banner — a surah name, a basmalah — may get as the reader zooms in, as a
|
|
52
|
+
/// multiple of its PRINTED size; 0 (the default) lets it grow with the words around it
|
|
53
|
+
/// until it fills the row. A host that draws its own frame around the printed name caps
|
|
54
|
+
/// it, or the name outgrows the frame. Only a reflowed page grows a banner at all.
|
|
55
|
+
public var bannerZoom: Float = 0 { didSet { guard oldValue != bannerZoom else { return }; relayout() } }
|
|
56
|
+
/// Draw source-native frames around surah names on the printed page.
|
|
57
|
+
public var surahFrames = true { didSet { guard oldValue != surahFrames else { return }; relayout() } }
|
|
58
|
+
/// How the rows of a reflowed page fill the width: centred (the default), justified or
|
|
59
|
+
/// ragged. The printed page keeps the print's own lines, so it only matters once the
|
|
60
|
+
/// reader zooms in.
|
|
61
|
+
public var reflowFill: QvpFill = .centred { didSet { guard oldValue != reflowFill else { return }; relayout() } }
|
|
62
|
+
/// How far a justified row's gaps may open, as a multiple of the page's usual air between
|
|
63
|
+
/// two words. A row that would need more opens that far and is centred; a negative value
|
|
64
|
+
/// lifts the cap. A row of few words has few gaps, so a reader who zooms far in needs more
|
|
65
|
+
/// room.
|
|
66
|
+
public var reflowMaxStretch: Float = QvpDefaults.REFLOW_MAX_STRETCH {
|
|
67
|
+
didSet { guard oldValue != reflowMaxStretch else { return }; relayout() }
|
|
68
|
+
}
|
|
69
|
+
/// Paper behind the page content, 0xRRGGBBAA (nil = transparent).
|
|
70
|
+
public var paperColor: UInt32?
|
|
71
|
+
/// 0xRRGGBBAA band colour of the drag selection.
|
|
72
|
+
public var selectionBand: UInt32 = QvpDefaults.SELECTION_BAND
|
|
73
|
+
public var onWordTap: ((QvpWord, QvpHit) -> Void)?
|
|
74
|
+
public var onDecorationTap: ((QvpDecoration, QvpHit) -> Void)?
|
|
75
|
+
public var onEmptyTap: (() -> Void)?
|
|
76
|
+
public var onSelectionChanged: (([Int]) -> Void)?
|
|
77
|
+
/// Horizontal swipe while the page is not zoomed in: +1 = finger moved right, -1 = left. The host flips pages.
|
|
78
|
+
public var onSwipe: ((Int) -> Void)?
|
|
79
|
+
/// Double-tap, with the gap-aware hit under it (nil off the page). nil (the default)
|
|
80
|
+
/// resets the view; a host that repurposes the gesture can still call `resetView()`
|
|
81
|
+
/// itself — `isZoomed` says when.
|
|
82
|
+
public var onDoubleTap: ((QvpHit?) -> Void)?
|
|
83
|
+
/// Long-press, with the gap-aware hit under the finger. Fires once, while the finger
|
|
84
|
+
/// is still down, and only while `selectionEnabled` is false — selection owns the
|
|
85
|
+
/// long-press otherwise. On iOS it is UIKit's recognizer, which fails on movement,
|
|
86
|
+
/// so it never takes a swipe from an enclosing pager.
|
|
87
|
+
public var onLongPress: ((QvpHit?) -> Void)?
|
|
88
|
+
public var longPressDuration: Double = 0.35
|
|
89
|
+
public var zoomEnabled = true {
|
|
90
|
+
// A canvas that may not zoom must not take up a zoom handed to it before it had a
|
|
91
|
+
// size: a host turns this off for a box the reading size does not belong in, and the
|
|
92
|
+
// carry would otherwise land on the next `setBounds` and reflow it anyway.
|
|
93
|
+
didSet { if !zoomEnabled { pendingCarry = nil } }
|
|
94
|
+
}
|
|
95
|
+
/// Zoom lasts only while the fingers are down: on release the page eases back to its fitted
|
|
96
|
+
/// size — a peek, not a reading zoom — so a pinch never leaves the page holding a pager's swipe.
|
|
97
|
+
public var zoomSpringsBack = false
|
|
98
|
+
/// How far the magnifying glass may go — the ceiling the pinch is clamped to under
|
|
99
|
+
/// `.magnify`, `QvpViewPolicy.maxZoom` unless the host lowers it. A host that draws its own
|
|
100
|
+
/// furniture beside the ink and scales it with the glass says here what that furniture can
|
|
101
|
+
/// survive; the engine's own ink costs the same at any size.
|
|
102
|
+
public var maxZoom: CGFloat = QvpViewPolicy.maxZoom
|
|
103
|
+
/// What a pinch does to the page. `.stepped` is what a reader gets: the pinch lands on one
|
|
104
|
+
/// of the page's own zoom steps and the page breaks its rows again at that size. `.magnify`
|
|
105
|
+
/// is the old behaviour, scaling the printed page. The engine owns the policy; this only
|
|
106
|
+
/// says which one.
|
|
107
|
+
public var zoomMode: QvpZoomMode = .stepped {
|
|
108
|
+
didSet {
|
|
109
|
+
guard oldValue != zoomMode else { return }
|
|
110
|
+
// Cleared before the page is even looked at: the policy the host has just set
|
|
111
|
+
// outranks a carry still waiting for a canvas, and a step carried from another
|
|
112
|
+
// page means nothing under the glass.
|
|
113
|
+
pendingCarry = nil
|
|
114
|
+
guard let p = page, p.isOpen else { return }
|
|
115
|
+
zoom = p.zoomMode(baseSpec, zoom, zoomMode); relayout(); resetView()
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/// Where the reader's zoom control stands, as the engine last answered.
|
|
119
|
+
public private(set) var zoom = QvpZoom()
|
|
120
|
+
/// The zoom steps this page ships with: what `.stepped` lands on, lowest first. Empty until
|
|
121
|
+
/// the canvas has a size, like `QvpPageView`'s: `zoomToStep` refuses without one, so a host
|
|
122
|
+
/// that draws a size control off this would otherwise show it live and act on nothing.
|
|
123
|
+
public var zoomSteps: [Float] { page.map { $0.isOpen && bounds.width > 0 ? $0.zoomSteps(baseSpec) : [] } ?? [] }
|
|
124
|
+
/// Move the control straight to a step. 0 is the printed page.
|
|
125
|
+
public func zoomToStep(_ step: Int) {
|
|
126
|
+
// An explicit step outranks a carry still waiting for the canvas.
|
|
127
|
+
pendingCarry = nil
|
|
128
|
+
guard let p = page, p.isOpen, bounds.width > 0 else { return }
|
|
129
|
+
apply(p.zoomToStep(layoutSpec, zoom, step, currentView))
|
|
130
|
+
}
|
|
131
|
+
/// Take up another page's zoom control on this one: what the reader was reading at,
|
|
132
|
+
/// carried onto the page they turned to (`QvpPage.zoomCarried` — a step as a step, since
|
|
133
|
+
/// every page's steps are its own; a free zoom as a size this page can reach). The page
|
|
134
|
+
/// opens at its top. Nothing happens when this page already stands there, so a host may
|
|
135
|
+
/// call it on every page turn.
|
|
136
|
+
public func carryZoom(_ other: QvpZoom) {
|
|
137
|
+
// Remembered, not dropped: a neighbouring page is handed the zoom before its canvas
|
|
138
|
+
// has reported a size, and the reader must not see it open printed and then jump.
|
|
139
|
+
// `setBounds` and a page attach take it up the moment they can.
|
|
140
|
+
pendingCarry = other
|
|
141
|
+
applyPendingCarry()
|
|
142
|
+
}
|
|
143
|
+
/// The zoom handed to this page that it could not yet take up.
|
|
144
|
+
@ObservationIgnored private var pendingCarry: QvpZoom?
|
|
145
|
+
private func applyPendingCarry() {
|
|
146
|
+
guard let other = pendingCarry, let p = page, p.isOpen, bounds.width > 0 else { return }
|
|
147
|
+
pendingCarry = nil
|
|
148
|
+
let carried = p.zoomCarried(baseSpec, other)
|
|
149
|
+
guard carried != zoom else { return }
|
|
150
|
+
zoom = carried; placements.removeAll(); cache.clear()
|
|
151
|
+
relayout(); resetView()
|
|
152
|
+
}
|
|
153
|
+
/// The host scrolls the page itself: it puts the canvas inside its own scroll view, sized
|
|
154
|
+
/// to the laid-out page (`hostPageSize`): a reflowed page, or a printed one too
|
|
155
|
+
/// tall for the box. The canvas then attaches no drag of its own — the scroll view takes
|
|
156
|
+
/// every vertical drag, with the momentum, bounce and indicator a reader expects — never
|
|
157
|
+
/// shrinks the page to fit the box (`fitScale` is the host's to ignore) nor centres it as if
|
|
158
|
+
/// it had (`fitX` goes with `fitScale`), keeps it at its top,
|
|
159
|
+
/// shrinks a dressed printed page only as far as its border needs to fit across the width,
|
|
160
|
+
/// and caches the ink for its whole bounds, which ARE the page, rather than a band around a
|
|
161
|
+
/// screen that no longer moves. A pinch still reaches the engine's zoom control.
|
|
162
|
+
///
|
|
163
|
+
/// The layout is then measured in `hostViewportHeight`, not in the canvas: see there. A
|
|
164
|
+
/// host may switch this at any time; the page is laid out again for the box it now has.
|
|
165
|
+
public var hostScrolls = false {
|
|
166
|
+
// Only on a real change: a host that re-states its policy on every page turn or mode
|
|
167
|
+
// check would otherwise re-read the box height from bounds that, once the page has
|
|
168
|
+
// reflowed, ARE the page — and a pinch would then paint the whole of it every frame.
|
|
169
|
+
didSet {
|
|
170
|
+
guard oldValue != hostScrolls else { return }
|
|
171
|
+
derivedBoxHeight = hostScrolls && bounds.height > 0 ? bounds.height : 0
|
|
172
|
+
// The box the layout is measured in just changed hands (`baseSpec`), and a page
|
|
173
|
+
// fitted to the canvas before the policy arrived must un-shrink.
|
|
174
|
+
relayout(); resetView()
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/// The height of the host's own scroll viewport in view points — the box the page is
|
|
178
|
+
/// looked at through. Under `hostScrolls` this is what the layout is measured in (what
|
|
179
|
+
/// `fillHeight` fills, what a pinch's repaint band is cut to, what decides that a page is
|
|
180
|
+
/// taller than the screen): the canvas is sized to the whole laid-out page, so the
|
|
181
|
+
/// controller's own bounds are the PAGE and say nothing about the screen. Only that host
|
|
182
|
+
/// knows the box, and it says so here.
|
|
183
|
+
///
|
|
184
|
+
/// 0 (the default) falls back to the smallest bounds this controller has ever been given
|
|
185
|
+
/// for the band, and to the canvas for the layout. That is right only while the host's
|
|
186
|
+
/// first layout is the printed page in a box the page fits: a canvas whose very first
|
|
187
|
+
/// bounds are already a reflowed page — a zoom carried in before it was ever shown
|
|
188
|
+
/// printed — never learns the screen height, and the band silently degrades to the whole
|
|
189
|
+
/// page. A host that knows its box says so and the guess is not used.
|
|
190
|
+
public var hostViewportHeight: CGFloat = 0 {
|
|
191
|
+
// A new box is a new fill target: the page is laid out again, and a changed `contentH`
|
|
192
|
+
// reaches the host through `layoutRevision`, which is how it resizes the canvas.
|
|
193
|
+
didSet {
|
|
194
|
+
guard oldValue != hostViewportHeight, hostScrolls else { return }
|
|
195
|
+
relayout()
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
public var selectionEnabled = true
|
|
199
|
+
public var hitOptions = QvpHitOptions(maxDistance: QvpDefaults.TAP_DISTANCE)
|
|
200
|
+
|
|
201
|
+
public private(set) var viewScale: CGFloat = 1
|
|
202
|
+
public private(set) var viewOx: CGFloat = 0
|
|
203
|
+
public private(set) var viewOy: CGFloat = 0
|
|
204
|
+
/// How far the glass is over the fitted page: `viewScale` over the fitted scale — 1 at
|
|
205
|
+
/// rest, in every mode but `.magnify`, and again once a peek has sprung back. A host
|
|
206
|
+
/// overlay that draws its own furniture beside the ink (a frame around a surah name)
|
|
207
|
+
/// divides this out of the view transform, draws the furniture ONCE at the fitted size,
|
|
208
|
+
/// and lets the glass scale that one raster — instead of drawing it again at every size
|
|
209
|
+
/// a pinch passes through.
|
|
210
|
+
public var peekScale: CGFloat { fitScale > 0 ? viewScale / fitScale : 1 }
|
|
211
|
+
/// The size a host that scrolls the page (`hostScrolls`) gives the canvas, in view points: the
|
|
212
|
+
/// laid-out page grown by a dress's border, from the engine (`dressView` at scale 0). The
|
|
213
|
+
/// engine shrinks a dressed box wider than the canvas to the canvas width and never
|
|
214
|
+
/// enlarges one, so the whole border fits across. Give the canvas this height and the
|
|
215
|
+
/// border's bottom is on it. nil before the canvas has a page and a width.
|
|
216
|
+
///
|
|
217
|
+
/// Size the canvas from this, and decide whether the page scrolls from it, never from
|
|
218
|
+
/// `currentLayout.contentH`. On a bordered page `contentH` is the text alone at the layout's
|
|
219
|
+
/// scale, before the border shrinks the page to the width. Under `fillHeight` a bordered page
|
|
220
|
+
/// that fits its box gets a height of exactly `hostViewportHeight`, border included. On an
|
|
221
|
+
/// undressed page, or one dressed without a border, this height is `contentH`.
|
|
222
|
+
public var hostPageSize: CGSize? {
|
|
223
|
+
// read so an observer asks again after a relayout or a redraw (`resetView` after a dress)
|
|
224
|
+
_ = layoutRevision; _ = revision
|
|
225
|
+
guard let p = page, p.isOpen, bounds.width > 0, p.currentLayout != nil else { return nil }
|
|
226
|
+
let d = p.dressView(0, viewportW: Float(bounds.width))
|
|
227
|
+
return CGSize(width: CGFloat(d.width), height: CGFloat(d.height))
|
|
228
|
+
}
|
|
229
|
+
/// Bumped by every relayout. A host's overlay reads this beside the view transform: a page
|
|
230
|
+
/// laid out into a box it fits exactly leaves `viewScale`/`viewOx`/`viewOy` at their
|
|
231
|
+
/// defaults, so the transform alone never tells the overlay that the geometry it draws
|
|
232
|
+
/// from now exists.
|
|
233
|
+
public private(set) var layoutRevision = 0
|
|
234
|
+
/// True while an engine transition is fading — the canvas keeps drawing frames.
|
|
235
|
+
public private(set) var animating = false
|
|
236
|
+
// stats for a HUD
|
|
237
|
+
@ObservationIgnored public private(set) var lastBaseMs = 0.0
|
|
238
|
+
@ObservationIgnored public private(set) var lastOverlayMs = 0.0
|
|
239
|
+
@ObservationIgnored public private(set) var lastHitUs = 0.0
|
|
240
|
+
@ObservationIgnored public private(set) var lastBasePaths = 0
|
|
241
|
+
@ObservationIgnored public private(set) var lastOverlayPaths = 0
|
|
242
|
+
@ObservationIgnored public private(set) var lastBands = 0
|
|
243
|
+
|
|
244
|
+
/// Redraw epoch: bumped by `invalidate()`; the canvas body reads it.
|
|
245
|
+
private(set) var revision = 0
|
|
246
|
+
/// Cached base-ink layer. A plain class so draw-time rebuilds don't re-enter observation.
|
|
247
|
+
@ObservationIgnored private let cache = BaseCache()
|
|
248
|
+
/// The dress's ornament layer, one image per slot like `cache`.
|
|
249
|
+
@ObservationIgnored let ornaments = QvpOrnamentRaster()
|
|
250
|
+
@ObservationIgnored private var bounds = CGSize.zero
|
|
251
|
+
/// Creation order of the newest canvas that reported a size (see `setBounds`).
|
|
252
|
+
@ObservationIgnored private var newestCanvas = 0
|
|
253
|
+
@ObservationIgnored private var fitScale: CGFloat = 1
|
|
254
|
+
@ObservationIgnored private var selectionHandle = 0
|
|
255
|
+
@ObservationIgnored private var selAnchor = -1
|
|
256
|
+
@ObservationIgnored var selecting = false
|
|
257
|
+
/// True while the reader's fingers are on the page. A host that shares ONE zoom across
|
|
258
|
+
/// several pages publishes it when this goes false, never while it is true: `zoom` moves
|
|
259
|
+
/// at the gesture's own frame rate, and following every move has every other page it
|
|
260
|
+
/// holds lay itself out again inside the gesture.
|
|
261
|
+
public private(set) var isPinching = false
|
|
262
|
+
@ObservationIgnored var pinchZoom = QvpZoom()
|
|
263
|
+
@ObservationIgnored var pinchView = QvpView()
|
|
264
|
+
/// Where the fingers went down, in view points — the band a pinch paints is built around
|
|
265
|
+
/// it, and held there for the whole gesture (a band that followed the fingers would repaint
|
|
266
|
+
/// every frame, since it is part of the cache key).
|
|
267
|
+
@ObservationIgnored private var pinchFocalY: CGFloat = 0
|
|
268
|
+
/// Under `hostScrolls` the bounds are the page; the smallest bounds ever reported are a
|
|
269
|
+
/// GUESS at the host's box — see `hostViewportHeight`, which replaces it when set.
|
|
270
|
+
@ObservationIgnored private var derivedBoxHeight: CGFloat = 0
|
|
271
|
+
/// The box a pinch's repaint band is measured in: what the host said, or the guess.
|
|
272
|
+
private var hostBoxHeight: CGFloat { hostViewportHeight > 0 ? hostViewportHeight : derivedBoxHeight }
|
|
273
|
+
@ObservationIgnored var lastDrag = CGSize.zero
|
|
274
|
+
@ObservationIgnored private var springTask: Task<Void, Never>?
|
|
275
|
+
/// True once the reader has zoomed in, by either road: the view magnified past the fitted
|
|
276
|
+
/// size, or the page reflowed to a size above the printed one. Panning then moves the page
|
|
277
|
+
/// rather than the book. The engine decides, so every platform draws the line in the same place.
|
|
278
|
+
public var isZoomed: Bool { zoom.isZoomed(currentView, fitScale: Float(fitScale)) }
|
|
279
|
+
|
|
280
|
+
/// The cached ink, one image per canvas the page is drawn as (`QvpPageCanvas.slices`), each
|
|
281
|
+
/// REPLACED when its own key moves on. Kept by key alone, every frame of a peek, of its
|
|
282
|
+
/// spring-back and of a pan is a key of its own, and the last few stayed behind the one on
|
|
283
|
+
/// screen until the next layout — a page-sized bitmap apiece. A pinch paints its band into
|
|
284
|
+
/// slot 0, and every canvas of the page blits that one image. Cleared whenever the layout
|
|
285
|
+
/// changes.
|
|
286
|
+
///
|
|
287
|
+
/// Each entry remembers the STYLED paths it was drawn without — they are drawn over it, or not
|
|
288
|
+
/// at all when their colour is transparent (a hidden word). So a reveal, which only takes paths
|
|
289
|
+
/// out of that set, adds those paths to the cached image instead of drawing the page again: a
|
|
290
|
+
/// memorization review reveals a word at a time, and each reveal used to re-rasterize every slice,
|
|
291
|
+
/// including a slice the word is not even on.
|
|
292
|
+
final class BaseCache {
|
|
293
|
+
struct Entry { let key: String; let styled: Set<Int>; let image: CGImage }
|
|
294
|
+
private var slots: [Int: Entry] = [:]
|
|
295
|
+
func entry(slot: Int) -> Entry? { slots[slot] }
|
|
296
|
+
func store(_ image: CGImage, key: String, styled: Set<Int>, slot: Int) {
|
|
297
|
+
slots[slot] = Entry(key: key, styled: styled, image: image)
|
|
298
|
+
}
|
|
299
|
+
func clear() { slots.removeAll() }
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/// What one frame reads from the engine, whichever canvas asks for it. A page drawn as several
|
|
303
|
+
/// canvases (`QvpPageCanvas.slices`) renders each in the same frame, and every one of them
|
|
304
|
+
/// ticked the engine clock and read the styled paths, the highlight boxes and the mask boxes
|
|
305
|
+
/// again. The token is the frame: the timeline's date, the revision and the layout, so a pan,
|
|
306
|
+
/// which moves none of these, reads the answers already in hand.
|
|
307
|
+
struct FrameInputs {
|
|
308
|
+
let moving: Bool
|
|
309
|
+
let styled: [(path: Int, color: UInt32)]
|
|
310
|
+
let styledSet: Set<Int>
|
|
311
|
+
let colors: [Int: UInt32]
|
|
312
|
+
let bands: [QvpBox]
|
|
313
|
+
let masks: [QvpBox]
|
|
314
|
+
}
|
|
315
|
+
private struct FrameToken: Equatable { let page: ObjectIdentifier; let revision: Int; let layout: Int; let date: Date }
|
|
316
|
+
@ObservationIgnored private var frameMemo: (token: FrameToken, inputs: FrameInputs)?
|
|
317
|
+
private func frameInputs(_ p: QvpPage, frame: Date?) -> FrameInputs {
|
|
318
|
+
let token = frame.map { FrameToken(page: ObjectIdentifier(p), revision: revision, layout: layoutRevision, date: $0) }
|
|
319
|
+
if let token, let memo = frameMemo, memo.token == token { return memo.inputs }
|
|
320
|
+
let moving = p.tick(now() * 1000)
|
|
321
|
+
let styled = p.styledPaths()
|
|
322
|
+
let inputs = FrameInputs(moving: moving, styled: styled, styledSet: Set(styled.map { $0.path }),
|
|
323
|
+
colors: Dictionary(styled, uniquingKeysWith: { a, _ in a }),
|
|
324
|
+
bands: p.highlightBoxesView(), masks: p.maskBoxesView())
|
|
325
|
+
if let token { frameMemo = (token, inputs) }
|
|
326
|
+
return inputs
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
public init() {}
|
|
330
|
+
|
|
331
|
+
/// Redraw after engine calls the controller cannot see (`highlight`, `style`, `mask`, `theme`, …).
|
|
332
|
+
/// It also asks the engine clock whether frames must run, so a transition the call just began
|
|
333
|
+
/// animates from this same update — not one draw and a main-actor hop later, by which time a
|
|
334
|
+
/// short fade had already spent its first frames.
|
|
335
|
+
public func invalidate() {
|
|
336
|
+
revision &+= 1
|
|
337
|
+
_ = syncAnimating()
|
|
338
|
+
}
|
|
339
|
+
/// `animating` = the engine reports a transition in flight now. True when it changed.
|
|
340
|
+
private func syncAnimating() -> Bool {
|
|
341
|
+
let moving = page.map { $0.isOpen && $0.tick(now() * 1000) } ?? false
|
|
342
|
+
guard moving != animating else { return false }
|
|
343
|
+
animating = moving
|
|
344
|
+
return true
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/// The layout the current size and knobs ask for, before the zoom control has its say.
|
|
348
|
+
var baseSpec: QvpLayoutSpec {
|
|
349
|
+
// Under `hostScrolls` the canvas is the laid-out page, so its height is this layout's
|
|
350
|
+
// OUTPUT. The box the layout is measured in — what `fillHeight` fills, what the printed
|
|
351
|
+
// pitch is opened up to, what decides whether the page is taller than the screen — is
|
|
352
|
+
// the one the host looks through. Read the canvas back as the viewport and a host that
|
|
353
|
+
// pads the page grows it by that padding on every pass, and a page that fits is spread
|
|
354
|
+
// to fill a box that is already the page.
|
|
355
|
+
let viewportH = hostScrolls && hostViewportHeight > 0 ? hostViewportHeight : bounds.height
|
|
356
|
+
return QvpLayoutSpec(viewportW: Float(bounds.width), viewportH: Float(viewportH),
|
|
357
|
+
padTop: Float(padTop), padBottom: Float(padBottom),
|
|
358
|
+
padLeft: Float(padSide), padRight: Float(padSide),
|
|
359
|
+
lineSpacing: lineSpacing, fillHeight: fillHeight,
|
|
360
|
+
cropLeft: cropLeft, cropRight: cropRight,
|
|
361
|
+
// zoom 0 is the printed page; the fill waits there for the pinch
|
|
362
|
+
// that reflows it, which the engine lays out inside the call
|
|
363
|
+
reflow: QvpReflowSpec(zoom: 0, fill: reflowFill, maxStretch: reflowMaxStretch),
|
|
364
|
+
bannerZoom: bannerZoom, surahFrames: surahFrames)
|
|
365
|
+
}
|
|
366
|
+
/// The spec in force: the knobs above with the reader's zoom control folded in.
|
|
367
|
+
public var layoutSpec: QvpLayoutSpec {
|
|
368
|
+
guard let p = page, p.isOpen else { return baseSpec }
|
|
369
|
+
return p.zoomSpec(baseSpec, zoom)
|
|
370
|
+
}
|
|
371
|
+
/// The pitch a PRINTED row is laid out at in this box, in page units: the print's own
|
|
372
|
+
/// pitch opened up by `fillHeight` and `lineSpacing`. A host that sizes its own furniture
|
|
373
|
+
/// to a printed row — a frame drawn over a printed surah name — reads this rather than
|
|
374
|
+
/// `currentLayout.lineSpacing`, which answers the SPREAD pitch on a printed page and the
|
|
375
|
+
/// printed one once the page has reflowed onto rows of its own. Sizing off that directly
|
|
376
|
+
/// drew the frame a fill-height's worth too small on every reflowed page.
|
|
377
|
+
///
|
|
378
|
+
/// 0 before the canvas has a size or a page.
|
|
379
|
+
public var printedPitch: Float {
|
|
380
|
+
guard let p = page, p.isOpen, bounds.width > 0 else { return 0 }
|
|
381
|
+
// `baseSpec` is already measured in the box the reader looks through, never this
|
|
382
|
+
// canvas's own bounds — on a reflowed page those are the page's, and asking what pitch
|
|
383
|
+
// would fill THAT with fifteen printed lines answers several times the truth.
|
|
384
|
+
let opened = fillHeight ? p.layoutLineSpacingToFill(baseSpec) : max(lineSpacing, 1)
|
|
385
|
+
return p.lineSpacing * opened
|
|
386
|
+
}
|
|
387
|
+
/// The page's height at the printed pitch when laid out for `width` with this controller's
|
|
388
|
+
/// knobs (crop, padding, the grid a short page sits on), in points — what `contentH` will be
|
|
389
|
+
/// before fill-height adds any leading. A host sizing the page's box asks this BEFORE it
|
|
390
|
+
/// sizes the canvas: the layout answers the same number, but only for the bounds it already
|
|
391
|
+
/// has. nil before a page is attached.
|
|
392
|
+
///
|
|
393
|
+
/// On a page dressed in a border it is the whole page, border included, fitted to `width`:
|
|
394
|
+
/// the height `hostPageSize` will have. Such a host sizes the canvas from `hostPageSize`,
|
|
395
|
+
/// not from `contentH`. With no padding the height is in proportion to the width, so a host
|
|
396
|
+
/// that shrinks a page to fit its box can divide by it.
|
|
397
|
+
public func printedHeight(forWidth width: CGFloat) -> CGFloat? {
|
|
398
|
+
guard let p = page, p.isOpen, width > 0 else { return nil }
|
|
399
|
+
let base = baseSpec
|
|
400
|
+
let spec = QvpLayoutSpec(viewportW: Float(width), viewportH: base.viewportH,
|
|
401
|
+
padTop: base.padTop, padBottom: base.padBottom,
|
|
402
|
+
padLeft: base.padLeft, padRight: base.padRight,
|
|
403
|
+
lineSpacing: base.lineSpacing, fillHeight: base.fillHeight,
|
|
404
|
+
cropLeft: base.cropLeft, cropRight: base.cropRight, bannerZoom: base.bannerZoom,
|
|
405
|
+
surahFrames: base.surahFrames)
|
|
406
|
+
return CGFloat(p.layoutPrintedHeight(spec))
|
|
407
|
+
}
|
|
408
|
+
/// Recompute the engine layout for the current size / knobs.
|
|
409
|
+
///
|
|
410
|
+
/// Under `hostScrolls` the view at rest is the engine's fit of the page to the canvas width
|
|
411
|
+
/// (`fittedView`), and on a page dressed in a border a new layout moves it: a new crop, fill
|
|
412
|
+
/// or box fits the border again. So the view follows the layout here, and a host that sets
|
|
413
|
+
/// a knob after `page.dress(...)` needs no `resetView()`. A pinch in progress, or a magnified
|
|
414
|
+
/// peek the reader is holding, keeps its own view.
|
|
415
|
+
public func relayout() {
|
|
416
|
+
guard let p = page, p.isOpen, bounds.width > 0, bounds.height > 0 else { return }
|
|
417
|
+
layoutSeen = p.layout(layoutSpec)
|
|
418
|
+
placements.removeAll()
|
|
419
|
+
layoutRevision &+= 1
|
|
420
|
+
if hostScrolls, !isPinching, springTask == nil, !(zoomMode == .magnify && viewScale > fitScale) {
|
|
421
|
+
let f = fittedView()
|
|
422
|
+
viewScale = f.scale; fitScale = f.scale; viewOx = f.offsetX; viewOy = f.offsetY
|
|
423
|
+
}
|
|
424
|
+
cache.clear(); invalidate()
|
|
425
|
+
}
|
|
426
|
+
/// Go back to the fitted view (`fittedView()`).
|
|
427
|
+
///
|
|
428
|
+
/// A dress or an undress lays the page out again inside the engine, without this controller.
|
|
429
|
+
/// The layout it made is taken up here as `relayout()` takes up its own: the draw lists and
|
|
430
|
+
/// the ink go, and `layoutRevision` moves, so a host's overlay redraws from the new rows.
|
|
431
|
+
public func resetView() {
|
|
432
|
+
springTask?.cancel(); springTask = nil
|
|
433
|
+
if let l = page?.currentLayout, l !== layoutSeen {
|
|
434
|
+
layoutSeen = l; placements.removeAll(); cache.clear(); layoutRevision &+= 1
|
|
435
|
+
}
|
|
436
|
+
let f = fittedView()
|
|
437
|
+
viewScale = f.scale; fitScale = f.scale; viewOx = f.offsetX; viewOy = f.offsetY
|
|
438
|
+
invalidate()
|
|
439
|
+
}
|
|
440
|
+
/// The engine layout `layoutRevision` last counted: the one `relayout()`, a gesture or
|
|
441
|
+
/// `resetView()` took up.
|
|
442
|
+
@ObservationIgnored private var layoutSeen: QvpLayout?
|
|
443
|
+
/// The transform `resetView()` applies. A printed page takes the layout's fit: the content
|
|
444
|
+
/// plus any dress overflow, shrunk to fit the view and centred. A reflowed page takes scale 1,
|
|
445
|
+
/// centred across, its top at the top.
|
|
446
|
+
/// A printed page the host scrolls takes `dressView`: the same box fitted to the width,
|
|
447
|
+
/// never enlarged, centred across, its top at the top.
|
|
448
|
+
private func fittedView() -> QvpZoomSpring.ViewTransform {
|
|
449
|
+
let l = page?.currentLayout
|
|
450
|
+
// The layout's fit already holds a dress's border: the engine fits content plus overflow.
|
|
451
|
+
// A reflowed page is taller than the screen on purpose: fitting its height would undo
|
|
452
|
+
// the size the reader asked for. It opens at its top and the reader scrolls. So does
|
|
453
|
+
// any page a host scrolls itself: a printed page too tall for the box is what that
|
|
454
|
+
// host's scroll view is FOR, and the engine still answers `fitScale` for a host that
|
|
455
|
+
// would rather shrink it — this renderer just no longer applies it. Nor, then, the
|
|
456
|
+
// centring that goes with it: a printed layout's `fitX` centres the page SHRUNK by
|
|
457
|
+
// `fitScale`, so at scale 1 it pushes the page off to one side by half the width
|
|
458
|
+
// the shrink would have freed. Centred at scale 1 instead — the reflow's own rule.
|
|
459
|
+
if let l, l.reflowed { return (1, CGFloat(l.fitX), CGFloat(l.fitY)) }
|
|
460
|
+
if hostScrolls, let p = page, p.isOpen {
|
|
461
|
+
// the engine's view: the dressed box fitted to the width (never enlarged), centred,
|
|
462
|
+
// its top at the canvas's top
|
|
463
|
+
let v = p.dressView(0, viewportW: Float(bounds.width)).view
|
|
464
|
+
return (CGFloat(v.scale), CGFloat(v.offsetX), CGFloat(v.offsetY))
|
|
465
|
+
}
|
|
466
|
+
return (CGFloat(l?.fitScale ?? 1), CGFloat(l?.fitX ?? 0), CGFloat(l?.fitY ?? 0))
|
|
467
|
+
}
|
|
468
|
+
/// Clear the selection band and the engine selection.
|
|
469
|
+
public func clearSelection() {
|
|
470
|
+
guard let p = page, p.isOpen else { return }
|
|
471
|
+
p.clearSelection(); if selectionHandle != 0 { p.removeHighlight(selectionHandle); selectionHandle = 0 }
|
|
472
|
+
onSelectionChanged?([]); invalidate()
|
|
473
|
+
}
|
|
474
|
+
/// Page units of `line` → view points (engine layout + pan/zoom).
|
|
475
|
+
public func lineTransform(_ line: Int) -> CGAffineTransform {
|
|
476
|
+
let l = page?.currentLayout
|
|
477
|
+
let dy = (l.flatMap { line < $0.lineDy.count ? $0.lineDy[line] : nil }) ?? 0
|
|
478
|
+
return transform(QvpPlacement(dx: 0, dy: dy, kx: 1, ky: 1))
|
|
479
|
+
}
|
|
480
|
+
/// Page units of a decoration's own box → view points, wherever the current layout put
|
|
481
|
+
/// it: on the printed page that is its line's transform; on a reflowed page a decoration
|
|
482
|
+
/// is a group of its own (a surah name keeps a row to itself), and this is that group's
|
|
483
|
+
/// placement. A host drawing its own frame over a printed surah name reads this and
|
|
484
|
+
/// never guesses where a row landed.
|
|
485
|
+
public func decorationTransform(_ index: Int) -> CGAffineTransform {
|
|
486
|
+
guard let p = page, p.isOpen, p.decorations.indices.contains(index) else { return .identity }
|
|
487
|
+
let deco = p.decorations[index]
|
|
488
|
+
guard p.currentLayout?.reflowed == true else { return lineTransform(deco.line) }
|
|
489
|
+
// Read once per layout, like the draw list: both answers copy a table the size of the
|
|
490
|
+
// page's paths, and this is called from a host overlay that re-runs on every pan and
|
|
491
|
+
// zoom tick — once per surah name each time.
|
|
492
|
+
if decoGroups?.revision != layoutRevision {
|
|
493
|
+
decoGroups = (layoutRevision, p.layoutPathGroups(), p.layoutGroups())
|
|
494
|
+
}
|
|
495
|
+
guard let g = decoGroups, g.paths.indices.contains(deco.firstPath) else { return lineTransform(deco.line) }
|
|
496
|
+
let group = g.paths[deco.firstPath]
|
|
497
|
+
guard g.places.indices.contains(group) else { return lineTransform(deco.line) }
|
|
498
|
+
return transform(g.places[group])
|
|
499
|
+
}
|
|
500
|
+
/// The reflowed layout's path→group map and group placements, held for the layout that
|
|
501
|
+
/// answered them — `layoutRevision` is the count of layouts, so a stale pair cannot be read.
|
|
502
|
+
@ObservationIgnored private var decoGroups: (revision: Int, paths: [Int], places: [QvpPlacement])?
|
|
503
|
+
/// Page units → view points under one placement (engine layout + pan/zoom).
|
|
504
|
+
func transform(_ q: QvpPlacement, offsetY: CGFloat? = nil) -> CGAffineTransform {
|
|
505
|
+
let l = page?.currentLayout
|
|
506
|
+
let ls = CGFloat(l?.scale ?? 1)
|
|
507
|
+
let s = viewScale * ls
|
|
508
|
+
return CGAffineTransform(a: s * CGFloat(q.kx), b: 0, c: 0, d: s * CGFloat(q.ky),
|
|
509
|
+
tx: viewOx + viewScale * (CGFloat(l?.offsetX ?? 0) + CGFloat(q.dx) * ls),
|
|
510
|
+
ty: (offsetY ?? viewOy) + viewScale * (CGFloat(l?.offsetY ?? 0) + CGFloat(q.dy) * ls))
|
|
511
|
+
}
|
|
512
|
+
/// Where the cached band of ink starts and how tall it is, in view points down the page.
|
|
513
|
+
///
|
|
514
|
+
/// A canvas whose host scrolls the page is the page, so its band is the page itself. While a
|
|
515
|
+
/// pinch runs it is two boxes around the fingers instead (see below).
|
|
516
|
+
///
|
|
517
|
+
/// Otherwise the engine picks it, as it does for `QvpPageView`: two screens around the
|
|
518
|
+
/// reader, with a top that moves in half-screen steps, so a drag inside one step is a blit
|
|
519
|
+
/// and nothing is drawn again. A page that fits in two screens is drawn whole. The band of
|
|
520
|
+
/// a dressed page holds every part of its border on the screen, except under a screen taller
|
|
521
|
+
/// than 16384 rows, where it keeps the page's ink and the top of the border can be clipped,
|
|
522
|
+
/// and the border is drawn
|
|
523
|
+
/// into a bitmap of the same band. The
|
|
524
|
+
/// limits are the bitmap's: 16384 rows, and two screens of pixels, which is the most this
|
|
525
|
+
/// canvas has ever kept for a band.
|
|
526
|
+
func band(displayScale: CGFloat) -> (top: CGFloat, height: CGFloat) {
|
|
527
|
+
if hostScrolls {
|
|
528
|
+
// While a pinch runs, the engine reflows live at every step the fingers cross, and
|
|
529
|
+
// painting the whole page each time is what made a pinch stutter: paint two boxes
|
|
530
|
+
// around the fingers, and the whole page once the pinch ends. Otherwise the bounds
|
|
531
|
+
// are the page and nothing moves under the canvas, so the band is the page itself.
|
|
532
|
+
if isPinching, hostBoxHeight > 0 {
|
|
533
|
+
// The band is cut in the SCALED page, which is what `layoutBand` divides back
|
|
534
|
+
// to layout points: the fingers' canvas y less the pan under it. A stepped
|
|
535
|
+
// reflow keeps the page at its top, so that is the same number; a magnify peek
|
|
536
|
+
// moves `viewOy` and `viewScale`, and a band cut in canvas points drifted off
|
|
537
|
+
// the fingers as the page grew under them — a blank box exactly where they were.
|
|
538
|
+
let focal = pinchFocalY - viewOy
|
|
539
|
+
let pageHeight = bounds.height * viewScale
|
|
540
|
+
let top = max(min(focal - hostBoxHeight, pageHeight - hostBoxHeight * 2), 0)
|
|
541
|
+
return (top, max(min(hostBoxHeight * 2, bounds.height * viewScale), 1))
|
|
542
|
+
}
|
|
543
|
+
return (-viewOy, max(bounds.height, 1))
|
|
544
|
+
}
|
|
545
|
+
guard let p = page, p.isOpen, p.currentLayout != nil else { return (0, max(bounds.height * 2, 1)) }
|
|
546
|
+
return p.inkBandPoints(currentView, viewScale: viewScale, viewportW: bounds.width, viewportH: bounds.height,
|
|
547
|
+
displayScale: displayScale, maxPixels: bounds.width * bounds.height * 2)
|
|
548
|
+
}
|
|
549
|
+
/// What the layout in hand draws and where: the engine's own answer, read once per layout.
|
|
550
|
+
/// A printed page and a reflowed one come back in the same shape, so nothing here has to
|
|
551
|
+
/// know which it is looking at.
|
|
552
|
+
struct DrawList { let draws: [QvpDraw], places: [QvpPlacement], band: ClosedRange<Float> }
|
|
553
|
+
/// One draw list per band asked for — a page drawn as a stack of canvases asks for each
|
|
554
|
+
/// slice's in turn, and a single slot rebuilt on every alternation. Cleared with the layout.
|
|
555
|
+
/// Written from the renderer, so kept out of observation like `cache`.
|
|
556
|
+
@ObservationIgnored var placements: [ClosedRange<Float>: DrawList] = [:]
|
|
557
|
+
/// The engine layout the lists in `placements` were read from.
|
|
558
|
+
@ObservationIgnored private var placementsLayout: QvpLayout?
|
|
559
|
+
/// A band of the canvas, in layout points — the pan and zoom divided out: what the engine is
|
|
560
|
+
/// asked to draw. `draw` hands it the band it is painting — its slice, or `band(displayScale:)`
|
|
561
|
+
/// (two screens around the reader, the page, or the pinch's two boxes) — never a band of its
|
|
562
|
+
/// own choosing, which for a slice is the wrong one.
|
|
563
|
+
func layoutBand(top: CGFloat, height: CGFloat) -> (top: Float, bottom: Float) {
|
|
564
|
+
let s = viewScale == 0 ? 1 : viewScale
|
|
565
|
+
return (Float(top / s), Float((top + height) / s))
|
|
566
|
+
}
|
|
567
|
+
func drawListNow(band b: (top: Float, bottom: Float)) -> DrawList? {
|
|
568
|
+
let range = b.top...b.bottom
|
|
569
|
+
// a list read from a layout the engine has since replaced (a dress lays the page out
|
|
570
|
+
// again) holds the old placements
|
|
571
|
+
if placementsLayout !== page?.currentLayout { placements.removeAll(); placementsLayout = page?.currentLayout }
|
|
572
|
+
if let q = placements[range] { return q }
|
|
573
|
+
guard let p = page, p.isOpen, p.currentLayout != nil else { return nil }
|
|
574
|
+
let q = DrawList(draws: p.layoutDrawList(band: b), places: p.layoutPlacements(), band: range)
|
|
575
|
+
if placements.count >= 4 { placements.removeAll() }
|
|
576
|
+
placements[range] = q; return q
|
|
577
|
+
}
|
|
578
|
+
/// The transform one entry of the draw list is drawn under.
|
|
579
|
+
func transform(_ q: DrawList, _ placement: Int, offsetY: CGFloat? = nil) -> CGAffineTransform {
|
|
580
|
+
transform(placement < q.places.count ? q.places[placement] : .identity, offsetY: offsetY)
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// ── input (called by QvpPageCanvas) ──
|
|
584
|
+
/// Takes a size only from the newest canvas of this controller. A host can show an outgoing
|
|
585
|
+
/// canvas and an incoming canvas for a moment, for example when a rotation moves the page from
|
|
586
|
+
/// a static layout to a scrolling layout. The outgoing canvas can report its transitional size
|
|
587
|
+
/// after the incoming canvas reported the real size, and the page then kept the wrong layout.
|
|
588
|
+
func setBounds(_ size: CGSize, fromCanvas order: Int) {
|
|
589
|
+
guard order >= newestCanvas else { return }
|
|
590
|
+
newestCanvas = order
|
|
591
|
+
guard size != bounds else { return }
|
|
592
|
+
if hostScrolls, size.height > 0 { derivedBoxHeight = derivedBoxHeight > 0 ? min(derivedBoxHeight, size.height) : size.height }
|
|
593
|
+
bounds = size; relayout(); resetView()
|
|
594
|
+
applyPendingCarry()
|
|
595
|
+
}
|
|
596
|
+
func hitAt(_ pt: CGPoint, _ o: QvpHitOptions? = nil) -> QvpHit? {
|
|
597
|
+
guard let p = page, p.isOpen else { return nil }
|
|
598
|
+
let t0 = now()
|
|
599
|
+
let at = p.viewToLayout(currentView, Float(pt.x), Float(pt.y))
|
|
600
|
+
let h = p.hitTestView(at.x, at.y, o ?? hitOptions)
|
|
601
|
+
lastHitUs = (now() - t0) * 1e6
|
|
602
|
+
return h
|
|
603
|
+
}
|
|
604
|
+
func tap(_ pt: CGPoint) {
|
|
605
|
+
guard let p = page, p.isOpen else { return }
|
|
606
|
+
let hit = hitAt(pt)
|
|
607
|
+
if let h = hit, h.word >= 0 { onWordTap?(p.words[h.word], h) }
|
|
608
|
+
else if let h = hit, h.decoration >= 0 { onDecorationTap?(p.decorations[h.decoration], h) }
|
|
609
|
+
else { onEmptyTap?() }
|
|
610
|
+
}
|
|
611
|
+
func doubleTap(_ pt: CGPoint) { if let cb = onDoubleTap { cb(hitAt(pt)) } else { resetView() } }
|
|
612
|
+
func longPress(_ pt: CGPoint) { onLongPress?(hitAt(pt)) }
|
|
613
|
+
/// The reader's pan and zoom as the engine has it.
|
|
614
|
+
var currentView: QvpView { QvpView(scale: Float(viewScale), offsetX: Float(viewOx), offsetY: Float(viewOy)) }
|
|
615
|
+
/// Take what a gesture produced: the page is already laid out at the new size, and the view
|
|
616
|
+
/// already holds the word the fingers were on.
|
|
617
|
+
private func apply(_ c: QvpZoomChange) {
|
|
618
|
+
zoom = c.zoom
|
|
619
|
+
viewScale = CGFloat(c.view.scale); viewOx = CGFloat(c.view.offsetX); viewOy = CGFloat(c.view.offsetY)
|
|
620
|
+
// The engine laid the page out inside the call rather than through `relayout()`, so the
|
|
621
|
+
// revision is bumped here too — it is the count of LAYOUTS, and a host overlay keying on
|
|
622
|
+
// it must not be told a pinch left the geometry where it was.
|
|
623
|
+
if c.relaid { placements.removeAll(); cache.clear(); layoutRevision &+= 1; layoutSeen = page?.currentLayout }
|
|
624
|
+
invalidate()
|
|
625
|
+
}
|
|
626
|
+
/// One frame of a pinch. `magnification` is the whole gesture against where the fingers
|
|
627
|
+
/// went down, and `focus` the point they went down at. The engine measures the gesture from
|
|
628
|
+
/// its start: the control and the focal point the pinch began on, and the factor of the
|
|
629
|
+
/// whole gesture. SwiftUI's `MagnifyGesture` reports no later focal point, so the fingers'
|
|
630
|
+
/// drift, which the other page views pan the page by, is zero here.
|
|
631
|
+
func pinch(_ magnification: CGFloat, at focus: CGPoint) {
|
|
632
|
+
guard zoomEnabled, !selecting else { return }
|
|
633
|
+
if !isPinching {
|
|
634
|
+
springTask?.cancel(); springTask = nil; isPinching = true
|
|
635
|
+
pinchZoom = zoom; pinchView = currentView; pinchFocalY = focus.y
|
|
636
|
+
}
|
|
637
|
+
guard let p = page, p.isOpen, zoomMode != .magnify else {
|
|
638
|
+
// The printed page under a magnifying glass: the rows never move. The engine zooms
|
|
639
|
+
// the view the pinch began on about the point it began at, with the settled page as
|
|
640
|
+
// the floor and the host's ceiling above, and holds the result against the viewport.
|
|
641
|
+
var v = pinchView.zoomAbout(focalX: Float(focus.x), focalY: Float(focus.y), factor: Float(magnification), min: Float(fitScale), max: Float(maxZoom))
|
|
642
|
+
if let p = page, p.isOpen { v = p.dressClamp(v, viewportW: Float(bounds.width), viewportH: Float(bounds.height)) }
|
|
643
|
+
viewScale = CGFloat(v.scale); viewOx = CGFloat(v.offsetX); viewOy = CGFloat(v.offsetY)
|
|
644
|
+
return
|
|
645
|
+
}
|
|
646
|
+
// `pinchZoom` stays where the gesture began: the engine measures the fingers against
|
|
647
|
+
// that, so a slow pinch walks the steps one at a time instead of running away. The view
|
|
648
|
+
// is the one the last frame returned: a step committed earlier in this gesture moved the
|
|
649
|
+
// page, and the engine finds the word under the fingers on the layout it has now.
|
|
650
|
+
let c = p.zoomPinch(layoutSpec, pinchZoom, pinchView, factor: Float(magnification), focalX: Float(focus.x), focalY: Float(focus.y))
|
|
651
|
+
pinchView = c.view
|
|
652
|
+
// held against the viewport, a dressed page with its border, as every pinch frame is
|
|
653
|
+
var v = c.view
|
|
654
|
+
if p.currentLayout != nil { v = p.dressClamp(v, viewportW: Float(bounds.width), viewportH: Float(bounds.height)) }
|
|
655
|
+
apply(QvpZoomChange(zoom: c.zoom, view: v, relaid: c.relaid))
|
|
656
|
+
}
|
|
657
|
+
func pinchEnded() {
|
|
658
|
+
isPinching = false
|
|
659
|
+
// A reflowed page is a size the reader chose, not a peek: it stays until they change it.
|
|
660
|
+
if zoomSpringsBack && zoomMode == .magnify { springBack() }
|
|
661
|
+
// The pinch painted a band around the fingers; the page is painted whole once, now.
|
|
662
|
+
if hostScrolls { invalidate() }
|
|
663
|
+
}
|
|
664
|
+
/// Ease from the released transform to the fitted one, one step per display frame or so.
|
|
665
|
+
private func springBack() {
|
|
666
|
+
let to = fittedView()
|
|
667
|
+
let spring = QvpZoomSpring(from: (viewScale, viewOx, viewOy), to: to, start: now())
|
|
668
|
+
fitScale = to.scale
|
|
669
|
+
springTask?.cancel()
|
|
670
|
+
springTask = Task { @MainActor [weak self] in
|
|
671
|
+
while let self, !Task.isCancelled {
|
|
672
|
+
let (v, done) = spring.value(at: self.now())
|
|
673
|
+
self.viewScale = v.scale; self.viewOx = v.offsetX; self.viewOy = v.offsetY
|
|
674
|
+
self.invalidate()
|
|
675
|
+
if done { self.springTask = nil; return }
|
|
676
|
+
try? await Task.sleep(nanoseconds: 8_000_000)
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
/// A reflowed page is the screen's own width: nothing to pan sideways, so it scrolls up and
|
|
681
|
+
/// down only, and a sideways drag turns the page.
|
|
682
|
+
private var isReflowed: Bool { page?.currentLayout?.reflowed ?? false }
|
|
683
|
+
func pan(_ translation: CGSize) {
|
|
684
|
+
guard zoomEnabled, !hostScrolls, !selecting, isZoomed || isReflowed, springTask == nil else { return }
|
|
685
|
+
// a reflowed page is the screen's own width, so it is dragged up and down only
|
|
686
|
+
let dx = isReflowed ? 0 : translation.width - lastDrag.width
|
|
687
|
+
var v = currentView.pan(dx: Float(dx), dy: Float(translation.height - lastDrag.height))
|
|
688
|
+
lastDrag = translation
|
|
689
|
+
// The engine holds the page against the viewport, so no drag opens a blank strip beside
|
|
690
|
+
// it; a dressed page holds its border on the screen too, not only its text.
|
|
691
|
+
if let p = page, p.isOpen { v = p.dressClamp(v, viewportW: Float(bounds.width), viewportH: Float(bounds.height)) }
|
|
692
|
+
viewOx = CGFloat(v.offsetX); viewOy = CGFloat(v.offsetY)
|
|
693
|
+
invalidate()
|
|
694
|
+
}
|
|
695
|
+
/// A sideways drag turns the page whether or not the reader has zoomed in: a reflowed page
|
|
696
|
+
/// has nothing to pan sideways, so the gesture is free to mean this.
|
|
697
|
+
func panEnded(_ t: CGSize, velocity v: CGSize) {
|
|
698
|
+
lastDrag = .zero
|
|
699
|
+
guard !isZoomed || isReflowed, !selecting, onSwipe != nil else { return }
|
|
700
|
+
if let dir = QvpViewPolicy.swipeDirection(translation: t, velocity: v) { onSwipe?(dir) }
|
|
701
|
+
}
|
|
702
|
+
func selectTo(_ pt: CGPoint) {
|
|
703
|
+
guard selectionEnabled, let p = page else { return }
|
|
704
|
+
if !selecting {
|
|
705
|
+
guard let h = hitAt(pt), h.word >= 0 else { return }
|
|
706
|
+
selecting = true; selAnchor = h.word
|
|
707
|
+
p.select(h.word, h.word); paintSelection()
|
|
708
|
+
} else if let h = hitAt(pt, QvpHitOptions()), h.word >= 0 {
|
|
709
|
+
p.select(selAnchor, h.word); paintSelection()
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
func selectEnded() { selecting = false }
|
|
713
|
+
private func paintSelection() {
|
|
714
|
+
guard let p = page, p.isOpen else { return }
|
|
715
|
+
let ws = p.selection()
|
|
716
|
+
let t = Target.words(ws)
|
|
717
|
+
if selectionHandle != 0 { p.moveHighlight(selectionHandle, t) }
|
|
718
|
+
else { selectionHandle = p.highlight(t, QvpHighlightStyle(mode: .band, band: selectionBand, padX: QvpDefaults.SELECTION_PAD_X, layer: QvpLayer.SELECTION)) }
|
|
719
|
+
onSelectionChanged?(ws); invalidate()
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// ── frame (called from the Canvas renderer) ──
|
|
723
|
+
/// One frame. `slice` is this canvas's part of the page when the page is drawn as a stack
|
|
724
|
+
/// of canvases (`QvpPageCanvas.slices`): the ink band is then that slice, cached in the
|
|
725
|
+
/// slice's own slot, and the context arrives translated so the slice's top is y = 0. A pinch
|
|
726
|
+
/// keeps painting its two boxes around the fingers whichever canvas asks — that band is what
|
|
727
|
+
/// keeps a pinch from repainting the whole page at every step the fingers cross.
|
|
728
|
+
func draw(in ctx: GraphicsContext, size: CGSize, displayScale: CGFloat,
|
|
729
|
+
slice: (index: Int, top: CGFloat, height: CGFloat)? = nil, frame: Date? = nil) {
|
|
730
|
+
guard let p = page, p.isOpen else { return }
|
|
731
|
+
if p.currentLayout == nil { relayout() }
|
|
732
|
+
guard let l = p.currentLayout else { return }
|
|
733
|
+
let inputs = frameInputs(p, frame: frame)
|
|
734
|
+
let moving = inputs.moving
|
|
735
|
+
let paths = p.buildPaths()
|
|
736
|
+
let styled = inputs.styled
|
|
737
|
+
let styledSet = inputs.styledSet
|
|
738
|
+
let ink = p.defaultInk
|
|
739
|
+
// Up, like the band's height: truncated, a width a hair under a whole pixel lost that
|
|
740
|
+
// pixel, and the bitmap came out one column short of the canvas it is drawn across.
|
|
741
|
+
let W = Int((size.width * displayScale).rounded(.up))
|
|
742
|
+
// The styled set is not in the key: the cache entry keeps it, so a reveal can add to the
|
|
743
|
+
// image rather than start it again (`BaseCache`).
|
|
744
|
+
var hasher = Hasher(); hasher.combine(l.lineDy)
|
|
745
|
+
// The cached ink is a band of the page, not the screen, so a drag inside it is one blit
|
|
746
|
+
// and nothing is drawn again. A slice's band is the slice, in page points: the canvas
|
|
747
|
+
// shows page row `y - viewOy` at canvas row `y`.
|
|
748
|
+
let sliced = isPinching ? nil : slice
|
|
749
|
+
let slot = sliced?.index ?? 0
|
|
750
|
+
let (top, bandH) = sliced.map { ($0.top - viewOy, $0.height) } ?? band(displayScale: displayScale)
|
|
751
|
+
let band = layoutBand(top: top, height: bandH)
|
|
752
|
+
let bandPx = Int((bandH * displayScale).rounded(.up))
|
|
753
|
+
let key = "\(viewScale)|\(viewOx)|\(top)|\(ink)|\(l.lineSpacing)|\(l.scale)|\(hasher.finalize())|\(W)x\(bandPx)|\(zoom.zoom)|\(l.rows)"
|
|
754
|
+
|
|
755
|
+
if let paper = paperColor {
|
|
756
|
+
ctx.fill(Path(p.paperRect(l, scale: viewScale, ox: viewOx, oy: viewOy)),
|
|
757
|
+
with: .color(color(paper)))
|
|
758
|
+
}
|
|
759
|
+
// the ornament layer, behind everything but the paper, under the ink's own transform
|
|
760
|
+
if W > 0, bandPx > 0,
|
|
761
|
+
let layer = ornaments.image(p, slot: slot, key: "\(viewScale)|\(viewOx)|\(top)", width: W, height: bandPx, scale: displayScale,
|
|
762
|
+
transform: { self.transform($0, offsetY: -top) }) {
|
|
763
|
+
ctx.draw(Image(decorative: layer, scale: displayScale),
|
|
764
|
+
in: CGRect(x: 0, y: viewOy + top,
|
|
765
|
+
width: CGFloat(layer.width) / displayScale, height: CGFloat(layer.height) / displayScale))
|
|
766
|
+
}
|
|
767
|
+
let bands = inputs.bands
|
|
768
|
+
drawBoxes(ctx, bands)
|
|
769
|
+
|
|
770
|
+
var img: CGImage?
|
|
771
|
+
if W > 0, bandPx > 0, let q = drawListNow(band: band) {
|
|
772
|
+
let t0 = now()
|
|
773
|
+
if let entry = cache.entry(slot: slot), entry.key == key,
|
|
774
|
+
entry.image.width == W, entry.image.height == bandPx, styledSet.isSubset(of: entry.styled) {
|
|
775
|
+
if entry.styled == styledSet {
|
|
776
|
+
img = entry.image
|
|
777
|
+
} else {
|
|
778
|
+
// Only a reveal: the paths that left the styled set join the ink in hand. Same
|
|
779
|
+
// colour over the same transparent ground, so the order they land in does not
|
|
780
|
+
// change the pixels beyond a rounding step.
|
|
781
|
+
let revealed = entry.styled.subtracting(styledSet)
|
|
782
|
+
let joining = q.draws.filter { revealed.contains($0.path) }
|
|
783
|
+
img = joining.isEmpty ? entry.image
|
|
784
|
+
: rasterizeBase(W: W, bandPx: bandPx, displayScale: displayScale, over: entry.image,
|
|
785
|
+
draws: joining, q: q, paths: paths, page: p, ink: ink, top: top)
|
|
786
|
+
if let img { cache.store(img, key: key, styled: styledSet, slot: slot) }
|
|
787
|
+
lastBaseMs = (now() - t0) * 1000; lastBasePaths = joining.count
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
if img == nil {
|
|
791
|
+
img = rasterizeBase(W: W, bandPx: bandPx, displayScale: displayScale, over: nil,
|
|
792
|
+
draws: q.draws.filter { !styledSet.contains($0.path) },
|
|
793
|
+
q: q, paths: paths, page: p, ink: ink, top: top)
|
|
794
|
+
if let img { cache.store(img, key: key, styled: styledSet, slot: slot) }
|
|
795
|
+
lastBaseMs = (now() - t0) * 1000
|
|
796
|
+
lastBasePaths = q.draws.count - q.draws.filter { styledSet.contains($0.path) }.count
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
if let img {
|
|
800
|
+
// At the bitmap's own size, never stretched to the band: the bitmap is whole pixels,
|
|
801
|
+
// rounded up, and one drawn a fraction of a pixel away from its size is resampled —
|
|
802
|
+
// every row down the band a blend of two, the softness this canvas exists to avoid.
|
|
803
|
+
ctx.draw(Image(decorative: img, scale: displayScale),
|
|
804
|
+
in: CGRect(x: 0, y: viewOy + top,
|
|
805
|
+
width: CGFloat(img.width) / displayScale, height: CGFloat(img.height) / displayScale))
|
|
806
|
+
}
|
|
807
|
+
let t1 = now()
|
|
808
|
+
if let q = drawListNow(band: band) {
|
|
809
|
+
let colors = inputs.colors
|
|
810
|
+
for d in q.draws {
|
|
811
|
+
guard let col = colors[d.path], col & 0xff != 0 else { continue }
|
|
812
|
+
var c = ctx
|
|
813
|
+
c.concatenate(transform(q, d.placement))
|
|
814
|
+
c.fill(Path(paths[d.path]), with: .color(color(col)), style: FillStyle(eoFill: p.pathEvenOdd(d.path)))
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
drawBoxes(ctx, inputs.masks)
|
|
818
|
+
lastOverlayMs = (now() - t1) * 1000; lastOverlayPaths = styled.count; lastBands = bands.count
|
|
819
|
+
if moving != animating {
|
|
820
|
+
// Ask the engine again at the hop rather than trusting this frame: a transition begun
|
|
821
|
+
// in between must not be paused by a stale "finished".
|
|
822
|
+
Task { @MainActor [weak self] in if let self, self.syncAnimating() { self.revision &+= 1 } }
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
/// A band of the page's default ink as a bitmap: `draws` filled in the ink colour, on a clear
|
|
826
|
+
/// ground or over `base`, a bitmap of the same band this adds to. `base` is copied in pixel
|
|
827
|
+
/// for pixel — no resampling, no blending — so what was drawn stays exactly as it was.
|
|
828
|
+
private func rasterizeBase(W: Int, bandPx: Int, displayScale: CGFloat, over base: CGImage?,
|
|
829
|
+
draws: [QvpDraw], q: DrawList, paths: [CGPath], page p: QvpPage,
|
|
830
|
+
ink: UInt32, top: CGFloat) -> CGImage? {
|
|
831
|
+
let cs = CGColorSpaceCreateDeviceRGB()
|
|
832
|
+
guard let bc = CGContext(data: nil, width: W, height: bandPx, bitsPerComponent: 8, bytesPerRow: 0, space: cs,
|
|
833
|
+
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)
|
|
834
|
+
else { return nil }
|
|
835
|
+
if let base {
|
|
836
|
+
bc.interpolationQuality = .none; bc.setBlendMode(.copy)
|
|
837
|
+
bc.draw(base, in: CGRect(x: 0, y: 0, width: W, height: bandPx))
|
|
838
|
+
bc.setBlendMode(.normal)
|
|
839
|
+
}
|
|
840
|
+
// flip to y-down page space so `makeImage()` comes out upright
|
|
841
|
+
bc.translateBy(x: 0, y: CGFloat(bandPx)); bc.scaleBy(x: displayScale, y: -displayScale)
|
|
842
|
+
bc.setFillColor(QvpColor.cgColor(ink))
|
|
843
|
+
bc.setAllowsAntialiasing(true); bc.setShouldAntialias(true)
|
|
844
|
+
var cur = -1
|
|
845
|
+
for d in draws {
|
|
846
|
+
// one state per placement, not per path: the list runs in that order
|
|
847
|
+
// the band is drawn under its own vertical offset: its top row is `top`
|
|
848
|
+
if d.placement != cur { if cur >= 0 { bc.restoreGState() }; bc.saveGState(); bc.concatenate(transform(q, d.placement, offsetY: -top)); cur = d.placement }
|
|
849
|
+
bc.addPath(paths[d.path]); bc.fillPath(using: p.pathEvenOdd(d.path) ? .evenOdd : .winding)
|
|
850
|
+
}
|
|
851
|
+
if cur >= 0 { bc.restoreGState() }
|
|
852
|
+
return bc.makeImage()
|
|
853
|
+
}
|
|
854
|
+
private func drawBoxes(_ ctx: GraphicsContext, _ boxes: [QvpBox]) {
|
|
855
|
+
if boxes.isEmpty { return }
|
|
856
|
+
var c = ctx
|
|
857
|
+
c.concatenate(CGAffineTransform(a: viewScale, b: 0, c: 0, d: viewScale, tx: viewOx, ty: viewOy))
|
|
858
|
+
var path = Path(), curColor: UInt32 = 0, curId = Int.min
|
|
859
|
+
func flush() { if !path.isEmpty { c.fill(path, with: .color(color(curColor))) }; path = Path() }
|
|
860
|
+
for b in boxes {
|
|
861
|
+
if b.id != curId || b.color != curColor { flush(); curId = b.id; curColor = b.color }
|
|
862
|
+
let r = CGRect(x: CGFloat(b.x0), y: CGFloat(b.y0), width: CGFloat(b.x1 - b.x0), height: CGFloat(b.y1 - b.y0))
|
|
863
|
+
if b.radius > 0 { path.addRoundedRect(in: r, cornerSize: CGSize(width: CGFloat(b.radius), height: CGFloat(b.radius))) }
|
|
864
|
+
else { path.addRect(r) }
|
|
865
|
+
}
|
|
866
|
+
flush()
|
|
867
|
+
}
|
|
868
|
+
private func color(_ rgba: UInt32) -> Color {
|
|
869
|
+
let c = QvpColor.components(rgba)
|
|
870
|
+
return Color(red: c.r, green: c.g, blue: c.b, opacity: c.a)
|
|
871
|
+
}
|
|
872
|
+
private func now() -> Double { Double(DispatchTime.now().uptimeNanoseconds) / 1e9 }
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
/// SwiftUI canvas over a `QvpCanvasController`. Give it a size (it fills what it is given),
|
|
876
|
+
/// set `controller.page`, and wire the controller's callbacks.
|
|
877
|
+
@available(iOS 17.0, macOS 14.0, *)
|
|
878
|
+
public struct QvpPageCanvas: View {
|
|
879
|
+
@Bindable private var controller: QvpCanvasController
|
|
880
|
+
@Environment(\.displayScale) private var displayScale
|
|
881
|
+
/// The order in which SwiftUI created this canvas. The controller ignores sizes from a canvas
|
|
882
|
+
/// that a newer canvas replaced.
|
|
883
|
+
@State private var order = QvpCanvasOrder.next()
|
|
884
|
+
|
|
885
|
+
public init(controller: QvpCanvasController) { self.controller = controller }
|
|
886
|
+
|
|
887
|
+
/// The tallest a canvas may be, in device pixels. Core Animation rasterizes a layer past this
|
|
888
|
+
/// to fit and stretches it back on screen, so everything on it goes soft — a surah name reads
|
|
889
|
+
/// as bold. A page reflowed to its top step on a phone is ~8,500 px tall. Measured on an
|
|
890
|
+
/// iPhone 17 Pro: a page at 8,228 px blurred, one at 8,181 px did not.
|
|
891
|
+
static let maxLayerPixels: CGFloat = 8192
|
|
892
|
+
/// The page cut into canvases no taller than `maxLayerPixels` — near equal, so none sits at
|
|
893
|
+
/// the limit. One slice, the page itself, for any page that fits.
|
|
894
|
+
///
|
|
895
|
+
/// Every cut is on a whole device pixel. SwiftUI lays each canvas on the pixel grid, while a
|
|
896
|
+
/// canvas draws its slice from the exact `top`: a cut between two pixels drew the canvas
|
|
897
|
+
/// below up to half a pixel off the one above — a step in every stroke crossing the seam.
|
|
898
|
+
/// Each cut is rounded UP: a slice stays within a pixel of its share, and a whole number of
|
|
899
|
+
/// pixels under one more than a share that is itself at most the limit never crosses it.
|
|
900
|
+
static func slices(height: CGFloat, displayScale: CGFloat) -> [(top: CGFloat, height: CGFloat)] {
|
|
901
|
+
let scale = max(displayScale, 1)
|
|
902
|
+
let maxPoints = maxLayerPixels / scale
|
|
903
|
+
guard height > maxPoints else { return [(top: 0, height: height)] }
|
|
904
|
+
let n = Int((height / maxPoints).rounded(.up))
|
|
905
|
+
let cuts = (0...n).map { i -> CGFloat in
|
|
906
|
+
i == 0 ? 0 : i == n ? height : (height * CGFloat(i) / CGFloat(n) * scale).rounded(.up) / scale
|
|
907
|
+
}
|
|
908
|
+
return (0..<n).map { (top: cuts[$0], height: cuts[$0 + 1] - cuts[$0]) }
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
public var body: some View {
|
|
912
|
+
// read the observable state the renderer depends on, so the canvas redraws on it
|
|
913
|
+
let _ = controller.revision
|
|
914
|
+
let _ = controller.viewScale; let _ = controller.viewOx; let _ = controller.viewOy
|
|
915
|
+
GeometryReader { geo in
|
|
916
|
+
// A page taller than a layer may be is drawn as a stack of canvases, each drawing
|
|
917
|
+
// the same frame translated to its own slice; one canvas, the page, otherwise.
|
|
918
|
+
let slices = Self.slices(height: geo.size.height, displayScale: displayScale)
|
|
919
|
+
TimelineView(.animation(minimumInterval: nil, paused: !controller.animating)) { timeline in
|
|
920
|
+
VStack(spacing: 0) {
|
|
921
|
+
ForEach(slices.indices, id: \.self) { i in
|
|
922
|
+
let slice = slices[i]
|
|
923
|
+
Canvas(opaque: false, rendersAsynchronously: false) { ctx, size in
|
|
924
|
+
// The renderer reads the frame's date so every timeline tick is a different
|
|
925
|
+
// canvas to SwiftUI. A renderer that captured only the controller looked
|
|
926
|
+
// unchanged tick to tick, and on device a running transition drew no frames.
|
|
927
|
+
_ = timeline.date
|
|
928
|
+
var c = ctx
|
|
929
|
+
c.translateBy(x: 0, y: -slice.top)
|
|
930
|
+
// Each canvas paints only its own rows. The frame fills paper,
|
|
931
|
+
// highlights and masks for the whole page, and a Canvas is clipped to
|
|
932
|
+
// its frame on screen but not in an `ImageRenderer` snapshot, where the
|
|
933
|
+
// canvas below would paint its paper over the ink of the one above.
|
|
934
|
+
if slices.count > 1 {
|
|
935
|
+
c.clip(to: Path(CGRect(x: 0, y: slice.top, width: size.width, height: slice.height)))
|
|
936
|
+
}
|
|
937
|
+
controller.draw(in: c, size: CGSize(width: size.width, height: geo.size.height),
|
|
938
|
+
displayScale: displayScale,
|
|
939
|
+
slice: slices.count > 1 ? (index: i, top: slice.top, height: slice.height) : nil,
|
|
940
|
+
frame: timeline.date)
|
|
941
|
+
}
|
|
942
|
+
.frame(height: slice.height)
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
// `invalidate()` is this view's setNeedsDisplay(). Engine calls the controller cannot
|
|
947
|
+
// see (mask, reveal, style) leave SwiftUI nothing to diff, and on iOS a bumped revision
|
|
948
|
+
// alone did not repaint a canvas whose timeline was paused. A new identity per revision
|
|
949
|
+
// always repaints; `.identity` keeps the swap from fading inside an animated transaction.
|
|
950
|
+
.id(controller.revision)
|
|
951
|
+
.transition(.identity)
|
|
952
|
+
}
|
|
953
|
+
// The size comes from the GeometryReader. Its identity does not change. The view inside
|
|
954
|
+
// gets a new identity at each redraw, so a size change in the same update did not reach
|
|
955
|
+
// its onAppear or its onChange, and the page kept the layout of its old size.
|
|
956
|
+
.onGeometryChange(for: CGSize.self) { $0.size } action: { controller.setBounds($0, fromCanvas: order) }
|
|
957
|
+
.contentShape(Rectangle())
|
|
958
|
+
.gesture(SpatialTapGesture(count: 2).onEnded { v in controller.doubleTap(v.location) }
|
|
959
|
+
.exclusively(before: SpatialTapGesture().onEnded { v in controller.tap(v.location) }))
|
|
960
|
+
.gesture(MagnifyGesture()
|
|
961
|
+
.onChanged { v in controller.pinch(v.magnification, at: v.startLocation) }
|
|
962
|
+
.onEnded { _ in controller.pinchEnded() },
|
|
963
|
+
including: controller.zoomEnabled ? .all : .subviews)
|
|
964
|
+
// detached at the fitted size when `onSwipe` is nil, so an enclosing pager keeps its swipe
|
|
965
|
+
.highPriorityGesture(DragGesture(minimumDistance: 12)
|
|
966
|
+
.onChanged { v in controller.pan(v.translation) }
|
|
967
|
+
.onEnded { v in controller.panEnded(v.translation, velocity: v.velocity) },
|
|
968
|
+
including: !controller.hostScrolls && (controller.isZoomed || controller.onSwipe != nil) ? .all : .subviews)
|
|
969
|
+
.gesture(LongPressGesture(minimumDuration: 0.35)
|
|
970
|
+
.sequenced(before: DragGesture(minimumDistance: 0))
|
|
971
|
+
.onChanged { v in if case .second(true, let drag) = v, let d = drag { controller.selectTo(d.location) } }
|
|
972
|
+
.onEnded { _ in controller.selectEnded() },
|
|
973
|
+
including: controller.selectionEnabled ? .all : .subviews)
|
|
974
|
+
.modifier(QvpLongPressAttachment(controller: controller))
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
/// Gives each canvas a number that increases in the order SwiftUI creates them.
|
|
979
|
+
@MainActor
|
|
980
|
+
enum QvpCanvasOrder {
|
|
981
|
+
private static var last = 0
|
|
982
|
+
static func next() -> Int {
|
|
983
|
+
last += 1
|
|
984
|
+
return last
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/// Attaches the long-press recognizer only when a host asked for the callback and
|
|
989
|
+
/// selection does not own the gesture.
|
|
990
|
+
@available(iOS 17.0, macOS 14.0, *)
|
|
991
|
+
private struct QvpLongPressAttachment: ViewModifier {
|
|
992
|
+
let controller: QvpCanvasController
|
|
993
|
+
|
|
994
|
+
func body(content: Content) -> some View {
|
|
995
|
+
#if canImport(UIKit)
|
|
996
|
+
if #available(iOS 18.0, *), controller.onLongPress != nil, !controller.selectionEnabled {
|
|
997
|
+
content.gesture(QvpLongPressRecognizer(duration: controller.longPressDuration) { controller.longPress($0) })
|
|
998
|
+
} else {
|
|
999
|
+
content
|
|
1000
|
+
}
|
|
1001
|
+
#else
|
|
1002
|
+
content
|
|
1003
|
+
#endif
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
#if canImport(UIKit)
|
|
1008
|
+
/// UIKit's long-press: it knows where the finger is at recognition (SwiftUI's
|
|
1009
|
+
/// `LongPressGesture` does not) and fails on movement, so a pager's pan is never taken.
|
|
1010
|
+
@available(iOS 18.0, *)
|
|
1011
|
+
private struct QvpLongPressRecognizer: UIGestureRecognizerRepresentable {
|
|
1012
|
+
let duration: Double
|
|
1013
|
+
let action: (CGPoint) -> Void
|
|
1014
|
+
|
|
1015
|
+
func makeUIGestureRecognizer(context: Context) -> UILongPressGestureRecognizer {
|
|
1016
|
+
let recognizer = UILongPressGestureRecognizer()
|
|
1017
|
+
recognizer.minimumPressDuration = duration
|
|
1018
|
+
return recognizer
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
func updateUIGestureRecognizer(_ recognizer: UILongPressGestureRecognizer, context: Context) {
|
|
1022
|
+
recognizer.minimumPressDuration = duration
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
func handleUIGestureRecognizerAction(_ recognizer: UILongPressGestureRecognizer, context: Context) {
|
|
1026
|
+
guard recognizer.state == .began else { return }
|
|
1027
|
+
action(context.converter.localLocation)
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
#endif
|
|
1031
|
+
#endif
|