Sources/OrgstarMobile/MobileEditor+Styling.swift
273 lines · 14788 bytes
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 for view in textViews { applyThemeToView(view) }
24 fragmentStyle.set(blockBackground: theme.color("block-background") ?? .clear, width: textView.bounds.width)
25 }
26
27 func applyThemeToView(_ view: UITextView) {
28 view.backgroundColor = theme.color("background") ?? .systemBackground
29 view.tintColor = theme.color("cursor")
30 view.typingAttributes = theme.base
31 (view as? KeyedTextView)?.textWidth = CGFloat(max(0, theme.spec.textWidth)) * theme.column
32 themeSelection(view)
33 }
34
35 /// The selection in the theme's selection color: the text view's selection display
36 /// interaction draws it with our highlight view; the cursor and handles keep the tint.
37 private func themeSelection(_ textView: UITextView) {
38 guard let interaction = textView.interactions.lazy.compactMap({ $0 as? UITextSelectionDisplayInteraction }).first else { return }
39 let view = interaction.highlightView as? SelectionHighlightView ?? SelectionHighlightView()
40 view.color = theme.color("selection") ?? UIColor.tintColor.withAlphaComponent(0.25)
41 if interaction.highlightView !== view { interaction.highlightView = view }
42 selectionColor = view.color
43 }
44
45 /// The highlight view draws under the text, so a block's band would cover it: blocks the
46 /// selection enters or leaves are laid out again to draw it over their band.
47 func redrawSelectedBlocks() {
48 let selected = textView.selectedRange
49 let range = selected.length > 0 ? selected.location..<NSMaxRange(selected) : nil
50 let old = fragmentStyle.selection?.range
51 fragmentStyle.set(selection: range, color: selectionColor)
52 let touched = [old, range].compactMap { $0 }
53 redraw(blocks: shaded.all.filter { block in touched.contains { $0.overlaps(block) } })
54 }
55
56 /// Lays `blocks` out again and asks their fragments, which are kept across layout passes,
57 /// to draw again.
58 private func redraw(blocks: [Range<Int>]) {
59 for manager in layoutManagers {
60 guard let content = manager.textContentManager else { continue }
61 for block in blocks {
62 guard let start = content.location(content.documentRange.location, offsetBy: block.lowerBound),
63 let end = content.location(start, offsetBy: block.count),
64 let textRange = NSTextRange(location: start, end: end) else { continue }
65 manager.invalidateRenderingAttributes(for: textRange)
66 manager.invalidateLayout(for: textRange)
67 }
68 }
69 for view in textViews { view.setNeedsDisplay() }
70 }
71
72 /// The band behind blocks spans the view's width, or the widest line's when truncated;
73 /// images are as wide as the view allows. Only the blocks read the band's width, so a
74 /// wider line in a truncated file, which widens the band on each layout pass, redraws
75 /// the blocks alone: laying the whole file out again moves the text under the view.
76 func viewResized() {
77 // With several views, the band spans the widest and images fit the narrowest.
78 let band = fragmentStyle.blockBand
79 let width = textViews.map { max($0.bounds.width, truncatesLines ? $0.contentSize.width : 0) }.max() ?? 0
80 let narrowest = textViews.map(\.bounds.width).filter { $0 > 0 }.min() ?? textView.bounds.width
81 let resized = imageWidth != narrowest
82 guard band.width != width || resized else { return }
83 fragmentStyle.set(blockBackground: band.color, width: width)
84 imageWidth = narrowest
85 guard resized else {
86 redraw(blocks: shaded.all)
87 return
88 }
89 keepingTopLine {
90 if showsImages { restyle(0..<textView.textStorage.length) }
91 for manager in layoutManagers {
92 manager.invalidateRenderingAttributes(for: manager.documentRange)
93 manager.invalidateLayout(for: manager.documentRange)
94 }
95 }
96 }
97
98 /// Styles the whole file again.
99 func restyleAll() {
100 let interval = Perf.begin("editor.restyleAll")
101 defer { interval.end() }
102 keepingTopLine {
103 restyle(0..<textView.textStorage.length)
104 for manager in layoutManagers { manager.invalidateLayout(for: manager.documentRange) }
105 }
106 }
107
108 /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
109 /// heading or opening line of a fold, whose fragment draws the fold mark. Laying out the
110 /// whole file again makes TextKit estimate the height of everything above the view afresh,
111 /// which moves the text under it.
112 func invalidateLayout(lines ranges: [Range<Int>]) {
113 guard !ranges.isEmpty else { return }
114 let text = textView.textStorage.string as NSString
115 for manager in layoutManagers {
116 guard let content = manager.textContentManager else { continue }
117 for range in ranges {
118 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
119 let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0)))
120 guard let start = content.location(content.documentRange.location, offsetBy: lower),
121 let end = content.location(start, offsetBy: upper - lower),
122 let textRange = NSTextRange(location: start, end: end) else { continue }
123 manager.invalidateLayout(for: textRange)
124 }
125 }
126 }
127
128 /// Runs `change`, which lays the whole file out again, and brings the line that was at the
129 /// top of the view back there. TextKit estimates the height of text it hasn't laid out,
130 /// so the same scroll position lands on different text after a fresh layout.
131 func keepingTopLine(_ change: () -> Void) {
132 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return change() }
133 let inset = textView.textContainerInset
134 let top = textView.contentOffset.y + textView.adjustedContentInset.top - inset.top
135 let start = content.documentRange.location
136 let anchor = manager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map {
137 (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY)
138 }
139 change()
140 guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset),
141 let above = NSTextRange(location: start, end: location) else { return }
142 manager.ensureLayout(for: above)
143 guard let fragment = manager.textLayoutFragment(for: location) else { return }
144 let frame = fragment.layoutFragmentFrame
145 manager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * textView.bounds.height))
146 // The view grows to the laid-out height on its next layout pass; the scroll needs it now.
147 let needed = manager.usageBoundsForTextContainer.maxY + inset.top + inset.bottom
148 if textView.contentSize.height < needed { textView.contentSize.height = needed }
149 let y = frame.minY + inset.top + max(0, min(anchor.within, frame.height)) - textView.adjustedContentInset.top
150 textView.contentOffset = CGPoint(x: textView.contentOffset.x, y: y)
151 }
152
153 /// Styles are set after the edit has been processed, as TextKit asks.
154 func scheduleRestyle(_ range: Range<Int>) {
155 if let pending = restyleScheduled {
156 restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound)
157 return
158 }
159 restyleScheduled = range
160 DispatchQueue.main.async { [weak self] in
161 guard let self, let range = self.restyleScheduled else { return }
162 self.restyleScheduled = nil
163 self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: [])
164 // Small files are restyled whole: a heading or block line changes what follows it.
165 let length = self.textView.textStorage.length
166 self.restyle(length < 60_000 ? 0..<length : range)
167 self.updateHidden()
168 self.textView.typingAttributes = self.theme.base
169 }
170 }
171
172 private var caretLine: NSRange {
173 let text = textView.textStorage.string as NSString
174 return text.lineRange(for: NSRange(location: min(textView.selectedRange.location, text.length), length: 0))
175 }
176
177 /// Sets attributes for the whole lines in `range`, as the Mac editor does.
178 func restyle(_ range: Range<Int>) {
179 let interval = Perf.begin("editor.restyle")
180 defer { interval.end() }
181 let storage = textView.textStorage
182 let ns = storage.string as NSString
183 guard ns.length > 0 else { return }
184 let lower = min(range.lowerBound, ns.length)
185 let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower)))
186 let whole = lines.location..<NSMaxRange(lines)
187 storage.beginEditing()
188 storage.setAttributes(theme.base, range: lines)
189 if indented {
190 for line in Presentation.lineIndents(document.tree, in: whole) {
191 storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
192 }
193 }
194 let revealed = caretLine
195 var scriptExclusions: [Range<Int>] = []
196 for run in Presentation.styles(document.tree, in: whole, highlighter: Self.highlighter) {
197 let clipped = NSIntersectionRange(NSRange(run.range), lines)
198 guard clipped.length > 0 else { continue }
199 if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue }
200 if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 {
201 storage.addAttributes(theme.hidden, range: clipped)
202 } else {
203 theme.apply(run.role, to: storage, range: clipped)
204 }
205 if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) }
206 }
207 if theme.mixedPitch {
208 for prefix in Presentation.fixedPitchPrefixes(ns, in: whole) {
209 let clipped = NSIntersectionRange(NSRange(prefix), lines)
210 guard clipped.length > 0 else { continue }
211 let current = storage.attribute(.font, at: clipped.location, effectiveRange: nil) as? UIFont ?? theme.body
212 storage.addAttribute(.font, value: theme.fixedPitch(current), range: clipped)
213 }
214 }
215 if !showMarkup, options.prettyEntities { prettify(whole, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
216 applyShrunk(whole, in: storage)
217 applyImages(whole, in: storage, revealed: revealed)
218 applyLatex(whole, in: storage, revealed: revealed)
219 if options.spellCheck { markMisspellings(in: whole, storage: storage) }
220 storage.endEditing()
221 }
222
223 func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
224 if let style = paragraphStyles[[firstLine, wrapped]] { return style }
225 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
226 paragraphStyles[[firstLine, wrapped]] = style
227 return style
228 }
229
230 /// `org-pretty-entities`: entities drawn as their character over the entity's last
231 /// character (the rest hidden), sub/superscripts raised without their markers.
232 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
233 let runs = Presentation.prettyRuns(
234 storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
235 scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
236 )
237 for (lineStart, run) in runs {
238 switch run {
239 case .entity(let r, let display):
240 let start = lineStart + r.lowerBound
241 let last = lineStart + r.upperBound - 1
242 let color = storage.attribute(.foregroundColor, at: last, effectiveRange: nil) as? UIColor ?? theme.foreground
243 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
244 storage.addAttributes([.foregroundColor: UIColor.clear, .orgEntityDisplay: display, .orgEntityColor: color], range: NSRange(location: last, length: 1))
245 case .script(let markers, let body, let superscript):
246 for marker in markers {
247 storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
248 }
249 let size = theme.font.pointSize
250 storage.addAttributes([
251 .font: theme.body.withSize(size * 0.7),
252 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
253 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
254 }
255 }
256 }
257
258 /// Moving to another line shows its markup and hides the last one's.
259 func revealCaretLine() {
260 // LaTeX previews show their source on the caret's line whether or not markup shows.
261 guard !showMarkup || showsLatex else { return }
262 let line = caretLine
263 guard line != revealedLine else { return }
264 let text = textView.textStorage.string as NSString
265 // The old line may have moved with edits since; restyle the line now at its start.
266 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
267 revealedLine = line
268 for range in [old, line].compactMap({ $0 }) {
269 restyle(range.location..<NSMaxRange(range))
270 }
271 }
272}
273#endif