Sources/OrgstarMobile/MobileEditor.swift
565 lines · 25818 bytes
1#if os(iOS)
2import OrgCore
3import OrgDocument
4import OrgPresentation
5import UIKit
6
7/// Ranges read by TextKit's delegate callbacks.
8final class LockedRanges: @unchecked Sendable {
9 private let lock = NSLock()
10 private var ranges: [Range<Int>] = []
11 private var starts: Set<Int> = []
12
13 func set(_ new: [Range<Int>], folded: Set<Int>) { lock.withLock { ranges = new; starts = folded } }
14 var all: [Range<Int>] { lock.withLock { ranges } }
15 func covers(_ start: Int, _ end: Int) -> Bool { lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } } }
16 func isFolded(_ start: Int) -> Bool { lock.withLock { starts.contains(start) } }
17 func containing(_ offset: Int) -> Range<Int>? { lock.withLock { ranges.first { $0.contains(offset) } } }
18}
19
20/// A text view that offers hardware-keyboard presses to the editor's keymap first.
21final class KeyedTextView: UITextView {
22 var keyHandler: ((UIKey) -> Bool)?
23 /// Keys the editor took, whose release the text system doesn't see. Optional: made by
24 /// UIKit's `init(usingTextLayoutManager:)`, the view skips Swift's default values.
25 private var handled: Set<UIKeyboardHIDUsage>?
26
27 override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
28 var rest: Set<UIPress> = []
29 for press in presses {
30 if let key = press.key, keyHandler?(key) == true {
31 handled = (handled ?? []).union([key.keyCode])
32 } else {
33 rest.insert(press)
34 }
35 }
36 if !rest.isEmpty { super.pressesBegan(rest, with: event) }
37 }
38
39 override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
40 let rest = presses.filter { press in
41 guard let code = press.key?.keyCode, handled?.contains(code) == true else { return true }
42 handled?.remove(code)
43 return false
44 }
45 if !rest.isEmpty { super.pressesEnded(rest, with: event) }
46 }
47}
48
49/// The iOS editor: a TextKit 2 text view that is the open file's live state, as the Mac's
50/// `OrgEditor` is. Typing and undo go through the text view and into the document; commands
51/// run on the document and apply their edits as one undo step; headings, drawers and blocks
52/// fold as TAB cycles them.
53@MainActor
54final class MobileEditor: NSObject, DocumentBuffer {
55 private(set) var document: DocumentState
56 let textView: UITextView
57 var options: EditingOptions = .org {
58 didSet { textView.spellCheckingType = options.spellCheck ? .yes : .no }
59 }
60 var keymap = KeymapPreset.emacs.keymap
61 var onChange: (() -> Void)?
62 var onMessage: ((String) -> Void)?
63 var onPrompt: ((Prompt, @escaping (String?) -> Void) -> Void)?
64 var onLink: ((OrgLink) -> Void)?
65 /// Edits being applied, which the typing hooks leave alone.
66 private var applyingEdits = false
67 /// Source blocks to write to their files (C-c C-v t).
68 var onTangle: ((Tangle.Scope) -> Void)?
69 /// A source block to run (C-c C-c).
70 var onBabel: ((BabelJob) -> Void)?
71 /// The file's setup files to read again (C-c C-c on a keyword line).
72 var onRefreshSetup: (() -> Void)?
73 /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
74 var onEditBlock: ((BlockEdit) -> Void)?
75 /// A followed timestamp's agenda days: the first (a `Days` number) and how many.
76 var onAgenda: ((Int, Int) -> Void)?
77 /// Commands the app runs, as `app.clock.in`.
78 var onAppCommand: ((String) -> Void)?
79 /// Tags used across the workspace, for completion.
80 var knownTags: @Sendable () -> [String] = { [] }
81
82 private let theme = MobileTheme()
83 private(set) var fold = FoldState()
84 private var globalVisibility: GlobalVisibility?
85 let hidden = LockedRanges()
86 private var loading = false
87 private var restyleScheduled: Range<Int>?
88
89 init(document: DocumentState, editable: Bool) {
90 self.document = document
91 let keyed = KeyedTextView(usingTextLayoutManager: true)
92 textView = keyed
93 super.init()
94 keyed.keyHandler = { [weak self] key in self?.handleKey(key) ?? false }
95 textView.isEditable = editable
96 textView.autocorrectionType = .no
97 textView.autocapitalizationType = .none
98 textView.smartQuotesType = .no
99 textView.smartDashesType = .no
100 textView.smartInsertDeleteType = .no
101 textView.spellCheckingType = options.spellCheck ? .yes : .no
102 textView.keyboardDismissMode = .interactive
103 textView.alwaysBounceVertical = true
104 textView.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
105 textView.delegate = self
106 textView.textStorage.delegate = self
107 textView.textLayoutManager?.delegate = self
108 (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
109 load(document.text)
110 let tree = document.tree
111 var state = Presentation.applyVisibilityProperties(Presentation.startupFoldState(tree) ?? FoldState(), in: tree)
112 state.wrapperFolds = Presentation.startupWrapperFolds(tree)
113 setFolds(state)
114 textView.selectedRange = NSRange(location: 0, length: 0)
115 }
116
117 // MARK: - DocumentBuffer
118
119 var selection: [Range<Int>] {
120 let selected = textView.selectedRange
121 return [selected.location..<NSMaxRange(selected)]
122 }
123
124 func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
125 let before = document.text
126 let defaultsBefore = document.defaults
127 let selected = textView.selectedRange
128 let result = try change(&document)
129 if document.text != before {
130 // A save that merged a change from disk, or a revert: the view shows the new text.
131 load(document.text)
132 let length = (document.text as NSString).length
133 textView.selectedRange = NSRange(location: min(selected.location, length), length: 0)
134 textView.undoManager?.removeAllActions()
135 setFolds(fold)
136 } else if document.defaults != defaultsBefore {
137 restyle(0..<(document.text as NSString).length)
138 }
139 return result
140 }
141
142 func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
143 let context = EditContext(
144 revision: document.revision, text: document.text, tree: document.tree, selection: selection,
145 now: now, answers: answers, hidden: hidden.all, options: options, knownTags: knownTags
146 )
147 let step = command.run(in: context)
148 switch step {
149 case .commit(let result):
150 guard textView.isEditable || result.edits.isEmpty else {
151 onMessage?("This file is read-only.")
152 return .failed("read-only")
153 }
154 applyEdits(result.edits)
155 if let selected = result.selection?.first {
156 unfold(around: selected.lowerBound)
157 textView.selectedRange = NSRange(location: selected.lowerBound, length: selected.count)
158 textView.scrollRangeToVisible(textView.selectedRange)
159 }
160 for effect in result.effects {
161 switch effect {
162 case .message(let text): onMessage?(text)
163 case .fold(let start):
164 var state = fold
165 state.folds.insert(start)
166 setFolds(state)
167 case .refreshSetup: onRefreshSetup?()
168 default: break
169 }
170 }
171 case .failed(let message):
172 onMessage?(message)
173 case .prompt(let prompt):
174 onPrompt?(prompt) { [weak self] answer in
175 guard let self else { return }
176 guard let answer else { return self.onMessage?("Quit") ?? () }
177 _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
178 }
179 case .external(.editBlock(let edit)) where onEditBlock != nil:
180 onEditBlock?(edit)
181 case .external(.babel(let job)) where onBabel != nil:
182 onBabel?(job)
183 case .external(.tangle(let scope)) where onTangle != nil:
184 onTangle?(scope)
185 case .external(.agenda(let start, let count)) where onAgenda != nil:
186 onAgenda?(start, count)
187 case .external(let request):
188 onMessage?(Self.unavailable(request, title: command.title))
189 }
190 return step
191 }
192
193 /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
194 static func unavailable(_ request: ExternalRequest, title: String) -> String {
195 if case .emacsTable(_, _, _, let reason, _) = request { return "This table needs Emacs, which runs on the Mac: \(reason)." }
196 return "\(title) isn't available on iPhone and iPad."
197 }
198
199 // MARK: - Commands by name and key
200
201 /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
202 func run(keys: String) {
203 guard let chords = KeySequence.parse(keys) else { return }
204 let context = editContext()
205 let binding = keymap.candidates(for: chords).first { binding in
206 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
207 }
208 guard let binding else { return onMessage?("Nothing to do here") ?? () }
209 run(binding.command)
210 }
211
212 func run(_ id: String) {
213 switch id {
214 case "org.cycle":
215 if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
216 case "org.cycle-global": cycleGlobal()
217 case "org.link.open": openLinkAtCaret()
218 case "edit.undo": textView.undoManager?.undo()
219 case "edit.redo": textView.undoManager?.redo()
220 case _ where id.hasPrefix("app."):
221 if let onAppCommand { onAppCommand(id) } else { onMessage?("Not available on iOS yet") }
222 default:
223 if let command = Commands.command(id) {
224 _ = perform(command)
225 } else {
226 onMessage?("Not available on iOS yet")
227 }
228 }
229 }
230
231 func applies(_ id: String, in context: EditContext) -> Bool {
232 if let command = Commands.command(id) { return command.applies(in: context) }
233 switch id {
234 case "org.cycle":
235 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
236 case "org.cycle-global", "edit.undo", "edit.redo": return true
237 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto": return onAppCommand != nil
238 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
239 default: return false
240 }
241 }
242
243 // MARK: - Hardware keyboard
244
245 private lazy var dispatcher = KeyDispatcher(keymap: keymap)
246
247 private static let named: [UIKeyboardHIDUsage: String] = [
248 .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
249 .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
250 .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
251 .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
252 ]
253
254 /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
255 static func chord(_ key: UIKey) -> KeyChord? {
256 var modifiers: KeyChord.Modifiers = []
257 let flags = key.modifierFlags
258 if flags.contains(.control) { modifiers.insert(.control) }
259 if flags.contains(.alternate) { modifiers.insert(.meta) }
260 if flags.contains(.command) { modifiers.insert(.command) }
261 if let name = named[key.keyCode] {
262 if flags.contains(.shift) { modifiers.insert(.shift) }
263 return KeyChord(name, modifiers)
264 }
265 var characters = key.charactersIgnoringModifiers
266 if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
267 guard characters.count == 1 else { return nil }
268 return KeyChord(characters, modifiers)
269 }
270
271 /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
272 /// and editing keys (C-a, C-e, C-k...) are the text system's.
273 func handleKey(_ key: UIKey) -> Bool {
274 guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
275 // Option alone types characters unless it begins a binding.
276 if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
277 keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
278 switch dispatcher.feed(chord) {
279 case .pending(let keys):
280 onMessage?(KeySequence.format(keys) + "-")
281 return true
282 case .cancelled:
283 onMessage?("Quit")
284 return true
285 case .undefined(let keys):
286 onMessage?("\(KeySequence.format(keys)) is undefined")
287 return true
288 case .unbound:
289 return false
290 case .complete(let keys, let candidates):
291 let context = editContext()
292 let runnable = candidates.first { binding in
293 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
294 }
295 // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
296 guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
297 if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
298 run(binding.command)
299 return true
300 }
301 }
302
303 func editContext() -> EditContext {
304 EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
305 }
306
307 private func openLinkAtCaret() {
308 let caret = textView.selectedRange.location
309 if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
310 onLink?(link)
311 } else if let days = Links.timestampDays(at: caret, text: document.text) {
312 onAgenda?(days.start, days.count)
313 } else {
314 onMessage?("No link here")
315 }
316 }
317
318 // MARK: - Editing
319
320 /// Applies `edits` (against the current text) through the text view as one undo step.
321 func applyEdits(_ edits: [TextEdit]) {
322 guard !edits.isEmpty else { return }
323 applyingEdits = true
324 defer { applyingEdits = false }
325 // Straight into the storage: replacing through text input would take the active
326 // keyboard's substitutions (smart dashes) when another view has the keyboard.
327 let storage = textView.textStorage
328 let old = storage.string as NSString
329 // By lines, so a fold between two changes stays.
330 let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
331 var inverse: [TextEdit] = []
332 var delta = 0
333 for edit in ascending {
334 let start = edit.range.lowerBound + delta
335 let length = (edit.replacement as NSString).length
336 inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
337 delta += length - edit.range.count
338 }
339 let caret = textView.selectedRange
340 // One at a time, last first: each is processed alone, so folds between them stay.
341 for edit in ascending.reversed() {
342 storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
343 }
344 textView.undoManager?.registerUndo(withTarget: self) { editor in
345 editor.applyEdits(inverse)
346 editor.textView.selectedRange = caret
347 }
348 }
349
350 /// The storage changed (typing, a command, undo): the document takes the same edit, and
351 /// folds and styles follow.
352 fileprivate func storageEdited(range: NSRange, delta: Int) {
353 guard !loading else { return }
354 let old = range.location..<(range.location + range.length - delta)
355 let replacement = (textView.textStorage.string as NSString).substring(with: range)
356 do {
357 try document.apply([TextEdit(range: old, replacement: replacement)], baseRevision: document.revision)
358 } catch {
359 // Out of step: the view's text wins.
360 load(textView.textStorage.string)
361 return
362 }
363 fold = FoldState(
364 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
365 wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
366 )
367 scheduleRestyle(range.location..<NSMaxRange(range))
368 onChange?()
369 }
370
371 /// Starts after the edit move with it; ones inside it go.
372 private static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
373 Set(starts.compactMap { start in
374 if start >= old.upperBound { return start + delta }
375 return start <= old.lowerBound ? start : nil
376 })
377 }
378
379 // MARK: - Styling
380
381 private func load(_ text: String) {
382 loading = true
383 textView.textStorage.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
384 loading = false
385 restyle(0..<(text as NSString).length)
386 textView.typingAttributes = theme.base
387 }
388
389 /// Styles are set after the edit has been processed, as TextKit asks.
390 private func scheduleRestyle(_ range: Range<Int>) {
391 if let pending = restyleScheduled {
392 restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound)
393 return
394 }
395 restyleScheduled = range
396 DispatchQueue.main.async { [weak self] in
397 guard let self, let range = self.restyleScheduled else { return }
398 self.restyleScheduled = nil
399 // Small files are restyled whole: a heading or block line changes what follows it.
400 let length = self.textView.textStorage.length
401 self.restyle(length < 60_000 ? 0..<length : range)
402 self.updateHidden()
403 self.textView.typingAttributes = self.theme.base
404 }
405 }
406
407 private func restyle(_ range: Range<Int>) {
408 let storage = textView.textStorage
409 let ns = storage.string as NSString
410 guard ns.length > 0 else { return }
411 let lower = min(range.lowerBound, ns.length)
412 let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower)))
413 storage.beginEditing()
414 storage.setAttributes(theme.base, range: lines)
415 for run in Presentation.styles(document.tree, in: lines.location..<NSMaxRange(lines)) {
416 let clipped = NSIntersectionRange(NSRange(location: run.range.lowerBound, length: run.range.count), lines)
417 if clipped.length > 0 { theme.apply(run.role, to: storage, range: clipped) }
418 }
419 storage.endEditing()
420 }
421
422 // MARK: - Folding
423
424 func setFolds(_ state: FoldState) {
425 fold = state
426 updateHidden()
427 }
428
429 private func updateHidden() {
430 let tree = document.tree
431 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
432 hidden.set(
433 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
434 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
435 )
436 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
437 textView.setNeedsDisplay()
438 }
439
440 /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
441 @discardableResult
442 func cycleAtCaret() -> Bool {
443 guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
444 setFolds(next)
445 return true
446 }
447
448 /// Shift-TAB: overview, contents, show all.
449 func cycleGlobal() {
450 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
451 globalVisibility = visibility
452 setFolds(state)
453 }
454
455 /// Opens the folds hiding `offset`.
456 func unfold(around offset: Int) {
457 var state = fold
458 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
459 state.folds.remove(entry.start)
460 state.bodyFolds.remove(entry.start)
461 }
462 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
463 state.wrapperFolds.remove(start)
464 }
465 if state != fold { setFolds(state) }
466 }
467
468 /// Shows the heading at `offset`, unfolded, at the top.
469 func reveal(_ offset: Int) {
470 let length = textView.textStorage.length
471 let target = min(max(0, offset), length)
472 unfold(around: target)
473 textView.selectedRange = NSRange(location: target, length: 0)
474 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
475 }
476
477 /// The caret left hidden text (a tap past a fold): what hides it opens.
478 fileprivate func selectionChanged() {
479 let caret = textView.selectedRange.location
480 if hidden.containing(caret) != nil { unfold(around: caret) }
481 }
482}
483
484extension MobileEditor: UITextViewDelegate {
485 func textViewDidChangeSelection(_ textView: UITextView) {
486 selectionChanged()
487 }
488
489 /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, from either keyboard.
490 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
491 guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
492 let selected = textView.selectedRange
493 let key: String
494 if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
495 key = "DEL"
496 } else if range == selected, text == "\n" {
497 key = "RET"
498 } else if range == selected, ElectricPairKey.characters.contains(text) {
499 key = text
500 } else {
501 return true
502 }
503 let command = ElectricPairKey(key: key)
504 guard command.applies(in: editContext()) else { return true }
505 _ = perform(command)
506 return false
507 }
508}
509
510extension MobileEditor: NSTextStorageDelegate {
511 nonisolated func textStorage(
512 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
513 ) {
514 guard editedMask.contains(.editedCharacters) else { return }
515 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
516 }
517}
518
519extension MobileEditor: NSTextContentStorageDelegate {
520 /// Folded text isn't enumerated, so it isn't laid out or drawn.
521 nonisolated func textContentManager(
522 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
523 ) -> Bool {
524 guard let range = textElement.elementRange else { return true }
525 let documentStart = textContentManager.documentRange.location
526 let start = textContentManager.offset(from: documentStart, to: range.location)
527 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
528 return !hidden.covers(start, end)
529 }
530}
531
532extension MobileEditor: NSTextLayoutManagerDelegate {
533 /// Folded headings, drawers and blocks end with `…`.
534 nonisolated func textLayoutManager(
535 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
536 ) -> NSTextLayoutFragment {
537 let range = textElement.elementRange
538 if let range, let manager = textLayoutManager.textContentManager {
539 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
540 if hidden.isFolded(offset) { return FoldedLineFragment(textElement: textElement, range: range) }
541 }
542 return NSTextLayoutFragment(textElement: textElement, range: range)
543 }
544}
545
546/// A folded line drawn with an ellipsis after it, like org's folded headings.
547final class FoldedLineFragment: NSTextLayoutFragment, @unchecked Sendable {
548 override func draw(at point: CGPoint, in context: CGContext) {
549 super.draw(at: point, in: context)
550 guard let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first else { return }
551 let bounds = line.typographicBounds
552 let ellipsis = NSAttributedString(string: " …", attributes: [
553 .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular),
554 .foregroundColor: UIColor.secondaryLabel,
555 ])
556 UIGraphicsPushContext(context)
557 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
558 UIGraphicsPopContext()
559 }
560
561 override var renderingSurfaceBounds: CGRect {
562 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
563 }
564}
565#endif