Sources/OrgstarMobile/MobileEditor+Display.swift

246 lines · 11889 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", attachment: attachment),
 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    /// `attachment:` links' files, for inline images.
 74    private var attachment: ((String, Int) -> String?)? {
 75        guard let attachmentPath else { return nil }
 76        let tree = document.tree
 77        return { attachmentPath($0, $1, tree) }
 78    }
 79
 80    /// An image link's image here: remote ones as `org-display-remote-inline-images` says,
 81    /// restyled when they come.
 82    func loadImage(_ path: String) -> UIImage? {
 83        Self.loadImage(path, relativeTo: baseDirectory, remote: RemoteImages.Mode(rawValue: options.remoteInlineImages) ?? .skip) { [weak self] in
 84            guard let self, self.showsImages else { return }
 85            self.restyleAll()
 86        }
 87    }
 88
 89    /// An image link's image, by its path or one relative to `baseDirectory`; an http(s)
 90    /// link's when `remote` allows it and it has come, `loaded` running when it does.
 91    static func loadImage(_ path: String, relativeTo baseDirectory: URL?, remote: RemoteImages.Mode = .skip, loaded: @escaping @MainActor () -> Void = {}) -> UIImage? {
 92        if path.contains("://") {
 93            guard let url = URL(string: path) else { return nil }
 94            return RemoteImages.shared.data(for: url, mode: remote, loaded: loaded).flatMap(UIImage.init(data:))
 95        }
 96        let expanded = (path as NSString).expandingTildeInPath
 97        let url: URL
 98        if expanded.hasPrefix("/") {
 99            url = URL(fileURLWithPath: expanded)
100        } else if let baseDirectory {
101            url = baseDirectory.appendingPathComponent(expanded)
102        } else {
103            return nil
104        }
105        let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
106        let key = "\(url.path)|\(modified)" as NSString
107        if let cached = Self.imageCache.object(forKey: key) { return cached }
108        guard let image = UIImage(contentsOfFile: url.path) else { return nil }
109        Self.imageCache.setObject(image, forKey: key)
110        return image
111    }
112
113    /// Image lines in `range` show the image over the link, which is hidden unless the caret is
114    /// on the line; then the image goes under it.
115    func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
116        guard showsImages else { return }
117        let text = storage.string as NSString
118        let inset = textView.textContainerInset
119        let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40)
120        var location = range.lowerBound
121        while location < range.upperBound, location < text.length {
122            let line = text.lineRange(for: NSRange(location: location, length: 0))
123            location = NSMaxRange(line)
124            guard let image = InlineImages.image(atLine: line.location, in: text, remote: options.remoteInlineImages != "skip", attachment: attachment),
125                  let picture = loadImage(image.path) else { continue }
126            let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth)
127            let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
128            let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
129            // Invisible, keeping the line's height.
130            let shown = line.location == revealed.location && content.length > 0
131            if !shown, content.length > 0 {
132                storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content)
133            }
134            storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height), below: shown), range: NSRange(location: line.location, length: max(1, content.length)))
135            let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
136            // The image sits where the line is, or under it while the link shows; the spacing
137            // makes room for the rest of it.
138            style.paragraphSpacing = shown ? height + 4 : max(0, height + 4 - theme.font.lineHeight)
139            storage.addAttribute(.paragraphStyle, value: style, range: line)
140        }
141    }
142
143    // MARK: - Truncation
144
145    /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead
146    /// of wrapping.
147    var truncatesLines: Bool {
148        get { (textView as? KeyedTextView)?.truncates ?? false }
149        set {
150            guard newValue != truncatesLines else { return }
151            keepingTopLine {
152                for case let view as KeyedTextView in textViews { view.truncates = newValue }
153                for manager in layoutManagers { manager.invalidateLayout(for: manager.documentRange) }
154            }
155        }
156    }
157
158    // MARK: - Folding
159
160    func setFolds(_ state: FoldState) {
161        fold = state
162        updateHidden()
163    }
164
165    func updateHidden() {
166        let tree = document.tree
167        let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
168        let before = hidden.folded
169        let oldHidden = hidden.all
170        hidden.set(
171            Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
172            folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
173        )
174        // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment.
175        let storage = textView.textStorage
176        let changed = before.symmetricDifference(hidden.folded).filter { $0 < storage.length }
177        if !changed.isEmpty {
178            let text = storage.string as NSString
179            storage.beginEditing()
180            for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) }
181            storage.endEditing()
182        }
183        invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all)))
184        textView.setNeedsDisplay()
185    }
186
187    /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
188    @discardableResult
189    func cycleAtCaret() -> Bool {
190        guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
191        setFolds(next)
192        return true
193    }
194
195    /// Shift-TAB: overview, contents, show all.
196    func cycleGlobal() {
197        let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
198        globalVisibility = visibility
199        setFolds(state)
200    }
201
202    /// Opens the folds hiding `offset`.
203    func unfold(around offset: Int) {
204        var state = fold
205        for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
206            state.folds.remove(entry.start)
207            state.bodyFolds.remove(entry.start)
208        }
209        for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
210            state.wrapperFolds.remove(start)
211        }
212        if state != fold { setFolds(state) }
213    }
214
215    /// Shows the heading at `offset`, unfolded, at the top.
216    func reveal(_ offset: Int) {
217        let length = textView.textStorage.length
218        let target = min(max(0, offset), length)
219        unfold(around: target)
220        textView.selectedRange = NSRange(location: target, length: 0)
221        textView.scrollRangeToVisible(NSRange(location: target, length: 0))
222    }
223
224    /// The caret in hidden text: an arrow key moving forward into a fold jumps past it and
225    /// moving back jumps to the end of the heading line, as on the Mac; a tap past a fold
226    /// opens it.
227    func selectionChanged() {
228        let interval = Perf.begin("editor.selection")
229        defer { interval.end() }
230        redrawSelectedBlocks()
231        let caret = textView.selectedRange.location
232        defer {
233            previousCaret = textView.selectedRange.location
234            movedByArrow = false
235        }
236        if let range = hidden.containing(caret) {
237            if movedByArrow, textView.selectedRange.length == 0 {
238                textView.selectedRange = NSRange(location: caret >= previousCaret ? range.upperBound : range.lowerBound - 1, length: 0)
239            } else {
240                unfold(around: caret)
241            }
242        }
243        revealCaretLine()
244    }
245}
246#endif