Sources/OrgstarMobile/MobileEditor.swift
397 lines · 17417 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/// The iOS editor: a TextKit 2 text view that is the open file's live state, as the Mac's
21/// `OrgEditor` is. Typing and undo go through the text view and into the document; commands
22/// run on the document and apply their edits as one undo step; headings, drawers and blocks
23/// fold as TAB cycles them.
24@MainActor
25final class MobileEditor: NSObject, DocumentBuffer {
26 private(set) var document: DocumentState
27 let textView: UITextView
28 var options: EditingOptions = .org
29 var keymap = KeymapPreset.emacs.keymap
30 var onChange: (() -> Void)?
31 var onMessage: ((String) -> Void)?
32 var onPrompt: ((Prompt, @escaping (String?) -> Void) -> Void)?
33 var onLink: ((OrgLink) -> Void)?
34 /// Tags used across the workspace, for completion.
35 var knownTags: @Sendable () -> [String] = { [] }
36
37 private let theme = MobileTheme()
38 private(set) var fold = FoldState()
39 private var globalVisibility: GlobalVisibility?
40 let hidden = LockedRanges()
41 private var loading = false
42 private var restyleScheduled: Range<Int>?
43
44 init(document: DocumentState, editable: Bool) {
45 self.document = document
46 textView = UITextView(usingTextLayoutManager: true)
47 super.init()
48 textView.isEditable = editable
49 textView.autocorrectionType = .no
50 textView.autocapitalizationType = .none
51 textView.smartQuotesType = .no
52 textView.smartDashesType = .no
53 textView.smartInsertDeleteType = .no
54 textView.spellCheckingType = .yes
55 textView.keyboardDismissMode = .interactive
56 textView.alwaysBounceVertical = true
57 textView.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
58 textView.delegate = self
59 textView.textStorage.delegate = self
60 textView.textLayoutManager?.delegate = self
61 (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
62 load(document.text)
63 let tree = document.tree
64 var state = Presentation.applyVisibilityProperties(Presentation.startupFoldState(tree) ?? FoldState(), in: tree)
65 state.wrapperFolds = Presentation.startupWrapperFolds(tree)
66 setFolds(state)
67 textView.selectedRange = NSRange(location: 0, length: 0)
68 }
69
70 // MARK: - DocumentBuffer
71
72 var selection: [Range<Int>] {
73 let selected = textView.selectedRange
74 return [selected.location..<NSMaxRange(selected)]
75 }
76
77 func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
78 let before = document.text
79 let selected = textView.selectedRange
80 let result = try change(&document)
81 if document.text != before {
82 // A save that merged a change from disk, or a revert: the view shows the new text.
83 load(document.text)
84 let length = (document.text as NSString).length
85 textView.selectedRange = NSRange(location: min(selected.location, length), length: 0)
86 textView.undoManager?.removeAllActions()
87 setFolds(fold)
88 }
89 return result
90 }
91
92 func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
93 let context = EditContext(
94 revision: document.revision, text: document.text, tree: document.tree, selection: selection,
95 now: now, answers: answers, hidden: hidden.all, options: options, knownTags: knownTags
96 )
97 let step = command.run(in: context)
98 switch step {
99 case .commit(let result):
100 guard textView.isEditable || result.edits.isEmpty else {
101 onMessage?("This file is read-only.")
102 return .failed("read-only")
103 }
104 applyEdits(result.edits)
105 if let selected = result.selection?.first {
106 unfold(around: selected.lowerBound)
107 textView.selectedRange = NSRange(location: selected.lowerBound, length: selected.count)
108 textView.scrollRangeToVisible(textView.selectedRange)
109 }
110 for effect in result.effects {
111 switch effect {
112 case .message(let text): onMessage?(text)
113 case .fold(let start):
114 var state = fold
115 state.folds.insert(start)
116 setFolds(state)
117 default: break
118 }
119 }
120 case .failed(let message):
121 onMessage?(message)
122 case .prompt(let prompt):
123 onPrompt?(prompt) { [weak self] answer in
124 guard let self else { return }
125 guard let answer else { return self.onMessage?("Quit") ?? () }
126 _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
127 }
128 case .external:
129 onMessage?("\(command.title) needs Emacs, which runs on the Mac.")
130 }
131 return step
132 }
133
134 // MARK: - Commands by name and key
135
136 /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
137 func run(keys: String) {
138 guard let chords = KeySequence.parse(keys) else { return }
139 let context = editContext()
140 let binding = keymap.candidates(for: chords).first { binding in
141 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
142 }
143 guard let binding else { return onMessage?("Nothing to do here") ?? () }
144 run(binding.command)
145 }
146
147 func run(_ id: String) {
148 switch id {
149 case "org.cycle":
150 if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
151 case "org.cycle-global": cycleGlobal()
152 case "org.link.open": openLinkAtCaret()
153 case "edit.undo": textView.undoManager?.undo()
154 case "edit.redo": textView.undoManager?.redo()
155 default:
156 if let command = Commands.command(id) {
157 _ = perform(command)
158 } else {
159 onMessage?("Not available on iOS yet")
160 }
161 }
162 }
163
164 func applies(_ id: String, in context: EditContext) -> Bool {
165 if let command = Commands.command(id) { return command.applies(in: context) }
166 switch id {
167 case "org.cycle":
168 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
169 case "org.cycle-global", "edit.undo", "edit.redo": return true
170 case "org.link.open": return Links.link(at: context.caret, text: context.text, tree: context.tree) != nil
171 default: return false
172 }
173 }
174
175 func editContext() -> EditContext {
176 EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
177 }
178
179 private func openLinkAtCaret() {
180 guard let link = Links.link(at: textView.selectedRange.location, text: document.text, tree: document.tree)?.link else {
181 return onMessage?("No link here") ?? ()
182 }
183 onLink?(link)
184 }
185
186 // MARK: - Editing
187
188 /// Applies `edits` (against the current text) through the text view as one undo step.
189 func applyEdits(_ edits: [TextEdit]) {
190 guard !edits.isEmpty else { return }
191 let undo = textView.undoManager
192 undo?.beginUndoGrouping()
193 for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
194 guard let start = textView.position(from: textView.beginningOfDocument, offset: edit.range.lowerBound),
195 let end = textView.position(from: textView.beginningOfDocument, offset: edit.range.upperBound),
196 let range = textView.textRange(from: start, to: end) else { continue }
197 textView.replace(range, withText: edit.replacement)
198 }
199 undo?.endUndoGrouping()
200 }
201
202 /// The storage changed (typing, a command, undo): the document takes the same edit, and
203 /// folds and styles follow.
204 fileprivate func storageEdited(range: NSRange, delta: Int) {
205 guard !loading else { return }
206 let old = range.location..<(range.location + range.length - delta)
207 let replacement = (textView.textStorage.string as NSString).substring(with: range)
208 do {
209 try document.apply([TextEdit(range: old, replacement: replacement)], baseRevision: document.revision)
210 } catch {
211 // Out of step: the view's text wins.
212 load(textView.textStorage.string)
213 return
214 }
215 fold = FoldState(
216 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
217 wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
218 )
219 scheduleRestyle(range.location..<NSMaxRange(range))
220 onChange?()
221 }
222
223 /// Starts after the edit move with it; ones inside it go.
224 private static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
225 Set(starts.compactMap { start in
226 if start >= old.upperBound { return start + delta }
227 return start <= old.lowerBound ? start : nil
228 })
229 }
230
231 // MARK: - Styling
232
233 private func load(_ text: String) {
234 loading = true
235 textView.textStorage.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
236 loading = false
237 restyle(0..<(text as NSString).length)
238 textView.typingAttributes = theme.base
239 }
240
241 /// Styles are set after the edit has been processed, as TextKit asks.
242 private func scheduleRestyle(_ range: Range<Int>) {
243 if let pending = restyleScheduled {
244 restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound)
245 return
246 }
247 restyleScheduled = range
248 DispatchQueue.main.async { [weak self] in
249 guard let self, let range = self.restyleScheduled else { return }
250 self.restyleScheduled = nil
251 // Small files are restyled whole: a heading or block line changes what follows it.
252 let length = self.textView.textStorage.length
253 self.restyle(length < 60_000 ? 0..<length : range)
254 self.updateHidden()
255 self.textView.typingAttributes = self.theme.base
256 }
257 }
258
259 private func restyle(_ range: Range<Int>) {
260 let storage = textView.textStorage
261 let ns = storage.string as NSString
262 guard ns.length > 0 else { return }
263 let lower = min(range.lowerBound, ns.length)
264 let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower)))
265 storage.beginEditing()
266 storage.setAttributes(theme.base, range: lines)
267 for run in Presentation.styles(document.tree, in: lines.location..<NSMaxRange(lines)) {
268 let clipped = NSIntersectionRange(NSRange(location: run.range.lowerBound, length: run.range.count), lines)
269 if clipped.length > 0 { theme.apply(run.role, to: storage, range: clipped) }
270 }
271 storage.endEditing()
272 }
273
274 // MARK: - Folding
275
276 func setFolds(_ state: FoldState) {
277 fold = state
278 updateHidden()
279 }
280
281 private func updateHidden() {
282 let tree = document.tree
283 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
284 hidden.set(
285 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
286 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
287 )
288 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
289 textView.setNeedsDisplay()
290 }
291
292 /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
293 @discardableResult
294 func cycleAtCaret() -> Bool {
295 guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
296 setFolds(next)
297 return true
298 }
299
300 /// Shift-TAB: overview, contents, show all.
301 func cycleGlobal() {
302 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
303 globalVisibility = visibility
304 setFolds(state)
305 }
306
307 /// Opens the folds hiding `offset`.
308 func unfold(around offset: Int) {
309 var state = fold
310 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
311 state.folds.remove(entry.start)
312 state.bodyFolds.remove(entry.start)
313 }
314 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
315 state.wrapperFolds.remove(start)
316 }
317 if state != fold { setFolds(state) }
318 }
319
320 /// Shows the heading at `offset`, unfolded, at the top.
321 func reveal(_ offset: Int) {
322 let length = textView.textStorage.length
323 let target = min(max(0, offset), length)
324 unfold(around: target)
325 textView.selectedRange = NSRange(location: target, length: 0)
326 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
327 }
328
329 /// The caret left hidden text (a tap past a fold): what hides it opens.
330 fileprivate func selectionChanged() {
331 let caret = textView.selectedRange.location
332 if hidden.containing(caret) != nil { unfold(around: caret) }
333 }
334}
335
336extension MobileEditor: UITextViewDelegate {
337 func textViewDidChangeSelection(_ textView: UITextView) {
338 selectionChanged()
339 }
340}
341
342extension MobileEditor: NSTextStorageDelegate {
343 nonisolated func textStorage(
344 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
345 ) {
346 guard editedMask.contains(.editedCharacters) else { return }
347 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
348 }
349}
350
351extension MobileEditor: NSTextContentStorageDelegate {
352 /// Folded text isn't enumerated, so it isn't laid out or drawn.
353 nonisolated func textContentManager(
354 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
355 ) -> Bool {
356 guard let range = textElement.elementRange else { return true }
357 let documentStart = textContentManager.documentRange.location
358 let start = textContentManager.offset(from: documentStart, to: range.location)
359 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
360 return !hidden.covers(start, end)
361 }
362}
363
364extension MobileEditor: NSTextLayoutManagerDelegate {
365 /// Folded headings, drawers and blocks end with `…`.
366 nonisolated func textLayoutManager(
367 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
368 ) -> NSTextLayoutFragment {
369 let range = textElement.elementRange
370 if let range, let manager = textLayoutManager.textContentManager {
371 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
372 if hidden.isFolded(offset) { return FoldedLineFragment(textElement: textElement, range: range) }
373 }
374 return NSTextLayoutFragment(textElement: textElement, range: range)
375 }
376}
377
378/// A folded line drawn with an ellipsis after it, like org's folded headings.
379final class FoldedLineFragment: NSTextLayoutFragment, @unchecked Sendable {
380 override func draw(at point: CGPoint, in context: CGContext) {
381 super.draw(at: point, in: context)
382 guard let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first else { return }
383 let bounds = line.typographicBounds
384 let ellipsis = NSAttributedString(string: " …", attributes: [
385 .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular),
386 .foregroundColor: UIColor.secondaryLabel,
387 ])
388 UIGraphicsPushContext(context)
389 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
390 UIGraphicsPopContext()
391 }
392
393 override var renderingSurfaceBounds: CGRect {
394 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
395 }
396}
397#endif