Sources/OrgstarMobile/MobileEditor+Display.swift
232 lines · 11213 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.
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 if line.location != revealed.location, content.length > 0 {
131 storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content)
132 }
133 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
134 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
135 // The image sits where the line is; the spacing makes room for the rest of it.
136 style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight)
137 storage.addAttribute(.paragraphStyle, value: style, range: line)
138 }
139 }
140
141 // MARK: - Truncation
142
143 /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead
144 /// of wrapping.
145 var truncatesLines: Bool {
146 get { (textView as? KeyedTextView)?.truncates ?? false }
147 set {
148 guard newValue != truncatesLines else { return }
149 keepingTopLine {
150 for case let view as KeyedTextView in textViews { view.truncates = newValue }
151 for manager in layoutManagers { manager.invalidateLayout(for: manager.documentRange) }
152 }
153 }
154 }
155
156 // MARK: - Folding
157
158 func setFolds(_ state: FoldState) {
159 fold = state
160 updateHidden()
161 }
162
163 func updateHidden() {
164 let tree = document.tree
165 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
166 let before = hidden.folded
167 let oldHidden = hidden.all
168 hidden.set(
169 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
170 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
171 )
172 // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment.
173 let storage = textView.textStorage
174 let changed = before.symmetricDifference(hidden.folded).filter { $0 < storage.length }
175 if !changed.isEmpty {
176 let text = storage.string as NSString
177 storage.beginEditing()
178 for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) }
179 storage.endEditing()
180 }
181 invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all)))
182 textView.setNeedsDisplay()
183 }
184
185 /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
186 @discardableResult
187 func cycleAtCaret() -> Bool {
188 guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
189 setFolds(next)
190 return true
191 }
192
193 /// Shift-TAB: overview, contents, show all.
194 func cycleGlobal() {
195 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
196 globalVisibility = visibility
197 setFolds(state)
198 }
199
200 /// Opens the folds hiding `offset`.
201 func unfold(around offset: Int) {
202 var state = fold
203 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
204 state.folds.remove(entry.start)
205 state.bodyFolds.remove(entry.start)
206 }
207 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
208 state.wrapperFolds.remove(start)
209 }
210 if state != fold { setFolds(state) }
211 }
212
213 /// Shows the heading at `offset`, unfolded, at the top.
214 func reveal(_ offset: Int) {
215 let length = textView.textStorage.length
216 let target = min(max(0, offset), length)
217 unfold(around: target)
218 textView.selectedRange = NSRange(location: target, length: 0)
219 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
220 }
221
222 /// The caret left hidden text (a tap past a fold): what hides it opens.
223 func selectionChanged() {
224 let interval = Perf.begin("editor.selection")
225 defer { interval.end() }
226 redrawSelectedBlocks()
227 let caret = textView.selectedRange.location
228 if hidden.containing(caret) != nil { unfold(around: caret) }
229 revealCaretLine()
230 }
231}
232#endif