Sources/OrgstarMobile/MobileEditor+Styling.swift

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