Sources/OrgstarMobile/MobileEditor.swift
560 lines · 25429 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(.emacsTable(_, _, _, let reason, _)):
188 onMessage?("This table needs Emacs, which runs on the Mac: \(reason).")
189 case .external:
190 onMessage?("\(command.title) needs Emacs, which runs on the Mac.")
191 }
192 return step
193 }
194
195 // MARK: - Commands by name and key
196
197 /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
198 func run(keys: String) {
199 guard let chords = KeySequence.parse(keys) else { return }
200 let context = editContext()
201 let binding = keymap.candidates(for: chords).first { binding in
202 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
203 }
204 guard let binding else { return onMessage?("Nothing to do here") ?? () }
205 run(binding.command)
206 }
207
208 func run(_ id: String) {
209 switch id {
210 case "org.cycle":
211 if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
212 case "org.cycle-global": cycleGlobal()
213 case "org.link.open": openLinkAtCaret()
214 case "edit.undo": textView.undoManager?.undo()
215 case "edit.redo": textView.undoManager?.redo()
216 case _ where id.hasPrefix("app."):
217 if let onAppCommand { onAppCommand(id) } else { onMessage?("Not available on iOS yet") }
218 default:
219 if let command = Commands.command(id) {
220 _ = perform(command)
221 } else {
222 onMessage?("Not available on iOS yet")
223 }
224 }
225 }
226
227 func applies(_ id: String, in context: EditContext) -> Bool {
228 if let command = Commands.command(id) { return command.applies(in: context) }
229 switch id {
230 case "org.cycle":
231 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
232 case "org.cycle-global", "edit.undo", "edit.redo": return true
233 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto": return onAppCommand != nil
234 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
235 default: return false
236 }
237 }
238
239 // MARK: - Hardware keyboard
240
241 private lazy var dispatcher = KeyDispatcher(keymap: keymap)
242
243 private static let named: [UIKeyboardHIDUsage: String] = [
244 .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
245 .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
246 .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
247 .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
248 ]
249
250 /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
251 static func chord(_ key: UIKey) -> KeyChord? {
252 var modifiers: KeyChord.Modifiers = []
253 let flags = key.modifierFlags
254 if flags.contains(.control) { modifiers.insert(.control) }
255 if flags.contains(.alternate) { modifiers.insert(.meta) }
256 if flags.contains(.command) { modifiers.insert(.command) }
257 if let name = named[key.keyCode] {
258 if flags.contains(.shift) { modifiers.insert(.shift) }
259 return KeyChord(name, modifiers)
260 }
261 var characters = key.charactersIgnoringModifiers
262 if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
263 guard characters.count == 1 else { return nil }
264 return KeyChord(characters, modifiers)
265 }
266
267 /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
268 /// and editing keys (C-a, C-e, C-k...) are the text system's.
269 func handleKey(_ key: UIKey) -> Bool {
270 guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
271 // Option alone types characters unless it begins a binding.
272 if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
273 keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
274 switch dispatcher.feed(chord) {
275 case .pending(let keys):
276 onMessage?(KeySequence.format(keys) + "-")
277 return true
278 case .cancelled:
279 onMessage?("Quit")
280 return true
281 case .undefined(let keys):
282 onMessage?("\(KeySequence.format(keys)) is undefined")
283 return true
284 case .unbound:
285 return false
286 case .complete(let keys, let candidates):
287 let context = editContext()
288 let runnable = candidates.first { binding in
289 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
290 }
291 guard let binding = runnable else { return keys.count > 1 }
292 if binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return keys.count > 1 }
293 run(binding.command)
294 return true
295 }
296 }
297
298 func editContext() -> EditContext {
299 EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
300 }
301
302 private func openLinkAtCaret() {
303 let caret = textView.selectedRange.location
304 if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
305 onLink?(link)
306 } else if let days = Links.timestampDays(at: caret, text: document.text) {
307 onAgenda?(days.start, days.count)
308 } else {
309 onMessage?("No link here")
310 }
311 }
312
313 // MARK: - Editing
314
315 /// Applies `edits` (against the current text) through the text view as one undo step.
316 func applyEdits(_ edits: [TextEdit]) {
317 guard !edits.isEmpty else { return }
318 applyingEdits = true
319 defer { applyingEdits = false }
320 // Straight into the storage: replacing through text input would take the active
321 // keyboard's substitutions (smart dashes) when another view has the keyboard.
322 let storage = textView.textStorage
323 let old = storage.string as NSString
324 // By lines, so a fold between two changes stays.
325 let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
326 var inverse: [TextEdit] = []
327 var delta = 0
328 for edit in ascending {
329 let start = edit.range.lowerBound + delta
330 let length = (edit.replacement as NSString).length
331 inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
332 delta += length - edit.range.count
333 }
334 let caret = textView.selectedRange
335 // One at a time, last first: each is processed alone, so folds between them stay.
336 for edit in ascending.reversed() {
337 storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
338 }
339 textView.undoManager?.registerUndo(withTarget: self) { editor in
340 editor.applyEdits(inverse)
341 editor.textView.selectedRange = caret
342 }
343 }
344
345 /// The storage changed (typing, a command, undo): the document takes the same edit, and
346 /// folds and styles follow.
347 fileprivate func storageEdited(range: NSRange, delta: Int) {
348 guard !loading else { return }
349 let old = range.location..<(range.location + range.length - delta)
350 let replacement = (textView.textStorage.string as NSString).substring(with: range)
351 do {
352 try document.apply([TextEdit(range: old, replacement: replacement)], baseRevision: document.revision)
353 } catch {
354 // Out of step: the view's text wins.
355 load(textView.textStorage.string)
356 return
357 }
358 fold = FoldState(
359 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
360 wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
361 )
362 scheduleRestyle(range.location..<NSMaxRange(range))
363 onChange?()
364 }
365
366 /// Starts after the edit move with it; ones inside it go.
367 private static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
368 Set(starts.compactMap { start in
369 if start >= old.upperBound { return start + delta }
370 return start <= old.lowerBound ? start : nil
371 })
372 }
373
374 // MARK: - Styling
375
376 private func load(_ text: String) {
377 loading = true
378 textView.textStorage.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
379 loading = false
380 restyle(0..<(text as NSString).length)
381 textView.typingAttributes = theme.base
382 }
383
384 /// Styles are set after the edit has been processed, as TextKit asks.
385 private func scheduleRestyle(_ range: Range<Int>) {
386 if let pending = restyleScheduled {
387 restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound)
388 return
389 }
390 restyleScheduled = range
391 DispatchQueue.main.async { [weak self] in
392 guard let self, let range = self.restyleScheduled else { return }
393 self.restyleScheduled = nil
394 // Small files are restyled whole: a heading or block line changes what follows it.
395 let length = self.textView.textStorage.length
396 self.restyle(length < 60_000 ? 0..<length : range)
397 self.updateHidden()
398 self.textView.typingAttributes = self.theme.base
399 }
400 }
401
402 private func restyle(_ range: Range<Int>) {
403 let storage = textView.textStorage
404 let ns = storage.string as NSString
405 guard ns.length > 0 else { return }
406 let lower = min(range.lowerBound, ns.length)
407 let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower)))
408 storage.beginEditing()
409 storage.setAttributes(theme.base, range: lines)
410 for run in Presentation.styles(document.tree, in: lines.location..<NSMaxRange(lines)) {
411 let clipped = NSIntersectionRange(NSRange(location: run.range.lowerBound, length: run.range.count), lines)
412 if clipped.length > 0 { theme.apply(run.role, to: storage, range: clipped) }
413 }
414 storage.endEditing()
415 }
416
417 // MARK: - Folding
418
419 func setFolds(_ state: FoldState) {
420 fold = state
421 updateHidden()
422 }
423
424 private func updateHidden() {
425 let tree = document.tree
426 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
427 hidden.set(
428 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
429 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
430 )
431 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
432 textView.setNeedsDisplay()
433 }
434
435 /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
436 @discardableResult
437 func cycleAtCaret() -> Bool {
438 guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
439 setFolds(next)
440 return true
441 }
442
443 /// Shift-TAB: overview, contents, show all.
444 func cycleGlobal() {
445 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
446 globalVisibility = visibility
447 setFolds(state)
448 }
449
450 /// Opens the folds hiding `offset`.
451 func unfold(around offset: Int) {
452 var state = fold
453 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
454 state.folds.remove(entry.start)
455 state.bodyFolds.remove(entry.start)
456 }
457 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
458 state.wrapperFolds.remove(start)
459 }
460 if state != fold { setFolds(state) }
461 }
462
463 /// Shows the heading at `offset`, unfolded, at the top.
464 func reveal(_ offset: Int) {
465 let length = textView.textStorage.length
466 let target = min(max(0, offset), length)
467 unfold(around: target)
468 textView.selectedRange = NSRange(location: target, length: 0)
469 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
470 }
471
472 /// The caret left hidden text (a tap past a fold): what hides it opens.
473 fileprivate func selectionChanged() {
474 let caret = textView.selectedRange.location
475 if hidden.containing(caret) != nil { unfold(around: caret) }
476 }
477}
478
479extension MobileEditor: UITextViewDelegate {
480 func textViewDidChangeSelection(_ textView: UITextView) {
481 selectionChanged()
482 }
483
484 /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, from either keyboard.
485 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
486 guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
487 let selected = textView.selectedRange
488 let key: String
489 if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
490 key = "DEL"
491 } else if range == selected, text == "\n" {
492 key = "RET"
493 } else if range == selected, ElectricPairKey.characters.contains(text) {
494 key = text
495 } else {
496 return true
497 }
498 let command = ElectricPairKey(key: key)
499 guard command.applies(in: editContext()) else { return true }
500 _ = perform(command)
501 return false
502 }
503}
504
505extension MobileEditor: NSTextStorageDelegate {
506 nonisolated func textStorage(
507 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
508 ) {
509 guard editedMask.contains(.editedCharacters) else { return }
510 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
511 }
512}
513
514extension MobileEditor: NSTextContentStorageDelegate {
515 /// Folded text isn't enumerated, so it isn't laid out or drawn.
516 nonisolated func textContentManager(
517 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
518 ) -> Bool {
519 guard let range = textElement.elementRange else { return true }
520 let documentStart = textContentManager.documentRange.location
521 let start = textContentManager.offset(from: documentStart, to: range.location)
522 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
523 return !hidden.covers(start, end)
524 }
525}
526
527extension MobileEditor: NSTextLayoutManagerDelegate {
528 /// Folded headings, drawers and blocks end with `…`.
529 nonisolated func textLayoutManager(
530 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
531 ) -> NSTextLayoutFragment {
532 let range = textElement.elementRange
533 if let range, let manager = textLayoutManager.textContentManager {
534 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
535 if hidden.isFolded(offset) { return FoldedLineFragment(textElement: textElement, range: range) }
536 }
537 return NSTextLayoutFragment(textElement: textElement, range: range)
538 }
539}
540
541/// A folded line drawn with an ellipsis after it, like org's folded headings.
542final class FoldedLineFragment: NSTextLayoutFragment, @unchecked Sendable {
543 override func draw(at point: CGPoint, in context: CGContext) {
544 super.draw(at: point, in: context)
545 guard let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first else { return }
546 let bounds = line.typographicBounds
547 let ellipsis = NSAttributedString(string: " …", attributes: [
548 .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular),
549 .foregroundColor: UIColor.secondaryLabel,
550 ])
551 UIGraphicsPushContext(context)
552 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
553 UIGraphicsPopContext()
554 }
555
556 override var renderingSurfaceBounds: CGRect {
557 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
558 }
559}
560#endif