Sources/OrgstarMobile/ReaderScreen.swift
713 lines · 35058 bytes
44 symbols in this file
ReaderRouteEditorRouteReaderScreenrunCommandindentheadingIndentbodyIndentisShownbodyRangeheadingstyledheadingWithTagstextViewtextstyledlineTextPartpartsattributedfgmarkFoundindexshowFounddepthopenloadFoldsrevealfollowReaderFindPositionTextRangefindInteractioncompareperformTextSearchdecorateclearAllDecoratedFoundTextscrollRangeToVisibleFindHostHostmakeUIViewupdateUIViewmakeCoordinatorCoordinatortrimmingTrailingNewlines
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 /// Headings' padded tags, by the heading's start.
39 @State private var tagGaps: [Int: TagGap] = [:]
40 /// The view's width, which images in a line's text are no wider than.
41 @State private var width: CGFloat = 0
42 @State private var showingOutline = false
43 @State private var showingCommands = false
44 @State private var showingExport = false
45 /// Present: the file's slides, full screen.
46 @State private var deck: SlideDeck?
47 /// The command chosen in Commands, run once the list is gone.
48 @State private var chosenCommand: String?
49 @State private var message: String?
50 /// The passphrase sheet for an encrypted file.
51 @State private var unlocking: CryptRequest?
52 /// A file a link opened, shown in Quick Look.
53 @State private var previewed: URL?
54 /// The pane the reader shows its file in, closed with the reader.
55 @State private var holder = PaneHolder()
56 /// The system find bar over the file's text, shown each time `findRequest` changes.
57 @State private var find = ReaderFind()
58 @State private var findRequest = 0
59 /// Find's results, true for the one shown, and the offset to scroll to.
60 @State private var found: [Range<Int>: Bool] = [:]
61 @State private var findTarget: Int?
62 @Environment(\.openURL) private var openURL
63 @Environment(MobileModel.self) private var model
64
65 private var pane: EditorPane? { holder.pane }
66 private var outline: [OutlineEntry] { pane?.outline ?? [] }
67 /// The file the reader's pane shows.
68 private var shownPath: String? { pane?.path }
69 private var document: DocumentState? { shownPath.flatMap(session.document(of:)) }
70
71 /// The file this reader shows.
72 private var path: String {
73 switch route {
74 case .file(let path), .offset(let path, _): path
75 case .heading(let location): location.path
76 }
77 }
78
79 /// The pane shows this reader's file; the session opens files by their resolved paths.
80 private var showsOwnFile: Bool {
81 guard let current = shownPath else { return false }
82 return current == path || current == URL(fileURLWithPath: path).resolvingSymlinksInPath().path
83 }
84
85 var body: some View {
86 let _ = pane?.editVersion
87 // Read again when settings or the Dynamic Type size change.
88 let _ = model.settingsVersion
89 let theme = MobileTheme(model.theme)
90 let truncated = startup?.truncated ?? false
91 ScrollViewReader { proxy in
92 ScrollView(truncated ? [.vertical, .horizontal] : .vertical) {
93 LazyVStack(alignment: .leading, spacing: 8) {
94 if let tree = document?.tree, showsOwnFile {
95 let length = (tree.text as NSString).length
96 let preambleEnd = min(outline.first?.start ?? length, length)
97 if preambleEnd > 0 { textView(tree, 0..<preambleEnd, theme) }
98 ForEach(Array(outline.enumerated()), id: \.element.start) { index, entry in
99 // While another file opens, rows can update with the last file's
100 // entries for a moment; those don't fit this text.
101 if index < outline.count, outline[index] == entry, entry.end <= length, isShown(index) {
102 heading(tree, entry, theme).id(entry.start)
103 if !fold.folds.contains(entry.start), !fold.bodyFolds.contains(entry.start) {
104 let body = bodyRange(index, tree)
105 if !body.isEmpty { textView(tree, body, theme).padding(.leading, bodyIndent(entry, theme)) }
106 }
107 }
108 }
109 }
110 }
111 .padding()
112 .frame(maxWidth: truncated ? nil : .infinity, alignment: .leading)
113 }
114 // Narrower than the view while truncated, the text still starts at the top left.
115 .defaultScrollAnchor(truncated ? .topLeading : nil)
116 .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 }
117 .background(theme.swiftColor("background") ?? Color(uiColor: .systemBackground))
118 .onChange(of: pane?.revealRequest?.id) {
119 guard let offset = pane?.revealRequest?.offset else { return }
120 reveal(offset, proxy)
121 }
122 .onChange(of: findTarget) {
123 guard let offset = findTarget else { return }
124 findTarget = nil
125 showFound(offset, proxy)
126 }
127 }
128 .navigationTitle(((shownPath ?? "") as NSString).lastPathComponent)
129 .navigationBarTitleDisplayMode(.inline)
130 .toolbar {
131 ToolbarItemGroup(placement: .primaryAction) {
132 Button("Find", systemImage: "magnifyingglass") {
133 find.text = (document?.tree.text ?? "") as NSString
134 findRequest += 1
135 }
136 .disabled(document == nil)
137 if let path = shownPath {
138 NavigationLink(value: EditorRoute(path: path, offset: nil)) { Label("Edit", systemImage: "pencil") }
139 }
140 Button("Commands", systemImage: "command") { showingCommands = true }
141 }
142 }
143 .sheet(isPresented: $showingCommands, onDismiss: {
144 // After the list has gone, so the command's own sheet can show.
145 if let id = chosenCommand {
146 chosenCommand = nil
147 runCommand(id)
148 }
149 }) {
150 CommandList(rows: commandRows) { chosenCommand = $0 }
151 }
152 .quickLookPreview($previewed)
153 .sheet(isPresented: $showingOutline) { outlineSheet }
154 .fullScreenCover(isPresented: Binding(get: { deck != nil }, set: { if !$0 { deck = nil } })) {
155 if let deck { PresentationScreen(deck: deck, theme: model.theme, options: session.options) }
156 }
157 .sheet(isPresented: $showingExport) {
158 if let path = shownPath, let tree = document?.tree { ExportScreen(path: path, tree: tree) { message = $0 } }
159 }
160 .message($message)
161 .overlay {
162 if DocumentSession.isEncryptedFile(path), !session.isOpen(path), unlocking == nil {
163 ContentUnavailableView {
164 Label("\((path as NSString).lastPathComponent) is encrypted", systemImage: "lock")
165 } actions: {
166 Button("Decrypt…") { unlocking = CryptRequest(mode: .openFile, path: path, offset: 0) }
167 }
168 }
169 }
170 .onChange(of: session.unlockRequest, initial: true) { _, request in
171 if request == path { unlocking = CryptRequest(mode: .openFile, path: path, offset: 0) }
172 }
173 .sheet(item: $unlocking) { request in
174 NavigationStack {
175 CryptSheet(request: request, session: session, text: { "" }, apply: { _ in }) { text in
176 unlocking = nil
177 if let text { message = text }
178 }
179 .navigationBarTitleDisplayMode(.inline)
180 }
181 }
182 .environment(\.openURL, OpenURLAction { url in follow(url) })
183 .background { FindHost(find: find, request: findRequest) }
184 .onAppear(perform: open)
185 .onChange(of: pane?.path) { loadFolds() }
186 .onChange(of: pane?.editVersion) { loadFolds() }
187 .onChange(of: model.settingsVersion) { loadFolds() }
188 .onReceive(NotificationCenter.default.publisher(for: OrgExport.refused)) { message = $0.object as? String }
189 }
190
191 // MARK: - Commands
192
193 /// The reader's commands: its own, capture, and the clock's that need no caret.
194 private var commandRows: [CommandRow] {
195 [
196 CommandRow(id: "reader.find", title: String(localized: "Find"), reason: document == nil ? String(localized: "Nothing to do here") : nil),
197 CommandRow(id: "reader.outline", title: String(localized: "Outline"), reason: outline.isEmpty ? String(localized: "Nothing to do here") : nil),
198 CommandRow(id: "reader.export", title: String(localized: "Export…"), reason: document == nil ? String(localized: "Nothing to do here") : nil),
199 CommandRow(id: "app.present", title: CommandTitle.localized("Present"), reason: document == nil ? String(localized: "Nothing to do here") : nil),
200 CommandRow(id: "app.toggle-markup", title: CommandTitle.localized("Show or Hide Markup")),
201 CommandRow(id: "app.capture", title: CommandTitle.localized("Capture…")),
202 ] + MobileClock.screenCommands.map { CommandRow(id: $0.id, title: CommandTitle.localized($0.title)) }
203 }
204
205 private func runCommand(_ id: String) {
206 switch id {
207 case "reader.find":
208 find.text = (document?.tree.text ?? "") as NSString
209 findRequest += 1
210 case "reader.outline": showingOutline = true
211 case "reader.export": showingExport = true
212 case "app.present":
213 guard let path = shownPath, let document else { return }
214 if let deck = SlideDeck(tree: document.tree, path: path, settings: document.defaults) {
215 self.deck = deck
216 } else {
217 message = String(localized: "Nothing to present")
218 }
219 case "app.toggle-markup": model.showMarkup.toggle()
220 case "app.capture": model.captureRequest = CaptureRequest()
221 default: _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
222 }
223 }
224
225 // MARK: - Content
226
227 private func indent(_ entry: OutlineEntry) -> CGFloat { CGFloat(entry.level - 1) * 14 }
228
229 private var indented: Bool { startup?.indented ?? true }
230
231 /// The text as the editor's display settings show it.
232 private var display: ReadingText.Display {
233 ReadingText.Display(showMarkup: model.showMarkup, options: session.options, highlighter: MobileEditor.highlighter)
234 }
235
236 /// org-indent: a heading's text and its body start past its stars, at level + 1 columns,
237 /// the fold mark standing where the last star and its space would. Without it nothing is
238 /// indented and the stars show.
239 private func headingIndent(_ entry: OutlineEntry, _ theme: MobileTheme) -> CGFloat {
240 indented ? CGFloat(entry.level - 1) * theme.column : 0
241 }
242
243 private func bodyIndent(_ entry: OutlineEntry, _ theme: MobileTheme) -> CGFloat {
244 indented ? CGFloat(entry.level + 1) * theme.column : 0
245 }
246
247 /// Hidden under a folded ancestor.
248 private func isShown(_ index: Int) -> Bool {
249 var parent = outline[index].parent
250 while let p = parent {
251 if fold.folds.contains(outline[p].start) { return false }
252 parent = outline[p].parent
253 }
254 return true
255 }
256
257 /// From after the heading line to the first child, or the section's end.
258 private func bodyRange(_ index: Int, _ tree: OrgTree) -> Range<Int> {
259 let entry = outline[index]
260 let ns = tree.text as NSString
261 let lineEnd = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
262 let firstChild = outline[(index + 1)...].first { $0.parent == index }?.start ?? entry.end
263 return min(lineEnd, firstChild)..<firstChild
264 }
265
266 private func heading(_ tree: OrgTree, _ entry: OutlineEntry, _ theme: MobileTheme) -> some View {
267 let ns = tree.text as NSString
268 let line = ns.lineRange(for: NSRange(location: entry.start, length: 0))
269 let start = indented ? min(entry.start + entry.level + 1, NSMaxRange(line)) : entry.start
270 let tags = tagGaps[entry.start].flatMap { $0.tags.upperBound <= NSMaxRange(line) ? $0 : nil }
271 func styled(_ range: Range<Int>) -> AttributedString {
272 attributed(ReadingText.segments(tree, in: range, display: display), heading: entry.level, theme)
273 }
274 let hasContent = entry.end > NSMaxRange(line)
275 let foldedMark = fold.folds.contains(entry.start) && hasContent
276 return HStack(alignment: .firstTextBaseline, spacing: 0) {
277 Image(systemName: foldedMark ? "chevron.right" : "chevron.down")
278 .font(.caption.weight(.semibold)).foregroundStyle(theme.swiftColor("markup") ?? Color(uiColor: .tertiaryLabel))
279 .opacity(hasContent ? 1 : 0)
280 .frame(width: 2 * theme.column, alignment: .leading)
281 if let tags, tags.gap.lowerBound >= start {
282 headingWithTags(title: styled(start..<tags.gap.lowerBound), gap: styled(tags.gap),
283 tags: styled(tags.tags.lowerBound..<NSMaxRange(line)).trimmingTrailingNewlines(), theme)
284 } else {
285 lineText(Text(styled(start..<NSMaxRange(line)).trimmingTrailingNewlines()), theme)
286 }
287 }
288 .padding(.leading, headingIndent(entry, theme))
289 .padding(.top, entry.level == 1 ? 6 : 0)
290 .contentShape(Rectangle())
291 .onTapGesture { fold = Presentation.cycle(entry.start, in: tree, fold) }
292 .accessibilityAddTraits(.isButton)
293 .accessibilityHint(foldedMark ? "Unfolds the heading" : "Folds the heading")
294 }
295
296 /// A heading whose tags are padded: as written when the line fits, the tags at the right
297 /// edge when they fit after one space, else the tags on a line of their own at the right.
298 private func headingWithTags(title: AttributedString, gap: AttributedString, tags: AttributedString, _ theme: MobileTheme) -> some View {
299 ViewThatFits(in: .horizontal) {
300 Text(title + gap + tags).fixedSize()
301 HStack(alignment: .firstTextBaseline, spacing: 0) {
302 Text(title).fixedSize()
303 Spacer(minLength: theme.column)
304 Text(tags).fixedSize()
305 }
306 VStack(alignment: .trailing, spacing: 0) {
307 lineText(Text(title), theme)
308 Text(tags).fixedSize()
309 }
310 }
311 .lineSpacing(CGFloat(max(0, theme.spec.lineSpacing)))
312 }
313
314 private func textView(_ tree: OrgTree, _ range: Range<Int>, _ theme: MobileTheme) -> some View {
315 VStack(alignment: .leading, spacing: 4) {
316 ForEach(parts(tree, range), id: \.range.lowerBound) { part in
317 if let image = part.image {
318 Image(uiImage: image.picture).resizable().scaledToFit()
319 .frame(maxWidth: image.width.map { CGFloat($0) } ?? image.picture.size.width, alignment: .leading)
320 .accessibilityLabel((image.path as NSString).lastPathComponent)
321 } else {
322 lineText(text(tree, part, theme), theme)
323 .textSelection(.enabled)
324 }
325 }
326 }
327 }
328
329 /// A part's text, with each image in it standing where its link is.
330 private func text(_ tree: OrgTree, _ part: Part, _ theme: MobileTheme) -> Text {
331 func styled(_ range: Range<Int>) -> AttributedString {
332 attributed(ReadingText.segments(tree, in: range, folded: folded, open: foldable.filter { !folded.contains($0) }, display: display), heading: nil, theme)
333 }
334 var text = Text("")
335 var start = part.range.lowerBound
336 for image in part.inText {
337 text = Text("\(text)\(Text(styled(start..<image.range.lowerBound)))\(Image(uiImage: image.picture))")
338 start = image.range.upperBound
339 }
340 return Text("\(text)\(Text(styled(start..<part.range.upperBound).trimmingTrailingNewlines()))")
341 }
342
343 /// Wrapped to the view's width, or on one line each, scrolling sideways, while truncated.
344 private func lineText(_ text: Text, _ theme: MobileTheme) -> some View {
345 text
346 .lineSpacing(CGFloat(max(0, theme.spec.lineSpacing)))
347 .fixedSize(horizontal: startup?.truncated ?? false, vertical: false)
348 .frame(maxWidth: startup?.truncated == true ? nil : .infinity, alignment: .leading)
349 }
350
351 private struct Part {
352 let range: Range<Int>
353 /// The image of a link that is all its line holds.
354 var image: (picture: UIImage, path: String, width: Int?)?
355 /// Images in the text, at their size, and the links they stand for.
356 var inText: [(range: Range<Int>, picture: UIImage)] = []
357 }
358
359 /// Text, and with inline images on, image links shown as their images: a link that is all
360 /// its line holds as a part of its own, others in their part's text.
361 private func parts(_ tree: OrgTree, _ range: Range<Int>) -> [Part] {
362 guard startup?.inlineImages == true, let path = shownPath else { return [Part(range: range)] }
363 // Read so that the view draws again when a remote image arrives.
364 _ = RemoteImages.shared.version
365 let remote = RemoteImages.Mode(rawValue: session.options.remoteInlineImages) ?? .skip
366 let base = URL(fileURLWithPath: path).deletingLastPathComponent()
367 let ns = tree.text as NSString
368 let maxWidth = width > 0 ? max(80, width - 72) : .greatestFiniteMagnitude
369 var parts: [Part] = []
370 var pending = Part(range: range.lowerBound..<range.lowerBound)
371 let links = InlineImages.links(tree, in: range, remote: remote != .skip, attachment: { DocumentSession.attachmentPath($0, at: $1, tree: tree, path: path) })
372 for placement in Presentation.imagePlacements(links, in: ns) {
373 let link = placement.link
374 guard link.range.lowerBound >= pending.range.lowerBound, link.range.upperBound <= range.upperBound,
375 folded.allSatisfy({ !$0.contains(link.range.lowerBound) }),
376 let picture = MobileEditor.loadImage(link.image.path, relativeTo: base, remote: remote) else { continue }
377 guard placement.ownLine else {
378 let size = Presentation.imageSize(natural: picture.size, width: link.image.width, maxWidth: maxWidth)
379 let sized = picture.cgImage.map { UIImage(cgImage: $0, scale: picture.size.width * picture.scale / max(1, size.width), orientation: picture.imageOrientation) }
380 pending.inText.append((link.range, sized ?? picture))
381 continue
382 }
383 let line = ns.lineRange(for: NSRange(location: link.range.lowerBound, length: 0))
384 if pending.range.lowerBound < line.location {
385 parts.append(Part(range: pending.range.lowerBound..<line.location, inText: pending.inText))
386 }
387 let end = min(NSMaxRange(line), range.upperBound)
388 parts.append(Part(range: line.location..<end, image: (picture, link.image.path, link.image.width)))
389 pending = Part(range: end..<end)
390 }
391 if pending.range.lowerBound < range.upperBound { parts.append(Part(range: pending.range.lowerBound..<range.upperBound, inText: pending.inText)) }
392 return parts
393 }
394
395 /// Segments as styled text in the theme's font and colors, as the editor styles them;
396 /// links get `orgstar-link:` URLs to follow.
397 private func attributed(_ segments: [ReadingText.Segment], heading level: Int?, _ theme: MobileTheme) -> AttributedString {
398 var result = AttributedString()
399 for segment in segments {
400 var part = AttributedString(segment.text)
401 var font = level.map(theme.headingFont) ?? theme.body
402 if theme.mixedPitch, segment.roles.contains(where: Presentation.isFixedPitch) { font = theme.fixedPitch(font) }
403 var color = level.flatMap { theme.color("heading-\(min(max($0, 1), 8))") } ?? theme.foreground
404 func fg(_ key: String) { if let c = theme.color(key) { color = c } }
405 // Outer roles first, so inner ones win.
406 for role in segment.roles.sorted(by: { Self.depth($0) < Self.depth($1) }) {
407 switch role {
408 case .todo, .done:
409 font = MobileTheme.adding(.traitBold, to: font)
410 if let c = theme.keywordColor(segment.text, done: role == .done) { color = c }
411 case .priority: fg("priority")
412 case .tags: fg("tags")
413 case .bold: font = MobileTheme.adding(.traitBold, to: font)
414 case .italic: font = MobileTheme.adding(.traitItalic, to: font)
415 case .underline: part.underlineStyle = .single
416 case .strikeThrough: part.strikethroughStyle = .single
417 case .verbatim, .code, .inlineSource:
418 if let background = theme.color("inline-background") { part.backgroundColor = Color(uiColor: background) }
419 fg(role == .verbatim ? "verbatim" : "code")
420 case .markup, .linkMarkup: fg("markup")
421 case .leadingStars:
422 // As the editor hides them; shown in the heading's color unless hidden.
423 if !Presentation.skipsLeadingStars(role, indented: indented, hideStars: startup?.hideStars ?? false) { color = .clear }
424 case .syntax(let category): if let key = category.themeKey { fg(key) }
425 case .timestamp: fg("timestamp")
426 case .comment: fg("comment")
427 case .keyword: fg("keyword")
428 case .metadata: fg("metadata")
429 case .blockDelimiter: fg("block-delimiter")
430 case .footnote, .cookie, .target, .macro, .latex: fg("special")
431 case .table, .rule: fg("table")
432 case .link:
433 part.underlineStyle = .single
434 fg("link")
435 case .heading, .block: break
436 }
437 }
438 if segment.link != nil {
439 // Found again by position when followed.
440 part.link = URL(string: "orgstar-link:\(segment.offset)")
441 }
442 if let start = segment.toggles { part.link = URL(string: "orgstar-fold:\(start)") }
443 if let superscript = segment.superscript {
444 // Raised or lowered as the editor draws `org-pretty-entities` scripts.
445 part.baselineOffset = (superscript ? 0.3 : -0.3) * font.pointSize
446 font = font.withSize(font.pointSize * 0.7)
447 }
448 part.font = Font(font as CTFont)
449 part.foregroundColor = Color(uiColor: color)
450 if !found.isEmpty { markFound(&part, segment) }
451 result += part
452 }
453 return result
454 }
455
456 /// Find's results in a segment's text: exactly where the segment shows the file as written,
457 /// otherwise the whole segment.
458 private func markFound(_ part: inout AttributedString, _ segment: ReadingText.Segment) {
459 let length = (segment.text as NSString).length
460 let span = segment.offset..<(segment.offset + length)
461 let source = (document?.tree.text ?? "") as NSString
462 let asWritten = span.upperBound <= source.length && source.substring(with: NSRange(span)) == segment.text
463 for (range, shown) in found where range.overlaps(span) || (span.isEmpty && range.contains(span.lowerBound)) {
464 let color = Color(uiColor: shown ? .systemYellow : .systemYellow.withAlphaComponent(0.35))
465 guard asWritten else {
466 part.backgroundColor = color
467 continue
468 }
469 let text = segment.text
470 func index(_ offset: Int) -> AttributedString.Index {
471 let utf16 = text.utf16.index(text.startIndex, offsetBy: min(max(0, offset - span.lowerBound), length))
472 return part.index(part.startIndex, offsetByCharacters: text.distance(from: text.startIndex, to: utf16))
473 }
474 let lower = index(range.lowerBound), upper = index(range.upperBound)
475 if lower < upper { part[lower..<upper].backgroundColor = color }
476 }
477 }
478
479 /// Unfolds the way to a find result, its heading and a drawer it's in, and scrolls to its heading.
480 private func showFound(_ offset: Int, _ proxy: ScrollViewProxy) {
481 folded.removeAll { $0.contains(offset) }
482 // Before the first heading, the text shows already.
483 guard let index = outline.lastIndex(where: { $0.start <= offset }) else { return }
484 fold.folds.remove(outline[index].start)
485 fold.bodyFolds.remove(outline[index].start)
486 reveal(offset, proxy)
487 }
488
489 /// How deep a role's text usually nests: elements, then objects, then their parts.
490 private static func depth(_ role: StyleRole) -> Int {
491 switch role {
492 case .heading: 0
493 case .metadata, .keyword, .comment, .block, .table, .rule: 1
494 case .blockDelimiter, .link, .bold, .italic, .underline, .strikeThrough, .timestamp, .footnote, .target, .macro, .latex: 2
495 default: 3
496 }
497 }
498
499 // MARK: - Actions
500
501 private func open() {
502 find.onChange = { found = $0 }
503 find.onShow = { findTarget = $0 }
504 let pane = holder.pane ?? {
505 let made = session.makePane()
506 holder.pane = made
507 holder.release = { [weak session] in session?.closePane(made) }
508 return made
509 }()
510 // What the reader opens and follows goes to its pane.
511 session.focused = pane
512 if loadedPath == nil {
513 switch route {
514 case .file(let path): session.open(path, in: pane)
515 case .offset(let path, let offset):
516 session.open(path, in: pane)
517 session.reveal(offset, in: pane)
518 case .heading(let location): session.show(location)
519 }
520 }
521 loadFolds()
522 }
523
524 /// The file's startup display, as the editor opens it; its heading folds are kept while
525 /// the same file is open.
526 private func loadFolds() {
527 guard let tree = document?.tree, showsOwnFile else { return }
528 let display = Presentation.startupDisplay(tree, options: session.options)
529 startup = display
530 let text = tree.text as NSString
531 tagGaps = Dictionary(Presentation.tagGaps(tree).map { (text.lineRange(for: NSRange(location: $0.gap.lowerBound, length: 0)).location, $0) }) { a, _ in a }
532 folded = display.wrappers.map(\.hidden)
533 foldable = folded
534 guard loadedPath != shownPath else { return }
535 loadedPath = shownPath
536 fold = display.folds
537 }
538
539 /// Unfolds the way to the heading containing `offset` and scrolls to it.
540 private func reveal(_ offset: Int, _ proxy: ScrollViewProxy) {
541 guard let index = outline.lastIndex(where: { $0.start <= offset }) else { return }
542 var parent = outline[index].parent
543 while let p = parent {
544 fold.folds.remove(outline[p].start)
545 parent = outline[p].parent
546 }
547 let start = outline[index].start
548 DispatchQueue.main.async { withAnimation { proxy.scrollTo(start, anchor: .top) } }
549 }
550
551 private func follow(_ url: URL) -> OpenURLAction.Result {
552 if url.scheme == "orgstar-fold", let start = Int(url.absoluteString.dropFirst("orgstar-fold:".count)) {
553 if folded.contains(where: { $0.lowerBound == start }) {
554 folded.removeAll { $0.lowerBound == start }
555 } else if let range = foldable.first(where: { $0.lowerBound == start }) {
556 folded.append(range)
557 }
558 return .handled
559 }
560 guard url.scheme == "orgstar-link", let offset = Int(url.absoluteString.dropFirst("orgstar-link:".count)),
561 let tree = document?.tree, let link = Links.link(at: offset, text: tree.text, tree: tree)?.link else {
562 return .systemAction
563 }
564 if let pane { session.focused = pane }
565 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
566 case .shown:
567 message = nil
568 // A link to another file shows it on its own screen; this pane keeps its file.
569 if let pane, let target = pane.path, target != path, !showsOwnFile {
570 let caret = session.caret(of: target) ?? 0
571 session.open(path, in: pane)
572 model.openRequest = .offset(target, caret)
573 }
574 case .openExternally(let target): if target.isFileURL { previewed = target } else { openURL(target) }
575 case .message(let text): message = text
576 case .choose(let question, let paths): message = question + paths.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
577 case .elisp: message = "Open the file in the editor to run elisp links."
578 // `Links.link` doesn't read citations, so none come here.
579 case .citation: break
580 }
581 return .handled
582 }
583
584 private var outlineSheet: some View {
585 NavigationStack {
586 List(outline, id: \.start) { entry in
587 Button {
588 showingOutline = false
589 if let pane { session.reveal(entry.start, in: pane) }
590 } label: {
591 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
592 .padding(.leading, indent(entry))
593 .foregroundStyle(.primary)
594 }
595 }
596 .navigationTitle("Outline")
597 .navigationBarTitleDisplayMode(.inline)
598 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { showingOutline = false } } }
599 }
600 }
601}
602
603/// The reader's find, for the system find bar: it searches the file as written and tells the
604/// reader which results to mark and which one to show.
605@MainActor
606final class ReaderFind: NSObject, @preconcurrency UITextSearching, UIFindInteractionDelegate {
607 /// The file's text, set when the find bar opens.
608 nonisolated(unsafe) var text: NSString = ""
609 /// Each result marked, true for the one shown.
610 var onChange: ([Range<Int>: Bool]) -> Void = { _ in }
611 /// The result to show, by its offset.
612 var onShow: (Int) -> Void = { _ in }
613 private var marked: [Range<Int>: Bool] = [:]
614
615 final class Position: UITextPosition {
616 let offset: Int
617 init(_ offset: Int) { self.offset = offset }
618 }
619
620 final class TextRange: UITextRange {
621 let range: Range<Int>
622 init(_ range: Range<Int>) { self.range = range }
623 override var start: UITextPosition { Position(range.lowerBound) }
624 override var end: UITextPosition { Position(range.upperBound) }
625 override var isEmpty: Bool { range.isEmpty }
626 }
627
628 func findInteraction(_ interaction: UIFindInteraction, sessionFor view: UIView) -> UIFindSession? {
629 UITextSearchingFindSession(searchableObject: self)
630 }
631
632 var selectedTextRange: UITextRange? { nil }
633
634 func compare(_ foundRange: UITextRange, toRange: UITextRange, document: AnyHashable??) -> ComparisonResult {
635 let a = (foundRange as? TextRange)?.range.lowerBound ?? 0, b = (toRange as? TextRange)?.range.lowerBound ?? 0
636 return a < b ? .orderedAscending : a > b ? .orderedDescending : .orderedSame
637 }
638
639 nonisolated func performTextSearch(queryString: String, options: UITextSearchOptions, resultAggregator: UITextSearchAggregator<AnyHashable?>) {
640 // The aggregator takes results from any thread; the ranges are made on the main thread.
641 nonisolated(unsafe) let aggregator = resultAggregator
642 let search = {
643 MainActor.assumeIsolated {
644 for found in EditorFind.matches(of: queryString, in: self.text, options: options) {
645 aggregator.foundRange(TextRange(found), searchString: queryString, document: nil)
646 }
647 }
648 aggregator.finishedSearching()
649 }
650 if Thread.isMainThread { search() } else { DispatchQueue.main.sync(execute: search) }
651 }
652
653 func decorate(foundTextRange: UITextRange, document: AnyHashable??, usingStyle style: UITextSearchFoundTextStyle) {
654 guard let range = (foundTextRange as? TextRange)?.range else { return }
655 switch style {
656 case .normal: marked[range] = nil
657 case .highlighted:
658 marked[range] = true
659 onShow(range.lowerBound)
660 default: marked[range] = false
661 }
662 onChange(marked)
663 }
664
665 func clearAllDecoratedFoundText() {
666 marked = [:]
667 onChange(marked)
668 }
669
670 func scrollRangeToVisible(_ range: UITextRange, inDocument: AnyHashable??) {
671 if let range = (range as? TextRange)?.range { onShow(range.lowerBound) }
672 }
673}
674
675/// Holds the find interaction for a SwiftUI screen, and shows its find bar when `request` changes.
676private struct FindHost: UIViewRepresentable {
677 let find: ReaderFind
678 let request: Int
679
680 /// The find bar shows for the first responder's interaction.
681 final class Host: UIView {
682 override var canBecomeFirstResponder: Bool { true }
683 }
684
685 func makeUIView(context: Context) -> Host {
686 let view = Host()
687 view.addInteraction(UIFindInteraction(sessionDelegate: find))
688 return view
689 }
690
691 func updateUIView(_ view: Host, context: Context) {
692 guard request != context.coordinator.shown else { return }
693 context.coordinator.shown = request
694 view.becomeFirstResponder()
695 view.interactions.lazy.compactMap { $0 as? UIFindInteraction }.first?.presentFindNavigator(showingReplace: false)
696 }
697
698 func makeCoordinator() -> Coordinator { Coordinator() }
699
700 final class Coordinator {
701 var shown = 0
702 }
703}
704
705private extension AttributedString {
706 /// Without the final newline, which `Text` would show as an empty line.
707 func trimmingTrailingNewlines() -> AttributedString {
708 var copy = self
709 while let last = copy.characters.last, last.isNewline { copy.characters.removeLast() }
710 return copy
711 }
712}
713#endif