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