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