Sources/OrgstarMobile/MobileEditor.swift
1145 lines · 57098 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import OrgHighlight
6import OrgPresentation
7import UIKit
8
9/// Ranges read by TextKit's delegate callbacks.
10final class LockedRanges: @unchecked Sendable {
11 private let lock = NSLock()
12 private var ranges: [Range<Int>] = []
13 private var starts: Set<Int> = []
14
15 func set(_ new: [Range<Int>], folded: Set<Int>) { lock.withLock { ranges = new; starts = folded } }
16 var all: [Range<Int>] { lock.withLock { ranges } }
17 func covers(_ start: Int, _ end: Int) -> Bool { lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } } }
18 func isFolded(_ start: Int) -> Bool { lock.withLock { starts.contains(start) } }
19 var folded: Set<Int> { lock.withLock { starts } }
20 func containing(_ offset: Int) -> Range<Int>? { lock.withLock { ranges.first { $0.contains(offset) } } }
21}
22
23/// What layout fragments draw beyond the text, read by TextKit's delegate callbacks.
24final class FragmentStyle: @unchecked Sendable {
25 private let lock = NSLock()
26 private var band: (color: UIColor, width: CGFloat) = (.clear, 0)
27 private var selected: (range: Range<Int>, color: UIColor)?
28
29 func set(blockBackground color: UIColor, width: CGFloat) { lock.withLock { band = (color, width) } }
30 var blockBand: (color: UIColor, width: CGFloat) { lock.withLock { band } }
31 /// The selection, which a block's fragment draws over its band, as the Mac's fragments do.
32 func set(selection range: Range<Int>?, color: UIColor) { lock.withLock { selected = range.map { ($0, color) } } }
33 var selection: (range: Range<Int>, color: UIColor)? { lock.withLock { selected } }
34}
35
36/// A text view that offers hardware-keyboard presses to the editor's keymap first.
37final class KeyedTextView: UITextView {
38 var keyHandler: ((UIKey) -> Bool)?
39 /// Keys the editor took, whose release the text system doesn't see. Optional: made by
40 /// UIKit's `init(usingTextLayoutManager:)`, the view skips Swift's default values.
41 private var handled: Set<UIKeyboardHIDUsage>?
42 /// Called after each layout pass, as the view's size settles.
43 var onLayout: (() -> Void)?
44 /// The text container's width while lines are truncated.
45 static let truncatedWidth: CGFloat = 100_000
46
47 /// Long lines run off the right edge and the view scrolls sideways.
48 var truncates: Bool {
49 get { !textContainer.widthTracksTextView }
50 set {
51 textContainer.widthTracksTextView = !newValue
52 if newValue {
53 textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude)
54 } else {
55 textContainer.size = CGSize(width: bounds.width - textContainerInset.left - textContainerInset.right, height: CGFloat.greatestFiniteMagnitude)
56 contentOffset.x = 0
57 }
58 showsHorizontalScrollIndicator = newValue
59 setNeedsLayout()
60 }
61 }
62
63 override func layoutSubviews() {
64 // The text view sets its container's width to its own when it lays out.
65 if truncates, textContainer.size.width != Self.truncatedWidth {
66 textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude)
67 }
68 super.layoutSubviews()
69 // The text view sizes its content to its own width; truncated lines need the widest
70 // laid-out line's.
71 if truncates, let manager = textLayoutManager {
72 let width = ceil(manager.usageBoundsForTextContainer.maxX + textContainerInset.left + textContainerInset.right)
73 if contentSize.width < width { contentSize.width = width }
74 }
75 onLayout?()
76 }
77
78 override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
79 var rest: Set<UIPress> = []
80 for press in presses {
81 if let key = press.key, keyHandler?(key) == true {
82 handled = (handled ?? []).union([key.keyCode])
83 } else {
84 rest.insert(press)
85 }
86 }
87 if !rest.isEmpty { super.pressesBegan(rest, with: event) }
88 }
89
90 override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
91 let rest = presses.filter { press in
92 guard let code = press.key?.keyCode, handled?.contains(code) == true else { return true }
93 handled?.remove(code)
94 return false
95 }
96 if !rest.isEmpty { super.pressesEnded(rest, with: event) }
97 }
98}
99
100/// The iOS editor: a TextKit 2 text view that is the open file's live state, as the Mac's
101/// `OrgEditor` is. Typing and undo go through the text view and into the document; commands
102/// run on the document and apply their edits as one undo step; headings, drawers and blocks
103/// fold as TAB cycles them.
104@MainActor
105final class MobileEditor: NSObject, DocumentBuffer {
106 /// One highlighter for every editor and the reader: it caches compiled grammars and results.
107 static let highlighter = TreeSitterHighlighter()
108 private(set) var document: DocumentState
109 let textView: UITextView
110 var options: EditingOptions = .org {
111 didSet {
112 textView.spellCheckingType = options.spellCheck ? .yes : .no
113 if !showMarkup, options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers || options.prettyEntities != oldValue.prettyEntities {
114 restyleAll()
115 }
116 }
117 }
118 /// Colors and type; a change, or a new Dynamic Type size, restyles the file.
119 var themeSpec: ThemeSpec {
120 get { theme.spec }
121 set {
122 let new = MobileTheme(newValue)
123 guard new.spec != theme.spec || new.font != theme.font else { return }
124 theme = new
125 paragraphStyles = [:]
126 applyThemeToView()
127 restyleAll()
128 }
129 }
130 /// Link brackets and targets, and emphasis markers when `org-hide-emphasis-markers` hides
131 /// them, shown. Hidden markup shows on the caret's line, so it can be edited.
132 var showMarkup = true {
133 didSet { if showMarkup != oldValue { restyleAll() } }
134 }
135 var keymap = KeymapPreset.emacs.keymap
136 var onChange: (() -> Void)?
137 var onMessage: ((String) -> Void)?
138 var onPrompt: ((Prompt, @escaping (String?) -> Void) -> Void)?
139 var onLink: ((OrgLink) -> Void)?
140 /// Edits being applied, which the typing hooks leave alone.
141 private var applyingEdits = false
142 /// Source blocks to write to their files (C-c C-v t).
143 var onTangle: ((Tangle.Scope) -> Void)?
144 /// A source block to run (C-c C-c).
145 var onBabel: ((BabelJob) -> Void)?
146 /// The file's setup files to read again (C-c C-c on a keyword line).
147 var onRefreshSetup: (() -> Void)?
148 /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
149 var onEditBlock: ((BlockEdit) -> Void)?
150 /// A followed timestamp's agenda days: the first (a `Days` number) and how many.
151 var onAgenda: ((Int, Int) -> Void)?
152 /// Commands the app runs, as `app.clock.in`.
153 var onAppCommand: ((String) -> Void)?
154 /// Tags used across the workspace, for completion.
155 var knownTags: @Sendable () -> [String] = { [] }
156
157 private var theme: MobileTheme
158 private(set) var fold = FoldState()
159 private var globalVisibility: GlobalVisibility?
160 let hidden = LockedRanges()
161 /// Blocks drawn on a band.
162 let shaded = LockedRanges()
163 let fragmentStyle = FragmentStyle()
164 private var selectionColor: UIColor = .clear
165 /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`.
166 private var indented = true
167 private var hideStars = false
168 /// One paragraph style per indent pair.
169 private var paragraphStyles: [[Int]: NSParagraphStyle] = [:]
170 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
171 private var revealedLine: NSRange?
172 /// `org-toggle-inline-images`: lines that are only an image link show the image.
173 private(set) var showsImages = false
174 /// The view width images were last sized for.
175 private var imageWidth: CGFloat = 0
176 /// The file's folder, for relative image paths.
177 let baseDirectory: URL?
178 private static let imageCache = NSCache<NSString, UIImage>()
179 private var loading = false
180 private var restyleScheduled: Range<Int>?
181 /// Narrowed table columns (`org-table-shrink`).
182 private var shrunk = ShrunkColumns()
183 /// A command's edits being applied, which keep shrunk columns narrow.
184 private var commandEditing = false
185
186 init(
187 document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default,
188 showMarkup: Bool = true, baseDirectory: URL? = nil
189 ) {
190 self.document = document
191 self.options = options
192 self.showMarkup = showMarkup
193 self.baseDirectory = baseDirectory
194 theme = MobileTheme(spec)
195 let keyed = KeyedTextView(usingTextLayoutManager: true)
196 textView = keyed
197 super.init()
198 keyed.keyHandler = { [weak self] key in self?.handleKey(key) ?? false }
199 keyed.onLayout = { [weak self] in self?.viewResized() }
200 textView.isEditable = editable
201 textView.autocorrectionType = .no
202 textView.autocapitalizationType = .none
203 textView.smartQuotesType = .no
204 textView.smartDashesType = .no
205 textView.smartInsertDeleteType = .no
206 textView.spellCheckingType = options.spellCheck ? .yes : .no
207 textView.keyboardDismissMode = .interactive
208 textView.alwaysBounceVertical = true
209 textView.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
210 textView.delegate = self
211 textView.textStorage.delegate = self
212 textView.textLayoutManager?.delegate = self
213 (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
214 let foldTap = UITapGestureRecognizer(target: self, action: #selector(tappedFold))
215 foldTap.delegate = self
216 textView.addGestureRecognizer(foldTap)
217 let startup = Presentation.startupDisplay(document.tree, options: options)
218 indented = startup.indented
219 hideStars = startup.hideStars
220 showsImages = startup.inlineImages
221 shrunk = ShrunkColumns.startup(document.tree)
222 applyThemeToView()
223 load(document.text)
224 setFolds(startup.folds)
225 if startup.alignTables { _ = perform(AlignAllTables()) }
226 truncatesLines = startup.truncated
227 textView.selectedRange = NSRange(location: 0, length: 0)
228 }
229
230 // MARK: - DocumentBuffer
231
232 var selection: [Range<Int>] {
233 let selected = textView.selectedRange
234 return [selected.location..<NSMaxRange(selected)]
235 }
236
237 func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
238 let before = document.text
239 let defaultsBefore = document.defaults
240 let selected = textView.selectedRange
241 let result = try change(&document)
242 if document.text != before {
243 // A save that merged a change from disk, or a revert: the view shows the new text.
244 shrunk = ShrunkColumns()
245 load(document.text)
246 let length = (document.text as NSString).length
247 textView.selectedRange = NSRange(location: min(selected.location, length), length: 0)
248 textView.undoManager?.removeAllActions()
249 setFolds(fold)
250 } else if document.defaults != defaultsBefore {
251 restyle(0..<(document.text as NSString).length)
252 }
253 return result
254 }
255
256 func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
257 let context = EditContext(
258 revision: document.revision, text: document.text, tree: document.tree, selection: selection,
259 now: now, answers: answers, hidden: hidden.all, options: options, knownTags: knownTags
260 )
261 let step = command.run(in: context)
262 switch step {
263 case .commit(let result):
264 guard textView.isEditable || result.edits.isEmpty else {
265 onMessage?("This file is read-only.")
266 return .failed("read-only")
267 }
268 commandEditing = true
269 applyEdits(result.edits)
270 commandEditing = false
271 if let selected = result.selection?.first {
272 unfold(around: selected.lowerBound)
273 textView.selectedRange = NSRange(location: selected.lowerBound, length: selected.count)
274 textView.scrollRangeToVisible(textView.selectedRange)
275 }
276 for effect in result.effects {
277 switch effect {
278 case .message(let text): onMessage?(text)
279 case .fold(let start):
280 var state = fold
281 state.folds.insert(start)
282 setFolds(state)
283 case .refreshSetup: onRefreshSetup?()
284 default: break
285 }
286 }
287 case .failed(let message):
288 onMessage?(message)
289 case .prompt(let prompt):
290 onPrompt?(prompt) { [weak self] answer in
291 guard let self else { return }
292 guard let answer else { return self.onMessage?("Quit") ?? () }
293 _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
294 }
295 case .external(.editBlock(let edit)) where onEditBlock != nil:
296 onEditBlock?(edit)
297 case .external(.babel(let job)) where onBabel != nil:
298 onBabel?(job)
299 case .external(.tangle(let scope)) where onTangle != nil:
300 onTangle?(scope)
301 case .external(.agenda(let start, let count)) where onAgenda != nil:
302 onAgenda?(start, count)
303 case .external(let request):
304 onMessage?(Self.unavailable(request, title: command.title))
305 }
306 return step
307 }
308
309 /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
310 static func unavailable(_ request: ExternalRequest, title: String) -> String {
311 if case .emacsTable(_, _, _, let reason, _) = request { return "This table needs Emacs, which runs on the Mac: \(reason)." }
312 return "\(title) isn't available on iPhone and iPad."
313 }
314
315 // MARK: - Commands by name and key
316
317 /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
318 func run(keys: String) {
319 guard let chords = KeySequence.parse(keys) else { return }
320 let context = editContext()
321 let binding = keymap.candidates(for: chords).first { binding in
322 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
323 }
324 guard let binding else { return onMessage?("Nothing to do here") ?? () }
325 run(binding.command)
326 }
327
328 func run(_ id: String) {
329 switch id {
330 case "org.cycle":
331 if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
332 case "org.cycle-global": cycleGlobal()
333 case "org.link.open": openLinkAtCaret()
334 case "org.toggle-inline-images": toggleImages()
335 case "editor.toggle-truncate-lines":
336 truncatesLines.toggle()
337 onMessage?(truncatesLines ? "Truncate long lines enabled" : "Truncate long lines disabled")
338 case "edit.undo": textView.undoManager?.undo()
339 case "edit.redo": textView.undoManager?.redo()
340 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": tableColumnWidth(id)
341 case _ where id.hasPrefix("app.") || Self.linkCommands.contains(id):
342 if let onAppCommand { onAppCommand(id) } else { onMessage?("Not available on iOS yet") }
343 default:
344 if let command = Commands.command(id) {
345 _ = perform(command)
346 } else {
347 onMessage?("Not available on iOS yet")
348 }
349 }
350 }
351
352 /// Link commands that need the stored links or the file, which the screen has.
353 static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"]
354
355 func applies(_ id: String, in context: EditContext) -> Bool {
356 if let command = Commands.command(id) { return command.applies(in: context) }
357 switch id {
358 case "org.cycle":
359 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
360 case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "editor.toggle-truncate-lines": return true
361 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
362 "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
363 case _ where Self.linkCommands.contains(id): return onAppCommand != nil
364 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
365 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
366 return TableShrink.table(at: context.caret, in: context.text) != nil
367 default: return false
368 }
369 }
370
371 // MARK: - Hardware keyboard
372
373 private lazy var dispatcher = KeyDispatcher(keymap: keymap)
374
375 private static let named: [UIKeyboardHIDUsage: String] = [
376 .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
377 .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
378 .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
379 .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
380 ]
381
382 /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
383 static func chord(_ key: UIKey) -> KeyChord? {
384 var modifiers: KeyChord.Modifiers = []
385 let flags = key.modifierFlags
386 if flags.contains(.control) { modifiers.insert(.control) }
387 if flags.contains(.alternate) { modifiers.insert(.meta) }
388 if flags.contains(.command) { modifiers.insert(.command) }
389 if let name = named[key.keyCode] {
390 if flags.contains(.shift) { modifiers.insert(.shift) }
391 return KeyChord(name, modifiers)
392 }
393 var characters = key.charactersIgnoringModifiers
394 if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
395 guard characters.count == 1 else { return nil }
396 return KeyChord(characters, modifiers)
397 }
398
399 /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
400 /// and editing keys (C-a, C-e, C-k...) are the text system's.
401 func handleKey(_ key: UIKey) -> Bool {
402 guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
403 // Option alone types characters unless it begins a binding.
404 if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
405 keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
406 switch dispatcher.feed(chord) {
407 case .pending(let keys):
408 onMessage?(KeySequence.format(keys) + "-")
409 return true
410 case .cancelled:
411 onMessage?("Quit")
412 return true
413 case .undefined(let keys):
414 onMessage?("\(KeySequence.format(keys)) is undefined")
415 return true
416 case .unbound:
417 return false
418 case .complete(let keys, let candidates):
419 let context = editContext()
420 let runnable = candidates.first { binding in
421 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
422 }
423 // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
424 guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
425 if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
426 run(binding.command)
427 return true
428 }
429 }
430
431 func editContext() -> EditContext {
432 EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
433 }
434
435 private func openLinkAtCaret() {
436 let caret = textView.selectedRange.location
437 if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
438 onLink?(link)
439 } else if let days = Links.timestampDays(at: caret, text: document.text) {
440 onAgenda?(days.start, days.count)
441 } else {
442 onMessage?("No link here")
443 }
444 }
445
446 // MARK: - Editing
447
448 /// Applies `edits` (against the current text) through the text view as one undo step.
449 func applyEdits(_ edits: [TextEdit]) {
450 let interval = Perf.begin("editor.applyEdits")
451 defer { interval.end() }
452 guard !edits.isEmpty else { return }
453 applyingEdits = true
454 defer { applyingEdits = false }
455 // Straight into the storage: replacing through text input would take the active
456 // keyboard's substitutions (smart dashes) when another view has the keyboard.
457 let storage = textView.textStorage
458 let old = storage.string as NSString
459 // By lines, so a fold between two changes stays.
460 let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
461 var inverse: [TextEdit] = []
462 var delta = 0
463 for edit in ascending {
464 let start = edit.range.lowerBound + delta
465 let length = (edit.replacement as NSString).length
466 inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
467 delta += length - edit.range.count
468 }
469 let caret = textView.selectedRange
470 // One at a time, last first: each is processed alone, so folds between them stay.
471 for edit in ascending.reversed() {
472 storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
473 }
474 textView.undoManager?.registerUndo(withTarget: self) { editor in
475 editor.applyEdits(inverse)
476 editor.textView.selectedRange = caret
477 }
478 }
479
480 /// The storage changed (typing, a command, undo): the document takes the same edit, and
481 /// folds and styles follow.
482 fileprivate func storageEdited(range: NSRange, delta: Int) {
483 let interval = Perf.begin("editor.edit")
484 defer { interval.end() }
485 guard !loading else { return }
486 let old = range.location..<(range.location + range.length - delta)
487 let replacement = (textView.textStorage.string as NSString).substring(with: range)
488 let edit = TextEdit(range: old, replacement: replacement)
489 do {
490 try document.apply([edit], baseRevision: document.revision)
491 } catch {
492 // Out of step: the view's text wins.
493 shrunk = ShrunkColumns()
494 load(textView.textStorage.string)
495 return
496 }
497 for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
498 fold = FoldState(
499 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
500 wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
501 )
502 scheduleRestyle(range.location..<NSMaxRange(range))
503 onChange?()
504 }
505
506 /// Starts after the edit move with it; ones inside it go.
507 private static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
508 Set(starts.compactMap { start in
509 if start >= old.upperBound { return start + delta }
510 return start <= old.lowerBound ? start : nil
511 })
512 }
513
514 // MARK: - Styling
515
516 private func load(_ text: String) {
517 loading = true
518 textView.textStorage.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
519 loading = false
520 shaded.set(Presentation.shadedBlocks(document.tree), folded: [])
521 restyle(0..<(text as NSString).length)
522 textView.typingAttributes = theme.base
523 }
524
525 /// The text view's own colors, and the block band's.
526 private func applyThemeToView() {
527 textView.backgroundColor = theme.color("background") ?? .systemBackground
528 textView.tintColor = theme.color("cursor")
529 textView.typingAttributes = theme.base
530 fragmentStyle.set(blockBackground: theme.color("block-background") ?? .clear, width: textView.bounds.width)
531 themeSelection()
532 }
533
534 /// The selection in the theme's selection color: the text view's selection display
535 /// interaction draws it with our highlight view; the cursor and handles keep the tint.
536 private func themeSelection() {
537 guard let interaction = textView.interactions.lazy.compactMap({ $0 as? UITextSelectionDisplayInteraction }).first else { return }
538 let view = interaction.highlightView as? SelectionHighlightView ?? SelectionHighlightView()
539 view.color = theme.color("selection") ?? UIColor.tintColor.withAlphaComponent(0.25)
540 if interaction.highlightView !== view { interaction.highlightView = view }
541 selectionColor = view.color
542 }
543
544 /// The highlight view draws under the text, so a block's band would cover it: blocks the
545 /// selection enters or leaves are laid out again to draw it over their band.
546 private func redrawSelectedBlocks() {
547 let selected = textView.selectedRange
548 let range = selected.length > 0 ? selected.location..<NSMaxRange(selected) : nil
549 let old = fragmentStyle.selection?.range
550 fragmentStyle.set(selection: range, color: selectionColor)
551 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return }
552 let touched = [old, range].compactMap { $0 }
553 for block in shaded.all where touched.contains(where: { $0.overlaps(block) }) {
554 guard let start = content.location(content.documentRange.location, offsetBy: block.lowerBound),
555 let end = content.location(start, offsetBy: block.count),
556 let textRange = NSTextRange(location: start, end: end) else { continue }
557 // Fragments are kept across layout passes, so they are asked to draw again too.
558 manager.invalidateRenderingAttributes(for: textRange)
559 manager.invalidateLayout(for: textRange)
560 }
561 textView.setNeedsDisplay()
562 }
563
564 /// The band behind blocks spans the view's width, or the widest line's when truncated;
565 /// images are as wide as the view allows.
566 private func viewResized() {
567 let band = fragmentStyle.blockBand
568 let width = max(textView.bounds.width, truncatesLines ? textView.contentSize.width : 0)
569 let resized = imageWidth != textView.bounds.width
570 guard band.width != width || resized else { return }
571 fragmentStyle.set(blockBackground: band.color, width: width)
572 imageWidth = textView.bounds.width
573 if showsImages, resized { restyle(0..<textView.textStorage.length) }
574 if let manager = textView.textLayoutManager {
575 manager.invalidateRenderingAttributes(for: manager.documentRange)
576 manager.invalidateLayout(for: manager.documentRange)
577 }
578 }
579
580 /// Styles the whole file again.
581 private func restyleAll() {
582 let interval = Perf.begin("editor.restyleAll")
583 defer { interval.end() }
584 restyle(0..<textView.textStorage.length)
585 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
586 }
587
588 /// Styles are set after the edit has been processed, as TextKit asks.
589 private func scheduleRestyle(_ range: Range<Int>) {
590 if let pending = restyleScheduled {
591 restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound)
592 return
593 }
594 restyleScheduled = range
595 DispatchQueue.main.async { [weak self] in
596 guard let self, let range = self.restyleScheduled else { return }
597 self.restyleScheduled = nil
598 self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: [])
599 // Small files are restyled whole: a heading or block line changes what follows it.
600 let length = self.textView.textStorage.length
601 self.restyle(length < 60_000 ? 0..<length : range)
602 self.updateHidden()
603 self.textView.typingAttributes = self.theme.base
604 }
605 }
606
607 private var caretLine: NSRange {
608 let text = textView.textStorage.string as NSString
609 return text.lineRange(for: NSRange(location: min(textView.selectedRange.location, text.length), length: 0))
610 }
611
612 /// Sets attributes for the whole lines in `range`, as the Mac editor does.
613 private func restyle(_ range: Range<Int>) {
614 let interval = Perf.begin("editor.restyle")
615 defer { interval.end() }
616 let storage = textView.textStorage
617 let ns = storage.string as NSString
618 guard ns.length > 0 else { return }
619 let lower = min(range.lowerBound, ns.length)
620 let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower)))
621 let whole = lines.location..<NSMaxRange(lines)
622 storage.beginEditing()
623 storage.setAttributes(theme.base, range: lines)
624 if indented {
625 for line in Presentation.lineIndents(document.tree, in: whole) {
626 storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
627 }
628 }
629 let revealed = caretLine
630 var scriptExclusions: [Range<Int>] = []
631 for run in Presentation.styles(document.tree, in: whole, highlighter: Self.highlighter) {
632 let clipped = NSIntersectionRange(NSRange(run.range), lines)
633 guard clipped.length > 0 else { continue }
634 if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue }
635 if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 {
636 storage.addAttributes(theme.hidden, range: clipped)
637 } else {
638 theme.apply(run.role, to: storage, range: clipped)
639 }
640 if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) }
641 }
642 if !showMarkup, options.prettyEntities { prettify(whole, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
643 applyShrunk(whole, in: storage)
644 applyImages(whole, in: storage, revealed: revealed)
645 storage.endEditing()
646 }
647
648 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
649 if let style = paragraphStyles[[firstLine, wrapped]] { return style }
650 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
651 paragraphStyles[[firstLine, wrapped]] = style
652 return style
653 }
654
655 /// `org-pretty-entities`: entities drawn as their character over the entity's last
656 /// character (the rest hidden), sub/superscripts raised without their markers.
657 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
658 let runs = Presentation.prettyRuns(
659 storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
660 scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
661 )
662 for (lineStart, run) in runs {
663 switch run {
664 case .entity(let r, let display):
665 let start = lineStart + r.lowerBound
666 let last = lineStart + r.upperBound - 1
667 let color = storage.attribute(.foregroundColor, at: last, effectiveRange: nil) as? UIColor ?? theme.foreground
668 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
669 storage.addAttributes([.foregroundColor: UIColor.clear, .orgEntityDisplay: display, .orgEntityColor: color], range: NSRange(location: last, length: 1))
670 case .script(let markers, let body, let superscript):
671 for marker in markers {
672 storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
673 }
674 let size = theme.font.pointSize
675 storage.addAttributes([
676 .font: theme.font.withSize(size * 0.7),
677 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
678 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
679 }
680 }
681 }
682
683 /// Moving to another line shows its markup and hides the last one's.
684 private func revealCaretLine() {
685 guard !showMarkup else { return }
686 let line = caretLine
687 guard line != revealedLine else { return }
688 let text = textView.textStorage.string as NSString
689 // The old line may have moved with edits since; restyle the line now at its start.
690 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
691 revealedLine = line
692 for range in [old, line].compactMap({ $0 }) {
693 restyle(range.location..<NSMaxRange(range))
694 }
695 }
696
697 // MARK: - Shrunk table columns
698
699 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
700 /// `expand` for `org-table-expand`.
701 private func tableColumnWidth(_ id: String) {
702 switch shrunk.change(for: id, at: textView.selectedRange.location, in: textView.textStorage.string) {
703 case .notInTable: onMessage?("Not in a table")
704 case .set(let columns, let table): setShrunk(columns, in: table)
705 case .ask(let table, let current, let max):
706 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
707 guard let self, let answer else { return }
708 self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table)
709 }
710 }
711 }
712
713 /// Narrows `columns` of `table` and widens its others.
714 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
715 shrunk.set(columns, in: table, text: textView.textStorage.string)
716 restyleAll()
717 }
718
719 /// Hides each shrunk segment's text and draws its display where the text was, as pretty
720 /// entities draw theirs.
721 private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
722 guard !shrunk.isEmpty else { return }
723 let cell = theme.column
724 for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
725 let r = segment.range
726 let shown = segment.display.count
727 let kept = min(shown, r.count)
728 if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
729 guard kept > 0 else { continue }
730 let visible = NSRange(location: r.upperBound - kept, length: kept)
731 let color = storage.attribute(.foregroundColor, at: visible.location, effectiveRange: nil) as? UIColor ?? theme.foreground
732 storage.addAttribute(.foregroundColor, value: UIColor.clear, range: visible)
733 storage.addAttributes([.orgEntityDisplay: segment.display, .orgEntityColor: color], range: NSRange(location: visible.location, length: 1))
734 if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
735 }
736 }
737
738 // MARK: - Inline images
739
740 private func toggleImages() {
741 showsImages.toggle()
742 restyleAll()
743 if showsImages {
744 let ns = textView.textStorage.string as NSString
745 var count = 0
746 var offset = 0
747 while offset < ns.length {
748 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
749 if let image = InlineImages.image(atLine: line.location, in: ns), Self.loadImage(image.path, relativeTo: baseDirectory) != nil { count += 1 }
750 offset = NSMaxRange(line)
751 }
752 onMessage?("\(count) images displayed inline")
753 } else {
754 onMessage?("Inline image display turned off")
755 }
756 }
757
758 /// An image link's image, by its path or one relative to `baseDirectory`.
759 static func loadImage(_ path: String, relativeTo baseDirectory: URL?) -> UIImage? {
760 let expanded = (path as NSString).expandingTildeInPath
761 let url: URL
762 if expanded.hasPrefix("/") {
763 url = URL(fileURLWithPath: expanded)
764 } else if let baseDirectory {
765 url = baseDirectory.appendingPathComponent(expanded)
766 } else {
767 return nil
768 }
769 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
770 let key = "\(url.path)|\(modified)" as NSString
771 if let cached = Self.imageCache.object(forKey: key) { return cached }
772 guard let image = UIImage(contentsOfFile: url.path) else { return nil }
773 Self.imageCache.setObject(image, forKey: key)
774 return image
775 }
776
777 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
778 /// on the line.
779 private func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
780 guard showsImages else { return }
781 let text = storage.string as NSString
782 let inset = textView.textContainerInset
783 let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40)
784 var location = range.lowerBound
785 while location < range.upperBound, location < text.length {
786 let line = text.lineRange(for: NSRange(location: location, length: 0))
787 location = NSMaxRange(line)
788 guard let image = InlineImages.image(atLine: line.location, in: text), let picture = Self.loadImage(image.path, relativeTo: baseDirectory) else { continue }
789 let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth)
790 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
791 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
792 // Invisible, keeping the line's height.
793 if line.location != revealed.location, content.length > 0 {
794 storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content)
795 }
796 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
797 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
798 // The image sits where the line is; the spacing makes room for the rest of it.
799 style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight)
800 storage.addAttribute(.paragraphStyle, value: style, range: line)
801 }
802 }
803
804 // MARK: - Truncation
805
806 /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead
807 /// of wrapping.
808 var truncatesLines: Bool {
809 get { (textView as? KeyedTextView)?.truncates ?? false }
810 set {
811 guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return }
812 view.truncates = newValue
813 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
814 }
815 }
816
817 // MARK: - Folding
818
819 func setFolds(_ state: FoldState) {
820 fold = state
821 updateHidden()
822 }
823
824 private func updateHidden() {
825 let tree = document.tree
826 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
827 let before = hidden.folded
828 hidden.set(
829 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
830 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
831 )
832 // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment.
833 let storage = textView.textStorage
834 let changed = before.symmetricDifference(hidden.folded).filter { $0 < storage.length }
835 if !changed.isEmpty {
836 let text = storage.string as NSString
837 storage.beginEditing()
838 for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) }
839 storage.endEditing()
840 }
841 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
842 textView.setNeedsDisplay()
843 }
844
845 /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
846 @discardableResult
847 func cycleAtCaret() -> Bool {
848 guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
849 setFolds(next)
850 return true
851 }
852
853 /// Shift-TAB: overview, contents, show all.
854 func cycleGlobal() {
855 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
856 globalVisibility = visibility
857 setFolds(state)
858 }
859
860 /// Opens the folds hiding `offset`.
861 func unfold(around offset: Int) {
862 var state = fold
863 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
864 state.folds.remove(entry.start)
865 state.bodyFolds.remove(entry.start)
866 }
867 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
868 state.wrapperFolds.remove(start)
869 }
870 if state != fold { setFolds(state) }
871 }
872
873 /// Shows the heading at `offset`, unfolded, at the top.
874 func reveal(_ offset: Int) {
875 let length = textView.textStorage.length
876 let target = min(max(0, offset), length)
877 unfold(around: target)
878 textView.selectedRange = NSRange(location: target, length: 0)
879 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
880 }
881
882 /// The caret left hidden text (a tap past a fold): what hides it opens.
883 fileprivate func selectionChanged() {
884 let interval = Perf.begin("editor.selection")
885 defer { interval.end() }
886 redrawSelectedBlocks()
887 let caret = textView.selectedRange.location
888 if hidden.containing(caret) != nil { unfold(around: caret) }
889 revealCaretLine()
890 }
891}
892
893extension MobileEditor: UITextViewDelegate {
894 func textViewDidChangeSelection(_ textView: UITextView) {
895 selectionChanged()
896 }
897
898 /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, from either keyboard.
899 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
900 guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
901 let selected = textView.selectedRange
902 let key: String
903 if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
904 key = "DEL"
905 } else if range == selected, text == "\n" {
906 key = "RET"
907 } else if range == selected, ElectricPairKey.characters.contains(text) {
908 key = text
909 } else {
910 return true
911 }
912 let command = ElectricPairKey(key: key)
913 guard command.applies(in: editContext()) else { return true }
914 _ = perform(command)
915 return false
916 }
917}
918
919extension MobileEditor: UIGestureRecognizerDelegate {
920 /// The start of the folded line whose `…` is at `point`: the space after its text.
921 private func foldedLine(at point: CGPoint) -> Int? {
922 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
923 let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
924 guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
925 let start = content.offset(from: content.documentRange.location, to: range.location)
926 guard hidden.isFolded(start),
927 let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first
928 else { return nil }
929 return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil
930 }
931
932 /// A tap on a fold's `…` opens it, as TAB on its line does.
933 @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
934 guard let start = foldedLine(at: tap.location(in: textView)),
935 let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
936 setFolds(next)
937 }
938
939 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
940 foldedLine(at: gestureRecognizer.location(in: textView)) != nil
941 }
942
943 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
944 true
945 }
946}
947
948extension MobileEditor: NSTextStorageDelegate {
949 nonisolated func textStorage(
950 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
951 ) {
952 guard editedMask.contains(.editedCharacters) else { return }
953 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
954 }
955}
956
957extension MobileEditor: NSTextContentStorageDelegate {
958 /// Folded text isn't enumerated, so it isn't laid out or drawn.
959 nonisolated func textContentManager(
960 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
961 ) -> Bool {
962 guard let range = textElement.elementRange else { return true }
963 let documentStart = textContentManager.documentRange.location
964 let start = textContentManager.offset(from: documentStart, to: range.location)
965 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
966 return !hidden.covers(start, end)
967 }
968}
969
970extension MobileEditor: NSTextLayoutManagerDelegate {
971 /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image lines
972 /// show their image; pretty entities draw their character.
973 nonisolated func textLayoutManager(
974 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
975 ) -> NSTextLayoutFragment {
976 let range = textElement.elementRange
977 guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
978 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
979 let folded = hidden.isFolded(offset)
980 let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
981 let string = (textElement as? NSTextParagraph)?.attributedString
982 let image = string.flatMap(OrgLineFragment.image)
983 let entities = string.map(OrgLineFragment.hasEntities) ?? false
984 guard folded || band != nil || image != nil || entities else { return NSTextLayoutFragment(textElement: textElement, range: range) }
985 let fragment = OrgLineFragment(textElement: textElement, range: range)
986 fragment.folded = folded
987 fragment.band = band
988 if band != nil {
989 fragment.start = offset
990 fragment.style = fragmentStyle
991 }
992 fragment.image = image
993 return fragment
994 }
995}
996
997extension NSAttributedString.Key {
998 /// The character an entity shows as, on the entity's last character.
999 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
1000 /// The color the entity's character is drawn in.
1001 static let orgEntityColor = NSAttributedString.Key("OrgEntityColor")
1002 /// The image an image link's line shows under it.
1003 static let orgImage = NSAttributedString.Key("OrgImage")
1004}
1005
1006final class InlineImageBox: NSObject, @unchecked Sendable {
1007 let image: UIImage
1008 let size: CGSize
1009 init(image: UIImage, size: CGSize) {
1010 self.image = image
1011 self.size = size
1012 }
1013}
1014
1015/// Selected text's background, in one color however the rects overlap.
1016final class SelectionHighlightView: UIView, UITextSelectionHighlightView {
1017 var selectionRects: [UITextSelectionRect] = [] { didSet { setNeedsDisplay() } }
1018 var color: UIColor = .clear { didSet { setNeedsDisplay() } }
1019
1020 override init(frame: CGRect) {
1021 super.init(frame: frame)
1022 isOpaque = false
1023 backgroundColor = .clear
1024 isUserInteractionEnabled = false
1025 registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: SelectionHighlightView, _) in view.setNeedsDisplay() }
1026 }
1027
1028 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
1029
1030 override func draw(_ rect: CGRect) {
1031 let path = UIBezierPath()
1032 for selection in selectionRects where !selection.rect.isEmpty { path.append(UIBezierPath(rect: selection.rect)) }
1033 color.setFill()
1034 path.fill()
1035 }
1036}
1037
1038/// A line drawn with more than its text, as the Mac editor's fragments draw them: a folded
1039/// line's ellipsis, a block's band across the view, an image under an image link, and pretty
1040/// entities' characters where the entities' last (invisible) characters sit.
1041final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable {
1042 var folded = false
1043 var band: (color: UIColor, width: CGFloat)?
1044 var image: InlineImageBox?
1045 /// For a block's lines: where the fragment starts, and where the selection is read.
1046 var start = 0
1047 var style: FragmentStyle?
1048
1049 static func image(_ string: NSAttributedString) -> InlineImageBox? {
1050 var found: InlineImageBox?
1051 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1052 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
1053 }
1054 return found
1055 }
1056
1057 static func hasEntities(_ string: NSAttributedString) -> Bool {
1058 var found = false
1059 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1060 if value != nil { found = true; stop.pointee = true }
1061 }
1062 return found
1063 }
1064
1065 private var bandRect: CGRect? {
1066 guard let band else { return nil }
1067 // Not under the empty line TextKit adds after a final newline.
1068 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
1069 // The width as it is now: the view may have been laid out since this fragment was made.
1070 let width = style?.blockBand.width ?? band.width
1071 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: max(width, layoutFragmentFrame.maxX), height: height)
1072 }
1073
1074 private var imageRect: CGRect? {
1075 guard let image, let line = textLineFragments.first else { return nil }
1076 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: image.size.width, height: image.size.height)
1077 }
1078
1079 override var renderingSurfaceBounds: CGRect {
1080 var bounds = super.renderingSurfaceBounds
1081 if folded { bounds = bounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) }
1082 for rect in [bandRect, imageRect].compactMap({ $0 }) { bounds = bounds.union(rect) }
1083 return bounds
1084 }
1085
1086 override func draw(at point: CGPoint, in context: CGContext) {
1087 if let band, let rect = bandRect {
1088 context.saveGState()
1089 context.setFillColor(band.color.cgColor)
1090 context.fill(rect.offsetBy(dx: point.x, dy: point.y))
1091 context.restoreGState()
1092 drawSelection(at: point, in: context, bandRect: rect)
1093 }
1094 super.draw(at: point, in: context)
1095 UIGraphicsPushContext(context)
1096 defer { UIGraphicsPopContext() }
1097 drawEntities(at: point)
1098 if let image, let rect = imageRect { image.image.draw(in: rect.offsetBy(dx: point.x, dy: point.y)) }
1099 if folded, let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first {
1100 let bounds = line.typographicBounds
1101 let ellipsis = NSAttributedString(string: " …", attributes: [
1102 .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular),
1103 .foregroundColor: UIColor.secondaryLabel,
1104 ])
1105 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
1106 }
1107 }
1108
1109 /// The selected part of each line, over the band; a selection running past a line's end
1110 /// fills to the band's edge.
1111 private func drawSelection(at point: CGPoint, in context: CGContext, bandRect: CGRect) {
1112 guard let selection = style?.selection else { return }
1113 context.saveGState()
1114 context.setFillColor(selection.color.cgColor)
1115 for line in textLineFragments where line.characterRange.length > 0 {
1116 let lineStart = start + line.characterRange.location
1117 let lineEnd = lineStart + line.characterRange.length
1118 let from = max(selection.range.lowerBound, lineStart), to = min(selection.range.upperBound, lineEnd)
1119 guard from < to || (from == to && selection.range.upperBound > lineEnd && from == lineEnd) else { continue }
1120 let bounds = line.typographicBounds
1121 // From the margin when the selection began on an earlier line, as the system draws it.
1122 let margin = bandRect.minX + (textLayoutManager?.textContainer?.lineFragmentPadding ?? 0)
1123 let x1 = selection.range.lowerBound < lineStart ? margin : bounds.minX + line.locationForCharacter(at: from - start).x
1124 let x2 = selection.range.upperBound >= lineEnd ? bandRect.maxX : bounds.minX + line.locationForCharacter(at: to - start).x
1125 context.fill(CGRect(x: point.x + x1, y: point.y + bounds.minY, width: max(0, x2 - x1), height: bounds.height))
1126 }
1127 context.restoreGState()
1128 }
1129
1130 private func drawEntities(at point: CGPoint) {
1131 guard let string = (textElement as? NSTextParagraph)?.attributedString else { return }
1132 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
1133 guard let display = value as? String,
1134 let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
1135 var attributes = string.attributes(at: range.location, effectiveRange: nil)
1136 attributes[.foregroundColor] = attributes[.orgEntityColor] ?? UIColor.label
1137 attributes[.orgEntityDisplay] = nil
1138 attributes[.orgEntityColor] = nil
1139 let x = line.locationForCharacter(at: range.location).x
1140 let bounds = line.typographicBounds
1141 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
1142 }
1143 }
1144}
1145#endif