Sources/OrgstarMobile/ReaderScreen.swift
454 lines · 22668 bytes
23 symbols in this file
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import OrgIndex
6import OrgPresentation
7import QuickLook
8import SwiftUI
9import UIKit
10
11/// What to read: a file, and where in it.
12enum ReaderRoute: Hashable {
13 case file(String)
14 case offset(String, Int)
15 /// A search result, found again if the file changed since it was indexed.
16 case heading(HeadingLocation)
17}
18
19/// Editing a file, from the reader.
20struct EditorRoute: Hashable {
21 let path: String
22 let offset: Int?
23}
24
25/// A file to read: headings that fold and unfold with a tap, as TAB cycles them, text styled as
26/// in the editor, and links to follow.
27struct ReaderScreen: View {
28 let route: ReaderRoute
29 let workspace: WorkspaceModel
30 let session: DocumentSession
31 @State private var fold = FoldState()
32 @State private var folded: [Range<Int>] = []
33 /// Drawers and blocks the file opens with folded, which fold and unfold from their first line.
34 @State private var foldable: [Range<Int>] = []
35 @State private var loadedPath: String?
36 /// The file's display: indentation, leading stars, inline images, truncation.
37 @State private var startup: StartupDisplay?
38 /// The view's width, which images in a line's text are no wider than.
39 @State private var width: CGFloat = 0
40 @State private var showingOutline = false
41 @State private var message: String?
42 /// A file a link opened, shown in Quick Look.
43 @State private var previewed: URL?
44 /// The pane the reader shows its file in, closed with the reader.
45 @State private var holder = PaneHolder()
46 @Environment(\.openURL) private var openURL
47 @Environment(MobileModel.self) private var model
48
49 private var pane: EditorPane? { holder.pane }
50 private var outline: [OutlineEntry] { pane?.outline ?? [] }
51 /// The file the reader's pane shows.
52 private var shownPath: String? { pane?.path }
53 private var document: DocumentState? { shownPath.flatMap(session.document(of:)) }
54
55 /// The file this reader shows.
56 private var path: String {
57 switch route {
58 case .file(let path), .offset(let path, _): path
59 case .heading(let location): location.path
60 }
61 }
62
63 /// The pane shows this reader's file; the session opens files by their resolved paths.
64 private var showsOwnFile: Bool {
65 guard let current = shownPath else { return false }
66 return current == path || current == URL(fileURLWithPath: path).resolvingSymlinksInPath().path
67 }
68
69 var body: some View {
70 let _ = pane?.editVersion
71 // Read again when settings or the Dynamic Type size change.
72 let _ = model.settingsVersion
73 let theme = MobileTheme(model.theme)
74 let truncated = startup?.truncated ?? false
75 ScrollViewReader { proxy in
76 ScrollView(truncated ? [.vertical, .horizontal] : .vertical) {
77 LazyVStack(alignment: .leading, spacing: 8) {
78 if let tree = document?.tree, showsOwnFile {
79 let length = (tree.text as NSString).length
80 let preambleEnd = min(outline.first?.start ?? length, length)
81 if preambleEnd > 0 { textView(tree, 0..<preambleEnd, theme) }
82 ForEach(Array(outline.enumerated()), id: \.element.start) { index, entry in
83 // While another file opens, rows can update with the last file's
84 // entries for a moment; those don't fit this text.
85 if index < outline.count, outline[index] == entry, entry.end <= length, isShown(index) {
86 heading(tree, entry, theme).id(entry.start)
87 if !fold.folds.contains(entry.start), !fold.bodyFolds.contains(entry.start) {
88 let body = bodyRange(index, tree)
89 if !body.isEmpty { textView(tree, body, theme).padding(.leading, bodyIndent(entry, theme)) }
90 }
91 }
92 }
93 }
94 }
95 .padding()
96 .frame(maxWidth: truncated ? nil : .infinity, alignment: .leading)
97 }
98 // Narrower than the view while truncated, the text still starts at the top left.
99 .defaultScrollAnchor(truncated ? .topLeading : nil)
100 .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 }
101 .background(theme.swiftColor("background") ?? Color(uiColor: .systemBackground))
102 .onChange(of: pane?.revealRequest?.id) {
103 guard let offset = pane?.revealRequest?.offset else { return }
104 reveal(offset, proxy)
105 }
106 }
107 .navigationTitle(((shownPath ?? "") as NSString).lastPathComponent)
108 .navigationBarTitleDisplayMode(.inline)
109 .toolbar {
110 ToolbarItemGroup(placement: .primaryAction) {
111 Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty)
112 if let path = shownPath {
113 if let tree = document?.tree { ExportMenu(path: path, tree: tree) { message = $0 } }
114 NavigationLink(value: EditorRoute(path: path, offset: nil)) { Label("Edit", systemImage: "square.and.pencil") }
115 }
116 }
117 }
118 .quickLookPreview($previewed)
119 .sheet(isPresented: $showingOutline) { outlineSheet }
120 .safeAreaInset(edge: .bottom) {
121 if let message {
122 Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
123 .onTapGesture { self.message = nil }
124 }
125 }
126 .environment(\.openURL, OpenURLAction { url in follow(url) })
127 .onAppear(perform: open)
128 .onChange(of: pane?.path) { loadFolds() }
129 .onChange(of: pane?.editVersion) { loadFolds() }
130 .onChange(of: model.settingsVersion) { loadFolds() }
131 .onReceive(NotificationCenter.default.publisher(for: OrgExport.refused)) { message = $0.object as? String }
132 }
133
134 // MARK: - Content
135
136 private func indent(_ entry: OutlineEntry) -> CGFloat { CGFloat(entry.level - 1) * 14 }
137
138 private var indented: Bool { startup?.indented ?? true }
139
140 /// The text as the editor's display settings show it.
141 private var display: ReadingText.Display {
142 ReadingText.Display(showMarkup: model.showMarkup, options: session.options, highlighter: MobileEditor.highlighter)
143 }
144
145 /// org-indent: a heading's text and its body start past its stars, at level + 1 columns,
146 /// the fold mark standing where the last star and its space would. Without it nothing is
147 /// indented and the stars show.
148 private func headingIndent(_ entry: OutlineEntry, _ theme: MobileTheme) -> CGFloat {
149 indented ? CGFloat(entry.level - 1) * theme.column : 0
150 }
151
152 private func bodyIndent(_ entry: OutlineEntry, _ theme: MobileTheme) -> CGFloat {
153 indented ? CGFloat(entry.level + 1) * theme.column : 0
154 }
155
156 /// Hidden under a folded ancestor.
157 private func isShown(_ index: Int) -> Bool {
158 var parent = outline[index].parent
159 while let p = parent {
160 if fold.folds.contains(outline[p].start) { return false }
161 parent = outline[p].parent
162 }
163 return true
164 }
165
166 /// From after the heading line to the first child, or the section's end.
167 private func bodyRange(_ index: Int, _ tree: OrgTree) -> Range<Int> {
168 let entry = outline[index]
169 let ns = tree.text as NSString
170 let lineEnd = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
171 let firstChild = outline[(index + 1)...].first { $0.parent == index }?.start ?? entry.end
172 return min(lineEnd, firstChild)..<firstChild
173 }
174
175 private func heading(_ tree: OrgTree, _ entry: OutlineEntry, _ theme: MobileTheme) -> some View {
176 let ns = tree.text as NSString
177 let line = ns.lineRange(for: NSRange(location: entry.start, length: 0))
178 let start = indented ? min(entry.start + entry.level + 1, NSMaxRange(line)) : entry.start
179 let text = attributed(ReadingText.segments(tree, in: start..<NSMaxRange(line), display: display), heading: entry.level, theme)
180 let hasContent = entry.end > NSMaxRange(line)
181 let foldedMark = fold.folds.contains(entry.start) && hasContent
182 return HStack(alignment: .firstTextBaseline, spacing: 0) {
183 Image(systemName: foldedMark ? "chevron.right" : "chevron.down")
184 .font(.caption.weight(.semibold)).foregroundStyle(theme.swiftColor("markup") ?? Color(uiColor: .tertiaryLabel))
185 .opacity(hasContent ? 1 : 0)
186 .frame(width: 2 * theme.column, alignment: .leading)
187 lineText(Text(text.trimmingTrailingNewlines()), theme)
188 }
189 .padding(.leading, headingIndent(entry, theme))
190 .padding(.top, entry.level == 1 ? 6 : 0)
191 .contentShape(Rectangle())
192 .onTapGesture { fold = Presentation.cycle(entry.start, in: tree, fold) }
193 .accessibilityAddTraits(.isButton)
194 .accessibilityHint(foldedMark ? "Unfolds the heading" : "Folds the heading")
195 }
196
197 private func textView(_ tree: OrgTree, _ range: Range<Int>, _ theme: MobileTheme) -> some View {
198 VStack(alignment: .leading, spacing: 4) {
199 ForEach(parts(tree, range), id: \.range.lowerBound) { part in
200 if let image = part.image {
201 Image(uiImage: image.picture).resizable().scaledToFit()
202 .frame(maxWidth: image.width.map { CGFloat($0) } ?? image.picture.size.width, alignment: .leading)
203 .accessibilityLabel((image.path as NSString).lastPathComponent)
204 } else {
205 lineText(text(tree, part, theme), theme)
206 .textSelection(.enabled)
207 }
208 }
209 }
210 }
211
212 /// A part's text, with each image in it standing where its link is.
213 private func text(_ tree: OrgTree, _ part: Part, _ theme: MobileTheme) -> Text {
214 func styled(_ range: Range<Int>) -> AttributedString {
215 attributed(ReadingText.segments(tree, in: range, folded: folded, open: foldable.filter { !folded.contains($0) }, display: display), heading: nil, theme)
216 }
217 var text = Text("")
218 var start = part.range.lowerBound
219 for image in part.inText {
220 text = Text("\(text)\(Text(styled(start..<image.range.lowerBound)))\(Image(uiImage: image.picture))")
221 start = image.range.upperBound
222 }
223 return Text("\(text)\(Text(styled(start..<part.range.upperBound).trimmingTrailingNewlines()))")
224 }
225
226 /// Wrapped to the view's width, or on one line each, scrolling sideways, while truncated.
227 private func lineText(_ text: Text, _ theme: MobileTheme) -> some View {
228 text
229 .lineSpacing(CGFloat(max(0, theme.spec.lineSpacing)))
230 .fixedSize(horizontal: startup?.truncated ?? false, vertical: false)
231 .frame(maxWidth: startup?.truncated == true ? nil : .infinity, alignment: .leading)
232 }
233
234 private struct Part {
235 let range: Range<Int>
236 /// The image of a link that is all its line holds.
237 var image: (picture: UIImage, path: String, width: Int?)?
238 /// Images in the text, at their size, and the links they stand for.
239 var inText: [(range: Range<Int>, picture: UIImage)] = []
240 }
241
242 /// Text, and with inline images on, image links shown as their images: a link that is all
243 /// its line holds as a part of its own, others in their part's text.
244 private func parts(_ tree: OrgTree, _ range: Range<Int>) -> [Part] {
245 guard startup?.inlineImages == true, let path = shownPath else { return [Part(range: range)] }
246 // Read so that the view draws again when a remote image arrives.
247 _ = RemoteImages.shared.version
248 let remote = RemoteImages.Mode(rawValue: session.options.remoteInlineImages) ?? .skip
249 let base = URL(fileURLWithPath: path).deletingLastPathComponent()
250 let ns = tree.text as NSString
251 let maxWidth = width > 0 ? max(80, width - 72) : .greatestFiniteMagnitude
252 var parts: [Part] = []
253 var pending = Part(range: range.lowerBound..<range.lowerBound)
254 let links = InlineImages.links(tree, in: range, remote: remote != .skip, attachment: { DocumentSession.attachmentPath($0, at: $1, tree: tree, path: path) })
255 for placement in Presentation.imagePlacements(links, in: ns) {
256 let link = placement.link
257 guard link.range.lowerBound >= pending.range.lowerBound, link.range.upperBound <= range.upperBound,
258 folded.allSatisfy({ !$0.contains(link.range.lowerBound) }),
259 let picture = MobileEditor.loadImage(link.image.path, relativeTo: base, remote: remote) else { continue }
260 guard placement.ownLine else {
261 let size = Presentation.imageSize(natural: picture.size, width: link.image.width, maxWidth: maxWidth)
262 let sized = picture.cgImage.map { UIImage(cgImage: $0, scale: picture.size.width * picture.scale / max(1, size.width), orientation: picture.imageOrientation) }
263 pending.inText.append((link.range, sized ?? picture))
264 continue
265 }
266 let line = ns.lineRange(for: NSRange(location: link.range.lowerBound, length: 0))
267 if pending.range.lowerBound < line.location {
268 parts.append(Part(range: pending.range.lowerBound..<line.location, inText: pending.inText))
269 }
270 let end = min(NSMaxRange(line), range.upperBound)
271 parts.append(Part(range: line.location..<end, image: (picture, link.image.path, link.image.width)))
272 pending = Part(range: end..<end)
273 }
274 if pending.range.lowerBound < range.upperBound { parts.append(Part(range: pending.range.lowerBound..<range.upperBound, inText: pending.inText)) }
275 return parts
276 }
277
278 /// Segments as styled text in the theme's font and colors, as the editor styles them;
279 /// links get `orgstar-link:` URLs to follow.
280 private func attributed(_ segments: [ReadingText.Segment], heading level: Int?, _ theme: MobileTheme) -> AttributedString {
281 var result = AttributedString()
282 for segment in segments {
283 var part = AttributedString(segment.text)
284 var font = level.map(theme.headingFont) ?? theme.body
285 if theme.mixedPitch, segment.roles.contains(where: Presentation.isFixedPitch) { font = theme.fixedPitch(font) }
286 var color = level.flatMap { theme.color("heading-\(min(max($0, 1), 8))") } ?? theme.foreground
287 func fg(_ key: String) { if let c = theme.color(key) { color = c } }
288 // Outer roles first, so inner ones win.
289 for role in segment.roles.sorted(by: { Self.depth($0) < Self.depth($1) }) {
290 switch role {
291 case .todo, .done:
292 font = MobileTheme.adding(.traitBold, to: font)
293 if let c = theme.keywordColor(segment.text, done: role == .done) { color = c }
294 case .priority: fg("priority")
295 case .tags: fg("tags")
296 case .bold: font = MobileTheme.adding(.traitBold, to: font)
297 case .italic: font = MobileTheme.adding(.traitItalic, to: font)
298 case .underline: part.underlineStyle = .single
299 case .strikeThrough: part.strikethroughStyle = .single
300 case .verbatim, .code, .inlineSource:
301 if let background = theme.color("inline-background") { part.backgroundColor = Color(uiColor: background) }
302 fg(role == .verbatim ? "verbatim" : "code")
303 case .markup, .linkMarkup: fg("markup")
304 case .leadingStars:
305 // As the editor hides them; shown in the heading's color unless hidden.
306 if !Presentation.skipsLeadingStars(role, indented: indented, hideStars: startup?.hideStars ?? false) { color = .clear }
307 case .syntax(let category): if let key = category.themeKey { fg(key) }
308 case .timestamp: fg("timestamp")
309 case .comment: fg("comment")
310 case .keyword: fg("keyword")
311 case .metadata: fg("metadata")
312 case .blockDelimiter: fg("block-delimiter")
313 case .footnote, .cookie, .target, .macro, .latex: fg("special")
314 case .table, .rule: fg("table")
315 case .link:
316 part.underlineStyle = .single
317 fg("link")
318 case .heading, .block: break
319 }
320 }
321 if segment.link != nil {
322 // Found again by position when followed.
323 part.link = URL(string: "orgstar-link:\(segment.offset)")
324 }
325 if let start = segment.toggles { part.link = URL(string: "orgstar-fold:\(start)") }
326 if let superscript = segment.superscript {
327 // Raised or lowered as the editor draws `org-pretty-entities` scripts.
328 part.baselineOffset = (superscript ? 0.3 : -0.3) * font.pointSize
329 font = font.withSize(font.pointSize * 0.7)
330 }
331 part.font = Font(font as CTFont)
332 part.foregroundColor = Color(uiColor: color)
333 result += part
334 }
335 return result
336 }
337
338 /// How deep a role's text usually nests: elements, then objects, then their parts.
339 private static func depth(_ role: StyleRole) -> Int {
340 switch role {
341 case .heading: 0
342 case .metadata, .keyword, .comment, .block, .table, .rule: 1
343 case .blockDelimiter, .link, .bold, .italic, .underline, .strikeThrough, .timestamp, .footnote, .target, .macro, .latex: 2
344 default: 3
345 }
346 }
347
348 // MARK: - Actions
349
350 private func open() {
351 let pane = holder.pane ?? {
352 let made = session.makePane()
353 holder.pane = made
354 holder.release = { [weak session] in session?.closePane(made) }
355 return made
356 }()
357 // What the reader opens and follows goes to its pane.
358 session.focused = pane
359 if loadedPath == nil {
360 switch route {
361 case .file(let path): session.open(path, in: pane)
362 case .offset(let path, let offset):
363 session.open(path, in: pane)
364 session.reveal(offset, in: pane)
365 case .heading(let location): session.show(location)
366 }
367 }
368 loadFolds()
369 }
370
371 /// The file's startup display, as the editor opens it; its heading folds are kept while
372 /// the same file is open.
373 private func loadFolds() {
374 guard let tree = document?.tree, showsOwnFile else { return }
375 let display = Presentation.startupDisplay(tree, options: session.options)
376 startup = display
377 folded = display.wrappers.map(\.hidden)
378 foldable = folded
379 guard loadedPath != shownPath else { return }
380 loadedPath = shownPath
381 fold = display.folds
382 }
383
384 /// Unfolds the way to the heading containing `offset` and scrolls to it.
385 private func reveal(_ offset: Int, _ proxy: ScrollViewProxy) {
386 guard let index = outline.lastIndex(where: { $0.start <= offset }) else { return }
387 var parent = outline[index].parent
388 while let p = parent {
389 fold.folds.remove(outline[p].start)
390 parent = outline[p].parent
391 }
392 let start = outline[index].start
393 DispatchQueue.main.async { withAnimation { proxy.scrollTo(start, anchor: .top) } }
394 }
395
396 private func follow(_ url: URL) -> OpenURLAction.Result {
397 if url.scheme == "orgstar-fold", let start = Int(url.absoluteString.dropFirst("orgstar-fold:".count)) {
398 if folded.contains(where: { $0.lowerBound == start }) {
399 folded.removeAll { $0.lowerBound == start }
400 } else if let range = foldable.first(where: { $0.lowerBound == start }) {
401 folded.append(range)
402 }
403 return .handled
404 }
405 guard url.scheme == "orgstar-link", let offset = Int(url.absoluteString.dropFirst("orgstar-link:".count)),
406 let tree = document?.tree, let link = Links.link(at: offset, text: tree.text, tree: tree)?.link else {
407 return .systemAction
408 }
409 if let pane { session.focused = pane }
410 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
411 case .shown:
412 message = nil
413 // A link to another file shows it on its own screen; this pane keeps its file.
414 if let pane, let target = pane.path, target != path, !showsOwnFile {
415 let caret = session.caret(of: target) ?? 0
416 session.open(path, in: pane)
417 model.openRequest = .offset(target, caret)
418 }
419 case .openExternally(let target): if target.isFileURL { previewed = target } else { openURL(target) }
420 case .message(let text): message = text
421 case .choose(let question, let paths): message = question + paths.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
422 case .elisp: message = "Open the file in the editor to run elisp links."
423 }
424 return .handled
425 }
426
427 private var outlineSheet: some View {
428 NavigationStack {
429 List(outline, id: \.start) { entry in
430 Button {
431 showingOutline = false
432 if let pane { session.reveal(entry.start, in: pane) }
433 } label: {
434 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
435 .padding(.leading, indent(entry))
436 .foregroundStyle(.primary)
437 }
438 }
439 .navigationTitle("Outline")
440 .navigationBarTitleDisplayMode(.inline)
441 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { showingOutline = false } } }
442 }
443 }
444}
445
446private extension AttributedString {
447 /// Without the final newline, which `Text` would show as an empty line.
448 func trimmingTrailingNewlines() -> AttributedString {
449 var copy = self
450 while let last = copy.characters.last, last.isNewline { copy.characters.removeLast() }
451 return copy
452 }
453}
454#endif