Faster reader, fewer redraws !199

merged merged by cmc on 2026-10-10 04:43 UTC · krz/orgstar:reader-responsiveness into main

11 files changed, +239 −64

Layout: unified · split

Sources/OrgApp/AgendaModel.swift +44 −9
@@ -9,6 +9,8 @@ import OrgPresentation
9@MainActor 9@MainActor
10public final class AgendaSourceCache { 10public final class AgendaSourceCache {
11 var entries: [String: (mtime: Date, size: Int, defaults: OrgSettings, blocking: Bool, source: AgendaSource)] = [:] 11 var entries: [String: (mtime: Date, size: Int, defaults: OrgSettings, blocking: Bool, source: AgendaSource)] = [:]
12 /// Open buffers' sources, kept while their text is the same.
13 var open: [String: (defaults: OrgSettings, blocking: Bool, source: AgendaSource)] = [:]
12 14
13 public init() {} 15 public init() {}
14} 16}
@@ -101,11 +103,12 @@ public final class AgendaModel {
101 return (days, list, events) 103 return (days, list, events)
102 }.value 104 }.value
103 guard id == generation else { return } 105 guard id == generation else { return }
104 days = result.0 106 // Unchanged results leave the views alone: a new value redraws the whole list.
105 list = result.1 107 if days != result.0 { days = result.0 }
106 events = result.2 108 if list != result.1 { list = result.1 }
107 self.today = today 109 if events != result.2 { events = result.2 }
108 self.calendar = calendar 110 if self.today != today { self.today = today }
111 if self.calendar != calendar { self.calendar = calendar }
109 isComputing = false 112 isComputing = false
110 } 113 }
111 114
@@ -131,7 +134,15 @@ public final class AgendaModel {
131 var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = [] 134 var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = []
132 for path in files { 135 for path in files {
133 if let text = open[path] { 136 if let text = open[path] {
134 reads.append((path, nil, .distantPast, -1, text)) 137 // The same text parsed before, as the buffer or as the file on disk.
138 func reusable(_ source: AgendaSource?, _ parsedWith: OrgSettings?, _ parsedBlocking: Bool?) -> AgendaSource? {
139 guard let source, parsedWith == defaults, parsedBlocking == blocking, !source.readsSetupFiles, source.text == text else { return nil }
140 return source
141 }
142 let fromOpen = cache.open[path]
143 let fromDisk = cache.entries[path]
144 let cached = reusable(fromOpen?.source, fromOpen?.defaults, fromOpen?.blocking) ?? reusable(fromDisk?.source, fromDisk?.defaults, fromDisk?.blocking)
145 reads.append((path, cached, .distantPast, -1, text))
135 continue 146 continue
136 } 147 }
137 let attributes = try? FileManager.default.attributesOfItem(atPath: path) 148 let attributes = try? FileManager.default.attributesOfItem(atPath: path)
@@ -147,7 +158,7 @@ public final class AgendaModel {
147 var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = [] 158 var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = []
148 for read in reads { 159 for read in reads {
149 if let cached = read.cached { 160 if let cached = read.cached {
150 sources.append((read.path, read.mtime, read.size, cached, true)) 161 sources.append((read.path, read.mtime, read.size, cached, read.text == nil))
151 } else if let text = read.text { 162 } else if let text = read.text {
152 sources.append((read.path, read.mtime, read.size, AgendaSource(path: read.path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: read.path, read: OrgSettings.readFile), checksBlocking: blocking), false)) 163 sources.append((read.path, read.mtime, read.size, AgendaSource(path: read.path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: read.path, read: OrgSettings.readFile), checksBlocking: blocking), false))
153 } else if let data = FileManager.default.contents(atPath: read.path) { 164 } else if let data = FileManager.default.contents(atPath: read.path) {
@@ -157,8 +168,12 @@ public final class AgendaModel {
157 } 168 }
158 return sources 169 return sources
159 }.value 170 }.value
160 for source in loaded where source.fromDisk { 171 for source in loaded {
161 cache.entries[source.path] = (source.mtime, source.size, defaults, blocking, source.source) 172 if source.fromDisk {
173 cache.entries[source.path] = (source.mtime, source.size, defaults, blocking, source.source)
174 } else {
175 cache.open[source.path] = (defaults, blocking, source.source)
176 }
162 } 177 }
163 return loaded.map(\.source) 178 return loaded.map(\.source)
164 } 179 }
@@ -169,6 +184,26 @@ public final class AgendaModel {
169 AgendaRows.groups(days, events: events, today: today, showAllDates: showAllDates, calendar: calendar, keep: keep) 184 AgendaRows.groups(days, events: events, today: today, showAllDates: showAllDates, calendar: calendar, keep: keep)
170 } 185 }
171 186
187 /// `groups` with `filter`, kept while the days, events and arguments are the same, as
188 /// views ask on every redraw.
189 public func groups(showAllDates: Bool, filter: AgendaFilter) -> [AgendaDayGroup] {
190 let key = GroupsKey(days: days, events: events, today: today, showAllDates: showAllDates, filter: filter)
191 if let groupsMemo, groupsMemo.key == key { return groupsMemo.groups }
192 let groups = groups(showAllDates: showAllDates, keep: filter.keeps)
193 groupsMemo = (key, groups)
194 return groups
195 }
196
197 private struct GroupsKey: Equatable {
198 let days: [AgendaDay]
199 let events: [AgendaEvent]
200 let today: Int
201 let showAllDates: Bool
202 let filter: AgendaFilter
203 }
204
205 @ObservationIgnored private var groupsMemo: (key: GroupsKey, groups: [AgendaDayGroup])?
206
172 nonisolated static func date(_ day: Int, calendar: Calendar) -> Date { 207 nonisolated static func date(_ day: Int, calendar: Calendar) -> Date {
173 let d = Days.date(day) 208 let d = Days.date(day)
174 return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date() 209 return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
Sources/OrgCore/Agenda/AgendaSource.swift +1 −1
@@ -109,7 +109,7 @@ public struct AgendaSource: Sendable {
109 /// Each keyword's first done keyword in the first sequence that has it. 109 /// Each keyword's first done keyword in the first sequence that has it.
110 let firstDone: [String: String] 110 let firstDone: [String: String]
111 /// The file's text, for the search view. 111 /// The file's text, for the search view.
112 let text: String 112 public let text: String
113 let priorities: Priorities 113 let priorities: Priorities
114 114
115 /// `checksBlocking` false leaves every heading unblocked, for when neither enforce 115 /// `checksBlocking` false leaves every heading unblocked, for when neither enforce
Sources/OrgCore/Syntax/SyntaxNode.swift +25 −1
@@ -1,3 +1,5 @@
1import Foundation
2
1/// A view of a green node at an absolute offset, with a parent link. Created on demand. 3/// A view of a green node at an absolute offset, with a parent link. Created on demand.
2public final class SyntaxNode: Sendable { 4public final class SyntaxNode: Sendable {
3 public let green: GreenNode 5 public let green: GreenNode
@@ -112,7 +114,29 @@ public struct SyntaxToken: Sendable, Equatable {
112public struct OrgTree: Sendable { 114public struct OrgTree: Sendable {
113 public let green: GreenNode 115 public let green: GreenNode
114 public let settings: OrgSettings 116 public let settings: OrgSettings
117 private let textCache = TextCache()
118
119 public init(green: GreenNode, settings: OrgSettings) {
120 self.green = green
121 self.settings = settings
122 }
115 123
116 public var root: SyntaxNode { SyntaxNode(green: green, offset: 0, parent: nil) } 124 public var root: SyntaxNode { SyntaxNode(green: green, offset: 0, parent: nil) }
117 public var text: String { green.text } 125 /// Built from the tree on first use, then kept: views read it once per heading.
126 public var text: String { textCache.text(of: green) }
127}
128
129/// An `OrgTree`'s text, built once.
130private final class TextCache: @unchecked Sendable {
131 private let lock = NSLock()
132 private var text: String?
133
134 func text(of green: GreenNode) -> String {
135 lock.withLock {
136 if let text { return text }
137 let built = green.text
138 text = built
139 return built
140 }
141 }
118} 142}
Sources/OrgCore/Syntax/Wrappers.swift +16 −12
@@ -1,3 +1,5 @@
1import Foundation
2
1/// Drawers and blocks, the elements org folds on their own (`org-fold-hide-drawer-toggle`, 3/// Drawers and blocks, the elements org folds on their own (`org-fold-hide-drawer-toggle`,
2/// `org-fold-hide-block-toggle`). 4/// `org-fold-hide-block-toggle`).
3public struct Wrapper: Sendable, Equatable { 5public struct Wrapper: Sendable, Equatable {
@@ -21,18 +23,19 @@ public enum Wrappers {
21 } 23 }
22 } 24 }
23 25
24 static func wrapper(_ node: SyntaxNode) -> Wrapper? { 26 /// `text` is the document's, read in place rather than copying the node's text.
27 static func wrapper(_ node: SyntaxNode, in text: NSString) -> Wrapper? {
25 guard let kind = kind(node.kind) else { return nil } 28 guard let kind = kind(node.kind) else { return nil }
26 let units = Array(node.text.utf16) 29 let start = node.range.lowerBound
27 // Blank lines after the element belong to it in the tree, not to the fold. 30 // Blank lines after the element belong to it in the tree, not to the fold.
28 var end = units.count 31 var end = node.range.upperBound
29 while end > 0, [9, 10, 13, 32].contains(units[end - 1]) { end -= 1 } 32 while end > start, [9, 10, 13, 32].contains(text.character(at: end - 1)) { end -= 1 }
30 guard let firstNewline = units.firstIndex(of: 10), firstNewline < end else { return nil } 33 let firstNewline = text.range(of: "\n", options: .literal, range: NSRange(start..<end)).location
34 guard firstNewline != NSNotFound else { return nil }
31 var closeStart = end 35 var closeStart = end
32 while closeStart > 0, units[closeStart - 1] != 10 { closeStart -= 1 } 36 while closeStart > start, text.character(at: closeStart - 1) != 10 { closeStart -= 1 }
33 let hiddenEnd = end < units.count ? end + 1 : end 37 let hiddenEnd = end < node.range.upperBound ? end + 1 : end
34 return Wrapper(kind: kind, start: node.range.lowerBound, closeLine: node.range.lowerBound + closeStart, 38 return Wrapper(kind: kind, start: start, closeLine: closeStart, hidden: (firstNewline + 1)..<hiddenEnd)
35 hidden: (node.range.lowerBound + firstNewline + 1)..<(node.range.lowerBound + hiddenEnd))
36 } 39 }
37 40
38 /// Elements a drawer or block can sit in. 41 /// Elements a drawer or block can sit in.
@@ -41,9 +44,10 @@ public enum Wrappers {
41 /// Every drawer and block, in document order, nested ones included. 44 /// Every drawer and block, in document order, nested ones included.
42 public static func all(_ tree: OrgTree) -> [Wrapper] { 45 public static func all(_ tree: OrgTree) -> [Wrapper] {
43 var result: [Wrapper] = [] 46 var result: [Wrapper] = []
47 let text = tree.text as NSString
44 func walk(_ node: SyntaxNode) { 48 func walk(_ node: SyntaxNode) {
45 for child in node.children { 49 for child in node.children {
46 if let wrapper = wrapper(child) { result.append(wrapper) } 50 if let wrapper = wrapper(child, in: text) { result.append(wrapper) }
47 if containers.contains(child.kind) { walk(child) } 51 if containers.contains(child.kind) { walk(child) }
48 } 52 }
49 } 53 }
@@ -55,7 +59,7 @@ public enum Wrappers {
55 public static func starting(at offset: Int, in tree: OrgTree) -> Wrapper? { 59 public static func starting(at offset: Int, in tree: OrgTree) -> Wrapper? {
56 var node = tree.root 60 var node = tree.root
57 while let child = node.child(containing: offset) { 61 while let child = node.child(containing: offset) {
58 if child.range.lowerBound == offset, let wrapper = wrapper(child) { return wrapper } 62 if child.range.lowerBound == offset, let wrapper = wrapper(child, in: tree.text as NSString) { return wrapper }
59 node = child 63 node = child
60 } 64 }
61 return nil 65 return nil
@@ -67,7 +71,7 @@ public enum Wrappers {
67 var node = tree.root 71 var node = tree.root
68 var found: Wrapper? 72 var found: Wrapper?
69 while let child = node.child(containing: offset) { 73 while let child = node.child(containing: offset) {
70 if let wrapper = wrapper(child), offset < wrapper.hidden.lowerBound || (wrapper.closeLine..<wrapper.hidden.upperBound).contains(offset) { 74 if let wrapper = wrapper(child, in: tree.text as NSString), offset < wrapper.hidden.lowerBound || (wrapper.closeLine..<wrapper.hidden.upperBound).contains(offset) {
71 found = wrapper 75 found = wrapper
72 } 76 }
73 node = child 77 node = child
Sources/OrgPresentation/Presentation.swift +13
@@ -1,4 +1,5 @@
1import OrgCore 1import OrgCore
2import os
2 3
3/// What a range of text is, for styling. Platform adapters map roles to attributes. 4/// What a range of text is, for styling. Platform adapters map roles to attributes.
4public enum StyleRole: Hashable, Sendable { 5public enum StyleRole: Hashable, Sendable {
@@ -208,7 +209,19 @@ public enum Presentation {
208 } 209 }
209 210
210 /// Blocks and fixed-width areas, drawn on a shaded band the width of the view. Sorted. 211 /// Blocks and fixed-width areas, drawn on a shaded band the width of the view. Sorted.
212 /// The last tree's are kept: the reader asks once per section.
211 public static func shadedBlocks(_ tree: OrgTree) -> [Range<Int>] { 213 public static func shadedBlocks(_ tree: OrgTree) -> [Range<Int>] {
214 shadedBlocksCache.withLock { last in
215 if let last, last.green === tree.green { return last.ranges }
216 let ranges = computeShadedBlocks(tree)
217 last = (tree.green, ranges)
218 return ranges
219 }
220 }
221
222 private static let shadedBlocksCache = OSAllocatedUnfairLock<(green: GreenNode, ranges: [Range<Int>])?>(initialState: nil)
223
224 private static func computeShadedBlocks(_ tree: OrgTree) -> [Range<Int>] {
212 var ranges: [Range<Int>] = [] 225 var ranges: [Range<Int>] = []
213 func walk(_ node: SyntaxNode) { 226 func walk(_ node: SyntaxNode) {
214 for child in node.children { 227 for child in node.children {
Sources/OrgPresentation/ReadingText.swift +38 −11
@@ -35,7 +35,6 @@ public enum ReadingText {
35 /// `folded` are drawers' and blocks' hidden ranges (`Wrapper.hidden`). 35 /// `folded` are drawers' and blocks' hidden ranges (`Wrapper.hidden`).
36 public static func segments(_ tree: OrgTree, in range: Range<Int>, folded: [Range<Int>] = [], display: Display = Display()) -> [Segment] { 36 public static func segments(_ tree: OrgTree, in range: Range<Int>, folded: [Range<Int>] = [], display: Display = Display()) -> [Segment] {
37 let text = tree.text as NSString 37 let text = tree.text as NSString
38 let runs = Presentation.styles(tree, in: range, highlighter: display.highlighter)
39 // A fold hides from the end of the opening line through the closing line, so the 38 // A fold hides from the end of the opening line through the closing line, so the
40 // marker sits on the opening line. 39 // marker sits on the opening line.
41 let folds = folded.compactMap { r -> Range<Int>? in 40 let folds = folded.compactMap { r -> Range<Int>? in
@@ -43,17 +42,28 @@ public enum ReadingText {
43 let end = r.upperBound > r.lowerBound && r.upperBound <= text.length && text.character(at: r.upperBound - 1) == 10 ? r.upperBound - 1 : r.upperBound 42 let end = r.upperBound > r.lowerBound && r.upperBound <= text.length && text.character(at: r.upperBound - 1) == 10 ? r.upperBound - 1 : r.upperBound
44 return (r.lowerBound - 1)..<min(end, range.upperBound) 43 return (r.lowerBound - 1)..<min(end, range.upperBound)
45 } 44 }
45 // Styled only where shown: a folded drawer can hold most of a section.
46 var visible: [Range<Int>] = []
47 var from = range.lowerBound
48 for fold in folds.sorted(by: { $0.lowerBound < $1.lowerBound }) where fold.upperBound > from {
49 if fold.lowerBound > from { visible.append(from..<fold.lowerBound) }
50 from = fold.upperBound
51 }
52 if from < range.upperBound || visible.isEmpty { visible.append(from..<max(from, range.upperBound)) }
53 let runs = visible.flatMap { Presentation.styles(tree, in: $0, highlighter: display.highlighter) }
46 var hidden = runs.filter { !display.showMarkup && Presentation.hidesWithMarkup($0.role, options: display.options) }.map(\.range) + folds 54 var hidden = runs.filter { !display.showMarkup && Presentation.hidesWithMarkup($0.role, options: display.options) }.map(\.range) + folds
47 // `org-pretty-entities`: an entity's last character shows its character, the rest hidden. 55 // `org-pretty-entities`: an entity's last character shows its character, the rest hidden.
48 var replaced: [Int: String] = [:] 56 var replaced: [Int: String] = [:]
49 var scripts: [(range: Range<Int>, superscript: Bool)] = [] 57 var scripts: [(range: Range<Int>, superscript: Bool)] = []
50 if !display.showMarkup, display.options.prettyEntities { 58 if !display.showMarkup, display.options.prettyEntities {
51 let blocks = Presentation.shadedBlocks(tree) 59 let blocks = Presentation.shadedBlocks(tree)
52 let pretty = Presentation.prettyRuns( 60 let exclusions = runs.filter { Presentation.excludesScripts($0.role) }.map(\.range)
53 text, in: range, revealedLine: nil, inBlock: { offset in blocks.contains { $0.contains(offset) } }, 61 let pretty = visible.flatMap { part in
54 scriptExclusions: runs.filter { Presentation.excludesScripts($0.role) }.map(\.range), 62 Presentation.prettyRuns(
55 subSuperscriptsNeedBraces: display.options.subSuperscriptsNeedBraces 63 text, in: part, revealedLine: nil, inBlock: { offset in blocks.contains { $0.contains(offset) } },
56 ) 64 scriptExclusions: exclusions, subSuperscriptsNeedBraces: display.options.subSuperscriptsNeedBraces
65 )
66 }
57 for (lineStart, run) in pretty { 67 for (lineStart, run) in pretty {
58 switch run { 68 switch run {
59 case .entity(let r, let shown): 69 case .entity(let r, let shown):
@@ -83,14 +93,31 @@ public enum ReadingText {
83 segments.append(segment) 93 segments.append(segment)
84 } 94 }
85 } 95 }
86 for (a, b) in zip(points, points.dropFirst()) where a < b { 96 // What covers each interval between consecutive points, marked range by range rather
87 if folds.contains(where: { $0.lowerBound == a }) { 97 // than tested interval by interval, which grows with the square of a long section.
98 let intervals = max(points.count - 1, 0)
99 var position: [Int: Int] = [:]
100 for (k, point) in points.enumerated() { position[point] = k }
101 func covered(_ r: Range<Int>) -> Range<Int> {
102 let lo = position[max(range.lowerBound, min(range.upperBound, r.lowerBound))]!
103 let hi = position[max(range.lowerBound, min(range.upperBound, r.upperBound))]!
104 return lo..<max(lo, hi)
105 }
106 var rolesAt = [Set<StyleRole>](repeating: [], count: intervals)
107 for run in runs { for k in covered(run.range) { rolesAt[k].insert(run.role) } }
108 var hiddenAt = [Bool](repeating: false, count: intervals)
109 for r in hidden { for k in covered(r) { hiddenAt[k] = true } }
110 var scriptAt = [Bool?](repeating: nil, count: intervals)
111 for script in scripts { for k in covered(script.range) where scriptAt[k] == nil { scriptAt[k] = script.superscript } }
112 let foldStarts = Set(folds.map(\.lowerBound))
113 for (k, (a, b)) in zip(points, points.dropFirst()).enumerated() {
114 if foldStarts.contains(a) {
88 segments.append(Segment(text: "…", roles: [.metadata], link: nil, offset: a)) 115 segments.append(Segment(text: "…", roles: [.metadata], link: nil, offset: a))
89 } 116 }
90 if hidden.contains(where: { $0.lowerBound <= a && b <= $0.upperBound }) { continue } 117 if hiddenAt[k] { continue }
91 let roles = Set(runs.filter { $0.range.lowerBound <= a && b <= $0.range.upperBound }.map(\.role)) 118 let roles = rolesAt[k]
92 let link = roles.contains(.link) ? Links.link(at: a, text: tree.text, tree: tree)?.link : nil 119 let link = roles.contains(.link) ? Links.link(at: a, text: tree.text, tree: tree)?.link : nil
93 let superscript = scripts.first { $0.range.lowerBound <= a && b <= $0.range.upperBound }?.superscript 120 let superscript = scriptAt[k]
94 let shown = replaced[a] ?? text.substring(with: NSRange(location: a, length: b - a)) 121 let shown = replaced[a] ?? text.substring(with: NSRange(location: a, length: b - a))
95 let segment = Segment(text: shown, roles: roles, link: link, offset: a, superscript: superscript) 122 let segment = Segment(text: shown, roles: roles, link: link, offset: a, superscript: superscript)
96 if replaced[a] != nil { segments.append(segment) } else { append(segment) } 123 if replaced[a] != nil { segments.append(segment) } else { append(segment) }
Sources/Orgstar/AgendaView.swift +1 −1
@@ -159,7 +159,7 @@ struct AgendaView: View {
159 } 159 }
160 160
161 private var groups: [AgendaDayGroup] { 161 private var groups: [AgendaDayGroup] {
162 isAgenda ? agenda.groups(showAllDates: showAllDates, keep: filter.keeps) : [] 162 isAgenda ? agenda.groups(showAllDates: showAllDates, filter: filter) : []
163 } 163 }
164 164
165 private var listRows: [AgendaRow] { 165 private var listRows: [AgendaRow] {
Sources/OrgstarMobile/AgendaScreen.swift +31 −10
@@ -8,7 +8,7 @@ import SwiftUI
8/// The agenda over the workspace's agenda files: the day/week view, the TODO list, tag and 8/// The agenda over the workspace's agenda files: the day/week view, the TODO list, tag and
9/// property matches, text search and the views in `views.toml`, with Org's filters and the 9/// property matches, text search and the views in `views.toml`, with Org's filters and the
10/// agenda's actions on each entry. 10/// agenda's actions on each entry.
11struct AgendaScreen: View { 11struct AgendaScreen: View, Equatable {
12 let workspace: WorkspaceModel 12 let workspace: WorkspaceModel
13 let session: DocumentSession 13 let session: DocumentSession
14 @Bindable var agenda: AgendaModel 14 @Bindable var agenda: AgendaModel
@@ -67,6 +67,11 @@ struct AgendaScreen: View {
67 var logMode: Bool 67 var logMode: Bool
68 } 68 }
69 69
70 /// The same models: the root redrawing for navigation leaves the list alone.
71 nonisolated static func == (a: Self, b: Self) -> Bool {
72 a.workspace === b.workspace && a.session === b.session && a.agenda === b.agenda && a.scheduler === b.scheduler
73 }
74
70 private var isDark: Bool { colorScheme == .dark } 75 private var isDark: Bool { colorScheme == .dark }
71 private var theme: ThemeSpec { model.theme } 76 private var theme: ThemeSpec { model.theme }
72 77
@@ -76,7 +81,7 @@ struct AgendaScreen: View {
76 if workspace.rootPaths.isEmpty { 81 if workspace.rootPaths.isEmpty {
77 } else if case .agenda = agenda.mode { 82 } else if case .agenda = agenda.mode {
78 let _ = model.settingsVersion 83 let _ = model.settingsVersion
79 ForEach(Perf.measure("agenda.groups") { agenda.groups(showAllDates: OrgPreferences.agendaShowAllDates(), keep: filter.keeps) }) { group in 84 ForEach(Perf.measure("agenda.groups") { agenda.groups(showAllDates: OrgPreferences.agendaShowAllDates(), filter: filter) }) { group in
80 Section { 85 Section {
81 day(group) 86 day(group)
82 } header: { 87 } header: {
@@ -203,14 +208,30 @@ struct AgendaScreen: View {
203 guard OrgPreferences.calendarEvents(), !CalendarEvents.isAuthorized else { return } 208 guard OrgPreferences.calendarEvents(), !CalendarEvents.isAuthorized else { return }
204 if await model.calendarEvents.requestAccess() { tick += 1 } 209 if await model.calendarEvents.requestAccess() { tick += 1 }
205 } 210 }
206 .task(id: Key(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, tick: tick, 211 .background { Refresher(workspace: workspace, session: session, agenda: agenda, model: model, tick: tick, logMode: logMode) }
207 mode: agenda.mode, start: agenda.start, span: agenda.span, startOffset: agenda.startOffset, 212 }
208 subfolders: agenda.includeSubfolders, settings: model.settingsVersion, logMode: logMode)) { 213
209 // Changes come in bursts (a folder scan, typing); a newer one cancels this wait. 214 /// Refreshes the agenda when files, edits or settings change. Its own view, so that what it
210 try? await Task.sleep(for: .milliseconds(150)) 215 /// watches redraws only it, not the whole list.
211 guard !Task.isCancelled else { return } 216 private struct Refresher: View {
212 agenda.options.logMode = logMode 217 let workspace: WorkspaceModel
213 await agenda.refresh(open: session.openTexts) 218 let session: DocumentSession
219 let agenda: AgendaModel
220 let model: MobileModel
221 let tick: Int
222 let logMode: Bool
223
224 var body: some View {
225 Color.clear
226 .task(id: Key(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, tick: tick,
227 mode: agenda.mode, start: agenda.start, span: agenda.span, startOffset: agenda.startOffset,
228 subfolders: agenda.includeSubfolders, settings: model.settingsVersion, logMode: logMode)) {
229 // Changes come in bursts (a folder scan, typing); a newer one cancels this wait.
230 try? await Task.sleep(for: .milliseconds(150))
231 guard !Task.isCancelled else { return }
232 agenda.options.logMode = logMode
233 await agenda.refresh(open: session.openTexts)
234 }
214 } 235 }
215 } 236 }
216 237
Sources/OrgstarMobile/OrgstarMobileApp.swift +33 −15
@@ -99,6 +99,37 @@ struct RootView: View {
99 99
100 private var session: DocumentSession { model.session } 100 private var session: DocumentSession { model.session }
101 101
102 /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
103 /// only it, not the tabs.
104 private struct BackgroundWork: View {
105 let model: MobileModel
106 let workspace: WorkspaceModel
107 let agenda: AgendaModel
108 let active: Bool
109 let hour: Int
110
111 private var session: DocumentSession { model.session }
112
113 var body: some View {
114 Color.clear
115 // Reminders follow the files, the settings, coming back to the app and the hour.
116 .task(id: ReminderKey(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
117 settings: model.settingsVersion, active: active, hour: hour)) {
118 guard active else { return }
119 try? await Task.sleep(for: .seconds(1))
120 // After the agenda's refresh, whose parsed files these share.
121 while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
122 guard !Task.isCancelled else { return }
123 await model.updateReminders()
124 await model.updateWidgets()
125 }
126 // Spotlight follows the files and saved edits.
127 .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
128 await model.spotlight.update(workspace.files)
129 }
130 }
131 }
132
102 private struct SpotlightKey: Equatable { 133 private struct SpotlightKey: Equatable {
103 var files: Int 134 var files: Int
104 var changed: Int? 135 var changed: Int?
@@ -119,6 +150,7 @@ struct RootView: View {
119 Tab("Agenda", systemImage: "calendar", value: .agenda) { 150 Tab("Agenda", systemImage: "calendar", value: .agenda) {
120 NavigationStack(path: $agendaPath) { 151 NavigationStack(path: $agendaPath) {
121 AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler) 152 AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
153 .equatable()
122 .toolbar { captureButton } 154 .toolbar { captureButton }
123 .readerDestination(workspace: workspace, session: session) 155 .readerDestination(workspace: workspace, session: session)
124 } 156 }
@@ -197,21 +229,7 @@ struct RootView: View {
197 hour += 1 229 hour += 1
198 } 230 }
199 } 231 }
200 // Reminders follow the files, the settings, coming back to the app and the hour. 232 .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, hour: hour) }
201 .task(id: ReminderKey(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
202 settings: model.settingsVersion, active: scenePhase == .active, hour: hour)) {
203 guard scenePhase == .active else { return }
204 try? await Task.sleep(for: .seconds(1))
205 // After the agenda's refresh, whose parsed files these share.
206 while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
207 guard !Task.isCancelled else { return }
208 await model.updateReminders()
209 await model.updateWidgets()
210 }
211 // Spotlight follows the files and saved edits.
212 .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
213 await model.spotlight.update(workspace.files)
214 }
215 .onContinueUserActivity(CSSearchableItemActionType) { activity in 233 .onContinueUserActivity(CSSearchableItemActionType) { activity in
216 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) } 234 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
217 } 235 }
Sources/OrgstarMobile/ReaderScreen.swift +22 −4
@@ -38,6 +38,21 @@ struct ReaderScreen: View {
38 38
39 private var outline: [OutlineEntry] { session.outline } 39 private var outline: [OutlineEntry] { session.outline }
40 40
41 /// The file this reader shows. Readers lower in the stack stay alive while the session
42 /// shows another file, and draw nothing then.
43 private var path: String {
44 switch route {
45 case .file(let path), .offset(let path, _): path
46 case .heading(let location): location.path
47 }
48 }
49
50 /// The session shows this reader's file; it opens files by their resolved paths.
51 private var showsOwnFile: Bool {
52 guard let current = session.path else { return false }
53 return current == path || current == URL(fileURLWithPath: path).resolvingSymlinksInPath().path
54 }
55
41 var body: some View { 56 var body: some View {
42 let _ = session.editVersion 57 let _ = session.editVersion
43 // Read again when settings or the Dynamic Type size change. 58 // Read again when settings or the Dynamic Type size change.
@@ -47,11 +62,14 @@ struct ReaderScreen: View {
47 ScrollViewReader { proxy in 62 ScrollViewReader { proxy in
48 ScrollView(truncated ? [.vertical, .horizontal] : .vertical) { 63 ScrollView(truncated ? [.vertical, .horizontal] : .vertical) {
49 LazyVStack(alignment: .leading, spacing: 8) { 64 LazyVStack(alignment: .leading, spacing: 8) {
50 if let tree = session.document?.tree { 65 if let tree = session.document?.tree, showsOwnFile {
51 let preambleEnd = outline.first?.start ?? (tree.text as NSString).length 66 let length = (tree.text as NSString).length
67 let preambleEnd = min(outline.first?.start ?? length, length)
52 if preambleEnd > 0 { textView(tree, 0..<preambleEnd, theme) } 68 if preambleEnd > 0 { textView(tree, 0..<preambleEnd, theme) }
53 ForEach(Array(outline.enumerated()), id: \.element.start) { index, entry in 69 ForEach(Array(outline.enumerated()), id: \.element.start) { index, entry in
54 if isShown(index) { 70 // While another file opens, rows can update with the last file's
71 // entries for a moment; those don't fit this text.
72 if index < outline.count, outline[index] == entry, entry.end <= length, isShown(index) {
55 heading(tree, entry, theme).id(entry.start) 73 heading(tree, entry, theme).id(entry.start)
56 if !fold.folds.contains(entry.start), !fold.bodyFolds.contains(entry.start) { 74 if !fold.folds.contains(entry.start), !fold.bodyFolds.contains(entry.start) {
57 let body = bodyRange(index, tree) 75 let body = bodyRange(index, tree)
@@ -293,7 +311,7 @@ struct ReaderScreen: View {
293 /// The file's startup display, as the editor opens it; its heading folds are kept while 311 /// The file's startup display, as the editor opens it; its heading folds are kept while
294 /// the same file is open. 312 /// the same file is open.
295 private func loadFolds() { 313 private func loadFolds() {
296 guard let tree = session.document?.tree else { return } 314 guard let tree = session.document?.tree, showsOwnFile else { return }
297 let display = Presentation.startupDisplay(tree, options: session.options) 315 let display = Presentation.startupDisplay(tree, options: session.options)
298 startup = display 316 startup = display
299 folded = display.wrappers.map(\.hidden) 317 folded = display.wrappers.map(\.hidden)
Tests/OrgAppTests/AppTests.swift +15
@@ -524,6 +524,21 @@ enum StateBufferCaret {
524 524
525@MainActor 525@MainActor
526struct AgendaModelTests { 526struct AgendaModelTests {
527 @Test func openBuffersFollowTheirText() async throws {
528 let notes = try Folder()
529 let file = try notes.write("a.org", "* TODO One\n")
530 let model = try WorkspaceModel(directory: nil)
531 try await model.addRoot(notes.url)
532 let agenda = AgendaModel(workspace: model)
533 agenda.mode = .todo(keywords: nil)
534 for text in ["* TODO One\n", "* TODO Two\n", "* TODO One\n", "* TODO Two\n"] {
535 await agenda.refresh(open: [file.path: text])
536 #expect(agenda.list.map(\.text) == [String(text.dropFirst(2).dropLast())])
537 }
538 await agenda.refresh(open: [:])
539 #expect(agenda.list.map(\.text) == ["TODO One"])
540 }
541
527 @Test func entriesKnowTheirDoneKeyword() async throws { 542 @Test func entriesKnowTheirDoneKeyword() async throws {
528 let notes = try Folder() 543 let notes = try Folder()
529 try notes.write("setup.org", "#+TODO: NEXT | FINISHED\n") 544 try notes.write("setup.org", "#+TODO: NEXT | FINISHED\n")