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