Sources/OrgstarMobile/MobileEditor+Display.swift
285 lines · 14520 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 /// `includeLinked` as `org-toggle-inline-images` with a prefix argument: links with a
55 /// description show their image too.
56 func toggleImages(includeLinked: Bool = false) {
57 showsImages.toggle()
58 imagesIncludeLinked = showsImages && includeLinked
59 restyleAll()
60 if showsImages {
61 let count = InlineImages.links(document.tree, in: 0..<textView.textStorage.length, includeLinked: imagesIncludeLinked,
62 remote: options.remoteInlineImages != "skip", attachment: attachment)
63 .count { loadImage($0.image.path) != nil }
64 onMessage?("\(count) images displayed inline")
65 } else {
66 onMessage?("Inline image display turned off")
67 }
68 }
69
70 /// `attachment:` links' files, for inline images.
71 private var attachment: ((String, Int) -> String?)? {
72 guard let attachmentPath else { return nil }
73 let tree = document.tree
74 return { attachmentPath($0, $1, tree) }
75 }
76
77 /// An image link's image here: remote ones as `org-display-remote-inline-images` says,
78 /// restyled when they come.
79 func loadImage(_ path: String) -> UIImage? {
80 Self.loadImage(path, relativeTo: baseDirectory, remote: RemoteImages.Mode(rawValue: options.remoteInlineImages) ?? .skip) { [weak self] in
81 guard let self, self.showsImages else { return }
82 self.restyleAll()
83 }
84 }
85
86 /// An image link's image, by its path or one relative to `baseDirectory`; an http(s)
87 /// link's when `remote` allows it and it has come, `loaded` running when it does.
88 static func loadImage(_ path: String, relativeTo baseDirectory: URL?, remote: RemoteImages.Mode = .skip, loaded: @escaping @MainActor () -> Void = {}) -> UIImage? {
89 if path.contains("://") {
90 guard let url = URL(string: path) else { return nil }
91 return RemoteImages.shared.data(for: url, mode: remote, loaded: loaded).flatMap(UIImage.init(data:))
92 }
93 let expanded = OrgPaths.expandingTilde(path)
94 let url: URL
95 if expanded.hasPrefix("/") {
96 url = URL(fileURLWithPath: expanded)
97 } else if let baseDirectory {
98 url = baseDirectory.appendingPathComponent(expanded)
99 } else {
100 return nil
101 }
102 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
103 let key = "\(url.path)|\(modified)" as NSString
104 if let cached = Self.imageCache.object(forKey: key) { return cached }
105 guard let image = UIImage(contentsOfFile: url.path) else { return nil }
106 Self.imageCache.setObject(image, forKey: key)
107 return image
108 }
109
110 /// Image links in `range` show their image, and the link is hidden unless the caret is on
111 /// its line. A link that is all its line holds keeps the line, with the image over it, or
112 /// under it while the link shows. A link in a line's text is as wide and as tall as its
113 /// image, which goes under the paragraph while the link shows.
114 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
115 guard showsImages else { return }
116 let text = storage.string as NSString
117 let inset = textView.textContainerInset
118 let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40)
119 let links = InlineImages.links(document.tree, in: range, includeLinked: imagesIncludeLinked, remote: options.remoteInlineImages != "skip", attachment: attachment)
120 for placement in Presentation.imagePlacements(links, in: text) {
121 guard let picture = loadImage(placement.link.image.path) else { continue }
122 let size = Presentation.imageSize(natural: picture.size, width: placement.link.image.width, maxWidth: maxWidth)
123 let link = NSRange(placement.link.range)
124 let line = text.lineRange(for: link)
125 let shown = NSLocationInRange(revealed.location, line)
126 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
127 defer { storage.addAttribute(.paragraphStyle, value: style, range: line) }
128 guard placement.ownLine else {
129 let first = NSRange(location: link.location, length: 1)
130 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: size, below: shown, inText: true), range: first)
131 if shown {
132 style.paragraphSpacing = max(style.paragraphSpacing, size.height + 4)
133 continue
134 }
135 // Pretty entities in the link would draw over the image.
136 storage.removeAttribute(.orgEntityDisplay, range: link)
137 storage.removeAttribute(.orgEntityColor, range: link)
138 storage.addAttributes(theme.hidden, range: link)
139 storage.addAttribute(.underlineStyle, value: 0, range: link)
140 let font = theme.font.withSize(Presentation.imageFontSize(height: size.height, pointSize: theme.font.pointSize, lineHeight: theme.font.lineHeight))
141 let advance = text.substring(with: first).size(withAttributes: [.font: font]).width
142 storage.addAttributes([.font: font, .kern: size.width - advance], range: first)
143 continue
144 }
145 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
146 // Invisible, keeping the line's height.
147 if !shown {
148 storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content)
149 }
150 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: size, below: shown), range: content)
151 // The image sits where the line is, or under it while the link shows; the spacing
152 // makes room for the rest of it.
153 style.paragraphSpacing = shown ? size.height + 4 : max(0, size.height + 4 - theme.font.lineHeight)
154 }
155 }
156
157 // MARK: - Truncation
158
159 /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead
160 /// of wrapping.
161 var truncatesLines: Bool {
162 get { (textView as? KeyedTextView)?.truncates ?? false }
163 set {
164 guard newValue != truncatesLines else { return }
165 keepingTopLine {
166 for case let view as KeyedTextView in textViews { view.truncates = newValue }
167 for manager in layoutManagers { manager.invalidateLayout(for: manager.documentRange) }
168 }
169 }
170 }
171
172 // MARK: - Folding
173
174 func setFolds(_ state: FoldState) {
175 fold = state
176 updateHidden()
177 }
178
179 func updateHidden() {
180 let tree = document.tree
181 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
182 let before = hidden.folded
183 let oldHidden = hidden.all
184 hidden.set(
185 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
186 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
187 )
188 // Lines that gain or lose their `…` are made again: TextKit keeps a shown line's fragment.
189 let storage = textView.textStorage
190 let changed = before.symmetricDifference(hidden.folded).filter { $0 < storage.length }
191 if !changed.isEmpty {
192 let text = storage.string as NSString
193 storage.beginEditing()
194 for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) }
195 storage.endEditing()
196 }
197 invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all)))
198 textView.setNeedsDisplay()
199 }
200
201 /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
202 @discardableResult
203 func cycleAtCaret() -> Bool {
204 guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
205 setFolds(next)
206 return true
207 }
208
209 /// Shift-TAB: overview, contents, show all.
210 func cycleGlobal() {
211 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
212 globalVisibility = visibility
213 setFolds(state)
214 }
215
216 /// Doom's `za`, `zo` (on a heading line), `zc` and `zO` (anywhere in a subtree), and `zR`,
217 /// `zM`, `zr` and `zm` for the whole buffer.
218 func foldCommand(_ id: String) {
219 let caret = textView.selectedRange.location
220 let tree = document.tree
221 let length = (document.text as NSString).length
222 let next: FoldState?
223 if id == "org.fold.close" || id == "org.fold.open-subtree" {
224 next = Presentation.outline(tree).last { $0.start <= caret && (caret < $0.end || $0.end == length) }
225 .map { id == "org.fold.close" ? Presentation.hideSubtree($0.start, fold) : Presentation.showSubtree($0.start, in: tree, fold) }
226 } else if id == "org.fold.open-all" {
227 next = Presentation.showAllHeadings(fold)
228 } else if id == "org.fold.close-all" {
229 next = Presentation.hideSublevels(1, in: tree, fold)
230 } else if id == "org.fold.more" || id == "org.fold.less" {
231 let level = Presentation.foldLevel(in: tree, fold)
232 next = Presentation.hideSublevels(id == "org.fold.more" ? level + 1 : max(1, level - 1), in: tree, fold)
233 } else {
234 next = Presentation.heading(containing: caret, in: tree).map {
235 id == "org.fold.open" ? Presentation.openFold($0, in: tree, fold) : Presentation.toggleFold($0, in: tree, fold)
236 }
237 }
238 if let next, next != fold { setFolds(next) }
239 }
240
241 /// Opens the folds hiding `offset`.
242 func unfold(around offset: Int) {
243 var state = fold
244 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
245 state.folds.remove(entry.start)
246 state.bodyFolds.remove(entry.start)
247 }
248 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
249 state.wrapperFolds.remove(start)
250 }
251 if state != fold { setFolds(state) }
252 }
253
254 /// Shows the heading at `offset`, unfolded, at the top.
255 func reveal(_ offset: Int) {
256 let length = textView.textStorage.length
257 let target = min(max(0, offset), length)
258 unfold(around: target)
259 textView.selectedRange = NSRange(location: target, length: 0)
260 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
261 }
262
263 /// The caret in hidden text: an arrow key moving forward into a fold jumps past it and
264 /// moving back jumps to the end of the heading line, as on the Mac; a tap past a fold
265 /// opens it.
266 func selectionChanged() {
267 let interval = Perf.begin("editor.selection")
268 defer { interval.end() }
269 redrawSelectedBlocks()
270 let caret = textView.selectedRange.location
271 defer {
272 previousCaret = textView.selectedRange.location
273 movedByArrow = false
274 }
275 if let range = hidden.containing(caret) {
276 if movedByArrow, textView.selectedRange.length == 0 {
277 textView.selectedRange = NSRange(location: caret >= previousCaret ? range.upperBound : range.lowerBound - 1, length: 0)
278 } else {
279 unfold(around: caret)
280 }
281 }
282 revealCaretLine()
283 }
284}
285#endif