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