Sources/OrgstarMobile/ReaderScreen.swift

3191c129ca5c91d95f0675eb7ae26f1a551be7f6
orgstar/Sources/OrgstarMobile/ReaderScreen.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form