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