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