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