Sources/OrgstarMobile/MobileEditor+Styling.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgstarMobile/MobileEditor+Styling.swift history · blame · raw

252 lines · 13710 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        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        applyLatex(whole, in: storage, revealed: revealed)
199        storage.endEditing()
200    }
201
202    func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
203        if let style = paragraphStyles[[firstLine, wrapped]] { return style }
204        let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
205        paragraphStyles[[firstLine, wrapped]] = style
206        return style
207    }
208
209    /// `org-pretty-entities`: entities drawn as their character over the entity's last
210    /// character (the rest hidden), sub/superscripts raised without their markers.
211    private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
212        let runs = Presentation.prettyRuns(
213            storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
214            scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
215        )
216        for (lineStart, run) in runs {
217            switch run {
218            case .entity(let r, let display):
219                let start = lineStart + r.lowerBound
220                let last = lineStart + r.upperBound - 1
221                let color = storage.attribute(.foregroundColor, at: last, effectiveRange: nil) as? UIColor ?? theme.foreground
222                if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
223                storage.addAttributes([.foregroundColor: UIColor.clear, .orgEntityDisplay: display, .orgEntityColor: color], range: NSRange(location: last, length: 1))
224            case .script(let markers, let body, let superscript):
225                for marker in markers {
226                    storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
227                }
228                let size = theme.font.pointSize
229                storage.addAttributes([
230                    .font: theme.font.withSize(size * 0.7),
231                    .baselineOffset: (superscript ? 0.3 : -0.3) * size,
232                ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
233            }
234        }
235    }
236
237    /// Moving to another line shows its markup and hides the last one's.
238    func revealCaretLine() {
239        // LaTeX previews show their source on the caret's line whether or not markup shows.
240        guard !showMarkup || showsLatex else { return }
241        let line = caretLine
242        guard line != revealedLine else { return }
243        let text = textView.textStorage.string as NSString
244        // The old line may have moved with edits since; restyle the line now at its start.
245        let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
246        revealedLine = line
247        for range in [old, line].compactMap({ $0 }) {
248            restyle(range.location..<NSMaxRange(range))
249        }
250    }
251}
252#endif