Sources/OrgstarMobile/MobileEditor+Display.swift
209 lines · 10016 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), Self.loadImage(image.path, relativeTo: baseDirectory) != nil { count += 1 }
64 offset = NSMaxRange(line)
65 }
66 onMessage?("\(count) images displayed inline")
67 } else {
68 onMessage?("Inline image display turned off")
69 }
70 }
71
72 /// An image link's image, by its path or one relative to `baseDirectory`.
73 static func loadImage(_ path: String, relativeTo baseDirectory: URL?) -> UIImage? {
74 let expanded = (path as NSString).expandingTildeInPath
75 let url: URL
76 if expanded.hasPrefix("/") {
77 url = URL(fileURLWithPath: expanded)
78 } else if let baseDirectory {
79 url = baseDirectory.appendingPathComponent(expanded)
80 } else {
81 return nil
82 }
83 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
84 let key = "\(url.path)|\(modified)" as NSString
85 if let cached = Self.imageCache.object(forKey: key) { return cached }
86 guard let image = UIImage(contentsOfFile: url.path) else { return nil }
87 Self.imageCache.setObject(image, forKey: key)
88 return image
89 }
90
91 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
92 /// on the line.
93 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
94 guard showsImages else { return }
95 let text = storage.string as NSString
96 let inset = textView.textContainerInset
97 let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40)
98 var location = range.lowerBound
99 while location < range.upperBound, location < text.length {
100 let line = text.lineRange(for: NSRange(location: location, length: 0))
101 location = NSMaxRange(line)
102 guard let image = InlineImages.image(atLine: line.location, in: text), let picture = Self.loadImage(image.path, relativeTo: baseDirectory) else { continue }
103 let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth)
104 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
105 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
106 // Invisible, keeping the line's height.
107 if line.location != revealed.location, content.length > 0 {
108 storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content)
109 }
110 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
111 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
112 // The image sits where the line is; the spacing makes room for the rest of it.
113 style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight)
114 storage.addAttribute(.paragraphStyle, value: style, range: line)
115 }
116 }
117
118 // MARK: - Truncation
119
120 /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead
121 /// of wrapping.
122 var truncatesLines: Bool {
123 get { (textView as? KeyedTextView)?.truncates ?? false }
124 set {
125 guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return }
126 keepingTopLine {
127 view.truncates = newValue
128 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
129 }
130 }
131 }
132
133 // MARK: - Folding
134
135 func setFolds(_ state: FoldState) {
136 fold = state
137 updateHidden()
138 }
139
140 func updateHidden() {
141 let tree = document.tree
142 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
143 let before = hidden.folded
144 let oldHidden = hidden.all
145 hidden.set(
146 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
147 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
148 )
149 // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment.
150 let storage = textView.textStorage
151 let changed = before.symmetricDifference(hidden.folded).filter { $0 < storage.length }
152 if !changed.isEmpty {
153 let text = storage.string as NSString
154 storage.beginEditing()
155 for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) }
156 storage.endEditing()
157 }
158 invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all)))
159 textView.setNeedsDisplay()
160 }
161
162 /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
163 @discardableResult
164 func cycleAtCaret() -> Bool {
165 guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
166 setFolds(next)
167 return true
168 }
169
170 /// Shift-TAB: overview, contents, show all.
171 func cycleGlobal() {
172 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
173 globalVisibility = visibility
174 setFolds(state)
175 }
176
177 /// Opens the folds hiding `offset`.
178 func unfold(around offset: Int) {
179 var state = fold
180 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
181 state.folds.remove(entry.start)
182 state.bodyFolds.remove(entry.start)
183 }
184 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
185 state.wrapperFolds.remove(start)
186 }
187 if state != fold { setFolds(state) }
188 }
189
190 /// Shows the heading at `offset`, unfolded, at the top.
191 func reveal(_ offset: Int) {
192 let length = textView.textStorage.length
193 let target = min(max(0, offset), length)
194 unfold(around: target)
195 textView.selectedRange = NSRange(location: target, length: 0)
196 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
197 }
198
199 /// The caret left hidden text (a tap past a fold): what hides it opens.
200 func selectionChanged() {
201 let interval = Perf.begin("editor.selection")
202 defer { interval.end() }
203 redrawSelectedBlocks()
204 let caret = textView.selectedRange.location
205 if hidden.containing(caret) != nil { unfold(around: caret) }
206 revealCaretLine()
207 }
208}
209#endif