Sources/OrgApp/DocumentSession.swift
82 lines · 3153 bytes
1import Foundation
2import Observation
3import OrgCore
4import OrgDocument
5import OrgIndex
6import OrgPresentation
7
8/// The file open in a window: its state, its outline, and requests for the editor to show a
9/// location. The view layer owns the text view and follows `revealRequest` and `diskBytes`.
10@MainActor
11@Observable
12public final class DocumentSession {
13 public private(set) var path: String?
14 public private(set) var document: DocumentState?
15 public private(set) var outline: [OutlineEntry] = []
16 /// Bumped to ask the editor to reveal an offset.
17 public private(set) var revealRequest: (offset: Int, id: Int)?
18 /// New bytes from disk for the open file, for the editor to merge or reload.
19 public private(set) var diskBytes: (bytes: [UInt8], id: Int)?
20 public var lastError: String?
21
22 private let fileSystem: FileSystem
23 private var requestID = 0
24
25 public init(fileSystem: FileSystem = CoordinatedFileSystem()) {
26 self.fileSystem = fileSystem
27 }
28
29 public func open(_ path: String) {
30 do {
31 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
32 lastError = "\((path as NSString).lastPathComponent) no longer exists."
33 return
34 }
35 let document = DocumentState(bytes: bytes)
36 self.path = path
37 self.document = document
38 outline = Presentation.outline(document.tree)
39 revealRequest = nil
40 diskBytes = nil
41 } catch {
42 lastError = "Can't open \(path): \(error.localizedDescription)"
43 }
44 }
45
46 /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
47 /// are used only if the file is unchanged since it was indexed; otherwise the heading is
48 /// found again by position and title.
49 public func show(_ location: HeadingLocation) {
50 if path != location.path { open(location.path) }
51 guard let document else { return }
52 let hash = FileRecord.hash(document.mergeBase)
53 let offset: Int
54 if hash == location.contentHash {
55 offset = location.start
56 } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
57 offset = outline[location.ordinal].start
58 } else if let entry = outline.first(where: { $0.title == location.title }) {
59 offset = entry.start
60 } else {
61 return
62 }
63 reveal(offset)
64 }
65
66 public func reveal(_ offset: Int) {
67 requestID += 1
68 revealRequest = (offset, requestID)
69 }
70
71 /// Called when the workspace sees the open file change on disk.
72 public func fileChanged(_ path: String) {
73 guard path == self.path, let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
74 guard bytes != document?.mergeBase else { return }
75 var updated = document ?? DocumentState(bytes: bytes)
76 _ = updated.diskChanged(to: bytes)
77 document = updated
78 outline = Presentation.outline(updated.tree)
79 requestID += 1
80 diskBytes = (bytes, requestID)
81 }
82}