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