Sources/OrgstarMobile/MobileEditor+Styling.swift

1136db9ac14f93d2ef778c0b591f9c5ec322ed1c
orgstar/Sources/OrgstarMobile/MobileEditor+Styling.swift

360 lines · 19243 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        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        refitTagGaps()
108        // With several views, the band spans the widest and images fit the narrowest.
109        let band = fragmentStyle.blockBand
110        let width = textViews.map { max($0.bounds.width, truncatesLines ? $0.contentSize.width : 0) }.max() ?? 0
111        let narrowest = textViews.map(\.bounds.width).filter { $0 > 0 }.min() ?? textView.bounds.width
112        let resized = imageWidth != narrowest
113        guard band.width != width || resized else { return }
114        fragmentStyle.set(blockBackground: band.color, width: width)
115        imageWidth = narrowest
116        guard resized else {
117            redraw(blocks: shaded.all)
118            return
119        }
120        keepingTopLine {
121            if showsImages { restartStyling() }
122            for manager in layoutManagers {
123                manager.invalidateRenderingAttributes(for: manager.documentRange)
124                manager.invalidateLayout(for: manager.documentRange)
125            }
126        }
127    }
128
129    /// Styles the whole file again, a screenful now and the rest in the background.
130    func restyleAll() {
131        let interval = Perf.begin("editor.restyleAll")
132        defer { interval.end() }
133        keepingTopLine {
134            restartStyling()
135            for manager in layoutManagers { manager.invalidateLayout(for: manager.documentRange) }
136        }
137    }
138
139    /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
140    /// heading or opening line of a fold, whose fragment draws the fold mark. Laying out the
141    /// whole file again makes TextKit estimate the height of everything above the view afresh,
142    /// which moves the text under it.
143    func invalidateLayout(lines ranges: [Range<Int>]) {
144        guard !ranges.isEmpty else { return }
145        let text = textView.textStorage.string as NSString
146        for manager in layoutManagers {
147            guard let content = manager.textContentManager else { continue }
148            for range in ranges {
149                let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
150                let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0)))
151                guard let start = content.location(content.documentRange.location, offsetBy: lower),
152                      let end = content.location(start, offsetBy: upper - lower),
153                      let textRange = NSTextRange(location: start, end: end) else { continue }
154                manager.invalidateLayout(for: textRange)
155            }
156        }
157    }
158
159    /// Runs `change`, which lays the whole file out again, and brings the line that was at the
160    /// top of the view back there. TextKit estimates the height of text it hasn't laid out,
161    /// so the same scroll position lands on different text after a fresh layout.
162    func keepingTopLine(_ change: () -> Void) {
163        guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return change() }
164        let inset = textView.textContainerInset
165        let top = textView.contentOffset.y + textView.adjustedContentInset.top - inset.top
166        let start = content.documentRange.location
167        let anchor = manager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map {
168            (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY)
169        }
170        change()
171        guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset),
172              let above = NSTextRange(location: start, end: location) else { return }
173        // Styled now, not in the background passes, which would lay the text out again.
174        while styled.end < anchor.offset { styleNextChunk(Self.styleChunk) }
175        manager.ensureLayout(for: above)
176        guard let fragment = manager.textLayoutFragment(for: location) else { return }
177        let frame = fragment.layoutFragmentFrame
178        manager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * textView.bounds.height))
179        // The view grows to the laid-out height on its next layout pass; the scroll needs it now.
180        let needed = manager.usageBoundsForTextContainer.maxY + inset.top + inset.bottom
181        if textView.contentSize.height < needed { textView.contentSize.height = needed }
182        let y = frame.minY + inset.top + max(0, min(anchor.within, frame.height)) - textView.adjustedContentInset.top
183        textView.contentOffset = CGPoint(x: textView.contentOffset.x, y: y)
184    }
185
186    /// Styles are set after the edit has been processed, as TextKit asks.
187    func scheduleRestyle(_ range: Range<Int>) {
188        if let pending = restyleScheduled {
189            restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound)
190            return
191        }
192        restyleScheduled = range
193        DispatchQueue.main.async { [weak self] in
194            guard let self, let range = self.restyleScheduled else { return }
195            self.restyleScheduled = nil
196            if self.blocksMayChange {
197                self.blocksMayChange = false
198                self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: [])
199            }
200            self.restyle(range)
201            self.updateHidden()
202            self.textView.typingAttributes = self.theme.base
203        }
204    }
205
206    var caretLine: NSRange {
207        let text = textView.textStorage.string as NSString
208        return text.lineRange(for: NSRange(location: min(textView.selectedRange.location, text.length), length: 0))
209    }
210
211    /// Sets attributes for the whole lines in `range`, as the Mac editor does.
212    func restyle(_ range: Range<Int>) {
213        let interval = Perf.begin("editor.restyle")
214        defer { interval.end() }
215        let storage = textView.textStorage
216        let ns = storage.string as NSString
217        guard ns.length > 0 else { return }
218        let lower = min(range.lowerBound, ns.length)
219        let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower)))
220        let whole = lines.location..<NSMaxRange(lines)
221        storage.beginEditing()
222        storage.setAttributes(theme.base, range: lines)
223        let revealed = caretLine
224        let (changes, scriptExclusions) = Presentation.styleChanges(
225            document.tree, in: whole, highlighter: Self.highlighter, indented: indented, hideStars: hideStars,
226            showMarkup: showMarkup, options: options, revealed: revealed.location..<NSMaxRange(revealed)
227        )
228        var tags: [Range<Int>] = []
229        for change in changes {
230            switch change {
231            case .indent(let line): storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
232            case .role(let role, let range):
233                theme.apply(role, to: storage, range: NSRange(range))
234                if role == .tags { tags.append(range) }
235            case .hidden(let range): storage.addAttributes(theme.hidden, range: NSRange(range))
236            }
237        }
238        if theme.mixedPitch {
239            for prefix in Presentation.fixedPitchPrefixes(ns, in: whole) {
240                let clipped = NSIntersectionRange(NSRange(prefix), lines)
241                guard clipped.length > 0 else { continue }
242                let current = storage.attribute(.font, at: clipped.location, effectiveRange: nil) as? UIFont ?? theme.body
243                storage.addAttribute(.font, value: theme.fixedPitch(current), range: clipped)
244            }
245        }
246        if !showMarkup, options.prettyEntities { prettify(whole, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
247        applyShrunk(whole, in: storage)
248        applyImages(whole, in: storage, revealed: revealed)
249        applyLatex(whole, in: storage, revealed: revealed)
250        fitTagGaps(tags, in: storage)
251        if options.spellCheck { markMisspellings(in: whole, storage: storage) }
252        storage.endEditing()
253    }
254
255    /// The text container's width, for tag gaps: the narrowest view's, as images are sized.
256    var tagGapAvailableWidth: CGFloat {
257        textViews.map { $0.textContainer.size.width - 2 * $0.textContainer.lineFragmentPadding }.filter { $0 > 0 }.min() ?? 0
258    }
259
260    /// Draws the spaces before each heading's tags in `tags` as one gap that fits the view
261    /// (`Presentation.tagGapWidth`): all but the last space hidden, the last widened.
262    private func fitTagGaps(_ tags: [Range<Int>], in storage: NSTextStorage) {
263        guard !tags.isEmpty else { return }
264        let available = tagGapAvailableWidth
265        guard available > 0 else { return }
266        // The storage's own string: `string` copies the whole text.
267        let text = storage.mutableString
268        for range in tags where range.upperBound <= text.length {
269            guard let gap = Presentation.tagGap(tags: range, in: text) else { continue }
270            let line = text.lineRange(for: NSRange(location: gap.gap.lowerBound, length: 0))
271            let indent = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.firstLineHeadIndent ?? 0
272            // Without the paragraph style, whose indent is taken from the width apart.
273            func width(_ range: Range<Int>) -> CGFloat {
274                let part = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: NSRange(range)))
275                part.removeAttribute(.paragraphStyle, range: NSRange(location: 0, length: part.length))
276                return part.size().width
277            }
278            // Spaces measured before the tags: trailing spaces may not count.
279            let last = gap.gap.upperBound - 1
280            let title = width(line.location..<gap.gap.lowerBound), tagsWidth = width(gap.tags)
281            let space = width(last..<gap.tags.upperBound) - tagsWidth
282            // A point to spare, so rounding doesn't wrap the tags.
283            guard let shown = Presentation.tagGapWidth(
284                title: title, gap: width(line.location..<gap.tags.upperBound) - title - tagsWidth, space: space, tags: tagsWidth,
285                available: available - indent - 1
286            ) else { continue }
287            storage.addAttributes(theme.hidden, range: NSRange(gap.gap.lowerBound..<last))
288            storage.addAttribute(.kern, value: max(0, shown - space), range: NSRange(location: last, length: 1))
289        }
290    }
291
292    /// Draws tag gaps again once the text's width has changed, after the layout pass that changed it.
293    private func refitTagGaps() {
294        guard !fittingTagGaps, tagGapWidth != tagGapAvailableWidth else { return }
295        fittingTagGaps = true
296        DispatchQueue.main.async { [weak self] in
297            guard let self else { return }
298            self.fittingTagGaps = false
299            let width = self.tagGapAvailableWidth
300            guard self.tagGapWidth != width else { return }
301            self.tagGapWidth = width
302            let text = self.textView.textStorage.string as NSString
303            for gap in Presentation.tagGaps(self.document.tree) where gap.tags.upperBound <= min(text.length, self.styled.end) {
304                let line = text.lineRange(for: NSRange(location: gap.gap.lowerBound, length: 0))
305                self.restyle(line.location..<NSMaxRange(line))
306            }
307        }
308    }
309
310    func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
311        if let style = paragraphStyles[[firstLine, wrapped]] { return style }
312        let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
313        paragraphStyles[[firstLine, wrapped]] = style
314        return style
315    }
316
317    /// `org-pretty-entities`: entities drawn as their character over the entity's last
318    /// character (the rest hidden), sub/superscripts raised without their markers.
319    private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
320        let runs = Presentation.prettyRuns(
321            storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
322            scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
323        )
324        for (lineStart, run) in runs {
325            switch run {
326            case .entity(let r, let display):
327                let start = lineStart + r.lowerBound
328                let last = lineStart + r.upperBound - 1
329                let color = storage.attribute(.foregroundColor, at: last, effectiveRange: nil) as? UIColor ?? theme.foreground
330                if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
331                storage.addAttributes([.foregroundColor: UIColor.clear, .orgEntityDisplay: display, .orgEntityColor: color], range: NSRange(location: last, length: 1))
332            case .script(let markers, let body, let superscript):
333                for marker in markers {
334                    storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
335                }
336                let size = theme.font.pointSize
337                storage.addAttributes([
338                    .font: theme.body.withSize(size * 0.7),
339                    .baselineOffset: (superscript ? 0.3 : -0.3) * size,
340                ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
341            }
342        }
343    }
344
345    /// Moving to another line shows its markup and hides the last one's.
346    func revealCaretLine() {
347        // LaTeX previews and images show their source on the caret's line whether or not markup shows.
348        guard !showMarkup || showsLatex || showsImages else { return }
349        let line = caretLine
350        guard line != revealedLine else { return }
351        let text = textView.textStorage.string as NSString
352        // The old line may have moved with edits since; restyle the line now at its start.
353        let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
354        revealedLine = line
355        for range in [old, line].compactMap({ $0 }) where range.location < styled.end {
356            restyle(range.location..<NSMaxRange(range))
357        }
358    }
359}
360#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form