1import UIKit
2
3private final class MetalView: UIView {
4 override class var layerClass: AnyClass { CAMetalLayer.self }
5}
6
7/// An offset into the active outline's shown text in UTF-16 units, paragraphs joined by a
8/// newline; collapsed paragraphs are not part of it.
9private final class Position: UITextPosition {
10 let value: Int
11 init(_ value: Int) { self.value = value }
12}
13
14private final class Range: UITextRange {
15 let lo: Int
16 let hi: Int
17 init(_ a: Int, _ b: Int) { (lo, hi) = (min(a, b), max(a, b)) }
18 override var start: UITextPosition { Position(lo) }
19 override var end: UITextPosition { Position(hi) }
20 override var isEmpty: Bool { lo == hi }
21}
22
23private final class SelectionRect: UITextSelectionRect {
24 private let frame: CGRect
25 private let first: Bool
26 private let last: Bool
27 init(_ frame: CGRect, first: Bool, last: Bool) { (self.frame, self.first, self.last) = (frame, first, last) }
28 override var rect: CGRect { frame }
29 override var writingDirection: NSWritingDirection { .leftToRight }
30 override var containsStart: Bool { first }
31 override var containsEnd: Bool { last }
32 override var isVertical: Bool { false }
33}
34
35private extension UITextPosition { var offset: Int { (self as! Position).value } }
36private extension UITextRange {
37 var lower: Int { (self as! Range).lo }
38 var upper: Int { (self as! Range).hi }
39}
40
41/// The page date's fields, from `sb_view_date_request`.
42enum DateField: Int8 {
43 case date, time
44}
45
46/// What a touch lands on; see `sb_view_target`.
47private enum Target: UInt8 {
48 case page, activeText, text, grip
49}
50
51/// Routes the system's undo (shake, three-finger swipe, the keyboard's undo key) to the
52/// canvas's history.
53private final class CanvasUndoManager: UndoManager {
54 weak var canvas: CanvasView?
55 override var canUndo: Bool { canvas?.canUndo(redo: false) ?? false }
56 override var canRedo: Bool { canvas?.canUndo(redo: true) ?? false }
57 override func undo() { canvas?.undo(redo: false) }
58 override func redo() { canvas?.undo(redo: true) }
59}
60
61/// A canvas page: a scroll view whose pan and pinch drive the canvas viewport, with the page
62/// drawn into a Metal layer pinned to the visible bounds, and the active outline's text
63/// behind `UITextInput` so the system keyboard, marked text, autocorrection, dictation, text
64/// interaction, loupe and edit menu work on it.
65final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextInteractionDelegate,
66 UIGestureRecognizerDelegate, UIEditMenuInteractionDelegate,
67 UIPencilInteractionDelegate, UIScribbleInteractionDelegate
68{
69 private struct WeakCanvas { weak var value: CanvasView? }
70 private static var active: [ObjectIdentifier: WeakCanvas] = [:]
71
72 /// Tears down every live canvas displaying a section of `notebook` so its Rust `View`
73 /// releases its section handle immediately.
74 static func tearDownAll(of notebook: Notebook) {
75 active = active.filter { $0.value.value != nil }
76 for entry in active.values {
77 guard let canvas = entry.value, canvas.section?.notebook === notebook else { continue }
78 canvas.tearDown()
79 }
80 }
81
82 /// The zoom a page opens at once the reader has pinched one.
83 private static let zoomKey = "zoom"
84
85 private var section: Section?
86 private let page: String
87 private let metal = MetalView()
88 /// Sized to the page content at 100%, so the scroll view's zoom scale is the page zoom.
89 private let content = UIView()
90 private var handle: OpaquePointer?
91 private var link: CADisplayLink?
92 private var dirty = true
93 /// The content's corner at 100%, from which the scroll offset is measured.
94 private var origin = CGPoint.zero
95 private var syncing = false
96 private var scrolled = false
97 private var drag: Drag?
98 /// The zoom and finger spread a pinch started from.
99 private var pinchStart: (zoom: CGFloat, spread: CGFloat)?
100 private var inDetent = false
101 private let detentTick = UISelectionFeedbackGenerator()
102 /// How far right of the content's corner a page opens.
103 private var left: CGFloat = 0
104 /// The zoom a double tap returns to.
105 private var resting: CGFloat = 1
106 private var canvasPlace: (zoom: CGFloat, resting: CGFloat, corner: CGPoint, left: CGFloat, scrolled: Bool, edited: Bool)?
107 private lazy var tap = UITapGestureRecognizer(target: self, action: #selector(tapped))
108 private lazy var doubleTap: UITapGestureRecognizer = {
109 let recognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
110 recognizer.numberOfTapsRequired = 2
111 return recognizer
112 }()
113 /// Moves or widens the focused outline from its grips.
114 private lazy var grip = UIPanGestureRecognizer(target: self, action: #selector(gripped))
115 /// Where the outline grip drag started.
116 private var touchStart = CGPoint.zero
117 private lazy var editMenu = UIEditMenuInteraction(delegate: self)
118 /// Owns text gestures and their caret, highlight, handles and loupe together.
119 private let interaction = UITextInteraction(for: .editable)
120 private let history = CanvasUndoManager()
121 private let spaceHint = Hint()
122 /// The Pencil's strokes, and a finger's while `fingerInks`.
123 private lazy var ink = InkGesture(target: self, action: #selector(inked))
124 /// The tool the canvas has, which touches switch between.
125 private var appliedTool = InkTool.select
126 /// The tool the Pencil draws with; the Pencil's double tap swaps it with the one before.
127 private(set) var inkTool = InkTool.pen(0)
128 private var previousInkTool = InkTool.eraser
129 /// A tool is picked for a finger too, from picking it until Select & Type or closing the
130 /// picker.
131 private var fingerDraws = false
132 /// The section's tab colour as a COLORREF, which its pen gallery and shapes follow.
133 private var sectionColor: UInt32 {
134 (section?.tab.color ?? []).enumerated().reduce(0) { $0 | UInt32($1.element) << (8 * UInt32($1.offset)) }
135 }
136 private lazy var picker = InkPicker(pens: Pen.gallery(sectionColor))
137
138 weak var inputDelegate: UITextInputDelegate?
139 lazy var tokenizer: UITextInputTokenizer = LineTokenizer(canvas: self)
140 /// Called when editing starts or stops and after each change, for the bar buttons.
141 var onChange: (() -> Void)?
142 /// Called once the page is first on screen.
143 var onOpened: (() -> Void)?
144 /// Called when a tap on the page date asks to change it, with the date it shows.
145 var onDate: ((DateField, Date) -> Void)?
146 /// Called when a tap on a recording, or beside a note linked to one, asks to play it.
147 var onPlay: ((PlayRequest) -> Void)?
148 /// Formatting above the keyboard.
149 let formatBar = FormatBar()
150 /// Room above the page for a bar over it.
151 var topInset: CGFloat = 0 {
152 didSet {
153 contentInset.top = topInset
154 home()
155 }
156 }
157
158 /// Room below the page, above the keyboard, for a bar over its foot.
159 var bottomInset: CGFloat = 0 {
160 didSet {
161 guard bottomInset != oldValue else { return }
162 contentInset.bottom += bottomInset - oldValue
163 verticalScrollIndicatorInsets.bottom = contentInset.bottom
164 revealCaret()
165 }
166 }
167
168 init(section: Section?, page: String) {
169 self.section = section
170 self.page = page
171 super.init(frame: .zero)
172 Self.active[ObjectIdentifier(self)] = WeakCanvas(value: self)
173 backgroundColor = .systemBackground
174 delegate = self
175 minimumZoomScale = 0.25
176 maximumZoomScale = 4
177 keyboardDismissMode = .interactive
178 // A phone on its side keeps the page clear of the sensor housing, as it keeps the top.
179 contentInsetAdjustmentBehavior = .always
180 addSubview(content)
181 insertSubview(metal, at: 0)
182 // Touches land on the scroll view itself, where the text interaction looks for them.
183 metal.isUserInteractionEnabled = false
184 content.isUserInteractionEnabled = false
185 let layer = metal.layer as! CAMetalLayer
186 layer.isOpaque = true
187 // Frames reach the screen with the transaction that moves UIKit's caret and handles.
188 layer.presentsWithTransaction = true
189 for recognizer in [tap, doubleTap, grip, ink] {
190 recognizer.delegate = self
191 addGestureRecognizer(recognizer)
192 }
193 // The Pencil draws; fingers, a trackpad and a mouse scroll and select.
194 ink.allowedTouchTypes = [UITouch.TouchType.pencil, .direct].map { NSNumber(value: $0.rawValue) }
195 let hands = [UITouch.TouchType.direct, .indirectPointer].map { NSNumber(value: $0.rawValue) }
196 let recognizers: [UIGestureRecognizer?] = [tap, doubleTap, grip, panGestureRecognizer, pinchGestureRecognizer]
197 for recognizer in recognizers {
198 recognizer?.allowedTouchTypes = hands
199 }
200 let pencil = UIPencilInteraction()
201 pencil.delegate = self
202 addInteraction(pencil)
203 addInteraction(UIScribbleInteraction(delegate: self))
204 picker.onPick = { [weak self] tool in self?.pick(tool) }
205 picker.onClose = { [weak self] in self?.showPicker(false) }
206 tap.require(toFail: doubleTap)
207 panGestureRecognizer.require(toFail: grip)
208 interaction.textInput = self
209 interaction.delegate = self
210 addInteraction(interaction)
211 for recognizer in interaction.gesturesForFailureRequirements {
212 panGestureRecognizer.require(toFail: recognizer)
213 }
214 addInteraction(editMenu)
215 history.canvas = self
216 NotificationCenter.default.addObserver(
217 self, selector: #selector(keyboardChanged), name: UIResponder.keyboardWillChangeFrameNotification,
218 object: nil)
219 registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: CanvasView, _) in view.paper() }
220 formatBar.onApply = { [weak self] command in self?.apply(command) }
221 formatBar.onStyle = { [weak self] place in self?.applyStyle(place) }
222 formatBar.stylePlace = { [weak self] in self?.stylePlace ?? -1 }
223 formatBar.onDismiss = { [weak self] in _ = self?.resignFirstResponder() }
224 }
225
226 required init?(coder: NSCoder) { fatalError() }
227
228 deinit {
229 Self.active[ObjectIdentifier(self)] = nil
230 tearDown()
231 }
232
233 /// Stops the display link, frees the Rust view, and drops the section reference
234 /// immediately so the underlying replica can close even while UIKit keeps the view alive.
235 func tearDown() {
236 link?.invalidate()
237 link = nil
238 if let handle {
239 sb_view_free(handle)
240 self.handle = nil
241 }
242 section = nil
243 }
244
245 // MARK: Drawing
246
247 override func layoutSubviews() {
248 super.layoutSubviews()
249 metal.frame = bounds
250 // Selection views go in at the back, where the opaque page would hide them.
251 sendSubviewToBack(metal)
252 let scale = window?.screen.scale ?? 3
253 metal.layer.contentsScale = scale
254 guard bounds.width > 0, bounds.height > 0 else { return }
255 let pixels = CGSize(width: (bounds.width * scale).rounded(), height: (bounds.height * scale).rounded())
256 if let handle {
257 // Scrolling lays the view out too; only a new size reconfigures the surface.
258 guard (metal.layer as! CAMetalLayer).drawableSize != pixels else { return }
259 sb_view_resize(handle, Float(bounds.width), Float(bounds.height), Float(scale))
260 if readingShown { reflowReading(readingWidth) } else { transform() }
261 } else {
262 guard let section, let sectionHandle = section.handle else { return }
263 handle = sb_view_new(
264 Unmanaged.passUnretained(metal.layer).toOpaque(), sectionHandle, page,
265 Float(bounds.width), Float(bounds.height), Float(scale))
266 guard let handle else { return }
267 sb_view_focus(handle, false)
268 paper()
269 sync()
270 let skip = margin
271 resting = openingZoom(skipping: skip)
272 zoomScale = resting
273 left = skip * resting
274 home()
275 onOpened?()
276 #if DEBUG
277 runScript()
278 #endif
279 }
280 }
281
282 override func safeAreaInsetsDidChange() {
283 super.safeAreaInsetsDidChange()
284 if readingShown { reflowReading(readingWidth) }
285 }
286
287 override func didMoveToWindow() {
288 super.didMoveToWindow()
289 link?.invalidate()
290 link = nil
291 guard window != nil else { return }
292 let link = CADisplayLink(target: self, selector: #selector(frame(_:)))
293 link.preferredFrameRateRange = CAFrameRateRange(minimum: 60, maximum: 120, preferred: 120)
294 link.add(to: .main, forMode: .common)
295 self.link = link
296 }
297
298 @objc private func frame(_ link: CADisplayLink) {
299 guard let handle else { return }
300 if sb_view_frame_pending(handle) { dirty = true }
301 guard dirty else { return }
302 dirty = false
303 // A frame presented with a transaction shows only once one commits, which an edit
304 // that moves no UIKit view would not otherwise cause.
305 CATransaction.begin()
306 sb_view_render(handle)
307 CATransaction.commit()
308 }
309
310 /// The page follows the system's appearance, on the desktop's dark paper in dark mode.
311 private func paper() {
312 guard let handle else { return }
313 sb_view_set_dark(handle, traitCollection.userInterfaceStyle == .dark)
314 dirty = true
315 }
316
317 // MARK: Scrolling and zoom
318
319 /// Sizes the scroll content to the page's after an edit, keeping the page point at the
320 /// view's corner. The scroll view owns the offset: the canvas's own clamping and caret
321 /// reveal know neither the navigation bar nor the keyboard, so `transform` overrides them.
322 private func sync() {
323 guard let handle else { return }
324 let shown = readingShown
325 var restored: CGPoint?
326 if !shown, let place = canvasPlace {
327 canvasPlace = nil
328 syncing = true
329 minimumZoomScale = 0.25
330 maximumZoomScale = 4
331 zoomScale = place.zoom
332 resting = place.resting
333 left = place.left
334 scrolled = place.scrolled
335 restored = place.corner
336 syncing = false
337 }
338 var bounds: [Float] = [0, 0, 0, 0]
339 sb_view_content(handle, &bounds)
340 let corner = restored ?? CGPoint(x: origin.x + contentOffset.x / zoomScale, y: origin.y + contentOffset.y / zoomScale)
341 origin = CGPoint(x: CGFloat(bounds[0]), y: CGFloat(bounds[1]))
342 let size = CGSize(width: CGFloat(bounds[2]) - origin.x, height: CGFloat(bounds[3]) - origin.y)
343 syncing = true
344 content.bounds = CGRect(origin: .zero, size: size)
345 content.center = CGPoint(x: size.width * zoomScale / 2, y: size.height * zoomScale / 2)
346 contentSize = CGSize(width: size.width * zoomScale, height: size.height * zoomScale)
347 contentOffset = CGPoint(x: (corner.x - origin.x) * zoomScale, y: (corner.y - origin.y) * zoomScale)
348 syncing = false
349 transform()
350 }
351
352 private func transform() {
353 guard let handle, !syncing else { return }
354 if readingShown {
355 syncing = true
356 zoomScale = 1
357 contentOffset.x = margin - adjustedContentInset.left
358 syncing = false
359 }
360 sb_view_set_transform(
361 handle, Float(zoomScale), Float(origin.x + contentOffset.x / zoomScale),
362 Float(origin.y + contentOffset.y / zoomScale))
363 metal.frame = bounds
364 dirty = true
365 }
366
367 /// The zoom the reader last pinched to, within reason, or before that 100%, where OneNote's
368 /// 11 pt body text shows at 17 points; less where that fits the page right of `skip`
369 /// across the screen.
370 private func openingZoom(skipping skip: CGFloat) -> CGFloat {
371 let pinched = UserDefaults.standard.object(forKey: Self.zoomKey) as? CGFloat ?? 1
372 let fit = bounds.inset(by: safeAreaInsets).width / max(1, content.bounds.width - skip)
373 // A page opens readable however far the last one was pinched or however wide it is.
374 return max(0.75, min(2, pinched, fit))
375 }
376
377 /// The empty page left of its first outline, which a phone skips on opening, keeping
378 /// room for the tags OneNote hangs left of the text.
379 private var margin: CGFloat {
380 guard let handle else { return 0 }
381 var block: [Float] = [0, 0, 0, 0]
382 guard sb_view_block(handle, 0, 0, &block) else { return 0 }
383 return max(0, CGFloat(block[0]) - origin.x - 34)
384 }
385
386 /// Until the reader scrolls, the page's corner stays below the navigation bar as its
387 /// insets settle.
388 override func adjustedContentInsetDidChange() {
389 super.adjustedContentInsetDidChange()
390 home()
391 }
392
393 private func home() {
394 if readingShown { transform() }
395 else if !scrolled { contentOffset = CGPoint(x: left - adjustedContentInset.left, y: -adjustedContentInset.top) }
396 }
397
398 /// A drag that starts within 30° of an axis sticks to it; a 24-point stretch of the
399 /// finger more than 40° off it lets go, and the page catches up over the next 48 points.
400 private struct Drag {
401 static let snap = tan(CGFloat.pi / 6)
402 static let release = tan(CGFloat.pi * 2 / 9)
403 static let stretch: CGFloat = 24
404 static let catchUp: CGFloat = 48
405
406 /// The axis the lock holds still.
407 let cross: WritableKeyPath<CGPoint, CGFloat>
408 var locked = true
409 /// The offset last shown, from which the scroll view's next step is measured.
410 var offset: CGPoint
411 /// The translation where the stretch of the gesture being judged began.
412 var stretch: CGPoint
413 /// How far the held axis trails the finger.
414 var lag: CGFloat = 0
415 }
416
417 func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
418 scrolled = true
419 if readingShown { drag = nil; return }
420 let moved = panGestureRecognizer.translation(in: self)
421 let cross: WritableKeyPath<CGPoint, CGFloat>? =
422 abs(moved.x) <= abs(moved.y) * Drag.snap ? \.x : abs(moved.y) <= abs(moved.x) * Drag.snap ? \.y : nil
423 drag = cross.map { Drag(cross: $0, offset: contentOffset, stretch: moved) }
424 }
425
426 func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
427 guard !readingShown else { return }
428 scrolled = true
429 drag = nil
430 pinchStart = spread.map { (zoomScale, $0) }
431 inDetent = abs(log(zoomScale)) < Self.detent
432 detentTick.prepare()
433 }
434
435 func viewForZooming(in scrollView: UIScrollView) -> UIView? { readingShown ? nil : content }
436
437 func scrollViewDidScroll(_ scrollView: UIScrollView) {
438 guard !syncing else { return }
439 if var drag, isDragging || isDecelerating, !isZooming {
440 let cross = drag.cross
441 let along = cross == \CGPoint.x ? \CGPoint.y : \CGPoint.x
442 var offset = contentOffset
443 let step = offset[keyPath: cross] - drag.offset[keyPath: cross]
444 if drag.locked {
445 drag.lag += step
446 offset[keyPath: cross] = drag.offset[keyPath: cross]
447 let moved = panGestureRecognizer.translation(in: self)
448 let stretch = CGPoint(x: moved.x - drag.stretch.x, y: moved.y - drag.stretch.y)
449 if isTracking, hypot(stretch.x, stretch.y) >= Drag.stretch {
450 drag.locked = abs(stretch[keyPath: cross]) <= abs(stretch[keyPath: along]) * Drag.release
451 drag.stretch = moved
452 }
453 } else {
454 let travel = hypot(step, offset[keyPath: along] - drag.offset[keyPath: along])
455 let paid = drag.lag * (1 - exp(-travel / Drag.catchUp))
456 offset[keyPath: cross] += paid
457 drag.lag -= paid
458 }
459 drag.offset = offset
460 self.drag = drag.locked || abs(drag.lag) >= 0.5 ? drag : nil
461 if offset != contentOffset { contentOffset = offset }
462 }
463 transform()
464 }
465
466 /// How far apart a pinch's two fingers are.
467 private var spread: CGFloat? {
468 guard let pinch = pinchGestureRecognizer, pinch.numberOfTouches == 2 else { return nil }
469 let a = pinch.location(ofTouch: 0, in: self), b = pinch.location(ofTouch: 1, in: self)
470 return hypot(a.x - b.x, a.y - b.y)
471 }
472
473 /// How far either side of 100% a pinch sticks, as a log of the zoom.
474 private static let detent = log(CGFloat(1.1))
475
476 /// Pinching near 100% sticks there: within `detent` of it the zoom follows the fingers
477 /// on a curve flat at 100% that meets them again at the band's edges.
478 func scrollViewDidZoom(_ scrollView: UIScrollView) {
479 guard !syncing else { return }
480 if readingShown {
481 transform()
482 inputDelegate?.selectionDidChange(self)
483 return
484 }
485 if let pinch = pinchGestureRecognizer, pinch.state == .changed, let pinchStart, let spread {
486 // The scroll view's pinch reports the zoom it shows, so the fingers give the raw one.
487 let raw = log(pinchStart.zoom * spread / pinchStart.spread)
488 let x = abs(raw) / Self.detent
489 if x < 1 {
490 if !inDetent { detentTick.selectionChanged() }
491 let shown = exp(Self.detent * x * x * (2 - x) * (raw < 0 ? -1 : 1))
492 if abs(shown - zoomScale) > 0.0001 {
493 let focus = pinch.location(in: content)
494 let screen = CGPoint(x: pinch.location(in: self).x - contentOffset.x, y: pinch.location(in: self).y - contentOffset.y)
495 zoomScale = shown
496 contentOffset = CGPoint(x: focus.x * shown - screen.x, y: focus.y * shown - screen.y)
497 }
498 }
499 inDetent = x < 1
500 }
501 transform()
502 // Scrolling carries the caret and handles along; zooming moves them within the page.
503 inputDelegate?.selectionDidChange(self)
504 }
505
506 func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
507 let pinched = pinchStart != nil
508 pinchStart = nil
509 guard !readingShown, pinched else { return }
510 // A pinch let go within the detent settles on 100%.
511 resting = abs(log(scale)) < Self.detent ? 1 : scale
512 if resting != scale { setZoomScale(resting, animated: true) }
513 UserDefaults.standard.set(Double(resting), forKey: Self.zoomKey)
514 }
515
516 @objc private func doubleTapped(_ recognizer: UITapGestureRecognizer) {
517 zoom(at: recognizer.location(in: self))
518 }
519
520 /// Zooms to fit the outline nearest `point` across the view, or back out, as a double
521 /// tap does in Safari.
522 func zoom(at point: CGPoint) {
523 guard let handle, !readingShown else { return }
524 var block: [Float] = [0, 0, 0, 0]
525 let local = visible(point)
526 guard zoomScale <= resting * 1.05, sb_view_block(handle, Float(local.x), Float(local.y), &block) else {
527 setZoomScale(resting, animated: true)
528 return
529 }
530 let width = bounds.inset(by: safeAreaInsets).width
531 let margin: CGFloat = 12
532 let scale = min(maximumZoomScale, (width - 2 * margin) / (CGFloat(block[2] - block[0])))
533 guard scale > zoomScale * 1.05 else {
534 setZoomScale(resting, animated: true)
535 return
536 }
537 let x = CGFloat(block[0]) - origin.x - margin / scale
538 let y = point.y / zoomScale - bounds.height / scale / 2
539 zoom(to: CGRect(x: x, y: y, width: width / scale, height: bounds.height / scale), animated: true)
540 }
541
542 @objc private func keyboardChanged(_ notification: Notification) {
543 guard let frame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
544 let window
545 else { return }
546 let keyboard = convert(frame, from: window.screen.coordinateSpace)
547 let overlap = max(0, bounds.maxY - keyboard.minY - safeAreaInsets.bottom)
548 contentInset.bottom = overlap + bottomInset
549 verticalScrollIndicatorInsets.bottom = contentInset.bottom
550 revealCaret()
551 }
552
553 // MARK: Touch
554
555 private func target(_ point: CGPoint) -> Target {
556 guard let handle else { return .page }
557 let local = visible(point)
558 return Target(rawValue: sb_view_target(handle, Float(local.x), Float(local.y))) ?? .page
559 }
560
561 func gestureRecognizer(_ recognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
562 if recognizer === ink { return !readOnly && (touch.type == .pencil || fingerInks && touch.type == .direct) }
563 if recognizer === grip { touchStart = touch.location(in: self) }
564 return !fingerInks || ![tap, doubleTap, grip].contains(recognizer)
565 }
566
567 override func gestureRecognizerShouldBegin(_ recognizer: UIGestureRecognizer) -> Bool {
568 switch recognizer {
569 case tap:
570 !readOnly && [.page, .grip].contains(target(recognizer.location(in: self)))
571 && !onHandle(recognizer.location(in: self))
572 case doubleTap: target(recognizer.location(in: self)) == .page
573 case grip: !readOnly && target(touchStart) == .grip
574 default: super.gestureRecognizerShouldBegin(recognizer)
575 }
576 }
577
578 /// The system's text interaction works in the outline taking input; a touch on another
579 /// outline's text focuses it first, as a tap there would.
580 func interactionShouldBegin(_ interaction: UITextInteraction, at point: CGPoint) -> Bool {
581 if readOnly || fingerInks || ink.state != .possible { return false }
582 if onHandle(point) { return true }
583 switch target(point) {
584 case .activeText: break
585 case .text: press(at: point)
586 case .page, .grip: return false
587 }
588 if !isFirstResponder { _ = becomeFirstResponder() }
589 return true
590 }
591
592 /// Whether `point` is on a selection handle, whose knob hangs off the text.
593 private func onHandle(_ point: CGPoint) -> Bool {
594 guard isFirstResponder, let range = selectedTextRange, !range.isEmpty else { return false }
595 return [range.start, range.end].contains {
596 caretRect(for: $0).insetBy(dx: -22, dy: -22).contains(point)
597 }
598 }
599
600 @objc private func tapped(_ recognizer: UITapGestureRecognizer) {
601 tap(at: recognizer.location(in: self))
602 }
603
604 /// A tap at `point` in the scroll view's bounds: places the caret, focuses an outline or
605 /// starts a new one, or picks a drawing.
606 func tap(at point: CGPoint) {
607 press(at: point)
608 var seconds: Int64 = 0
609 if let request = playRequest() {
610 onPlay?(request)
611 } else if let handle, let field = DateField(rawValue: sb_view_date_request(handle, &seconds)) {
612 onDate?(field, Date(timeIntervalSince1970: TimeInterval(seconds)))
613 } else if inkFrame != nil {
614 showInkMenu()
615 } else if !isFirstResponder {
616 _ = becomeFirstResponder()
617 }
618 }
619
620 /// Gives the page `date`, which the date and time under its title show.
621 func changeDate(_ date: Date) {
622 guard let handle else { return }
623 let (day, time) = titleDate(date)
624 edit(external: true) { sb_view_change_date(handle, Int64(date.timeIntervalSince1970.rounded()), day, time) }
625 }
626
627 private func press(at point: CGPoint) {
628 guard let handle else { return }
629 fingerTool(at: point)
630 let point = visible(point)
631 edit(external: true) {
632 let pressed = sb_view_press(handle, Float(point.x), Float(point.y))
633 return sb_view_release(handle) || pressed
634 }
635 }
636
637 @objc private func gripped(_ recognizer: UIPanGestureRecognizer) {
638 guard let handle else { return }
639 let point = visible(recognizer.location(in: self))
640 switch recognizer.state {
641 case .began:
642 inputDelegate?.selectionWillChange(self)
643 fingerTool(at: touchStart)
644 let start = visible(touchStart)
645 _ = sb_view_press(handle, Float(start.x), Float(start.y))
646 _ = sb_view_drag(handle, Float(point.x), Float(point.y))
647 inputDelegate?.selectionDidChange(self)
648 editMenu.dismissMenu()
649 dirty = true
650 case .changed:
651 _ = sb_view_drag(handle, Float(point.x), Float(point.y))
652 dirty = true
653 default:
654 edit(external: true) { sb_view_release(handle) }
655 spaceHint.hide()
656 }
657 }
658
659 // MARK: Drawing tools
660
661 /// Gives the canvas `tool` for the touch starting, where it has another: switching lets
662 /// picked drawings go.
663 private func use(_ tool: InkTool) {
664 guard let handle else { return }
665 if tool != .select, readingShown { showReading(false) }
666 guard tool != appliedTool else { return }
667 appliedTool = tool
668 sb_view_set_tool(handle, tool.code.tool, tool.code.detail, sectionColor)
669 dirty = true
670 }
671
672 /// A finger draws with the picked tool, unless the system keeps drawing to the Pencil.
673 private var fingerInks: Bool { fingerDraws && !UIPencilInteraction.prefersPencilOnlyDrawing }
674
675 /// A finger scrolls, selects and types, and drags what the lasso picked with the lasso.
676 private func fingerTool(at point: CGPoint) {
677 if inkFrame?.contains(point) != true { use(.select) }
678 }
679
680 /// The frame of the drawings the lasso or a tap picked, in the scroll view's bounds.
681 private var inkFrame: CGRect? {
682 guard let handle else { return nil }
683 var rect: [Float] = [0, 0, 0, 0]
684 return sb_view_ink_selection(handle, &rect) ? bounded(rect) : nil
685 }
686
687 /// The Pencil's tool, and a finger's while `fingerInks`.
688 func setInkTool(_ tool: InkTool) {
689 guard tool != .select else { return }
690 if tool != inkTool { previousInkTool = inkTool }
691 inkTool = tool
692 picker.show(inkTool, fingerDraws: fingerInks)
693 }
694
695 /// A tool picked in the picker, which a finger draws with too, or Select & Type as nil.
696 private func pick(_ tool: InkTool?) {
697 if let tool { setInkTool(tool) }
698 setFingerDraws(tool != nil)
699 }
700
701 private func setFingerDraws(_ draws: Bool) {
702 fingerDraws = draws
703 // Two fingers scroll while one draws.
704 panGestureRecognizer.minimumNumberOfTouches = fingerInks ? 2 : 1
705 if fingerInks { _ = resignFirstResponder() }
706 picker.show(inkTool, fingerDraws: fingerInks)
707 onChange?()
708 }
709
710 var pickerShown: Bool { picker.superview != nil }
711
712 /// Shows the drawing tools over the bottom of the page, or puts them away. Showing them from
713 /// the bar picks the Pencil's tool for a finger too; closing them returns it to Select & Type.
714 func showPicker(_ shown: Bool, fingerDraws draws: Bool = true) {
715 guard shown != pickerShown, let host = superview else { return }
716 if shown {
717 if readingShown { showReading(false) }
718 picker.translatesAutoresizingMaskIntoConstraints = false
719 host.addSubview(picker)
720 NSLayoutConstraint.activate([
721 picker.centerXAnchor.constraint(equalTo: host.centerXAnchor),
722 picker.widthAnchor.constraint(lessThanOrEqualTo: host.safeAreaLayoutGuide.widthAnchor, constant: -16),
723 picker.bottomAnchor.constraint(equalTo: host.keyboardLayoutGuide.topAnchor, constant: -12),
724 ])
725 setFingerDraws(draws)
726 } else {
727 picker.removeFromSuperview()
728 setFingerDraws(false)
729 }
730 }
731
732 /// The Pencil's double tap, as the reader set it in Settings.
733 func pencilInteractionDidTap(_ interaction: UIPencilInteraction) {
734 switch UIPencilInteraction.preferredTapAction {
735 case .switchEraser: setInkTool(inkTool == .eraser ? previousInkTool : .eraser)
736 case .switchPrevious: setInkTool(previousInkTool)
737 case .showColorPalette, .showInkAttributes: showPicker(!pickerShown, fingerDraws: fingerDraws)
738 default: break
739 }
740 }
741
742 /// Writing with the Pencil draws ink on the page rather than typing.
743 func scribbleInteraction(_ interaction: UIScribbleInteraction, shouldBeginAt location: CGPoint) -> Bool { false }
744
745 @objc private func inked(_ gesture: InkGesture) {
746 let points = gesture.points
747 gesture.points = []
748 switch gesture.state {
749 case .began:
750 inkPressed(points[0])
751 inkMoved(points.dropFirst())
752 case .changed: inkMoved(points[...])
753 case .ended:
754 inkMoved(points[...])
755 inkReleased()
756 default:
757 // A second finger scrolls instead: the gesture under way goes, storing nothing.
758 guard let handle else { return }
759 edit { sb_view_cancel(handle) }
760 }
761 }
762
763 /// The Pencil, or a drawing finger, comes down at `sample`'s point in the scroll view's bounds.
764 func inkPressed(_ sample: InkSample) {
765 guard let handle else { return }
766 // Drawing puts the keyboard away, as Notes does.
767 if isFirstResponder { _ = resignFirstResponder() }
768 use(inkTool)
769 editMenu.dismissMenu()
770 let point = visible(sample.point)
771 sb_view_pressure(handle, sample.pressure)
772 edit { sb_view_press(handle, Float(point.x), Float(point.y)) }
773 }
774
775 func inkMoved(_ samples: ArraySlice<InkSample>) {
776 guard let handle else { return }
777 for sample in samples {
778 let point = visible(sample.point)
779 sb_view_pressure(handle, sample.pressure)
780 _ = sb_view_drag(handle, Float(point.x), Float(point.y))
781 }
782 dirty = true
783 }
784
785 /// The stroke, erasure, lasso or drag ends: one edit, and the menu for what the lasso picked.
786 func inkReleased() {
787 guard let handle else { return }
788 edit { sb_view_release(handle) }
789 showInkMenu()
790 }
791
792 private static let inkMenu = "ink" as NSString
793
794 private func showInkMenu() {
795 guard let frame = inkFrame else { return }
796 editMenu.presentEditMenu(
797 with: UIEditMenuConfiguration(identifier: Self.inkMenu, sourcePoint: CGPoint(x: frame.midX, y: frame.minY)))
798 }
799
800 func editMenuInteraction(
801 _ interaction: UIEditMenuInteraction, menuFor configuration: UIEditMenuConfiguration,
802 suggestedActions: [UIMenuElement]
803 ) -> UIMenu? {
804 guard configuration.identifier as? NSString == Self.inkMenu else {
805 return selectedTextRange.flatMap { editMenu(for: $0, suggestedActions: suggestedActions) }
806 ?? UIMenu(children: suggestedActions)
807 }
808 return UIMenu(children: [
809 UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { [weak self] _ in
810 self?.deleteInk()
811 }
812 ])
813 }
814
815 func editMenuInteraction(
816 _ interaction: UIEditMenuInteraction, targetRectFor configuration: UIEditMenuConfiguration
817 ) -> CGRect {
818 configuration.identifier as? NSString == Self.inkMenu ? inkFrame ?? .null : .null
819 }
820
821 /// Deletes the drawings the lasso or a tap picked.
822 func deleteInk() {
823 guard let handle, inkFrame != nil else { return }
824 edit(external: true) { sb_delete_backward(handle) }
825 }
826
827 /// Runs a change to the page, telling the system when it did not ask for it; returns
828 /// whether it changed.
829 @discardableResult
830 private func edit(external: Bool = false, _ change: () -> Bool) -> Bool {
831 if external {
832 inputDelegate?.selectionWillChange(self)
833 inputDelegate?.textWillChange(self)
834 }
835 let changed = change()
836 dirty = true
837 if changed {
838 canvasPlace?.edited = true
839 sync()
840 revealCaret()
841 }
842 if external {
843 inputDelegate?.textDidChange(self)
844 inputDelegate?.selectionDidChange(self)
845 }
846 changedSelection()
847 return changed
848 }
849
850 /// Tells the bar buttons and the format bar what the selection now has.
851 private func changedSelection() {
852 formatBar.show(format)
853 onChange?()
854 }
855
856 private func revealCaret() {
857 guard handle != nil, isFirstResponder, let range = selectedTextRange else { return }
858 reveal(caretRect(for: range.end))
859 }
860
861 private func reveal(_ rect: CGRect) {
862 scrollRectToVisible(rect.insetBy(dx: -8, dy: -16), animated: false)
863 }
864
865 // MARK: Responder
866
867 override var canBecomeFirstResponder: Bool { handle != nil && !readOnly }
868
869 override var inputAccessoryView: UIView? { formatBar }
870
871 override func becomeFirstResponder() -> Bool {
872 if Prototype.welcome, Author.name == nil, let controller = window?.rootViewController {
873 Prototype.askName(from: controller) { [weak self] in _ = self?.becomeFirstResponder() }
874 return false
875 }
876 guard super.becomeFirstResponder() else { return false }
877 if let handle { sb_view_focus(handle, true) }
878 dirty = true
879 changedSelection()
880 return true
881 }
882
883 override func resignFirstResponder() -> Bool {
884 guard super.resignFirstResponder() else { return false }
885 TagGrid.shown?.close()
886 if let handle { sb_view_focus(handle, false) }
887 dirty = true
888 onChange?()
889 return true
890 }
891
892 override var undoManager: UndoManager? { history }
893
894 func canUndo(redo: Bool) -> Bool { handle.map { sb_view_can_undo($0, redo) } ?? false }
895
896 func undo(redo: Bool) {
897 guard let handle else { return }
898 edit(external: true) { sb_view_undo(handle, redo) }
899 }
900
901 private var selection: (lo: Int, hi: Int) {
902 guard let range = selectedTextRange else { return (0, 0) }
903 return (range.lower, range.upper)
904 }
905
906 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
907 let (lo, hi) = selection
908 switch action {
909 case #selector(copy(_:)), #selector(cut(_:)), #selector(delete(_:)),
910 #selector(toggleBoldface(_:)), #selector(toggleItalics(_:)), #selector(toggleUnderline(_:)):
911 return lo < hi
912 case #selector(paste(_:)): return UIPasteboard.general.hasStrings || UIPasteboard.general.hasImages
913 case #selector(select(_:)): return lo == hi && hasText
914 case #selector(selectAll(_:)): return hasText && (lo > 0 || hi < endOfDocument.offset)
915 default: return super.canPerformAction(action, withSender: sender)
916 }
917 }
918
919 /// A page selection copies every outline, as OneNote 2010 copies it.
920 override func copy(_ sender: Any?) {
921 guard let handle, let text = take(sb_view_copy(handle, false)) else { return }
922 UIPasteboard.general.string = text
923 }
924
925 override func cut(_ sender: Any?) {
926 guard let handle else { return }
927 var text: String?
928 edit(external: true) {
929 text = take(sb_view_copy(handle, true))
930 return text != nil
931 }
932 if let text { UIPasteboard.general.string = text }
933 }
934
935 override func delete(_ sender: Any?) {
936 guard let range = selectedTextRange else { return }
937 edit(external: true) { replacing(range, with: "") }
938 }
939
940 /// Pasted text takes the keyboard's language, as Windows gives the clipboard. Text wins
941 /// over a picture, which apps put beside copied text.
942 override func paste(_ sender: Any?) {
943 guard let handle else { return }
944 if let text = UIPasteboard.general.string {
945 edit(external: true) { sb_paste(handle, text, textInputMode?.primaryLanguage ?? "") }
946 } else if let image = UIPasteboard.general.image {
947 insertPicture(image)
948 }
949 }
950
951 override func select(_ sender: Any?) {
952 guard let caret = selectedTextRange?.start,
953 let word = tokenizer.rangeEnclosingPosition(caret, with: .word, inDirection: .storage(.backward))
954 ?? tokenizer.rangeEnclosingPosition(caret, with: .word, inDirection: .storage(.forward))
955 else { return }
956 edit(external: true) { choose(word) }
957 }
958
959 override func selectAll(_ sender: Any?) {
960 guard let handle else { return }
961 edit(external: true) { sb_select_more(handle) }
962 }
963
964 override func toggleBoldface(_ sender: Any?) { apply(0) }
965 override func toggleItalics(_ sender: Any?) { apply(1) }
966 override func toggleUnderline(_ sender: Any?) { apply(2) }
967
968 /// OneNote's highlighter colours, COLORREF, as its Text Highlight Color offers them.
969 private static let highlights: [(UInt32, String)] = [
970 (0x00ffff, "Yellow"), (0x00ff00, "Bright Green"), (0xffff00, "Turquoise"), (0xff00ff, "Pink"),
971 (0xff0000, "Blue"), (0x0000ff, "Red"), (0x800000, "Dark Blue"), (0x808000, "Teal"), (0x008000, "Green"),
972 (0x800080, "Violet"), (0x000080, "Dark Red"), (0x008080, "Dark Yellow"), (0x808080, "Gray 50%"),
973 (0xc0c0c0, "Gray 25%"), (0x000000, "Black"),
974 ]
975
976 /// The highlighter leads the system's text actions for a selection, tags follow them.
977 func editMenu(for textRange: UITextRange, suggestedActions: [UIMenuElement]) -> UIMenu? {
978 guard let handle else { return nil }
979 let bits = sb_view_format(handle)
980 let tag = UIMenu(
981 title: "Tag", image: UIImage(systemName: "tag"),
982 children: Tags.menu(bits: bits) { [weak self] in self?.apply($0) })
983 var highlight: [UIMenuElement] = []
984 if !textRange.isEmpty {
985 let colors = Self.highlights.map { color, name in
986 let swatch = UIGraphicsImageRenderer(size: CGSize(width: 20, height: 20)).image { _ in
987 let dot = UIBezierPath(ovalIn: CGRect(x: 1, y: 1, width: 18, height: 18))
988 UIColor(rgb: [UInt8(color & 0xff), UInt8(color >> 8 & 0xff), UInt8(color >> 16 & 0xff)]).setFill()
989 dot.fill()
990 UIColor.separator.setStroke()
991 dot.stroke()
992 }
993 return UIAction(title: name, image: swatch.withRenderingMode(.alwaysOriginal)) { [weak self] _ in
994 self?.highlight(Int64(color))
995 }
996 }
997 let none = UIAction(title: "No Highlight", image: UIImage(systemName: "circle.slash")) { [weak self] _ in
998 self?.highlight(-1)
999 }
1000 highlight = [UIMenu(title: "Highlight", image: UIImage(systemName: "highlighter"), children: colors + [none])]
1001 }
1002 return UIMenu(
1003 children: spellingActions() + highlight + suggestedActions + [UIMenu(options: .displayInline, children: [tag])])
1004 }
1005
1006 private struct Correction: Decodable {
1007 let word: String
1008 let suggestions: [String]
1009 let repeated: Bool
1010 }
1011
1012 /// OneNote's corrections for the marked word at the selection, first in the menu.
1013 private func spellingActions() -> [UIMenuElement] {
1014 guard let handle, let correction = decode(Correction.self, sb_view_correction(handle)) else { return [] }
1015 let correct = { [weak self] (command: UInt8, text: String?) in
1016 guard let self, let handle = self.handle else { return }
1017 self.edit(external: true) { sb_view_correct(handle, command, text) }
1018 }
1019 let replacements =
1020 correction.repeated
1021 ? [UIAction(title: "Delete Repeated Word") { _ in correct(0, "") }]
1022 : correction.suggestions.map { word in UIAction(title: word) { _ in correct(0, word) } }
1023 let ignore = UIAction(title: "Ignore") { _ in correct(1, nil) }
1024 let learn = UIAction(title: "Add to Dictionary") { _ in correct(2, nil) }
1025 return [
1026 UIMenu(options: .displayInline, children: replacements + (correction.repeated ? [ignore] : [ignore, learn]))
1027 ]
1028 }
1029
1030 // MARK: Page
1031
1032 /// A conflict page, which shows what is stored and takes no edits.
1033 var readOnly: Bool { handle.map(sb_view_read_only) ?? false }
1034
1035 /// The column a reading view fills: the screen's width less the room tags hang in.
1036 private var readingWidth: Float { Float(bounds.inset(by: safeAreaInsets).width - 34 - 12) }
1037
1038 private var readingAnchor: [Float] {
1039 [Float(origin.x + (contentOffset.x + adjustedContentInset.left + 34) / zoomScale),
1040 Float(origin.y + (contentOffset.y + adjustedContentInset.top) / zoomScale)]
1041 }
1042
1043 struct Reading: Decodable {
1044 let offered: Bool
1045 let shown: Bool
1046 }
1047
1048 var reading: Reading? {
1049 guard let handle else { return nil }
1050 return decode(Reading.self, sb_view_reading(handle, readingWidth))
1051 }
1052
1053 var readingShown: Bool {
1054 guard let handle else { return false }
1055 return decode(Reading.self, sb_view_reading(handle, 0))?.shown ?? false
1056 }
1057
1058 /// Shows the page reflowed into the screen's width at 100%, or as laid out.
1059 func showReading(_ on: Bool) {
1060 guard on != readingShown else { return }
1061 reflowReading(on ? readingWidth : 0)
1062 }
1063
1064 private func reflowReading(_ width: Float) {
1065 guard let handle else { return }
1066 let wasShown = readingShown
1067 let place = (zoom: zoomScale, resting: resting,
1068 corner: CGPoint(x: origin.x + contentOffset.x / zoomScale, y: origin.y + contentOffset.y / zoomScale),
1069 left: left, scrolled: scrolled, edited: false)
1070 let edited = canvasPlace?.edited ?? false
1071 var anchor = readingAnchor
1072 inputDelegate?.selectionWillChange(self)
1073 let shown = sb_view_set_reading(handle, width, &anchor)
1074 if shown, !wasShown {
1075 canvasPlace = place
1076 syncing = true
1077 minimumZoomScale = 1
1078 maximumZoomScale = 1
1079 zoomScale = 1
1080 resting = 1
1081 scrolled = true
1082 drag = nil
1083 pinchStart = nil
1084 syncing = false
1085 }
1086 sync()
1087 if shown {
1088 let y = CGFloat(anchor[1]) - origin.y - adjustedContentInset.top
1089 contentOffset.y = max(-adjustedContentInset.top, min(y, contentSize.height - bounds.height + adjustedContentInset.bottom))
1090 } else if edited {
1091 revealCaret()
1092 }
1093 inputDelegate?.selectionDidChange(self)
1094 dirty = true
1095 onChange?()
1096 }
1097
1098 /// The title as typed; nil on a page without an editable title.
1099 var pageTitle: String? { handle.flatMap { take(sb_view_title($0)) } }
1100
1101 /// Keeps the page as shown as a page of its own after an edit was refused; false when nothing was kept.
1102 func keep() -> Bool { handle.map(sb_view_keep) ?? false }
1103
1104 /// The page on `paper`, in points, as OneNote 2010 prints it, each sheet's footer naming
1105 /// `section`.
1106 func pdf(paper: CGSize, section: String) -> Data? {
1107 guard let handle else { return nil }
1108 var length = 0
1109 guard let bytes = sb_view_pdf(handle, Float(paper.width), Float(paper.height), section, &length) else {
1110 return nil
1111 }
1112 defer { sb_bytes_free(bytes, length) }
1113 return Data(bytes: bytes, count: length)
1114 }
1115
1116 /// The selection's formatting, from `sb_view_format`.
1117 var format: UInt64 { handle.map(sb_view_format) ?? 0 }
1118
1119 var pagePaper: Paper? { handle.flatMap { decode(Paper.self, sb_view_paper($0)) } }
1120
1121 /// Gives the page colour `color` and rule lines `ruled` of `paper.rules`, or none.
1122 func setPaper(color: [UInt8]?, ruled: Int?) {
1123 guard let handle else { return }
1124 edit(external: true) {
1125 sb_view_set_paper(
1126 handle, color.map { Int16($0[0]) } ?? -1, color?[1] ?? 0, color?[2] ?? 0, Int8(ruled ?? -1))
1127 }
1128 }
1129
1130 /// Puts template `name`'s art behind the page, or none.
1131 func setArt(_ name: String?) {
1132 guard let handle else { return }
1133 edit(external: true) { sb_view_set_art(handle, name) }
1134 }
1135
1136 /// Insert Space: the next drag moves what lies below or right of where it starts.
1137 func insertSpace() {
1138 guard let handle else { return }
1139 if readingShown { showReading(false) }
1140 sb_view_insert_space(handle)
1141 spaceHint.show("Drag down or right to add space", in: self)
1142 }
1143
1144 /// Types the date, time or both as the system writes them short, and a space, as
1145 /// OneNote's Insert Date and Time do.
1146 func insertDate(_ date: Bool, time: Bool) {
1147 let now = Date()
1148 let text = DateFormatter.localizedString(
1149 from: now, dateStyle: date ? .short : .none, timeStyle: time ? .short : .none)
1150 if !isFirstResponder { _ = becomeFirstResponder() }
1151 insertText(text + " ")
1152 }
1153
1154 /// Selects paragraph `id` and brings it into view.
1155 func selectParagraph(_ id: String) -> Bool {
1156 guard let handle else { return false }
1157 let found = edit(external: true) { sb_view_select_paragraph(handle, id) }
1158 if found { reveal(selectedTextRange.map { firstRect(for: $0) } ?? .zero) }
1159 return found
1160 }
1161
1162 /// Applies `sb_view_apply` formatting to the selection.
1163 func apply(_ command: UInt8) {
1164 guard let handle else { return }
1165 edit(external: true) { sb_view_apply(handle, command) }
1166 }
1167
1168 /// Highlights the selection in COLORREF `color`, or takes its highlight away where negative.
1169 func highlight(_ color: Int64) {
1170 guard let handle else { return }
1171 edit(external: true) { sb_view_highlight(handle, color) }
1172 }
1173
1174 /// Gives the selected paragraphs style `place` of OneNote's gallery, in the page's theme.
1175 func applyStyle(_ place: UInt8) {
1176 guard let handle else { return }
1177 edit(external: true) { sb_view_style(handle, place) }
1178 }
1179
1180 /// The selection's style's place in the gallery, or -1.
1181 var stylePlace: Int32 { handle.map(sb_view_style_place) ?? -1 }
1182
1183 /// Shows the page as stored; with `discard`, after an edit was refused.
1184 func reload(discard: Bool, pendingOnly: Bool = false) {
1185 guard let handle else { return }
1186 if pendingOnly && !sb_view_reload_ready(handle) { return }
1187 guard readingShown else {
1188 edit(external: true) { sb_view_reload(handle, discard, nil) }
1189 return
1190 }
1191 var anchor = readingAnchor
1192 inputDelegate?.selectionWillChange(self)
1193 inputDelegate?.textWillChange(self)
1194 let changed = sb_view_reload(handle, discard, &anchor)
1195 sync()
1196 if readingShown {
1197 let y = CGFloat(anchor[1]) - origin.y - adjustedContentInset.top
1198 contentOffset.y = max(-adjustedContentInset.top, min(y, contentSize.height - bounds.height + adjustedContentInset.bottom))
1199 } else if changed {
1200 revealCaret()
1201 }
1202 inputDelegate?.textDidChange(self)
1203 inputDelegate?.selectionDidChange(self)
1204 dirty = true
1205 changedSelection()
1206 }
1207
1208 /// Selects the first place `query` occurs and brings it into view.
1209 func find(_ query: String) -> Bool {
1210 guard let handle else { return false }
1211 let found = edit(external: true) { sb_view_find(handle, query) }
1212 if found { reveal(selectedTextRange.map { firstRect(for: $0) } ?? .zero) }
1213 return found
1214 }
1215
1216 /// Puts the caret at the end of the page title.
1217 func focusTitle() -> Bool {
1218 guard let handle else { return false }
1219 return edit(external: true) { sb_view_focus_title(handle) }
1220 }
1221
1222 /// A photo as OneNote 2010 can read it: JPEG, at most 2048 pixels across, shown at most
1223 /// 220 points wide.
1224 func insertPicture(_ image: UIImage) {
1225 let longest: CGFloat = 2048
1226 let scale = min(1, longest / max(image.size.width * image.scale, image.size.height * image.scale))
1227 let pixels = CGSize(
1228 width: (image.size.width * image.scale * scale).rounded(),
1229 height: (image.size.height * image.scale * scale).rounded())
1230 let format = UIGraphicsImageRendererFormat()
1231 format.scale = 1
1232 let drawn = UIGraphicsImageRenderer(size: pixels, format: format).image { _ in
1233 image.draw(in: CGRect(origin: .zero, size: pixels))
1234 }
1235 guard let data = drawn.jpegData(compressionQuality: 0.85) else { return }
1236 // OneNote shows a picture's pixels at 96 per inch.
1237 var size = CGSize(width: pixels.width * 0.75, height: pixels.height * 0.75)
1238 if size.width > 220 { size = CGSize(width: 220, height: size.height * 220 / size.width) }
1239 insertPicture(data, size: size)
1240 }
1241
1242 /// Puts a JPEG or PNG at the caret at `size` points.
1243 func insertPicture(_ data: Data, size: CGSize) {
1244 guard let handle else { return }
1245 edit(external: true) {
1246 data.withUnsafeBytes { bytes in
1247 sb_view_insert_picture(
1248 handle, bytes.bindMemory(to: UInt8.self).baseAddress, bytes.count, Float(size.width),
1249 Float(size.height))
1250 }
1251 }
1252 }
1253
1254 // MARK: Recordings
1255
1256 /// Starts recording at the caret, under a line saying when; whether it started.
1257 func startRecording(video: Bool) -> Bool {
1258 guard let handle else { return false }
1259 let (day, time) = titleDate()
1260 return edit(external: true) { sb_view_start_recording(handle, video, day, time) }
1261 }
1262
1263 /// How far the recording has got in milliseconds, without its pauses, and whether it is
1264 /// paused; nil when nothing records.
1265 var recording: (ms: Int64, paused: Bool)? {
1266 guard let handle else { return nil }
1267 var paused = false
1268 let ms = sb_view_recording(handle, &paused)
1269 return ms < 0 ? nil : (ms, paused)
1270 }
1271
1272 /// Nothing typed while the recording is paused links to it.
1273 func pauseRecording(_ paused: Bool) {
1274 guard let handle else { return }
1275 sb_view_pause_recording(handle, paused)
1276 }
1277
1278 /// Puts the recording made where it started: a PCM WAV file, or with `video` the AVI
1279 /// file of `sb_movie_finish`. Nil forgets a recording whose file never came.
1280 func finishRecording(_ file: Data?, video: Bool) {
1281 guard let handle else { return }
1282 _ = edit(external: true) {
1283 guard let file else { return sb_view_finish_recording(handle, nil, 0, video) }
1284 return file.withUnsafeBytes { bytes in
1285 sb_view_finish_recording(handle, bytes.bindMemory(to: UInt8.self).baseAddress, bytes.count, video)
1286 }
1287 }
1288 }
1289
1290 /// The recording the last tap asked to play, with its files written out to play from.
1291 private func playRequest() -> PlayRequest? {
1292 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("Playback")
1293 guard let handle, let json = sb_view_play_request(handle, folder.path) else { return nil }
1294 defer { sb_string_free(json) }
1295 let decoder = JSONDecoder()
1296 decoder.keyDecodingStrategy = .convertFromSnakeCase
1297 return try? decoder.decode(PlayRequest.self, from: Data(String(cString: json).utf8))
1298 }
1299
1300 /// See Playback: the note linked at `ms` into the recording playing is highlighted; nil
1301 /// ends playback.
1302 func played(at ms: Int64?) {
1303 guard let handle, sb_view_played(handle, ms ?? -1) else { return }
1304 dirty = true
1305 }
1306
1307 /// Commits marked text, so it is stored before the app leaves the screen.
1308 func commitComposition() {
1309 guard markedTextRange != nil else { return }
1310 unmarkText()
1311 }
1312
1313 override var keyCommands: [UIKeyCommand]? {
1314 guard isFirstResponder else { return nil }
1315 // Ctrl+1 to Ctrl+9 in OneNote, where the Mac's Command stands for Control.
1316 let tags = Tags.all.prefix(Tags.keyed).enumerated().map { index, tag in
1317 UIKeyCommand(
1318 title: tag.name, action: #selector(formatted), input: "\(index + 1)", modifierFlags: .command,
1319 propertyList: 16 + index)
1320 }
1321 // The desktop's chords, as OneNote for Mac's.
1322 let formats: [(String, String, UIKeyModifierFlags, Int)] = [
1323 ("Strikethrough", "x", [.command, .shift], 3),
1324 ("Bullets", ".", .command, 4),
1325 ("Numbering", "/", .command, 5),
1326 ("Increase Indent", "]", .command, 6),
1327 ("Decrease Indent", "[", .command, 7),
1328 ("Remove Tag", "0", [.command, .control], 8),
1329 ("Clear Formatting", "n", [.command, .shift], 9),
1330 ("Highlight", "h", [.command, .control], 10),
1331 ("Decrease Indent", "\t", .shift, 7),
1332 ]
1333 let commands = tags + formats.map { title, input, modifiers, command in
1334 UIKeyCommand(
1335 title: title, action: #selector(formatted), input: input, modifierFlags: modifiers,
1336 propertyList: command)
1337 }
1338 for command in commands { command.wantsPriorityOverSystemBehavior = true }
1339 let done = UIKeyCommand(title: "Done", action: #selector(finished), input: UIKeyCommand.inputEscape)
1340 return commands + [done]
1341 }
1342
1343 @objc private func formatted(_ command: UIKeyCommand) {
1344 guard let command = command.propertyList as? Int else { return }
1345 apply(UInt8(command))
1346 }
1347
1348 @objc private func finished() { _ = resignFirstResponder() }
1349
1350 // MARK: Coordinates
1351
1352 /// A point in the scroll view's bounds as the canvas view's points from its corner.
1353 private func visible(_ point: CGPoint) -> CGPoint {
1354 CGPoint(x: point.x - contentOffset.x, y: point.y - contentOffset.y)
1355 }
1356
1357 private func bounded(_ rect: [Float]) -> CGRect {
1358 CGRect(
1359 x: CGFloat(rect[0]) + contentOffset.x, y: CGFloat(rect[1]) + contentOffset.y,
1360 width: CGFloat(rect[2]), height: CGFloat(rect[3]))
1361 }
1362
1363 // MARK: UIKeyInput
1364
1365 var hasText: Bool { handle.map { sb_text_length($0) > 0 } ?? false }
1366
1367 func insertText(_ text: String) {
1368 guard let handle else { return }
1369 edit { sb_insert(handle, text) }
1370 }
1371
1372 func deleteBackward() {
1373 guard let handle else { return }
1374 edit { sb_delete_backward(handle) }
1375 }
1376
1377 // MARK: UITextInput
1378
1379 func text(in range: UITextRange) -> String? {
1380 guard let handle, let text = sb_text(handle, UInt32(range.lower), UInt32(range.upper)) else { return nil }
1381 defer { sb_string_free(text) }
1382 return String(cString: text)
1383 }
1384
1385 private func replacing(_ range: UITextRange, with text: String) -> Bool {
1386 guard let handle else { return false }
1387 return sb_replace(handle, UInt32(range.lower), UInt32(range.upper), text)
1388 }
1389
1390 func replace(_ range: UITextRange, withText text: String) {
1391 edit { replacing(range, with: text) }
1392 }
1393
1394 private func choose(_ range: UITextRange) -> Bool {
1395 guard let handle else { return false }
1396 return sb_select(handle, UInt32(range.lower), UInt32(range.upper))
1397 }
1398
1399 var selectedTextRange: UITextRange? {
1400 get {
1401 // Outline previews move before their text geometry is committed.
1402 guard let handle, grip.state != .began, grip.state != .changed else { return nil }
1403 var range: [UInt32] = [0, 0]
1404 sb_selection(handle, &range)
1405 return Range(Int(range[0]), Int(range[1]))
1406 }
1407 set {
1408 guard let newValue else { return }
1409 if choose(newValue) { canvasPlace?.edited = true }
1410 sync()
1411 revealCaret()
1412 dirty = true
1413 changedSelection()
1414 }
1415 }
1416
1417 var markedTextRange: UITextRange? {
1418 guard let handle else { return nil }
1419 var range: [UInt32] = [0, 0]
1420 return sb_marked(handle, &range) ? Range(Int(range[0]), Int(range[1])) : nil
1421 }
1422
1423 var markedTextStyle: [NSAttributedString.Key: Any]?
1424
1425 func setMarkedText(_ markedText: String?, selectedRange: NSRange) {
1426 guard let handle else { return }
1427 edit {
1428 sb_set_marked(
1429 handle, markedText ?? "", UInt32(selectedRange.location),
1430 UInt32(selectedRange.location + selectedRange.length))
1431 }
1432 }
1433
1434 func unmarkText() {
1435 guard let handle else { return }
1436 inputDelegate?.selectionWillChange(self)
1437 inputDelegate?.textWillChange(self)
1438 sb_unmark(handle)
1439 canvasPlace?.edited = true
1440 sync()
1441 revealCaret()
1442 inputDelegate?.textDidChange(self)
1443 inputDelegate?.selectionDidChange(self)
1444 dirty = true
1445 changedSelection()
1446 }
1447
1448 var beginningOfDocument: UITextPosition { Position(0) }
1449 var endOfDocument: UITextPosition { Position(handle.map { Int(sb_text_length($0)) } ?? 0) }
1450
1451 func textRange(from fromPosition: UITextPosition, to toPosition: UITextPosition) -> UITextRange? {
1452 Range(fromPosition.offset, toPosition.offset)
1453 }
1454
1455 func position(from position: UITextPosition, offset: Int) -> UITextPosition? {
1456 let target = position.offset + offset
1457 guard target >= 0, target <= endOfDocument.offset else { return nil }
1458 return Position(target)
1459 }
1460
1461 func position(
1462 from position: UITextPosition, in direction: UITextLayoutDirection, offset: Int
1463 ) -> UITextPosition? {
1464 switch direction {
1465 case .left: return self.position(from: position, offset: -offset)
1466 case .right: return self.position(from: position, offset: offset)
1467 default:
1468 let caret = caretRect(for: position)
1469 let step = (direction == .up ? -1 : 1) * CGFloat(offset) * caret.height
1470 return closestPosition(to: CGPoint(x: caret.midX, y: caret.midY + step))
1471 }
1472 }
1473
1474 func compare(_ position: UITextPosition, to other: UITextPosition) -> ComparisonResult {
1475 position.offset < other.offset
1476 ? .orderedAscending : position.offset > other.offset ? .orderedDescending : .orderedSame
1477 }
1478
1479 func offset(from: UITextPosition, to toPosition: UITextPosition) -> Int { toPosition.offset - from.offset }
1480
1481 func position(within range: UITextRange, farthestIn direction: UITextLayoutDirection) -> UITextPosition? {
1482 direction == .left || direction == .up ? range.start : range.end
1483 }
1484
1485 func characterRange(byExtending position: UITextPosition, in direction: UITextLayoutDirection)
1486 -> UITextRange?
1487 {
1488 direction == .left || direction == .up
1489 ? Range(0, position.offset) : Range(position.offset, endOfDocument.offset)
1490 }
1491
1492 func baseWritingDirection(
1493 for position: UITextPosition, in direction: UITextStorageDirection
1494 ) -> NSWritingDirection { .leftToRight }
1495
1496 func setBaseWritingDirection(_ writingDirection: NSWritingDirection, for range: UITextRange) {}
1497
1498 func firstRect(for range: UITextRange) -> CGRect {
1499 selectionRects(for: range).first?.rect ?? caretRect(for: range.start)
1500 }
1501
1502 func caretRect(for position: UITextPosition) -> CGRect {
1503 guard let handle else { return .zero }
1504 var rect: [Float] = [0, 0, 0, 0]
1505 guard sb_caret_rect(handle, UInt32(position.offset), &rect) else { return .zero }
1506 var caret = bounded(rect)
1507 caret.origin.x -= 1
1508 caret.size.width = 2
1509 return caret
1510 }
1511
1512 func selectionRects(for range: UITextRange) -> [UITextSelectionRect] {
1513 guard let handle else { return [] }
1514 let capacity = 256
1515 var rects = [(Float, Float, Float, Float)](repeating: (0, 0, 0, 0), count: capacity)
1516 let count = min(capacity, sb_range_rects(handle, UInt32(range.lower), UInt32(range.upper), &rects, capacity))
1517 return (0..<count).map {
1518 let rect = rects[$0]
1519 return SelectionRect(
1520 bounded([rect.0, rect.1, rect.2, rect.3]), first: $0 == 0, last: $0 == count - 1)
1521 }
1522 }
1523
1524 func closestPosition(to point: CGPoint) -> UITextPosition? {
1525 guard let handle else { return nil }
1526 let local = visible(point)
1527 return Position(Int(sb_closest(handle, Float(local.x), Float(local.y))))
1528 }
1529
1530 func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? {
1531 let offset = closestPosition(to: point)?.offset ?? range.lower
1532 return Position(min(max(offset, range.lower), range.upper))
1533 }
1534
1535 func characterRange(at point: CGPoint) -> UITextRange? {
1536 guard let position = closestPosition(to: point) else { return nil }
1537 return Range(position.offset, min(position.offset + 1, endOfDocument.offset))
1538 }
1539}
1540
1541/// Words and sentences come from the text; lines come from the canvas's layout, which the
1542/// string tokenizer cannot see, so a tap after a line's last word stays on that line.
1543private final class LineTokenizer: UITextInputStringTokenizer {
1544 private unowned let canvas: CanvasView
1545
1546 init(canvas: CanvasView) {
1547 self.canvas = canvas
1548 super.init(textInput: canvas)
1549 }
1550
1551 private func forward(_ direction: UITextDirection) -> Bool {
1552 [UITextStorageDirection.forward.rawValue, UITextLayoutDirection.right.rawValue,
1553 UITextLayoutDirection.down.rawValue].contains(direction.rawValue)
1554 }
1555
1556 private func line(_ offset: Int) -> CGFloat { canvas.caretRect(for: Position(offset)).minY.rounded() }
1557
1558 private func atEdge(_ offset: Int, forward: Bool) -> Bool {
1559 let end = canvas.endOfDocument.offset
1560 return forward
1561 ? offset >= end || line(offset + 1) != line(offset)
1562 : offset <= 0 || line(offset - 1) != line(offset)
1563 }
1564
1565 private func edge(_ offset: Int, forward: Bool) -> Int {
1566 var offset = offset
1567 while !atEdge(offset, forward: forward) { offset += forward ? 1 : -1 }
1568 return offset
1569 }
1570
1571 override func isPosition(
1572 _ position: UITextPosition, atBoundary granularity: UITextGranularity, inDirection direction: UITextDirection
1573 ) -> Bool {
1574 guard granularity == .line else {
1575 return super.isPosition(position, atBoundary: granularity, inDirection: direction)
1576 }
1577 return atEdge(position.offset, forward: forward(direction))
1578 }
1579
1580 override func position(
1581 from position: UITextPosition, toBoundary granularity: UITextGranularity, inDirection direction: UITextDirection
1582 ) -> UITextPosition? {
1583 guard granularity == .line else {
1584 return super.position(from: position, toBoundary: granularity, inDirection: direction)
1585 }
1586 return Position(edge(position.offset, forward: forward(direction)))
1587 }
1588
1589 override func rangeEnclosingPosition(
1590 _ position: UITextPosition, with granularity: UITextGranularity, inDirection direction: UITextDirection
1591 ) -> UITextRange? {
1592 guard granularity == .line else {
1593 return super.rangeEnclosingPosition(position, with: granularity, inDirection: direction)
1594 }
1595 return Range(edge(position.offset, forward: false), edge(position.offset, forward: true))
1596 }
1597
1598 override func isPosition(
1599 _ position: UITextPosition, withinTextUnit granularity: UITextGranularity, inDirection direction: UITextDirection
1600 ) -> Bool {
1601 granularity == .line || super.isPosition(position, withinTextUnit: granularity, inDirection: direction)
1602 }
1603}
1604
1605/// A short instruction floating at the bottom of the page until the gesture it asks for.
1606private final class Hint: UIVisualEffectView {
1607 private let label = UILabel()
1608
1609 init() {
1610 super.init(effect: UIBlurEffect(style: .systemThickMaterial))
1611 label.font = .preferredFont(forTextStyle: .subheadline)
1612 label.textAlignment = .center
1613 label.translatesAutoresizingMaskIntoConstraints = false
1614 contentView.addSubview(label)
1615 NSLayoutConstraint.activate([
1616 label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
1617 label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
1618 label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
1619 label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10),
1620 ])
1621 layer.cornerRadius = 18
1622 clipsToBounds = true
1623 isUserInteractionEnabled = false
1624 }
1625
1626 required init?(coder: NSCoder) { fatalError() }
1627
1628 /// Shows `text` over the bottom of `view`'s visible area, and says it.
1629 func show(_ text: String, in view: UIScrollView) {
1630 label.text = text
1631 guard let host = view.superview else { return }
1632 translatesAutoresizingMaskIntoConstraints = false
1633 host.addSubview(self)
1634 NSLayoutConstraint.activate([
1635 centerXAnchor.constraint(equalTo: host.centerXAnchor),
1636 bottomAnchor.constraint(equalTo: host.keyboardLayoutGuide.topAnchor, constant: -16),
1637 ])
1638 alpha = 0
1639 UIView.animate(withDuration: 0.2) { self.alpha = 1 }
1640 UIAccessibility.post(notification: .announcement, argument: text)
1641 }
1642
1643 func hide() {
1644 guard superview != nil else { return }
1645 UIView.animate(withDuration: 0.2, animations: { self.alpha = 0 }) { _ in self.removeFromSuperview() }
1646 }
1647}