@quran.ws/qvp-react-native 0.8.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 +78 -35
- package/android/build.gradle +16 -8
- package/android/src/main/java/ws/quran/qvp/rn/QvpModule.kt +1 -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/index.tsx +86 -10
|
@@ -0,0 +1,711 @@
|
|
|
1
|
+
#if canImport(UIKit)
|
|
2
|
+
import UIKit
|
|
3
|
+
import QuartzCore
|
|
4
|
+
|
|
5
|
+
/// Host-canvas renderer for a `QvpPage` (CoreGraphics). Draw order per frame:
|
|
6
|
+
/// a dress's ornament layer (cached per dress revision and view transform) → highlight bands (one path per highlight id, nonzero, behind the ink) → cached base ink
|
|
7
|
+
/// (a bitmap of every non-styled path at the current transform, rebuilt only when the styled
|
|
8
|
+
/// set / layout / transform changes) → styled ink from `styledPaths()` → mask boxes.
|
|
9
|
+
/// Each frame calls `page.tick(now)`; a CADisplayLink keeps running while the engine says so.
|
|
10
|
+
/// Gestures: tap → gap-aware hit-test → `onWordTap` / `onDecorationTap` / `onEmptyTap`; long-press +
|
|
11
|
+
/// drag → whole-word selection (engine `select`, band in the selection layer); pinch / pan on
|
|
12
|
+
/// top of the engine layout; double-tap resets the view (or runs `onDoubleTap` when set).
|
|
13
|
+
/// After `page.dress(...)` or `page.undress()`, call `resetView()`: a dressed page is fitted
|
|
14
|
+
/// with its border.
|
|
15
|
+
public final class QvpPageView: UIView, UIGestureRecognizerDelegate, UIScrollViewDelegate {
|
|
16
|
+
public var page: QvpPage? {
|
|
17
|
+
didSet {
|
|
18
|
+
base = nil; baseKey = ""; selectionHandle = 0; drawList = nil; ornaments.clear()
|
|
19
|
+
// A step means the same size to the reader on any page: the engine chose every
|
|
20
|
+
// page's steps so the ink barely changes across a turn. So the step carries over,
|
|
21
|
+
// and the new page says what it means. Carrying the size instead and rounding it to
|
|
22
|
+
// the new page's steps loses a step on every turn, because a step that sits a
|
|
23
|
+
// little higher on the next page rounds down.
|
|
24
|
+
if let p = page, p.isOpen, bounds.width > 0 { zoom = p.zoomCarried(baseSpec, zoom) }
|
|
25
|
+
relayout(); resetView(); invalidateContent()
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
// layout knobs (viewport size comes from the view)
|
|
29
|
+
public var padTop: CGFloat = 0 { didSet { relayout() } }
|
|
30
|
+
public var padBottom: CGFloat = 0 { didSet { relayout() } }
|
|
31
|
+
public var padSide: CGFloat = 0 { didSet { relayout() } }
|
|
32
|
+
public var lineSpacing: Float = 1 { didSet { relayout() } }
|
|
33
|
+
public var fillHeight = false { didSet { relayout() } }
|
|
34
|
+
/// Draw source-native frames around surah names on the printed page.
|
|
35
|
+
public var surahFrames = true { didSet { guard oldValue != surahFrames else { return }; relayout() } }
|
|
36
|
+
/// How the words are broken onto rows as the reader zooms in.
|
|
37
|
+
public var reflowBreaks: QvpBreaks = .fitted { didSet { guard oldValue != reflowBreaks else { return }; relayout() } }
|
|
38
|
+
/// Paper behind the page content (nil = transparent).
|
|
39
|
+
public var paperColor: UIColor? { didSet { invalidateContent() } }
|
|
40
|
+
/// 0xRRGGBBAA band colour of the drag selection.
|
|
41
|
+
public var selectionBand: UInt32 = QvpDefaults.SELECTION_BAND
|
|
42
|
+
public var onWordTap: ((QvpWord, QvpHit) -> Void)?
|
|
43
|
+
public var onDecorationTap: ((QvpDecoration, QvpHit) -> Void)?
|
|
44
|
+
public var onEmptyTap: (() -> Void)?
|
|
45
|
+
public var onSelectionChanged: (([Int]) -> Void)?
|
|
46
|
+
/// A sideways flick, in pages: +1 the page after this one, -1 the page before it. The
|
|
47
|
+
/// muṣḥaf's own order, so a host adds it to the page it is on.
|
|
48
|
+
public var onSwipe: ((Int) -> Void)?
|
|
49
|
+
/// The size the reader is at changed: a pinch committed, or a step was asked for.
|
|
50
|
+
public var onZoomChanged: ((QvpZoom) -> Void)?
|
|
51
|
+
/// Double-tap. nil (the default) resets the view; a host that repurposes the gesture
|
|
52
|
+
/// (e.g. marking reading progress) can still call `resetView()` itself — `isZoomed` says when.
|
|
53
|
+
public var onDoubleTap: ((QvpHit?) -> Void)?
|
|
54
|
+
/// Long-press, with the gap-aware hit under the finger. Fires once, on recognition,
|
|
55
|
+
/// only while `selectionEnabled` is false — selection owns the long-press otherwise.
|
|
56
|
+
public var onLongPress: ((QvpHit?) -> Void)?
|
|
57
|
+
public var longPressDuration: Double = 0.35 { didSet { longPressRecognizer?.minimumPressDuration = longPressDuration } }
|
|
58
|
+
private weak var longPressRecognizer: UILongPressGestureRecognizer?
|
|
59
|
+
public var zoomEnabled = true
|
|
60
|
+
/// Zoom lasts only while the fingers are down: on release the page eases back to its fitted
|
|
61
|
+
/// size — a peek, not a reading zoom — so a pinch never leaves the page holding the pan.
|
|
62
|
+
public var zoomSpringsBack = false
|
|
63
|
+
/// How far the magnifying glass may go — the ceiling the pinch is clamped to under
|
|
64
|
+
/// `.magnify`, `QvpViewPolicy.maxZoom` unless the host lowers it. A host that draws its own
|
|
65
|
+
/// furniture beside the ink and scales it with the glass says here what that furniture can
|
|
66
|
+
/// survive; the engine's own ink costs the same at any size.
|
|
67
|
+
public var maxZoom: CGFloat = QvpViewPolicy.maxZoom
|
|
68
|
+
/// How far the glass is over the fitted page: `viewScale` over the fitted scale — 1 at
|
|
69
|
+
/// rest and in every mode but `.magnify`. A host overlay divides this out of the view
|
|
70
|
+
/// transform to draw its furniture once and let the glass scale that one raster.
|
|
71
|
+
public var peekScale: CGFloat { fitScale > 0 ? viewScale / fitScale : 1 }
|
|
72
|
+
/// What a pinch does to the page. `.stepped` is what a reader gets: the pinch lands on one
|
|
73
|
+
/// of the page's own zoom steps and the page breaks its rows again at that size. `.magnify`
|
|
74
|
+
/// scales the printed page instead. The engine owns the behaviour; this picks which.
|
|
75
|
+
public var zoomMode: QvpZoomMode = .stepped {
|
|
76
|
+
didSet {
|
|
77
|
+
guard let p = page, p.isOpen, oldValue != zoomMode else { return }
|
|
78
|
+
zoom = p.zoomMode(baseSpec, zoom, zoomMode); relayout(); resetView()
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/// Where the reader's zoom control stands, as the engine last answered.
|
|
82
|
+
public private(set) var zoom = QvpZoom()
|
|
83
|
+
/// The zoom steps this page ships with: what `.stepped` lands on, lowest first.
|
|
84
|
+
public var zoomSteps: [Float] { page.map { $0.isOpen && bounds.width > 0 ? $0.zoomSteps(baseSpec) : [] } ?? [] }
|
|
85
|
+
/// Scroll the page by `dy` points, held against the viewport: what a reflowed page, which
|
|
86
|
+
/// is taller than the screen, is read with.
|
|
87
|
+
public func scroll(by dy: CGFloat) {
|
|
88
|
+
guard let p = page, p.isOpen, p.currentLayout != nil else { return }
|
|
89
|
+
// a dressed page holds its border on the screen too, not only its text
|
|
90
|
+
let v = p.dressClamp(currentView.pan(dx: 0, dy: Float(dy)), viewportW: Float(bounds.width), viewportH: Float(bounds.height))
|
|
91
|
+
viewOx = CGFloat(v.offsetX); viewOy = CGFloat(v.offsetY)
|
|
92
|
+
refresh()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// Move the control straight to a step. 0 is the printed page.
|
|
96
|
+
///
|
|
97
|
+
/// A step asked for before the view has a size is remembered and taken as soon as it has
|
|
98
|
+
/// one, so a host can set the reader's size while building the screen.
|
|
99
|
+
public func zoomToStep(_ step: Int) {
|
|
100
|
+
guard let p = page, p.isOpen, bounds.width > 0, bounds.height > 0 else { pendingStep = step; return }
|
|
101
|
+
pendingStep = nil
|
|
102
|
+
apply(p.zoomToStep(layoutSpec, zoom, step, currentView))
|
|
103
|
+
}
|
|
104
|
+
private var pendingStep: Int?
|
|
105
|
+
public var selectionEnabled = true
|
|
106
|
+
public var hitOptions = QvpHitOptions(maxDistance: QvpDefaults.TAP_DISTANCE)
|
|
107
|
+
|
|
108
|
+
public private(set) var viewScale: CGFloat = 1
|
|
109
|
+
public private(set) var viewOx: CGFloat = 0
|
|
110
|
+
public private(set) var viewOy: CGFloat = 0
|
|
111
|
+
// stats for a HUD
|
|
112
|
+
public private(set) var lastBaseMs = 0.0, lastOverlayMs = 0.0, lastHitUs = 0.0
|
|
113
|
+
public private(set) var lastBasePaths = 0, lastOverlayPaths = 0, lastBands = 0
|
|
114
|
+
public private(set) var animating = false
|
|
115
|
+
|
|
116
|
+
private var base: CGImage?
|
|
117
|
+
private var baseKey = ""
|
|
118
|
+
/// The band of page content, as one image in a layer of its own. Scrolling moves the layer
|
|
119
|
+
/// and draws nothing: the reader's finger only changes where the band sits on screen.
|
|
120
|
+
private let contentLayer = CALayer()
|
|
121
|
+
/// A reflowed page is taller than the screen, so the platform's own scroll view carries it:
|
|
122
|
+
/// the reader gets the deceleration, the rubber band at the ends and the indicator they get
|
|
123
|
+
/// everywhere else on the phone, and the band layer is moved by the compositor rather than
|
|
124
|
+
/// by us. It is `contentHost` that the band sits in, and the scroll view that moves it.
|
|
125
|
+
private let scroller = UIScrollView()
|
|
126
|
+
private let contentHost = UIView()
|
|
127
|
+
private var selectionHandle = 0
|
|
128
|
+
private var selAnchor = -1
|
|
129
|
+
private var selecting = false
|
|
130
|
+
private var link: CADisplayLink?
|
|
131
|
+
private var spring: QvpZoomSpring?
|
|
132
|
+
private var springLink: CADisplayLink?
|
|
133
|
+
private var pinchZoom = QvpZoom()
|
|
134
|
+
/// The view the engine works from in a pinch: the one the pinch began on, and under the
|
|
135
|
+
/// reflowing controls the one the last frame returned, before the drift.
|
|
136
|
+
private var pinchView = QvpView()
|
|
137
|
+
/// Where the fingers went down: the point every pinch frame zooms about.
|
|
138
|
+
private var pinchFocal = CGPoint.zero
|
|
139
|
+
/// True while a pinch drives the page. The pan recognizer runs beside the pinch, and the
|
|
140
|
+
/// pinch pans the page by its own drift, so a drag inside it would move the page twice; the
|
|
141
|
+
/// drag stands aside until the fingers lift.
|
|
142
|
+
private var pinching = false
|
|
143
|
+
private var fitScale: CGFloat = 1
|
|
144
|
+
/// True once the reader has zoomed in, by either road: the view magnified past the fitted
|
|
145
|
+
/// size, or the page reflowed to a size above the printed one. The engine decides, so every
|
|
146
|
+
/// platform draws the line in the same place.
|
|
147
|
+
public var isZoomed: Bool { zoom.isZoomed(currentView, fitScale: Float(fitScale)) }
|
|
148
|
+
/// What a sideways drag means here: pan a magnified page, or turn the page.
|
|
149
|
+
private var sideways: QvpSideways {
|
|
150
|
+
page?.sidewaysDrag(zoom, currentView, fitScale: Float(fitScale)) ?? .turnPage
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
public override init(frame: CGRect) { super.init(frame: frame); setup() }
|
|
154
|
+
public required init?(coder: NSCoder) { super.init(coder: coder); setup() }
|
|
155
|
+
private func setup() {
|
|
156
|
+
// the band is taller than the view and hangs past both edges: it is the view that says
|
|
157
|
+
// how much of it the reader sees
|
|
158
|
+
layer.masksToBounds = true
|
|
159
|
+
contentLayer.actions = ["contents": NSNull(), "position": NSNull(), "bounds": NSNull()]
|
|
160
|
+
contentHost.layer.addSublayer(contentLayer)
|
|
161
|
+
scroller.addSubview(contentHost)
|
|
162
|
+
scroller.delegate = self
|
|
163
|
+
scroller.backgroundColor = .clear
|
|
164
|
+
scroller.showsHorizontalScrollIndicator = false
|
|
165
|
+
scroller.isDirectionalLockEnabled = true
|
|
166
|
+
scroller.contentInsetAdjustmentBehavior = .never
|
|
167
|
+
scroller.alwaysBounceVertical = false
|
|
168
|
+
addSubview(scroller)
|
|
169
|
+
isOpaque = false
|
|
170
|
+
backgroundColor = .clear
|
|
171
|
+
contentMode = .redraw
|
|
172
|
+
isMultipleTouchEnabled = true
|
|
173
|
+
let dbl = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap)); dbl.numberOfTapsRequired = 2
|
|
174
|
+
let tap = UITapGestureRecognizer(target: self, action: #selector(onTap)); tap.require(toFail: dbl)
|
|
175
|
+
let pinch = UIPinchGestureRecognizer(target: self, action: #selector(onPinch))
|
|
176
|
+
let pan = UIPanGestureRecognizer(target: self, action: #selector(onPan)); pan.maximumNumberOfTouches = 2
|
|
177
|
+
let long = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress)); long.minimumPressDuration = longPressDuration; longPressRecognizer = long
|
|
178
|
+
pan.require(toFail: long)
|
|
179
|
+
for g in [dbl, tap, pinch, pan, long] { g.delegate = self; addGestureRecognizer(g) }
|
|
180
|
+
// A page turn answers the moment UIKit recognises the swipe, rather than waiting for
|
|
181
|
+
// the finger to lift and reading the drag afterwards.
|
|
182
|
+
for dir in [UISwipeGestureRecognizer.Direction.left, .right] {
|
|
183
|
+
let sw = UISwipeGestureRecognizer(target: self, action: #selector(onSwipeGesture))
|
|
184
|
+
sw.direction = dir
|
|
185
|
+
sw.delegate = self
|
|
186
|
+
addGestureRecognizer(sw)
|
|
187
|
+
// The scroll view waits for the swipe to fail before it scrolls. A swipe fails as
|
|
188
|
+
// soon as the finger is going the other way, so an up-and-down drag loses almost
|
|
189
|
+
// nothing of its start, and a sideways flick is never eaten by the scroll.
|
|
190
|
+
scroller.panGestureRecognizer.require(toFail: sw)
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
deinit { link?.invalidate(); springLink?.invalidate() }
|
|
194
|
+
|
|
195
|
+
public func gestureRecognizer(_ a: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith b: UIGestureRecognizer) -> Bool {
|
|
196
|
+
// The page-turn swipe runs beside the scroll view's drag rather than waiting for it to
|
|
197
|
+
// fail, which would put a hesitation at the start of every scroll. It only answers a
|
|
198
|
+
// quick sideways flick, and the scroll view is locked to the other axis, so the two
|
|
199
|
+
// cannot both mean something.
|
|
200
|
+
if a is UISwipeGestureRecognizer || b is UISwipeGestureRecognizer { return true }
|
|
201
|
+
return (a is UIPinchGestureRecognizer && b is UIPanGestureRecognizer) || (a is UIPanGestureRecognizer && b is UIPinchGestureRecognizer)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
public override func gestureRecognizerShouldBegin(_ g: UIGestureRecognizer) -> Bool {
|
|
205
|
+
// A reflowed page is scrolled by the scroll view, so our own drag stands aside rather
|
|
206
|
+
// than moving the page twice.
|
|
207
|
+
if g is UIPanGestureRecognizer, g !== scroller.panGestureRecognizer, isReflowed { return false }
|
|
208
|
+
return true
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ── gestures ──
|
|
212
|
+
private func hitAt(_ pt: CGPoint, _ o: QvpHitOptions? = nil) -> QvpHit? {
|
|
213
|
+
guard let p = page, p.isOpen else { return nil }
|
|
214
|
+
let t0 = CACurrentMediaTime()
|
|
215
|
+
let at = p.viewToLayout(currentView, Float(pt.x), Float(pt.y))
|
|
216
|
+
let h = p.hitTestView(at.x, at.y, o ?? hitOptions)
|
|
217
|
+
lastHitUs = (CACurrentMediaTime() - t0) * 1e6
|
|
218
|
+
return h
|
|
219
|
+
}
|
|
220
|
+
@objc private func onTap(_ g: UITapGestureRecognizer) {
|
|
221
|
+
guard let p = page else { return }
|
|
222
|
+
let hit = hitAt(g.location(in: self))
|
|
223
|
+
if let h = hit, h.word >= 0 { onWordTap?(p.words[h.word], h) }
|
|
224
|
+
else if let h = hit, h.decoration >= 0 { onDecorationTap?(p.decorations[h.decoration], h) }
|
|
225
|
+
else { onEmptyTap?() }
|
|
226
|
+
}
|
|
227
|
+
@objc private func handleDoubleTap(_ g: UITapGestureRecognizer) { if let cb = onDoubleTap { cb(hitAt(g.location(in: self))) } else { resetView() } }
|
|
228
|
+
@objc private func onPinch(_ g: UIPinchGestureRecognizer) {
|
|
229
|
+
// Set before any early return: a pinch that ends while the reader selects, or with zoom
|
|
230
|
+
// off, must not leave the one-finger drag switched off.
|
|
231
|
+
pinching = zoomEnabled && !selecting && [.began, .changed].contains(g.state)
|
|
232
|
+
// The pinch pans the page by its own drift, so the scroll view's drag stands aside too
|
|
233
|
+
// until the fingers lift. Two drags would move a reflowed page twice.
|
|
234
|
+
if scroller.panGestureRecognizer.isEnabled == pinching { scroller.panGestureRecognizer.isEnabled = !pinching }
|
|
235
|
+
guard zoomEnabled, !selecting else { return }
|
|
236
|
+
if g.state == .began { stopSpring(); pinchZoom = zoom; pinchView = currentView; pinchFocal = g.location(in: self) }
|
|
237
|
+
// A reflowed page is a size the reader chose, not a peek: only a magnifying pinch springs back.
|
|
238
|
+
if zoomSpringsBack, zoomMode == .magnify, [.ended, .cancelled, .failed].contains(g.state) { springBack(); return }
|
|
239
|
+
// A frame needs both fingers: the point between them is what the drift is measured by.
|
|
240
|
+
guard pinching, g.numberOfTouches >= 2 else { return }
|
|
241
|
+
// the fingers' drift since the pinch began: it pans the page, so two fingers drag it
|
|
242
|
+
let f = g.location(in: self)
|
|
243
|
+
let driftX = Float(f.x - pinchFocal.x), driftY = Float(f.y - pinchFocal.y)
|
|
244
|
+
guard let p = page, p.isOpen, zoomMode != .magnify else {
|
|
245
|
+
// The printed page under a magnifying glass: the rows never move. The engine zooms
|
|
246
|
+
// the view the pinch began on about the point it began at, by the whole gesture,
|
|
247
|
+
// with the settled page as the floor and the host's ceiling above, then pans it by
|
|
248
|
+
// the drift and holds it against the viewport.
|
|
249
|
+
var v = pinchView.zoomAbout(focalX: Float(pinchFocal.x), focalY: Float(pinchFocal.y), factor: Float(g.scale), min: Float(fitScale), max: Float(maxZoom))
|
|
250
|
+
.pan(dx: driftX, dy: driftY)
|
|
251
|
+
if let p = page, p.isOpen, p.currentLayout != nil { v = p.dressClamp(v, viewportW: Float(bounds.width), viewportH: Float(bounds.height)) }
|
|
252
|
+
viewScale = CGFloat(v.scale); viewOx = CGFloat(v.offsetX); viewOy = CGFloat(v.offsetY)
|
|
253
|
+
invalidateContent()
|
|
254
|
+
return
|
|
255
|
+
}
|
|
256
|
+
// `pinchZoom` and the focal point stay where the gesture began: the engine measures the
|
|
257
|
+
// fingers against them, so a slow pinch walks the steps one at a time instead of running
|
|
258
|
+
// away. The view is the one the last frame returned, before the drift: a step committed
|
|
259
|
+
// earlier in this gesture moved the page, and the engine finds the word under the
|
|
260
|
+
// fingers on the layout it has now.
|
|
261
|
+
let c = p.zoomPinch(layoutSpec, pinchZoom, pinchView, factor: Float(g.scale), focalX: Float(pinchFocal.x), focalY: Float(pinchFocal.y))
|
|
262
|
+
pinchView = c.view
|
|
263
|
+
var v = c.view.pan(dx: driftX, dy: driftY)
|
|
264
|
+
if p.currentLayout != nil { v = p.dressClamp(v, viewportW: Float(bounds.width), viewportH: Float(bounds.height)) }
|
|
265
|
+
apply(QvpZoomChange(zoom: c.zoom, view: v, relaid: c.relaid))
|
|
266
|
+
}
|
|
267
|
+
@objc private func onPan(_ g: UIPanGestureRecognizer) {
|
|
268
|
+
// The pinch moves the page by its own drift. The drag drops what it counted meanwhile,
|
|
269
|
+
// or the first frame after the pinch would move the page by all of it at once.
|
|
270
|
+
if pinching { g.setTranslation(.zero, in: self); return }
|
|
271
|
+
guard zoomEnabled, !selecting, spring == nil else { return }
|
|
272
|
+
// A reflowed page is the screen's own width and the scroll view owns the one axis it
|
|
273
|
+
// has. A printed page nobody has zoomed is not dragged either: a sideways flick on it
|
|
274
|
+
// turns the page, and that is the swipe recogniser's to answer, not this one's. Both
|
|
275
|
+
// answering it turned two pages at a time.
|
|
276
|
+
guard sideways == .pan else { return }
|
|
277
|
+
let d = g.translation(in: self)
|
|
278
|
+
g.setTranslation(.zero, in: self)
|
|
279
|
+
// The engine moves the view and holds it against the viewport, so no drag opens a blank
|
|
280
|
+
// strip beside the page.
|
|
281
|
+
var v = currentView.pan(dx: Float(d.x), dy: Float(d.y))
|
|
282
|
+
if let p = page, p.isOpen, p.currentLayout != nil { v = p.dressClamp(v, viewportW: Float(bounds.width), viewportH: Float(bounds.height)) }
|
|
283
|
+
viewOx = CGFloat(v.offsetX); viewOy = CGFloat(v.offsetY)
|
|
284
|
+
refresh()
|
|
285
|
+
}
|
|
286
|
+
@objc private func handleLongPress(_ g: UILongPressGestureRecognizer) {
|
|
287
|
+
if !selectionEnabled {
|
|
288
|
+
if g.state == .began { onLongPress?(hitAt(g.location(in: self))) }
|
|
289
|
+
return
|
|
290
|
+
}
|
|
291
|
+
guard let p = page else { return }
|
|
292
|
+
let pt = g.location(in: self)
|
|
293
|
+
switch g.state {
|
|
294
|
+
case .began:
|
|
295
|
+
guard let h = hitAt(pt), h.word >= 0 else { return }
|
|
296
|
+
selecting = true; selAnchor = h.word
|
|
297
|
+
p.select(h.word, h.word); paintSelection()
|
|
298
|
+
case .changed:
|
|
299
|
+
guard selecting, let h = hitAt(pt, QvpHitOptions()), h.word >= 0 else { return }
|
|
300
|
+
p.select(selAnchor, h.word); paintSelection()
|
|
301
|
+
default:
|
|
302
|
+
selecting = false
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
private func paintSelection() {
|
|
306
|
+
guard let p = page else { return }
|
|
307
|
+
let ws = p.selection()
|
|
308
|
+
let t = Target.words(ws)
|
|
309
|
+
if selectionHandle != 0 { p.moveHighlight(selectionHandle, t) }
|
|
310
|
+
else { selectionHandle = p.highlight(t, QvpHighlightStyle(mode: .band, band: selectionBand, padX: QvpDefaults.SELECTION_PAD_X, layer: QvpLayer.SELECTION)) }
|
|
311
|
+
onSelectionChanged?(ws); invalidateContent()
|
|
312
|
+
}
|
|
313
|
+
/// Clear the selection band and the engine selection.
|
|
314
|
+
public func clearSelection() {
|
|
315
|
+
guard let p = page else { return }
|
|
316
|
+
p.clearSelection(); if selectionHandle != 0 { p.removeHighlight(selectionHandle); selectionHandle = 0 }
|
|
317
|
+
onSelectionChanged?([]); invalidateContent()
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ── layout ──
|
|
321
|
+
public override func layoutSubviews() {
|
|
322
|
+
super.layoutSubviews()
|
|
323
|
+
guard bounds.size != lastSize else { return }
|
|
324
|
+
lastSize = bounds.size; relayout(); resetView()
|
|
325
|
+
if let s = pendingStep { zoomToStep(s) }
|
|
326
|
+
invalidateContent()
|
|
327
|
+
}
|
|
328
|
+
private var lastSize = CGSize.zero
|
|
329
|
+
/// The layout the current size and knobs ask for, before the zoom control has its say: the
|
|
330
|
+
/// printed page this view lays out. Kotlin's `QvpPageView.layoutSpec()` is the same spec.
|
|
331
|
+
/// `layoutLineSpacingToFill`, `layoutWastedFraction` and `layoutPrintedHeight` measure it.
|
|
332
|
+
public var baseSpec: QvpLayoutSpec {
|
|
333
|
+
QvpLayoutSpec(viewportW: Float(bounds.width), viewportH: Float(bounds.height), padTop: Float(padTop), padBottom: Float(padBottom), padLeft: Float(padSide), padRight: Float(padSide), lineSpacing: lineSpacing, fillHeight: fillHeight,
|
|
334
|
+
reflow: QvpReflowSpec(zoom: 0, breaks: reflowBreaks), surahFrames: surahFrames)
|
|
335
|
+
}
|
|
336
|
+
/// The spec in force: the knobs above with the reader's zoom control folded in.
|
|
337
|
+
public var layoutSpec: QvpLayoutSpec {
|
|
338
|
+
guard let p = page, p.isOpen else { return baseSpec }
|
|
339
|
+
return p.zoomSpec(baseSpec, zoom)
|
|
340
|
+
}
|
|
341
|
+
/// Recompute the engine layout for the current size / knobs.
|
|
342
|
+
public func relayout() {
|
|
343
|
+
guard let p = page, p.isOpen, bounds.width > 0, bounds.height > 0 else { return }
|
|
344
|
+
let sp = layoutSpec
|
|
345
|
+
p.layout(sp)
|
|
346
|
+
drawList = nil
|
|
347
|
+
baseKey = ""; invalidateContent()
|
|
348
|
+
}
|
|
349
|
+
/// Go back to the fitted view (`fittedView()`).
|
|
350
|
+
public func resetView() {
|
|
351
|
+
stopSpring()
|
|
352
|
+
let f = fittedView()
|
|
353
|
+
viewScale = f.scale; fitScale = f.scale; viewOx = f.offsetX; viewOy = f.offsetY
|
|
354
|
+
invalidateContent()
|
|
355
|
+
}
|
|
356
|
+
/// The transform `resetView()` applies. A printed page takes the layout's fit: the content
|
|
357
|
+
/// plus any dress overflow, shrunk to fit the view and centred. A reflowed page takes scale 1,
|
|
358
|
+
/// centred across, its top at the top.
|
|
359
|
+
private func fittedView() -> QvpZoomSpring.ViewTransform {
|
|
360
|
+
let l = page?.currentLayout
|
|
361
|
+
// The layout's fit already holds a dress's border: the engine fits content plus overflow.
|
|
362
|
+
// A reflowed page is taller than the screen on purpose: fitting its height would undo
|
|
363
|
+
// the size the reader asked for. It opens at its top and the reader scrolls.
|
|
364
|
+
if let l, l.reflowed { return (1, CGFloat(l.fitX), CGFloat(l.fitY)) }
|
|
365
|
+
return (CGFloat(l?.fitScale ?? 1), CGFloat(l?.fitX ?? 0), CGFloat(l?.fitY ?? 0))
|
|
366
|
+
}
|
|
367
|
+
/// How far a dress's border reaches past the laid-out content, in layout px: nil when the
|
|
368
|
+
/// page in hand is not dressed. Only the page in hand: a page drawn ahead is drawn bare.
|
|
369
|
+
private func dressOverflow(_ p: QvpPage) -> DressOverflow? {
|
|
370
|
+
p === page ? p.dressOverflow : nil
|
|
371
|
+
}
|
|
372
|
+
/// Ease from the released transform to the fitted one on a display link of its own.
|
|
373
|
+
private func springBack() {
|
|
374
|
+
let to = fittedView()
|
|
375
|
+
fitScale = to.scale
|
|
376
|
+
spring = QvpZoomSpring(from: (viewScale, viewOx, viewOy), to: to, start: CACurrentMediaTime())
|
|
377
|
+
if springLink == nil { let l = CADisplayLink(target: self, selector: #selector(onSpringFrame)); l.add(to: .main, forMode: .common); springLink = l }
|
|
378
|
+
}
|
|
379
|
+
@objc private func onSpringFrame() {
|
|
380
|
+
guard let s = spring else { stopSpring(); return }
|
|
381
|
+
let (v, done) = s.value(at: CACurrentMediaTime())
|
|
382
|
+
viewScale = v.scale; viewOx = v.offsetX; viewOy = v.offsetY
|
|
383
|
+
invalidateContent()
|
|
384
|
+
if done { stopSpring() }
|
|
385
|
+
}
|
|
386
|
+
private func stopSpring() { spring = nil; springLink?.invalidate(); springLink = nil }
|
|
387
|
+
/// Page units of `line` → view points (engine layout + pan/zoom).
|
|
388
|
+
public func lineTransform(_ line: Int) -> CGAffineTransform {
|
|
389
|
+
let l = page?.currentLayout
|
|
390
|
+
let dy = (l.flatMap { line < $0.lineDy.count ? $0.lineDy[line] : nil }) ?? 0
|
|
391
|
+
return transform(QvpPlacement(dx: 0, dy: dy, kx: 1, ky: 1))
|
|
392
|
+
}
|
|
393
|
+
/// Page units → view points under one placement (engine layout + pan/zoom).
|
|
394
|
+
func transform(_ q: QvpPlacement, offsetY: CGFloat? = nil) -> CGAffineTransform {
|
|
395
|
+
let l = page?.currentLayout
|
|
396
|
+
let ls = CGFloat(l?.scale ?? 1)
|
|
397
|
+
let s = viewScale * ls
|
|
398
|
+
return CGAffineTransform(a: s * CGFloat(q.kx), b: 0, c: 0, d: s * CGFloat(q.ky),
|
|
399
|
+
tx: viewOx + viewScale * (CGFloat(l?.offsetX ?? 0) + CGFloat(q.dx) * ls),
|
|
400
|
+
ty: (offsetY ?? viewOy) + viewScale * (CGFloat(l?.offsetY ?? 0) + CGFloat(q.dy) * ls))
|
|
401
|
+
}
|
|
402
|
+
/// What the layout in hand draws and where: the engine's own answer, read once per layout.
|
|
403
|
+
/// A printed page and a reflowed one come back in the same shape.
|
|
404
|
+
/// `layout` is the engine layout the list was read from: a dress lays the page out again,
|
|
405
|
+
/// and a list from the layout it replaced holds the old placements.
|
|
406
|
+
struct DrawList { let draws: [QvpDraw], places: [QvpPlacement], band: ClosedRange<Float>, layout: QvpLayout? }
|
|
407
|
+
private var drawList: DrawList?
|
|
408
|
+
/// The band of the laid-out page worth drawing: the screen, with a screen of slack either
|
|
409
|
+
/// side so a fast drag has somewhere to go before the next frame asks again.
|
|
410
|
+
/// How much ink to keep ready at once. A page that fits inside this is drawn once — the
|
|
411
|
+
/// parts past both ends of the screen included — and then scrolling never draws again: the
|
|
412
|
+
/// scroll view moves the finished image and the compositor does the rest. A page too tall
|
|
413
|
+
/// for the budget keeps a band of itself instead, two screens tall, which is redrawn when
|
|
414
|
+
/// the reader scrolls out of it.
|
|
415
|
+
///
|
|
416
|
+
/// The whole of a page of this muṣḥaf is about 17 MB at the first zoom step and 44 MB at
|
|
417
|
+
/// the last, on a phone at three pixels to the point.
|
|
418
|
+
public var inkBudget = 64 << 20
|
|
419
|
+
/// How much ink already drawn to keep beside the page in hand, so a page the reader turns
|
|
420
|
+
/// to — or back to — is ready without being drawn again. Two pages' worth by default: the
|
|
421
|
+
/// one before and the one after, which is what a reader moves between.
|
|
422
|
+
public var inkCacheBudget = 2 * (64 << 20)
|
|
423
|
+
/// Ink drawn earlier, most recent first. The key is the page and the size it was drawn at,
|
|
424
|
+
/// so a page kept at one zoom step is not mistaken for the same page at another.
|
|
425
|
+
private var inkCache: [(key: String, image: CGImage, bytes: Int)] = []
|
|
426
|
+
|
|
427
|
+
private func cachedInk(_ key: String) -> CGImage? {
|
|
428
|
+
guard let i = inkCache.firstIndex(where: { $0.key == key }) else { return nil }
|
|
429
|
+
let hit = inkCache.remove(at: i)
|
|
430
|
+
inkCache.insert(hit, at: 0)
|
|
431
|
+
return hit.image
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
private func keepInk(_ key: String, _ image: CGImage) {
|
|
435
|
+
inkCache.removeAll { $0.key == key }
|
|
436
|
+
inkCache.insert((key, image, image.height * image.bytesPerRow), at: 0)
|
|
437
|
+
var total = 0
|
|
438
|
+
inkCache = inkCache.filter { entry in
|
|
439
|
+
total += entry.bytes
|
|
440
|
+
return total <= inkCacheBudget
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/// Draw a page the reader has not reached yet, at the size they are reading, and keep it. A
|
|
445
|
+
/// turn onto that page then shows ink that is already drawn.
|
|
446
|
+
///
|
|
447
|
+
/// This is work, so a host calls it when nothing else is happening — after a turn has
|
|
448
|
+
/// settled, not while one is running.
|
|
449
|
+
public func prepare(_ other: QvpPage) {
|
|
450
|
+
guard other.isOpen, bounds.width > 0, bounds.height > 0, other !== page else { return }
|
|
451
|
+
var z = zoom
|
|
452
|
+
if zoomMode == .stepped, z.step > 0 {
|
|
453
|
+
z = QvpZoom(mode: .stepped, step: min(z.step, other.zoomSteps(baseSpec).count), zoom: 1)
|
|
454
|
+
}
|
|
455
|
+
// a page the reader has not reached opens at its top, which is where it will be drawn
|
|
456
|
+
_ = renderInk(other, z, offsetY: 0)
|
|
457
|
+
}
|
|
458
|
+
/// Where the cached ink starts and how tall it is, for the page and place in hand.
|
|
459
|
+
private var currentBand: (top: CGFloat, height: CGFloat) {
|
|
460
|
+
guard let p = page, p.isOpen, p.currentLayout != nil else { return (0, max(bounds.height, 1)) }
|
|
461
|
+
return band(for: p, offsetY: viewOy, scale: window?.screen.scale ?? contentScaleFactor)
|
|
462
|
+
}
|
|
463
|
+
private var bandTop: CGFloat { currentBand.top }
|
|
464
|
+
private var bandHeight: CGFloat { currentBand.height }
|
|
465
|
+
/// True when the page is broken onto rows of its own and so is taller than the screen.
|
|
466
|
+
private var isReflowed: Bool { page?.currentLayout?.reflowed ?? false }
|
|
467
|
+
/// Where the band sits in the layer that holds it: down the scroll view's content while it
|
|
468
|
+
/// owns the axis, and on the screen itself otherwise.
|
|
469
|
+
private var bandOriginY: CGFloat { isReflowed ? bandTop : viewOy + bandTop }
|
|
470
|
+
/// True while the ink in hand already covers what the reader can see, so a scroll has
|
|
471
|
+
/// nothing to do but let the scroll view move it.
|
|
472
|
+
private var inkCoversScreen: Bool {
|
|
473
|
+
let top = -viewOy, bottom = top + bounds.height
|
|
474
|
+
return bandTop <= top + 0.5 && bandTop + bandHeight >= bottom - 0.5
|
|
475
|
+
}
|
|
476
|
+
/// The same band in layout points: what the engine is asked to draw.
|
|
477
|
+
private var visibleBand: (top: Float, bottom: Float) {
|
|
478
|
+
let s = viewScale == 0 ? 1 : viewScale
|
|
479
|
+
return (Float(bandTop / s), Float((bandTop + bandHeight) / s))
|
|
480
|
+
}
|
|
481
|
+
private func drawListNow() -> DrawList? {
|
|
482
|
+
let b = visibleBand
|
|
483
|
+
if let q = drawList, q.band == b.top...b.bottom, q.layout === page?.currentLayout { return q }
|
|
484
|
+
guard let p = page, p.isOpen, p.currentLayout != nil else { return nil }
|
|
485
|
+
let q = DrawList(draws: p.layoutDrawList(band: b), places: p.layoutPlacements(), band: b.top...b.bottom, layout: p.currentLayout)
|
|
486
|
+
drawList = q; return q
|
|
487
|
+
}
|
|
488
|
+
private func transform(_ q: DrawList, _ placement: Int, offsetY: CGFloat? = nil) -> CGAffineTransform {
|
|
489
|
+
transform(placement < q.places.count ? q.places[placement] : .identity, offsetY: offsetY)
|
|
490
|
+
}
|
|
491
|
+
/// The reader's pan and zoom as the engine has it.
|
|
492
|
+
var currentView: QvpView { QvpView(scale: Float(viewScale), offsetX: Float(viewOx), offsetY: Float(viewOy)) }
|
|
493
|
+
/// Take what a gesture produced: the page is already laid out at the new size, and the view
|
|
494
|
+
/// already holds the word the fingers were on.
|
|
495
|
+
private func apply(_ c: QvpZoomChange) {
|
|
496
|
+
let moved = c.zoom != zoom
|
|
497
|
+
zoom = c.zoom
|
|
498
|
+
if moved { onZoomChanged?(c.zoom) }
|
|
499
|
+
viewScale = CGFloat(c.view.scale); viewOx = CGFloat(c.view.offsetX); viewOy = CGFloat(c.view.offsetY)
|
|
500
|
+
if c.relaid { drawList = nil; baseKey = "" }
|
|
501
|
+
invalidateContent()
|
|
502
|
+
}
|
|
503
|
+
/// Layout viewport px (highlight / mask boxes) → view points.
|
|
504
|
+
private func boxTransform(offsetY: CGFloat) -> CGAffineTransform {
|
|
505
|
+
CGAffineTransform(a: viewScale, b: 0, c: 0, d: viewScale, tx: viewOx, ty: offsetY)
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
private func drawBoxes(_ ctx: CGContext, _ boxes: [QvpBox], offsetY: CGFloat) {
|
|
509
|
+
if boxes.isEmpty { return }
|
|
510
|
+
ctx.saveGState(); ctx.concatenate(boxTransform(offsetY: offsetY))
|
|
511
|
+
var curId = Int.min, curColor: UInt32 = 0, path: CGMutablePath?
|
|
512
|
+
func flush() { if let p = path { ctx.setFillColor(QvpColor.cgColor(curColor)); ctx.addPath(p); ctx.fillPath(using: .winding) }; path = nil }
|
|
513
|
+
for b in boxes {
|
|
514
|
+
if path == nil || b.id != curId || b.color != curColor { flush(); path = CGMutablePath(); curId = b.id; curColor = b.color }
|
|
515
|
+
let r = CGRect(x: CGFloat(b.x0), y: CGFloat(b.y0), width: CGFloat(b.x1 - b.x0), height: CGFloat(b.y1 - b.y0))
|
|
516
|
+
if b.radius > 0 { path!.addRoundedRect(in: r, cornerWidth: min(CGFloat(b.radius), r.width / 2), cornerHeight: min(CGFloat(b.radius), r.height / 2)) } else { path!.addRect(r) }
|
|
517
|
+
}
|
|
518
|
+
flush(); ctx.restoreGState()
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// ── frame ──
|
|
522
|
+
/// The page content is one image in `contentLayer`, covering a band of the page. Scrolling
|
|
523
|
+
/// repositions that layer and draws nothing; everything else rebuilds it.
|
|
524
|
+
public override func draw(_ rect: CGRect) {}
|
|
525
|
+
|
|
526
|
+
/// A host that has changed what the page shows — a style, a highlight, the reveal — says so
|
|
527
|
+
/// the way it says so to any view. The content is drawn again, since this view's drawing is
|
|
528
|
+
/// an image it keeps rather than something UIKit asks it for each time.
|
|
529
|
+
public override func setNeedsDisplay() {
|
|
530
|
+
super.setNeedsDisplay()
|
|
531
|
+
invalidateContent()
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/// The content has changed — a style, the selection, the layout, the page — so the band is
|
|
535
|
+
/// built again.
|
|
536
|
+
private func invalidateContent() { baseKey = ""; refresh() }
|
|
537
|
+
|
|
538
|
+
/// Put the band where the reader is, building it again first if it no longer covers them.
|
|
539
|
+
private func refresh() {
|
|
540
|
+
syncScroller()
|
|
541
|
+
rebuildBand()
|
|
542
|
+
CATransaction.begin(); CATransaction.setDisableActions(true)
|
|
543
|
+
contentLayer.frame = CGRect(x: 0, y: bandOriginY, width: bounds.width, height: bandHeight)
|
|
544
|
+
CATransaction.commit()
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/// Hand the scroll view the page's height, so the reader scrolls the page rather than a
|
|
548
|
+
/// view of it. A page that fits the screen does not scroll at all, and a magnified one is
|
|
549
|
+
/// dragged in both directions by our own pan instead.
|
|
550
|
+
private func syncScroller() {
|
|
551
|
+
scroller.frame = bounds
|
|
552
|
+
let contentH = (page?.currentLayout).map { CGFloat($0.contentH) * viewScale } ?? bounds.height
|
|
553
|
+
let reflowed = isReflowed
|
|
554
|
+
scroller.isScrollEnabled = reflowed
|
|
555
|
+
scroller.showsVerticalScrollIndicator = reflowed
|
|
556
|
+
let size = CGSize(width: bounds.width, height: reflowed ? max(contentH, bounds.height) : bounds.height)
|
|
557
|
+
if scroller.contentSize != size { scroller.contentSize = size }
|
|
558
|
+
// a dressed page's border stands above and below the reflowed rows
|
|
559
|
+
let o = page.flatMap(dressOverflow)
|
|
560
|
+
let inset = reflowed && o != nil ? UIEdgeInsets(top: o!.top * viewScale, left: 0, bottom: o!.bottom * viewScale, right: 0) : .zero
|
|
561
|
+
if scroller.contentInset != inset { scroller.contentInset = inset }
|
|
562
|
+
contentHost.frame = CGRect(origin: .zero, size: size)
|
|
563
|
+
// the reader's place is one number, kept on both sides of it
|
|
564
|
+
if reflowed, !scroller.isDragging, !scroller.isDecelerating, abs(scroller.contentOffset.y + viewOy) > 0.5 {
|
|
565
|
+
scroller.setContentOffset(CGPoint(x: 0, y: -viewOy), animated: false)
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/// The scroll view moved the page: take the reader's place from it and follow with the band.
|
|
570
|
+
public func scrollViewDidScroll(_ sv: UIScrollView) {
|
|
571
|
+
guard isReflowed else { return }
|
|
572
|
+
viewOy = -sv.contentOffset.y
|
|
573
|
+
// The ink is laid out down the scroll view's own content, so the scroll view has already
|
|
574
|
+
// moved it. There is nothing left to do unless the reader has scrolled off the end of
|
|
575
|
+
// what is drawn.
|
|
576
|
+
if inkCoversScreen { return }
|
|
577
|
+
rebuildBand()
|
|
578
|
+
CATransaction.begin(); CATransaction.setDisableActions(true)
|
|
579
|
+
contentLayer.frame = CGRect(x: 0, y: bandOriginY, width: bounds.width, height: bandHeight)
|
|
580
|
+
CATransaction.commit()
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/// A sideways swipe turns the page. The scroll view owns the up-and-down axis and locks the
|
|
584
|
+
/// sideways one, so the gesture is free to mean this whether or not the reader has zoomed in.
|
|
585
|
+
@objc private func onSwipeGesture(_ g: UISwipeGestureRecognizer) {
|
|
586
|
+
guard let cb = onSwipe, !selecting, sideways == .turnPage else { return }
|
|
587
|
+
// the muṣḥaf runs right to left: a flick right is the next page. The engine's own
|
|
588
|
+
// classifier says which, from a drag that stands for the flick.
|
|
589
|
+
let w: CGFloat = g.direction == .right ? 200 : -200
|
|
590
|
+
cb(qvpSwipePages(translation: CGSize(width: w, height: 0), velocity: .zero) ?? 0)
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
private func rebuildBand() {
|
|
594
|
+
guard let p = page, p.isOpen else { contentLayer.contents = nil; return }
|
|
595
|
+
if p.currentLayout == nil { relayout() }
|
|
596
|
+
let moving = p.tick(CACurrentMediaTime() * 1000)
|
|
597
|
+
// a page whose colours are still moving is drawn again on every frame, which is what a
|
|
598
|
+
// fade is, so it is never taken from what was kept
|
|
599
|
+
guard let (key, image) = renderInk(p, zoom, offsetY: viewOy, reuse: !moving) else { return }
|
|
600
|
+
base = image; baseKey = key
|
|
601
|
+
CATransaction.begin(); CATransaction.setDisableActions(true)
|
|
602
|
+
contentLayer.contents = image
|
|
603
|
+
contentLayer.contentsScale = window?.screen.scale ?? contentScaleFactor
|
|
604
|
+
CATransaction.commit()
|
|
605
|
+
setAnimating(moving)
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/// Draw one page's ink, or hand back what was drawn before. `offsetY` is where the reader
|
|
609
|
+
/// stands on it: the band is taken from there.
|
|
610
|
+
@discardableResult
|
|
611
|
+
private func renderInk(_ p: QvpPage, _ z: QvpZoom, offsetY: CGFloat, reuse: Bool = true) -> (String, CGImage)? {
|
|
612
|
+
guard p.isOpen else { return nil }
|
|
613
|
+
let spec = p.zoomSpec(baseSpec, z)
|
|
614
|
+
guard let l = p.currentLayout?.reflowed == (spec.reflow != nil) && p === page ? p.currentLayout : p.layout(spec) else { return nil }
|
|
615
|
+
let styled = p.styledPaths()
|
|
616
|
+
let styledSet = Set(styled.map { $0.path })
|
|
617
|
+
let ink = p.defaultInk
|
|
618
|
+
let scale = window?.screen.scale ?? contentScaleFactor
|
|
619
|
+
let (top, bandH) = band(for: p, offsetY: offsetY, scale: scale)
|
|
620
|
+
let W = Int(bounds.width * scale), bandPx = Int((bandH * scale).rounded(.up))
|
|
621
|
+
guard W > 0, bandPx > 0 else { return nil }
|
|
622
|
+
let bands = p.highlightBoxesView()
|
|
623
|
+
let masks = p.maskBoxesView()
|
|
624
|
+
var hasher = Hasher()
|
|
625
|
+
hasher.combine(styledSet.sorted()); hasher.combine(l.lineDy)
|
|
626
|
+
hasher.combine(bands.map { $0.id }); hasher.combine(masks.map { $0.id })
|
|
627
|
+
// The key holds where the band starts, never where the reader has scrolled to, so a
|
|
628
|
+
// drag inside the band changes nothing.
|
|
629
|
+
// the ornament layer is drawn into the band, so its revision is part of the key
|
|
630
|
+
let dress = p === page ? p.dressInfo() : nil
|
|
631
|
+
let key = "\(p.pageNo)|\(viewScale)|\(viewOx)|\(top)|\(ink)|\(l.lineSpacing)|\(l.scale)|\(hasher.finalize())|\(W)x\(bandPx)|\(z.zoom)|\(l.rows)|\(dress?.revision ?? -1)"
|
|
632
|
+
if reuse, let kept = cachedInk(key) { return (key, kept) }
|
|
633
|
+
|
|
634
|
+
let t0 = CACurrentMediaTime()
|
|
635
|
+
let cs = CGColorSpaceCreateDeviceRGB()
|
|
636
|
+
guard let bc = CGContext(data: nil, width: W, height: bandPx, bitsPerComponent: 8, bytesPerRow: 0, space: cs,
|
|
637
|
+
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)
|
|
638
|
+
else { return nil }
|
|
639
|
+
// flip to UIKit's y-down space, and put the band's own top row at y = 0
|
|
640
|
+
bc.translateBy(x: 0, y: CGFloat(bandPx)); bc.scaleBy(x: scale, y: -scale)
|
|
641
|
+
bc.setAllowsAntialiasing(true); bc.setShouldAntialias(true)
|
|
642
|
+
let off = -top
|
|
643
|
+
if let paper = paperColor {
|
|
644
|
+
bc.setFillColor(paper.cgColor)
|
|
645
|
+
bc.fill(p.paperRect(l, scale: viewScale, ox: viewOx, oy: off))
|
|
646
|
+
}
|
|
647
|
+
// the ornament layer, behind everything but the paper
|
|
648
|
+
if dress != nil, let layer = ornaments.image(p, key: "\(viewScale)|\(viewOx)|\(top)", width: W, height: bandPx, scale: scale,
|
|
649
|
+
transform: { self.transform($0, offsetY: off) }) {
|
|
650
|
+
bc.saveGState()
|
|
651
|
+
bc.translateBy(x: 0, y: CGFloat(bandPx) / scale); bc.scaleBy(x: 1, y: -1)
|
|
652
|
+
bc.draw(layer, in: CGRect(x: 0, y: 0, width: CGFloat(W) / scale, height: CGFloat(bandPx) / scale))
|
|
653
|
+
bc.restoreGState()
|
|
654
|
+
}
|
|
655
|
+
drawBoxes(bc, bands, offsetY: off)
|
|
656
|
+
bc.setFillColor(QvpColor.cgColor(ink))
|
|
657
|
+
let draws = p.layoutDrawList(band: (top: Float(top / max(viewScale, 0.001)), bottom: Float((top + bandH) / max(viewScale, 0.001))))
|
|
658
|
+
let places = p.layoutPlacements()
|
|
659
|
+
let place = { (i: Int) -> QvpPlacement in i < places.count ? places[i] : .identity }
|
|
660
|
+
var cur = -1, n = 0
|
|
661
|
+
for d in draws where !styledSet.contains(d.path) {
|
|
662
|
+
if d.placement != cur { if cur >= 0 { bc.restoreGState() }; bc.saveGState(); bc.concatenate(transform(place(d.placement), offsetY: off)); cur = d.placement }
|
|
663
|
+
bc.addPath(paths(p)[d.path]); bc.fillPath(using: p.pathEvenOdd(d.path) ? .evenOdd : .winding); n += 1
|
|
664
|
+
}
|
|
665
|
+
if cur >= 0 { bc.restoreGState() }
|
|
666
|
+
lastBaseMs = (CACurrentMediaTime() - t0) * 1000; lastBasePaths = n
|
|
667
|
+
let t1 = CACurrentMediaTime()
|
|
668
|
+
cur = -1
|
|
669
|
+
let colors = Dictionary(styled, uniquingKeysWith: { a, _ in a })
|
|
670
|
+
for d in draws {
|
|
671
|
+
guard let col = colors[d.path], col & 0xff != 0 else { continue }
|
|
672
|
+
if d.placement != cur { if cur >= 0 { bc.restoreGState() }; bc.saveGState(); bc.concatenate(transform(place(d.placement), offsetY: off)); cur = d.placement }
|
|
673
|
+
bc.setFillColor(QvpColor.cgColor(col)); bc.addPath(paths(p)[d.path]); bc.fillPath(using: p.pathEvenOdd(d.path) ? .evenOdd : .winding)
|
|
674
|
+
}
|
|
675
|
+
if cur >= 0 { bc.restoreGState() }
|
|
676
|
+
drawBoxes(bc, masks, offsetY: off)
|
|
677
|
+
lastOverlayMs = (CACurrentMediaTime() - t1) * 1000; lastOverlayPaths = styled.count; lastBands = bands.count
|
|
678
|
+
|
|
679
|
+
guard let image = bc.makeImage() else { return nil }
|
|
680
|
+
keepInk(key, image)
|
|
681
|
+
return (key, image)
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/// The band of one page worth drawing, in view points down the page. The engine picks it:
|
|
685
|
+
/// the whole page when it fits, otherwise two screens around the reader, with a top that
|
|
686
|
+
/// moves in steps. Its limits are the bitmap's, in device pixels made points: 16384 rows,
|
|
687
|
+
/// and the ink budget at four bytes a pixel.
|
|
688
|
+
/// The band of a dressed page holds every part of its border on the screen, except under a
|
|
689
|
+
/// screen taller than 16384 rows, where it keeps the page's ink and the top of the border can
|
|
690
|
+
/// be clipped, and this view
|
|
691
|
+
/// draws the border into the same bitmap as the ink, so the band is the bitmap.
|
|
692
|
+
private func band(for p: QvpPage, offsetY: CGFloat, scale: CGFloat) -> (top: CGFloat, height: CGFloat) {
|
|
693
|
+
let s = max(scale, 1)
|
|
694
|
+
let view = QvpView(scale: Float(viewScale), offsetX: Float(viewOx), offsetY: Float(offsetY))
|
|
695
|
+
return p.inkBandPoints(view, viewScale: viewScale, viewportW: bounds.width, viewportH: bounds.height,
|
|
696
|
+
displayScale: scale, maxPixels: CGFloat(inkBudget) / (4 * s * s))
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
private func paths(_ p: QvpPage) -> [CGPath] { p.buildPaths() }
|
|
700
|
+
|
|
701
|
+
/// The dress's ornament layer, drawn once per dress revision, view transform and band.
|
|
702
|
+
private let ornaments = QvpOrnamentRaster()
|
|
703
|
+
|
|
704
|
+
private func setAnimating(_ on: Bool) {
|
|
705
|
+
animating = on
|
|
706
|
+
if on, link == nil { let l = CADisplayLink(target: self, selector: #selector(onFrame)); l.add(to: .main, forMode: .common); link = l }
|
|
707
|
+
if !on, let l = link { l.invalidate(); link = nil }
|
|
708
|
+
}
|
|
709
|
+
@objc private func onFrame() { invalidateContent() }
|
|
710
|
+
}
|
|
711
|
+
#endif
|