Commit e401b435a8

e401b435a8497ae4bfbbfb0d4fcf1341479c93c6

parent: 2e0daf23dd

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 04:05 UTC

Split MobileEditor.swift

Layout: unified · split

Sources/OrgstarMobile/MobileEditor+Display.swift added +209
@@ -0,0 +1,209 @@
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import OrgHighlight
6import OrgPresentation
7import UIKit
8
9extension MobileEditor {
10 // MARK: - Shrunk table columns
11
12 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
13 /// `expand` for `org-table-expand`.
14 func tableColumnWidth(_ id: String) {
15 switch shrunk.change(for: id, at: textView.selectedRange.location, in: textView.textStorage.string) {
16 case .notInTable: onMessage?("Not in a table")
17 case .set(let columns, let table): setShrunk(columns, in: table)
18 case .ask(let table, let current, let max):
19 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
20 guard let self, let answer else { return }
21 self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table)
22 }
23 }
24 }
25
26 /// Narrows `columns` of `table` and widens its others.
27 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
28 shrunk.set(columns, in: table, text: textView.textStorage.string)
29 restyle(table)
30 invalidateLayout(lines: [table])
31 }
32
33 /// Hides each shrunk segment's text and draws its display where the text was, as pretty
34 /// entities draw theirs.
35 func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
36 guard !shrunk.isEmpty else { return }
37 let cell = theme.column
38 for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
39 let r = segment.range
40 let shown = segment.display.count
41 let kept = min(shown, r.count)
42 if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
43 guard kept > 0 else { continue }
44 let visible = NSRange(location: r.upperBound - kept, length: kept)
45 let color = storage.attribute(.foregroundColor, at: visible.location, effectiveRange: nil) as? UIColor ?? theme.foreground
46 storage.addAttribute(.foregroundColor, value: UIColor.clear, range: visible)
47 storage.addAttributes([.orgEntityDisplay: segment.display, .orgEntityColor: color], range: NSRange(location: visible.location, length: 1))
48 if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
49 }
50 }
51
52 // MARK: - Inline images
53
54 func toggleImages() {
55 showsImages.toggle()
56 restyleAll()
57 if showsImages {
58 let ns = textView.textStorage.string as NSString
59 var count = 0
60 var offset = 0
61 while offset < ns.length {
62 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
63 if let image = InlineImages.image(atLine: line.location, in: ns), Self.loadImage(image.path, relativeTo: baseDirectory) != nil { count += 1 }
64 offset = NSMaxRange(line)
65 }
66 onMessage?("\(count) images displayed inline")
67 } else {
68 onMessage?("Inline image display turned off")
69 }
70 }
71
72 /// An image link's image, by its path or one relative to `baseDirectory`.
73 static func loadImage(_ path: String, relativeTo baseDirectory: URL?) -> UIImage? {
74 let expanded = (path as NSString).expandingTildeInPath
75 let url: URL
76 if expanded.hasPrefix("/") {
77 url = URL(fileURLWithPath: expanded)
78 } else if let baseDirectory {
79 url = baseDirectory.appendingPathComponent(expanded)
80 } else {
81 return nil
82 }
83 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
84 let key = "\(url.path)|\(modified)" as NSString
85 if let cached = Self.imageCache.object(forKey: key) { return cached }
86 guard let image = UIImage(contentsOfFile: url.path) else { return nil }
87 Self.imageCache.setObject(image, forKey: key)
88 return image
89 }
90
91 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
92 /// on the line.
93 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
94 guard showsImages else { return }
95 let text = storage.string as NSString
96 let inset = textView.textContainerInset
97 let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40)
98 var location = range.lowerBound
99 while location < range.upperBound, location < text.length {
100 let line = text.lineRange(for: NSRange(location: location, length: 0))
101 location = NSMaxRange(line)
102 guard let image = InlineImages.image(atLine: line.location, in: text), let picture = Self.loadImage(image.path, relativeTo: baseDirectory) else { continue }
103 let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth)
104 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
105 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
106 // Invisible, keeping the line's height.
107 if line.location != revealed.location, content.length > 0 {
108 storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content)
109 }
110 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
111 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
112 // The image sits where the line is; the spacing makes room for the rest of it.
113 style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight)
114 storage.addAttribute(.paragraphStyle, value: style, range: line)
115 }
116 }
117
118 // MARK: - Truncation
119
120 /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead
121 /// of wrapping.
122 var truncatesLines: Bool {
123 get { (textView as? KeyedTextView)?.truncates ?? false }
124 set {
125 guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return }
126 keepingTopLine {
127 view.truncates = newValue
128 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
129 }
130 }
131 }
132
133 // MARK: - Folding
134
135 func setFolds(_ state: FoldState) {
136 fold = state
137 updateHidden()
138 }
139
140 func updateHidden() {
141 let tree = document.tree
142 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
143 let before = hidden.folded
144 let oldHidden = hidden.all
145 hidden.set(
146 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
147 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
148 )
149 // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment.
150 let storage = textView.textStorage
151 let changed = before.symmetricDifference(hidden.folded).filter { $0 < storage.length }
152 if !changed.isEmpty {
153 let text = storage.string as NSString
154 storage.beginEditing()
155 for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) }
156 storage.endEditing()
157 }
158 invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all)))
159 textView.setNeedsDisplay()
160 }
161
162 /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
163 @discardableResult
164 func cycleAtCaret() -> Bool {
165 guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
166 setFolds(next)
167 return true
168 }
169
170 /// Shift-TAB: overview, contents, show all.
171 func cycleGlobal() {
172 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
173 globalVisibility = visibility
174 setFolds(state)
175 }
176
177 /// Opens the folds hiding `offset`.
178 func unfold(around offset: Int) {
179 var state = fold
180 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
181 state.folds.remove(entry.start)
182 state.bodyFolds.remove(entry.start)
183 }
184 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
185 state.wrapperFolds.remove(start)
186 }
187 if state != fold { setFolds(state) }
188 }
189
190 /// Shows the heading at `offset`, unfolded, at the top.
191 func reveal(_ offset: Int) {
192 let length = textView.textStorage.length
193 let target = min(max(0, offset), length)
194 unfold(around: target)
195 textView.selectedRange = NSRange(location: target, length: 0)
196 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
197 }
198
199 /// The caret left hidden text (a tap past a fold): what hides it opens.
200 func selectionChanged() {
201 let interval = Perf.begin("editor.selection")
202 defer { interval.end() }
203 redrawSelectedBlocks()
204 let caret = textView.selectedRange.location
205 if hidden.containing(caret) != nil { unfold(around: caret) }
206 revealCaretLine()
207 }
208}
209#endif
Sources/OrgstarMobile/MobileEditor+Styling.swift added +250
@@ -0,0 +1,250 @@
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import OrgHighlight
6import OrgPresentation
7import UIKit
8
9extension MobileEditor {
10 // MARK: - Styling
11
12 func load(_ text: String) {
13 loading = true
14 textView.textStorage.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
15 loading = false
16 shaded.set(Presentation.shadedBlocks(document.tree), folded: [])
17 restyle(0..<(text as NSString).length)
18 textView.typingAttributes = theme.base
19 }
20
21 /// The text view's own colors, and the block band's.
22 func applyThemeToView() {
23 textView.backgroundColor = theme.color("background") ?? .systemBackground
24 textView.tintColor = theme.color("cursor")
25 textView.typingAttributes = theme.base
26 fragmentStyle.set(blockBackground: theme.color("block-background") ?? .clear, width: textView.bounds.width)
27 themeSelection()
28 }
29
30 /// The selection in the theme's selection color: the text view's selection display
31 /// interaction draws it with our highlight view; the cursor and handles keep the tint.
32 private func themeSelection() {
33 guard let interaction = textView.interactions.lazy.compactMap({ $0 as? UITextSelectionDisplayInteraction }).first else { return }
34 let view = interaction.highlightView as? SelectionHighlightView ?? SelectionHighlightView()
35 view.color = theme.color("selection") ?? UIColor.tintColor.withAlphaComponent(0.25)
36 if interaction.highlightView !== view { interaction.highlightView = view }
37 selectionColor = view.color
38 }
39
40 /// The highlight view draws under the text, so a block's band would cover it: blocks the
41 /// selection enters or leaves are laid out again to draw it over their band.
42 func redrawSelectedBlocks() {
43 let selected = textView.selectedRange
44 let range = selected.length > 0 ? selected.location..<NSMaxRange(selected) : nil
45 let old = fragmentStyle.selection?.range
46 fragmentStyle.set(selection: range, color: selectionColor)
47 let touched = [old, range].compactMap { $0 }
48 redraw(blocks: shaded.all.filter { block in touched.contains { $0.overlaps(block) } })
49 }
50
51 /// Lays `blocks` out again and asks their fragments, which are kept across layout passes,
52 /// to draw again.
53 private func redraw(blocks: [Range<Int>]) {
54 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return }
55 for block in blocks {
56 guard let start = content.location(content.documentRange.location, offsetBy: block.lowerBound),
57 let end = content.location(start, offsetBy: block.count),
58 let textRange = NSTextRange(location: start, end: end) else { continue }
59 manager.invalidateRenderingAttributes(for: textRange)
60 manager.invalidateLayout(for: textRange)
61 }
62 textView.setNeedsDisplay()
63 }
64
65 /// The band behind blocks spans the view's width, or the widest line's when truncated;
66 /// images are as wide as the view allows. Only the blocks read the band's width, so a
67 /// wider line in a truncated file, which widens the band on each layout pass, redraws
68 /// the blocks alone: laying the whole file out again moves the text under the view.
69 func viewResized() {
70 let band = fragmentStyle.blockBand
71 let width = max(textView.bounds.width, truncatesLines ? textView.contentSize.width : 0)
72 let resized = imageWidth != textView.bounds.width
73 guard band.width != width || resized else { return }
74 fragmentStyle.set(blockBackground: band.color, width: width)
75 imageWidth = textView.bounds.width
76 guard resized else {
77 redraw(blocks: shaded.all)
78 return
79 }
80 keepingTopLine {
81 if showsImages { restyle(0..<textView.textStorage.length) }
82 if let manager = textView.textLayoutManager {
83 manager.invalidateRenderingAttributes(for: manager.documentRange)
84 manager.invalidateLayout(for: manager.documentRange)
85 }
86 }
87 }
88
89 /// Styles the whole file again.
90 func restyleAll() {
91 let interval = Perf.begin("editor.restyleAll")
92 defer { interval.end() }
93 keepingTopLine {
94 restyle(0..<textView.textStorage.length)
95 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
96 }
97 }
98
99 /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
100 /// heading or opening line of a fold, whose fragment draws the fold mark. Laying out the
101 /// whole file again makes TextKit estimate the height of everything above the view afresh,
102 /// which moves the text under it.
103 func invalidateLayout(lines ranges: [Range<Int>]) {
104 guard !ranges.isEmpty, let manager = textView.textLayoutManager, let content = manager.textContentManager else { return }
105 let text = textView.textStorage.string as NSString
106 for range in ranges {
107 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
108 let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0)))
109 guard let start = content.location(content.documentRange.location, offsetBy: lower),
110 let end = content.location(start, offsetBy: upper - lower),
111 let textRange = NSTextRange(location: start, end: end) else { continue }
112 manager.invalidateLayout(for: textRange)
113 }
114 }
115
116 /// Runs `change`, which lays the whole file out again, and brings the line that was at the
117 /// top of the view back there. TextKit estimates the height of text it hasn't laid out,
118 /// so the same scroll position lands on different text after a fresh layout.
119 func keepingTopLine(_ change: () -> Void) {
120 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return change() }
121 let inset = textView.textContainerInset
122 let top = textView.contentOffset.y + textView.adjustedContentInset.top - inset.top
123 let start = content.documentRange.location
124 let anchor = manager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map {
125 (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY)
126 }
127 change()
128 guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset),
129 let above = NSTextRange(location: start, end: location) else { return }
130 manager.ensureLayout(for: above)
131 guard let fragment = manager.textLayoutFragment(for: location) else { return }
132 let frame = fragment.layoutFragmentFrame
133 manager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * textView.bounds.height))
134 // The view grows to the laid-out height on its next layout pass; the scroll needs it now.
135 let needed = manager.usageBoundsForTextContainer.maxY + inset.top + inset.bottom
136 if textView.contentSize.height < needed { textView.contentSize.height = needed }
137 let y = frame.minY + inset.top + max(0, min(anchor.within, frame.height)) - textView.adjustedContentInset.top
138 textView.contentOffset = CGPoint(x: textView.contentOffset.x, y: y)
139 }
140
141 /// Styles are set after the edit has been processed, as TextKit asks.
142 func scheduleRestyle(_ range: Range<Int>) {
143 if let pending = restyleScheduled {
144 restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound)
145 return
146 }
147 restyleScheduled = range
148 DispatchQueue.main.async { [weak self] in
149 guard let self, let range = self.restyleScheduled else { return }
150 self.restyleScheduled = nil
151 self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: [])
152 // Small files are restyled whole: a heading or block line changes what follows it.
153 let length = self.textView.textStorage.length
154 self.restyle(length < 60_000 ? 0..<length : range)
155 self.updateHidden()
156 self.textView.typingAttributes = self.theme.base
157 }
158 }
159
160 private var caretLine: NSRange {
161 let text = textView.textStorage.string as NSString
162 return text.lineRange(for: NSRange(location: min(textView.selectedRange.location, text.length), length: 0))
163 }
164
165 /// Sets attributes for the whole lines in `range`, as the Mac editor does.
166 func restyle(_ range: Range<Int>) {
167 let interval = Perf.begin("editor.restyle")
168 defer { interval.end() }
169 let storage = textView.textStorage
170 let ns = storage.string as NSString
171 guard ns.length > 0 else { return }
172 let lower = min(range.lowerBound, ns.length)
173 let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower)))
174 let whole = lines.location..<NSMaxRange(lines)
175 storage.beginEditing()
176 storage.setAttributes(theme.base, range: lines)
177 if indented {
178 for line in Presentation.lineIndents(document.tree, in: whole) {
179 storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
180 }
181 }
182 let revealed = caretLine
183 var scriptExclusions: [Range<Int>] = []
184 for run in Presentation.styles(document.tree, in: whole, highlighter: Self.highlighter) {
185 let clipped = NSIntersectionRange(NSRange(run.range), lines)
186 guard clipped.length > 0 else { continue }
187 if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue }
188 if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 {
189 storage.addAttributes(theme.hidden, range: clipped)
190 } else {
191 theme.apply(run.role, to: storage, range: clipped)
192 }
193 if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) }
194 }
195 if !showMarkup, options.prettyEntities { prettify(whole, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
196 applyShrunk(whole, in: storage)
197 applyImages(whole, in: storage, revealed: revealed)
198 storage.endEditing()
199 }
200
201 func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
202 if let style = paragraphStyles[[firstLine, wrapped]] { return style }
203 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
204 paragraphStyles[[firstLine, wrapped]] = style
205 return style
206 }
207
208 /// `org-pretty-entities`: entities drawn as their character over the entity's last
209 /// character (the rest hidden), sub/superscripts raised without their markers.
210 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
211 let runs = Presentation.prettyRuns(
212 storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
213 scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
214 )
215 for (lineStart, run) in runs {
216 switch run {
217 case .entity(let r, let display):
218 let start = lineStart + r.lowerBound
219 let last = lineStart + r.upperBound - 1
220 let color = storage.attribute(.foregroundColor, at: last, effectiveRange: nil) as? UIColor ?? theme.foreground
221 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
222 storage.addAttributes([.foregroundColor: UIColor.clear, .orgEntityDisplay: display, .orgEntityColor: color], range: NSRange(location: last, length: 1))
223 case .script(let markers, let body, let superscript):
224 for marker in markers {
225 storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
226 }
227 let size = theme.font.pointSize
228 storage.addAttributes([
229 .font: theme.font.withSize(size * 0.7),
230 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
231 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
232 }
233 }
234 }
235
236 /// Moving to another line shows its markup and hides the last one's.
237 func revealCaretLine() {
238 guard !showMarkup else { return }
239 let line = caretLine
240 guard line != revealedLine else { return }
241 let text = textView.textStorage.string as NSString
242 // The old line may have moved with edits since; restyle the line now at its start.
243 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
244 revealedLine = line
245 for range in [old, line].compactMap({ $0 }) {
246 restyle(range.location..<NSMaxRange(range))
247 }
248 }
249}
250#endif
Sources/OrgstarMobile/MobileEditor.swift +15 −693
@@ -6,97 +6,6 @@ import OrgHighlight
6import OrgPresentation 6import OrgPresentation
7import UIKit 7import UIKit
8 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 9/// 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 10/// `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 11/// run on the document and apply their edits as one undo step; headings, drawers and blocks
@@ -154,32 +63,32 @@ final class MobileEditor: NSObject, DocumentBuffer {
154 /// Tags used across the workspace, for completion. 63 /// Tags used across the workspace, for completion.
155 var knownTags: @Sendable () -> [String] = { [] } 64 var knownTags: @Sendable () -> [String] = { [] }
156 65
157 private var theme: MobileTheme 66 var theme: MobileTheme
158 private(set) var fold = FoldState() 67 internal(set) var fold = FoldState()
159 private var globalVisibility: GlobalVisibility? 68 var globalVisibility: GlobalVisibility?
160 let hidden = LockedRanges() 69 let hidden = LockedRanges()
161 /// Blocks drawn on a band. 70 /// Blocks drawn on a band.
162 let shaded = LockedRanges() 71 let shaded = LockedRanges()
163 let fragmentStyle = FragmentStyle() 72 let fragmentStyle = FragmentStyle()
164 private var selectionColor: UIColor = .clear 73 var selectionColor: UIColor = .clear
165 /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`. 74 /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`.
166 private var indented = true 75 var indented = true
167 private var hideStars = false 76 var hideStars = false
168 /// One paragraph style per indent pair. 77 /// One paragraph style per indent pair.
169 private var paragraphStyles: [[Int]: NSParagraphStyle] = [:] 78 var paragraphStyles: [[Int]: NSParagraphStyle] = [:]
170 /// The line last revealed while markup is hidden, to hide again when the caret leaves. 79 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
171 private var revealedLine: NSRange? 80 var revealedLine: NSRange?
172 /// `org-toggle-inline-images`: lines that are only an image link show the image. 81 /// `org-toggle-inline-images`: lines that are only an image link show the image.
173 private(set) var showsImages = false 82 internal(set) var showsImages = false
174 /// The view width images were last sized for. 83 /// The view width images were last sized for.
175 private var imageWidth: CGFloat = 0 84 var imageWidth: CGFloat = 0
176 /// The file's folder, for relative image paths. 85 /// The file's folder, for relative image paths.
177 let baseDirectory: URL? 86 let baseDirectory: URL?
178 private static let imageCache = NSCache<NSString, UIImage>() 87 static let imageCache = NSCache<NSString, UIImage>()
179 private var loading = false 88 var loading = false
180 private var restyleScheduled: Range<Int>? 89 var restyleScheduled: Range<Int>?
181 /// Narrowed table columns (`org-table-shrink`). 90 /// Narrowed table columns (`org-table-shrink`).
182 private var shrunk = ShrunkColumns() 91 var shrunk = ShrunkColumns()
183 /// A command's edits being applied, which keep shrunk columns narrow. 92 /// A command's edits being applied, which keep shrunk columns narrow.
184 private var commandEditing = false 93 private var commandEditing = false
185 94
@@ -504,451 +413,13 @@ final class MobileEditor: NSObject, DocumentBuffer {
504 } 413 }
505 414
506 /// Starts after the edit move with it; ones inside it go. 415 /// 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> { 416 static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
508 Set(starts.compactMap { start in 417 Set(starts.compactMap { start in
509 if start >= old.upperBound { return start + delta } 418 if start >= old.upperBound { return start + delta }
510 return start <= old.lowerBound ? start : nil 419 return start <= old.lowerBound ? start : nil
511 }) 420 })
512 } 421 }
513 422
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 let touched = [old, range].compactMap { $0 }
552 redraw(blocks: shaded.all.filter { block in touched.contains { $0.overlaps(block) } })
553 }
554
555 /// Lays `blocks` out again and asks their fragments, which are kept across layout passes,
556 /// to draw again.
557 private func redraw(blocks: [Range<Int>]) {
558 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return }
559 for block in blocks {
560 guard let start = content.location(content.documentRange.location, offsetBy: block.lowerBound),
561 let end = content.location(start, offsetBy: block.count),
562 let textRange = NSTextRange(location: start, end: end) else { continue }
563 manager.invalidateRenderingAttributes(for: textRange)
564 manager.invalidateLayout(for: textRange)
565 }
566 textView.setNeedsDisplay()
567 }
568
569 /// The band behind blocks spans the view's width, or the widest line's when truncated;
570 /// images are as wide as the view allows. Only the blocks read the band's width, so a
571 /// wider line in a truncated file, which widens the band on each layout pass, redraws
572 /// the blocks alone: laying the whole file out again moves the text under the view.
573 private func viewResized() {
574 let band = fragmentStyle.blockBand
575 let width = max(textView.bounds.width, truncatesLines ? textView.contentSize.width : 0)
576 let resized = imageWidth != textView.bounds.width
577 guard band.width != width || resized else { return }
578 fragmentStyle.set(blockBackground: band.color, width: width)
579 imageWidth = textView.bounds.width
580 guard resized else {
581 redraw(blocks: shaded.all)
582 return
583 }
584 keepingTopLine {
585 if showsImages { restyle(0..<textView.textStorage.length) }
586 if let manager = textView.textLayoutManager {
587 manager.invalidateRenderingAttributes(for: manager.documentRange)
588 manager.invalidateLayout(for: manager.documentRange)
589 }
590 }
591 }
592
593 /// Styles the whole file again.
594 private func restyleAll() {
595 let interval = Perf.begin("editor.restyleAll")
596 defer { interval.end() }
597 keepingTopLine {
598 restyle(0..<textView.textStorage.length)
599 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
600 }
601 }
602
603 /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
604 /// heading or opening line of a fold, whose fragment draws the fold mark. Laying out the
605 /// whole file again makes TextKit estimate the height of everything above the view afresh,
606 /// which moves the text under it.
607 private func invalidateLayout(lines ranges: [Range<Int>]) {
608 guard !ranges.isEmpty, let manager = textView.textLayoutManager, let content = manager.textContentManager else { return }
609 let text = textView.textStorage.string as NSString
610 for range in ranges {
611 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
612 let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0)))
613 guard let start = content.location(content.documentRange.location, offsetBy: lower),
614 let end = content.location(start, offsetBy: upper - lower),
615 let textRange = NSTextRange(location: start, end: end) else { continue }
616 manager.invalidateLayout(for: textRange)
617 }
618 }
619
620 /// Runs `change`, which lays the whole file out again, and brings the line that was at the
621 /// top of the view back there. TextKit estimates the height of text it hasn't laid out,
622 /// so the same scroll position lands on different text after a fresh layout.
623 private func keepingTopLine(_ change: () -> Void) {
624 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return change() }
625 let inset = textView.textContainerInset
626 let top = textView.contentOffset.y + textView.adjustedContentInset.top - inset.top
627 let start = content.documentRange.location
628 let anchor = manager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map {
629 (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY)
630 }
631 change()
632 guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset),
633 let above = NSTextRange(location: start, end: location) else { return }
634 manager.ensureLayout(for: above)
635 guard let fragment = manager.textLayoutFragment(for: location) else { return }
636 let frame = fragment.layoutFragmentFrame
637 manager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * textView.bounds.height))
638 // The view grows to the laid-out height on its next layout pass; the scroll needs it now.
639 let needed = manager.usageBoundsForTextContainer.maxY + inset.top + inset.bottom
640 if textView.contentSize.height < needed { textView.contentSize.height = needed }
641 let y = frame.minY + inset.top + max(0, min(anchor.within, frame.height)) - textView.adjustedContentInset.top
642 textView.contentOffset = CGPoint(x: textView.contentOffset.x, y: y)
643 }
644
645 /// Styles are set after the edit has been processed, as TextKit asks.
646 private func scheduleRestyle(_ range: Range<Int>) {
647 if let pending = restyleScheduled {
648 restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound)
649 return
650 }
651 restyleScheduled = range
652 DispatchQueue.main.async { [weak self] in
653 guard let self, let range = self.restyleScheduled else { return }
654 self.restyleScheduled = nil
655 self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: [])
656 // Small files are restyled whole: a heading or block line changes what follows it.
657 let length = self.textView.textStorage.length
658 self.restyle(length < 60_000 ? 0..<length : range)
659 self.updateHidden()
660 self.textView.typingAttributes = self.theme.base
661 }
662 }
663
664 private var caretLine: NSRange {
665 let text = textView.textStorage.string as NSString
666 return text.lineRange(for: NSRange(location: min(textView.selectedRange.location, text.length), length: 0))
667 }
668
669 /// Sets attributes for the whole lines in `range`, as the Mac editor does.
670 private func restyle(_ range: Range<Int>) {
671 let interval = Perf.begin("editor.restyle")
672 defer { interval.end() }
673 let storage = textView.textStorage
674 let ns = storage.string as NSString
675 guard ns.length > 0 else { return }
676 let lower = min(range.lowerBound, ns.length)
677 let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower)))
678 let whole = lines.location..<NSMaxRange(lines)
679 storage.beginEditing()
680 storage.setAttributes(theme.base, range: lines)
681 if indented {
682 for line in Presentation.lineIndents(document.tree, in: whole) {
683 storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
684 }
685 }
686 let revealed = caretLine
687 var scriptExclusions: [Range<Int>] = []
688 for run in Presentation.styles(document.tree, in: whole, highlighter: Self.highlighter) {
689 let clipped = NSIntersectionRange(NSRange(run.range), lines)
690 guard clipped.length > 0 else { continue }
691 if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue }
692 if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 {
693 storage.addAttributes(theme.hidden, range: clipped)
694 } else {
695 theme.apply(run.role, to: storage, range: clipped)
696 }
697 if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) }
698 }
699 if !showMarkup, options.prettyEntities { prettify(whole, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
700 applyShrunk(whole, in: storage)
701 applyImages(whole, in: storage, revealed: revealed)
702 storage.endEditing()
703 }
704
705 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
706 if let style = paragraphStyles[[firstLine, wrapped]] { return style }
707 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
708 paragraphStyles[[firstLine, wrapped]] = style
709 return style
710 }
711
712 /// `org-pretty-entities`: entities drawn as their character over the entity's last
713 /// character (the rest hidden), sub/superscripts raised without their markers.
714 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
715 let runs = Presentation.prettyRuns(
716 storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
717 scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
718 )
719 for (lineStart, run) in runs {
720 switch run {
721 case .entity(let r, let display):
722 let start = lineStart + r.lowerBound
723 let last = lineStart + r.upperBound - 1
724 let color = storage.attribute(.foregroundColor, at: last, effectiveRange: nil) as? UIColor ?? theme.foreground
725 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
726 storage.addAttributes([.foregroundColor: UIColor.clear, .orgEntityDisplay: display, .orgEntityColor: color], range: NSRange(location: last, length: 1))
727 case .script(let markers, let body, let superscript):
728 for marker in markers {
729 storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
730 }
731 let size = theme.font.pointSize
732 storage.addAttributes([
733 .font: theme.font.withSize(size * 0.7),
734 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
735 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
736 }
737 }
738 }
739
740 /// Moving to another line shows its markup and hides the last one's.
741 private func revealCaretLine() {
742 guard !showMarkup else { return }
743 let line = caretLine
744 guard line != revealedLine else { return }
745 let text = textView.textStorage.string as NSString
746 // The old line may have moved with edits since; restyle the line now at its start.
747 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
748 revealedLine = line
749 for range in [old, line].compactMap({ $0 }) {
750 restyle(range.location..<NSMaxRange(range))
751 }
752 }
753
754 // MARK: - Shrunk table columns
755
756 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
757 /// `expand` for `org-table-expand`.
758 private func tableColumnWidth(_ id: String) {
759 switch shrunk.change(for: id, at: textView.selectedRange.location, in: textView.textStorage.string) {
760 case .notInTable: onMessage?("Not in a table")
761 case .set(let columns, let table): setShrunk(columns, in: table)
762 case .ask(let table, let current, let max):
763 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
764 guard let self, let answer else { return }
765 self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table)
766 }
767 }
768 }
769
770 /// Narrows `columns` of `table` and widens its others.
771 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
772 shrunk.set(columns, in: table, text: textView.textStorage.string)
773 restyle(table)
774 invalidateLayout(lines: [table])
775 }
776
777 /// Hides each shrunk segment's text and draws its display where the text was, as pretty
778 /// entities draw theirs.
779 private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
780 guard !shrunk.isEmpty else { return }
781 let cell = theme.column
782 for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
783 let r = segment.range
784 let shown = segment.display.count
785 let kept = min(shown, r.count)
786 if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
787 guard kept > 0 else { continue }
788 let visible = NSRange(location: r.upperBound - kept, length: kept)
789 let color = storage.attribute(.foregroundColor, at: visible.location, effectiveRange: nil) as? UIColor ?? theme.foreground
790 storage.addAttribute(.foregroundColor, value: UIColor.clear, range: visible)
791 storage.addAttributes([.orgEntityDisplay: segment.display, .orgEntityColor: color], range: NSRange(location: visible.location, length: 1))
792 if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
793 }
794 }
795
796 // MARK: - Inline images
797
798 private func toggleImages() {
799 showsImages.toggle()
800 restyleAll()
801 if showsImages {
802 let ns = textView.textStorage.string as NSString
803 var count = 0
804 var offset = 0
805 while offset < ns.length {
806 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
807 if let image = InlineImages.image(atLine: line.location, in: ns), Self.loadImage(image.path, relativeTo: baseDirectory) != nil { count += 1 }
808 offset = NSMaxRange(line)
809 }
810 onMessage?("\(count) images displayed inline")
811 } else {
812 onMessage?("Inline image display turned off")
813 }
814 }
815
816 /// An image link's image, by its path or one relative to `baseDirectory`.
817 static func loadImage(_ path: String, relativeTo baseDirectory: URL?) -> UIImage? {
818 let expanded = (path as NSString).expandingTildeInPath
819 let url: URL
820 if expanded.hasPrefix("/") {
821 url = URL(fileURLWithPath: expanded)
822 } else if let baseDirectory {
823 url = baseDirectory.appendingPathComponent(expanded)
824 } else {
825 return nil
826 }
827 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
828 let key = "\(url.path)|\(modified)" as NSString
829 if let cached = Self.imageCache.object(forKey: key) { return cached }
830 guard let image = UIImage(contentsOfFile: url.path) else { return nil }
831 Self.imageCache.setObject(image, forKey: key)
832 return image
833 }
834
835 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
836 /// on the line.
837 private func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
838 guard showsImages else { return }
839 let text = storage.string as NSString
840 let inset = textView.textContainerInset
841 let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40)
842 var location = range.lowerBound
843 while location < range.upperBound, location < text.length {
844 let line = text.lineRange(for: NSRange(location: location, length: 0))
845 location = NSMaxRange(line)
846 guard let image = InlineImages.image(atLine: line.location, in: text), let picture = Self.loadImage(image.path, relativeTo: baseDirectory) else { continue }
847 let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth)
848 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
849 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
850 // Invisible, keeping the line's height.
851 if line.location != revealed.location, content.length > 0 {
852 storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content)
853 }
854 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
855 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
856 // The image sits where the line is; the spacing makes room for the rest of it.
857 style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight)
858 storage.addAttribute(.paragraphStyle, value: style, range: line)
859 }
860 }
861
862 // MARK: - Truncation
863
864 /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead
865 /// of wrapping.
866 var truncatesLines: Bool {
867 get { (textView as? KeyedTextView)?.truncates ?? false }
868 set {
869 guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return }
870 keepingTopLine {
871 view.truncates = newValue
872 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
873 }
874 }
875 }
876
877 // MARK: - Folding
878
879 func setFolds(_ state: FoldState) {
880 fold = state
881 updateHidden()
882 }
883
884 private func updateHidden() {
885 let tree = document.tree
886 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
887 let before = hidden.folded
888 let oldHidden = hidden.all
889 hidden.set(
890 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
891 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
892 )
893 // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment.
894 let storage = textView.textStorage
895 let changed = before.symmetricDifference(hidden.folded).filter { $0 < storage.length }
896 if !changed.isEmpty {
897 let text = storage.string as NSString
898 storage.beginEditing()
899 for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) }
900 storage.endEditing()
901 }
902 invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all)))
903 textView.setNeedsDisplay()
904 }
905
906 /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
907 @discardableResult
908 func cycleAtCaret() -> Bool {
909 guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
910 setFolds(next)
911 return true
912 }
913
914 /// Shift-TAB: overview, contents, show all.
915 func cycleGlobal() {
916 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
917 globalVisibility = visibility
918 setFolds(state)
919 }
920
921 /// Opens the folds hiding `offset`.
922 func unfold(around offset: Int) {
923 var state = fold
924 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
925 state.folds.remove(entry.start)
926 state.bodyFolds.remove(entry.start)
927 }
928 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
929 state.wrapperFolds.remove(start)
930 }
931 if state != fold { setFolds(state) }
932 }
933
934 /// Shows the heading at `offset`, unfolded, at the top.
935 func reveal(_ offset: Int) {
936 let length = textView.textStorage.length
937 let target = min(max(0, offset), length)
938 unfold(around: target)
939 textView.selectedRange = NSRange(location: target, length: 0)
940 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
941 }
942
943 /// The caret left hidden text (a tap past a fold): what hides it opens.
944 fileprivate func selectionChanged() {
945 let interval = Perf.begin("editor.selection")
946 defer { interval.end() }
947 redrawSelectedBlocks()
948 let caret = textView.selectedRange.location
949 if hidden.containing(caret) != nil { unfold(around: caret) }
950 revealCaretLine()
951 }
952} 423}
953 424
954extension MobileEditor: UITextViewDelegate { 425extension MobileEditor: UITextViewDelegate {
@@ -1057,153 +528,4 @@ extension MobileEditor: NSTextLayoutManagerDelegate {
1057 return fragment 528 return fragment
1058 } 529 }
1059} 530}
1060
1061extension NSAttributedString.Key {
1062 /// The character an entity shows as, on the entity's last character.
1063 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
1064 /// The color the entity's character is drawn in.
1065 static let orgEntityColor = NSAttributedString.Key("OrgEntityColor")
1066 /// The image an image link's line shows under it.
1067 static let orgImage = NSAttributedString.Key("OrgImage")
1068}
1069
1070final class InlineImageBox: NSObject, @unchecked Sendable {
1071 let image: UIImage
1072 let size: CGSize
1073 init(image: UIImage, size: CGSize) {
1074 self.image = image
1075 self.size = size
1076 }
1077}
1078
1079/// Selected text's background, in one color however the rects overlap.
1080final class SelectionHighlightView: UIView, UITextSelectionHighlightView {
1081 var selectionRects: [UITextSelectionRect] = [] { didSet { setNeedsDisplay() } }
1082 var color: UIColor = .clear { didSet { setNeedsDisplay() } }
1083
1084 override init(frame: CGRect) {
1085 super.init(frame: frame)
1086 isOpaque = false
1087 backgroundColor = .clear
1088 isUserInteractionEnabled = false
1089 registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: SelectionHighlightView, _) in view.setNeedsDisplay() }
1090 }
1091
1092 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
1093
1094 override func draw(_ rect: CGRect) {
1095 let path = UIBezierPath()
1096 for selection in selectionRects where !selection.rect.isEmpty { path.append(UIBezierPath(rect: selection.rect)) }
1097 color.setFill()
1098 path.fill()
1099 }
1100}
1101
1102/// A line drawn with more than its text, as the Mac editor's fragments draw them: a folded
1103/// line's ellipsis, a block's band across the view, an image under an image link, and pretty
1104/// entities' characters where the entities' last (invisible) characters sit.
1105final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable {
1106 var folded = false
1107 var band: (color: UIColor, width: CGFloat)?
1108 var image: InlineImageBox?
1109 /// For a block's lines: where the fragment starts, and where the selection is read.
1110 var start = 0
1111 var style: FragmentStyle?
1112
1113 static func image(_ string: NSAttributedString) -> InlineImageBox? {
1114 var found: InlineImageBox?
1115 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1116 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
1117 }
1118 return found
1119 }
1120
1121 static func hasEntities(_ string: NSAttributedString) -> Bool {
1122 var found = false
1123 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1124 if value != nil { found = true; stop.pointee = true }
1125 }
1126 return found
1127 }
1128
1129 private var bandRect: CGRect? {
1130 guard let band else { return nil }
1131 // Not under the empty line TextKit adds after a final newline.
1132 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
1133 // The width as it is now: the view may have been laid out since this fragment was made.
1134 let width = style?.blockBand.width ?? band.width
1135 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: max(width, layoutFragmentFrame.maxX), height: height)
1136 }
1137
1138 private var imageRect: CGRect? {
1139 guard let image, let line = textLineFragments.first else { return nil }
1140 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: image.size.width, height: image.size.height)
1141 }
1142
1143 override var renderingSurfaceBounds: CGRect {
1144 var bounds = super.renderingSurfaceBounds
1145 if folded { bounds = bounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) }
1146 for rect in [bandRect, imageRect].compactMap({ $0 }) { bounds = bounds.union(rect) }
1147 return bounds
1148 }
1149
1150 override func draw(at point: CGPoint, in context: CGContext) {
1151 if let band, let rect = bandRect {
1152 context.saveGState()
1153 context.setFillColor(band.color.cgColor)
1154 context.fill(rect.offsetBy(dx: point.x, dy: point.y))
1155 context.restoreGState()
1156 drawSelection(at: point, in: context, bandRect: rect)
1157 }
1158 super.draw(at: point, in: context)
1159 UIGraphicsPushContext(context)
1160 defer { UIGraphicsPopContext() }
1161 drawEntities(at: point)
1162 if let image, let rect = imageRect { image.image.draw(in: rect.offsetBy(dx: point.x, dy: point.y)) }
1163 if folded, let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first {
1164 let bounds = line.typographicBounds
1165 let ellipsis = NSAttributedString(string: " …", attributes: [
1166 .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular),
1167 .foregroundColor: UIColor.secondaryLabel,
1168 ])
1169 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
1170 }
1171 }
1172
1173 /// The selected part of each line, over the band; a selection running past a line's end
1174 /// fills to the band's edge.
1175 private func drawSelection(at point: CGPoint, in context: CGContext, bandRect: CGRect) {
1176 guard let selection = style?.selection else { return }
1177 context.saveGState()
1178 context.setFillColor(selection.color.cgColor)
1179 for line in textLineFragments where line.characterRange.length > 0 {
1180 let lineStart = start + line.characterRange.location
1181 let lineEnd = lineStart + line.characterRange.length
1182 let from = max(selection.range.lowerBound, lineStart), to = min(selection.range.upperBound, lineEnd)
1183 guard from < to || (from == to && selection.range.upperBound > lineEnd && from == lineEnd) else { continue }
1184 let bounds = line.typographicBounds
1185 // From the margin when the selection began on an earlier line, as the system draws it.
1186 let margin = bandRect.minX + (textLayoutManager?.textContainer?.lineFragmentPadding ?? 0)
1187 let x1 = selection.range.lowerBound < lineStart ? margin : bounds.minX + line.locationForCharacter(at: from - start).x
1188 let x2 = selection.range.upperBound >= lineEnd ? bandRect.maxX : bounds.minX + line.locationForCharacter(at: to - start).x
1189 context.fill(CGRect(x: point.x + x1, y: point.y + bounds.minY, width: max(0, x2 - x1), height: bounds.height))
1190 }
1191 context.restoreGState()
1192 }
1193
1194 private func drawEntities(at point: CGPoint) {
1195 guard let string = (textElement as? NSTextParagraph)?.attributedString else { return }
1196 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
1197 guard let display = value as? String,
1198 let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
1199 var attributes = string.attributes(at: range.location, effectiveRange: nil)
1200 attributes[.foregroundColor] = attributes[.orgEntityColor] ?? UIColor.label
1201 attributes[.orgEntityDisplay] = nil
1202 attributes[.orgEntityColor] = nil
1203 let x = line.locationForCharacter(at: range.location).x
1204 let bounds = line.typographicBounds
1205 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
1206 }
1207 }
1208}
1209#endif 531#endif
Sources/OrgstarMobile/MobileFragments.swift added +248
@@ -0,0 +1,248 @@
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
100extension NSAttributedString.Key {
101 /// The character an entity shows as, on the entity's last character.
102 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
103 /// The color the entity's character is drawn in.
104 static let orgEntityColor = NSAttributedString.Key("OrgEntityColor")
105 /// The image an image link's line shows under it.
106 static let orgImage = NSAttributedString.Key("OrgImage")
107}
108
109final class InlineImageBox: NSObject, @unchecked Sendable {
110 let image: UIImage
111 let size: CGSize
112 init(image: UIImage, size: CGSize) {
113 self.image = image
114 self.size = size
115 }
116}
117
118/// Selected text's background, in one color however the rects overlap.
119final class SelectionHighlightView: UIView, UITextSelectionHighlightView {
120 var selectionRects: [UITextSelectionRect] = [] { didSet { setNeedsDisplay() } }
121 var color: UIColor = .clear { didSet { setNeedsDisplay() } }
122
123 override init(frame: CGRect) {
124 super.init(frame: frame)
125 isOpaque = false
126 backgroundColor = .clear
127 isUserInteractionEnabled = false
128 registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: SelectionHighlightView, _) in view.setNeedsDisplay() }
129 }
130
131 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
132
133 override func draw(_ rect: CGRect) {
134 let path = UIBezierPath()
135 for selection in selectionRects where !selection.rect.isEmpty { path.append(UIBezierPath(rect: selection.rect)) }
136 color.setFill()
137 path.fill()
138 }
139}
140
141/// A line drawn with more than its text, as the Mac editor's fragments draw them: a folded
142/// line's ellipsis, a block's band across the view, an image under an image link, and pretty
143/// entities' characters where the entities' last (invisible) characters sit.
144final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable {
145 var folded = false
146 var band: (color: UIColor, width: CGFloat)?
147 var image: InlineImageBox?
148 /// For a block's lines: where the fragment starts, and where the selection is read.
149 var start = 0
150 var style: FragmentStyle?
151
152 static func image(_ string: NSAttributedString) -> InlineImageBox? {
153 var found: InlineImageBox?
154 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
155 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
156 }
157 return found
158 }
159
160 static func hasEntities(_ string: NSAttributedString) -> Bool {
161 var found = false
162 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
163 if value != nil { found = true; stop.pointee = true }
164 }
165 return found
166 }
167
168 var bandRect: CGRect? {
169 guard let band else { return nil }
170 // Not under the empty line TextKit adds after a final newline.
171 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
172 // The width as it is now: the view may have been laid out since this fragment was made.
173 let width = style?.blockBand.width ?? band.width
174 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: max(width, layoutFragmentFrame.maxX), height: height)
175 }
176
177 private var imageRect: CGRect? {
178 guard let image, let line = textLineFragments.first else { return nil }
179 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: image.size.width, height: image.size.height)
180 }
181
182 override var renderingSurfaceBounds: CGRect {
183 var bounds = super.renderingSurfaceBounds
184 if folded { bounds = bounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) }
185 for rect in [bandRect, imageRect].compactMap({ $0 }) { bounds = bounds.union(rect) }
186 return bounds
187 }
188
189 override func draw(at point: CGPoint, in context: CGContext) {
190 if let band, let rect = bandRect {
191 context.saveGState()
192 context.setFillColor(band.color.cgColor)
193 context.fill(rect.offsetBy(dx: point.x, dy: point.y))
194 context.restoreGState()
195 drawSelection(at: point, in: context, bandRect: rect)
196 }
197 super.draw(at: point, in: context)
198 UIGraphicsPushContext(context)
199 defer { UIGraphicsPopContext() }
200 drawEntities(at: point)
201 if let image, let rect = imageRect { image.image.draw(in: rect.offsetBy(dx: point.x, dy: point.y)) }
202 if folded, let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first {
203 let bounds = line.typographicBounds
204 let ellipsis = NSAttributedString(string: " …", attributes: [
205 .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular),
206 .foregroundColor: UIColor.secondaryLabel,
207 ])
208 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
209 }
210 }
211
212 /// The selected part of each line, over the band; a selection running past a line's end
213 /// fills to the band's edge.
214 private func drawSelection(at point: CGPoint, in context: CGContext, bandRect: CGRect) {
215 guard let selection = style?.selection else { return }
216 context.saveGState()
217 context.setFillColor(selection.color.cgColor)
218 for line in textLineFragments where line.characterRange.length > 0 {
219 let lineStart = start + line.characterRange.location
220 let lineEnd = lineStart + line.characterRange.length
221 let from = max(selection.range.lowerBound, lineStart), to = min(selection.range.upperBound, lineEnd)
222 guard from < to || (from == to && selection.range.upperBound > lineEnd && from == lineEnd) else { continue }
223 let bounds = line.typographicBounds
224 // From the margin when the selection began on an earlier line, as the system draws it.
225 let margin = bandRect.minX + (textLayoutManager?.textContainer?.lineFragmentPadding ?? 0)
226 let x1 = selection.range.lowerBound < lineStart ? margin : bounds.minX + line.locationForCharacter(at: from - start).x
227 let x2 = selection.range.upperBound >= lineEnd ? bandRect.maxX : bounds.minX + line.locationForCharacter(at: to - start).x
228 context.fill(CGRect(x: point.x + x1, y: point.y + bounds.minY, width: max(0, x2 - x1), height: bounds.height))
229 }
230 context.restoreGState()
231 }
232
233 private func drawEntities(at point: CGPoint) {
234 guard let string = (textElement as? NSTextParagraph)?.attributedString else { return }
235 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
236 guard let display = value as? String,
237 let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
238 var attributes = string.attributes(at: range.location, effectiveRange: nil)
239 attributes[.foregroundColor] = attributes[.orgEntityColor] ?? UIColor.label
240 attributes[.orgEntityDisplay] = nil
241 attributes[.orgEntityColor] = nil
242 let x = line.locationForCharacter(at: range.location).x
243 let bounds = line.typographicBounds
244 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
245 }
246 }
247}
248#endif