Sources/OrgstarMobile/MobileEditor+Display.swift

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

225 lines · 10912 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import OrgDocument
  5import OrgHighlight
  6import OrgPresentation
  7import UIKit
  8
  9extension MobileEditor {
 10    // MARK: - Shrunk table columns
 11
 12    /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
 13    /// `expand` for `org-table-expand`.
 14    func tableColumnWidth(_ id: String) {
 15        switch shrunk.change(for: id, at: textView.selectedRange.location, in: textView.textStorage.string) {
 16        case .notInTable: onMessage?("Not in a table")
 17        case .set(let columns, let table): setShrunk(columns, in: table)
 18        case .ask(let table, let current, let max):
 19            onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
 20                guard let self, let answer else { return }
 21                self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table)
 22            }
 23        }
 24    }
 25
 26    /// Narrows `columns` of `table` and widens its others.
 27    private func setShrunk(_ columns: [Int], in table: Range<Int>) {
 28        shrunk.set(columns, in: table, text: textView.textStorage.string)
 29        restyle(table)
 30        invalidateLayout(lines: [table])
 31    }
 32
 33    /// Hides each shrunk segment's text and draws its display where the text was, as pretty
 34    /// entities draw theirs.
 35    func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
 36        guard !shrunk.isEmpty else { return }
 37        let cell = theme.column
 38        for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
 39            let r = segment.range
 40            let shown = segment.display.count
 41            let kept = min(shown, r.count)
 42            if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
 43            guard kept > 0 else { continue }
 44            let visible = NSRange(location: r.upperBound - kept, length: kept)
 45            let color = storage.attribute(.foregroundColor, at: visible.location, effectiveRange: nil) as? UIColor ?? theme.foreground
 46            storage.addAttribute(.foregroundColor, value: UIColor.clear, range: visible)
 47            storage.addAttributes([.orgEntityDisplay: segment.display, .orgEntityColor: color], range: NSRange(location: visible.location, length: 1))
 48            if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
 49        }
 50    }
 51
 52    // MARK: - Inline images
 53
 54    func toggleImages() {
 55        showsImages.toggle()
 56        restyleAll()
 57        if showsImages {
 58            let ns = textView.textStorage.string as NSString
 59            var count = 0
 60            var offset = 0
 61            while offset < ns.length {
 62                let line = ns.lineRange(for: NSRange(location: offset, length: 0))
 63                if let image = InlineImages.image(atLine: line.location, in: ns, remote: options.remoteInlineImages != "skip"),
 64                   loadImage(image.path) != nil { count += 1 }
 65                offset = NSMaxRange(line)
 66            }
 67            onMessage?("\(count) images displayed inline")
 68        } else {
 69            onMessage?("Inline image display turned off")
 70        }
 71    }
 72
 73    /// An image link's image here: remote ones as `org-display-remote-inline-images` says,
 74    /// restyled when they come.
 75    func loadImage(_ path: String) -> UIImage? {
 76        Self.loadImage(path, relativeTo: baseDirectory, remote: RemoteImages.Mode(rawValue: options.remoteInlineImages) ?? .skip) { [weak self] in
 77            guard let self, self.showsImages else { return }
 78            self.restyleAll()
 79        }
 80    }
 81
 82    /// An image link's image, by its path or one relative to `baseDirectory`; an http(s)
 83    /// link's when `remote` allows it and it has come, `loaded` running when it does.
 84    static func loadImage(_ path: String, relativeTo baseDirectory: URL?, remote: RemoteImages.Mode = .skip, loaded: @escaping @MainActor () -> Void = {}) -> UIImage? {
 85        if path.contains("://") {
 86            guard let url = URL(string: path) else { return nil }
 87            return RemoteImages.shared.data(for: url, mode: remote, loaded: loaded).flatMap(UIImage.init(data:))
 88        }
 89        let expanded = (path as NSString).expandingTildeInPath
 90        let url: URL
 91        if expanded.hasPrefix("/") {
 92            url = URL(fileURLWithPath: expanded)
 93        } else if let baseDirectory {
 94            url = baseDirectory.appendingPathComponent(expanded)
 95        } else {
 96            return nil
 97        }
 98        let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
 99        let key = "\(url.path)|\(modified)" as NSString
100        if let cached = Self.imageCache.object(forKey: key) { return cached }
101        guard let image = UIImage(contentsOfFile: url.path) else { return nil }
102        Self.imageCache.setObject(image, forKey: key)
103        return image
104    }
105
106    /// Image lines in `range` show the image over the link, which is hidden unless the caret is
107    /// on the line.
108    func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
109        guard showsImages else { return }
110        let text = storage.string as NSString
111        let inset = textView.textContainerInset
112        let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40)
113        var location = range.lowerBound
114        while location < range.upperBound, location < text.length {
115            let line = text.lineRange(for: NSRange(location: location, length: 0))
116            location = NSMaxRange(line)
117            guard let image = InlineImages.image(atLine: line.location, in: text, remote: options.remoteInlineImages != "skip"),
118                  let picture = loadImage(image.path) else { continue }
119            let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth)
120            let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
121            let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
122            // Invisible, keeping the line's height.
123            if line.location != revealed.location, content.length > 0 {
124                storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content)
125            }
126            storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
127            let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
128            // The image sits where the line is; the spacing makes room for the rest of it.
129            style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight)
130            storage.addAttribute(.paragraphStyle, value: style, range: line)
131        }
132    }
133
134    // MARK: - Truncation
135
136    /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead
137    /// of wrapping.
138    var truncatesLines: Bool {
139        get { (textView as? KeyedTextView)?.truncates ?? false }
140        set {
141            guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return }
142            keepingTopLine {
143                view.truncates = newValue
144                if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
145            }
146        }
147    }
148
149    // MARK: - Folding
150
151    func setFolds(_ state: FoldState) {
152        fold = state
153        updateHidden()
154    }
155
156    func updateHidden() {
157        let tree = document.tree
158        let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
159        let before = hidden.folded
160        let oldHidden = hidden.all
161        hidden.set(
162            Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
163            folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
164        )
165        // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment.
166        let storage = textView.textStorage
167        let changed = before.symmetricDifference(hidden.folded).filter { $0 < storage.length }
168        if !changed.isEmpty {
169            let text = storage.string as NSString
170            storage.beginEditing()
171            for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) }
172            storage.endEditing()
173        }
174        invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all)))
175        textView.setNeedsDisplay()
176    }
177
178    /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
179    @discardableResult
180    func cycleAtCaret() -> Bool {
181        guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
182        setFolds(next)
183        return true
184    }
185
186    /// Shift-TAB: overview, contents, show all.
187    func cycleGlobal() {
188        let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
189        globalVisibility = visibility
190        setFolds(state)
191    }
192
193    /// Opens the folds hiding `offset`.
194    func unfold(around offset: Int) {
195        var state = fold
196        for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
197            state.folds.remove(entry.start)
198            state.bodyFolds.remove(entry.start)
199        }
200        for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
201            state.wrapperFolds.remove(start)
202        }
203        if state != fold { setFolds(state) }
204    }
205
206    /// Shows the heading at `offset`, unfolded, at the top.
207    func reveal(_ offset: Int) {
208        let length = textView.textStorage.length
209        let target = min(max(0, offset), length)
210        unfold(around: target)
211        textView.selectedRange = NSRange(location: target, length: 0)
212        textView.scrollRangeToVisible(NSRange(location: target, length: 0))
213    }
214
215    /// The caret left hidden text (a tap past a fold): what hides it opens.
216    func selectionChanged() {
217        let interval = Perf.begin("editor.selection")
218        defer { interval.end() }
219        redrawSelectedBlocks()
220        let caret = textView.selectedRange.location
221        if hidden.containing(caret) != nil { unfold(around: caret) }
222        revealCaretLine()
223    }
224}
225#endif