1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// SPDX-License-Identifier: GPL-3.0-or-later
// File: ./src/journal.rs
/*
* cfait/src/journal.rs
*
* Offline action journal for syncing changes.
*
* This module uses an explicit `AppContext` for resolving filesystem locations.
* All public IO functions take a `&dyn AppContext` argument; there are no
* hidden globals here.
*/
use crate::client::core::strip_host;
use crate::context::AppContext;
use crate::model::Task;
use crate::storage::LocalStorage;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::PathBuf;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum Action {
Create(Task),
Update(Task),
Delete(Task),
Move(Task, String),
}
#[derive(Clone, Debug)]
pub struct UndoRecord {
pub description: String,
pub primary_uid: Option<String>,
pub forward: Vec<Action>,
pub reverse: Vec<Action>,
}
/// Bounded undo/redo history with a shared cap. The bookkeeping (push, pop,
/// clear-redo-on-new-action, cap at `MAX_HISTORY`) is identical across all
/// frontends; only the *application* of actions differs, so callers handle
/// that themselves and use this struct purely for stack management.
#[derive(Clone, Debug, Default)]
pub struct UndoHistory {
pub undo_stack: Vec<UndoRecord>,
pub redo_stack: Vec<UndoRecord>,
}
const MAX_HISTORY: usize = 50;
impl UndoHistory {
pub fn new() -> Self {
Self::default()
}
/// Push a new record onto the undo stack, clear redo, and enforce the cap.
pub fn push(&mut self, record: UndoRecord) {
self.undo_stack.push(record);
self.redo_stack.clear();
if self.undo_stack.len() > MAX_HISTORY {
self.undo_stack.remove(0);
}
}
/// Pop a record from the undo stack for replay in reverse.
/// The caller is responsible for applying `record.reverse` and then
/// calling `push_redo(record)`.
pub fn pop_undo(&mut self) -> Option<UndoRecord> {
self.undo_stack.pop()
}
/// Pop a record from the redo stack for replay in forward.
pub fn pop_redo(&mut self) -> Option<UndoRecord> {
self.redo_stack.pop()
}
/// Push a record back onto the redo stack after an undo, enforcing the cap.
pub fn push_redo(&mut self, record: UndoRecord) {
self.redo_stack.push(record);
if self.redo_stack.len() > MAX_HISTORY {
self.redo_stack.remove(0);
}
}
/// Push a record back onto the undo stack after a redo.
pub fn push_undo(&mut self, record: UndoRecord) {
self.undo_stack.push(record);
if self.undo_stack.len() > MAX_HISTORY {
self.undo_stack.remove(0);
}
}
pub fn is_undo_empty(&self) -> bool {
self.undo_stack.is_empty()
}
pub fn is_redo_empty(&self) -> bool {
self.redo_stack.is_empty()
}
}
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Journal {
pub queue: Vec<Action>,
}
impl Journal {
/// Return the on-disk journal path for the given context, if available.
pub fn get_path(ctx: &dyn AppContext) -> Option<PathBuf> {
ctx.get_journal_path()
}
/// Internal helper: load journal structure from a path without acquiring locks.
fn load_internal(path: &PathBuf) -> Self {
if path.exists()
&& let Ok(content) = fs::read_to_string(path)
&& let Ok(journal) = serde_json::from_str(&content)
{
return journal;
}
Self::default()
}
/// Load the journal from disk using the provided context.
pub fn load(ctx: &dyn AppContext) -> Self {
if let Some(path) = Self::get_path(ctx) {
if !path.exists() {
return Self::default();
}
return LocalStorage::with_lock(&path, || Ok(Self::load_internal(&path)))
.unwrap_or_default();
}
Self::default()
}
/// Modify the journal by applying a closure to the queue, persisting changes.
pub fn modify<F>(ctx: &dyn AppContext, f: F) -> Result<()>
where
F: FnOnce(&mut Vec<Action>),
{
if let Some(path) = Self::get_path(ctx) {
LocalStorage::with_lock(&path, || {
let mut journal = Self::load_internal(&path);
f(&mut journal.queue);
let json = serde_json::to_string(&journal)?;
LocalStorage::atomic_write(&path, json)?;
Ok(())
})?;
}
Ok(())
}
/// Push a new action into the journal.
pub fn push(ctx: &dyn AppContext, action: Action) -> Result<()> {
Self::modify(ctx, |queue| queue.push(action))
}
/// Is the in-memory journal empty?
pub fn is_empty(&self) -> bool {
self.queue.is_empty()
}
/// Compact the journal by merging redundant operations for the same UID.
pub fn compact(&mut self) {
let mut uid_map: HashMap<String, usize> = HashMap::new();
let mut compacted: Vec<Option<Action>> = Vec::new();
for action in self.queue.drain(..) {
let uid = match &action {
Action::Create(t) => t.uid.clone(),
Action::Update(t) => t.uid.clone(),
Action::Delete(t) => t.uid.clone(),
Action::Move(t, _) => t.uid.clone(),
};
let mut merged = false;
if let Some(&idx) = uid_map.get(&uid)
&& let Some(prev) = &compacted[idx]
{
let same_calendar = match (prev, &action) {
(Action::Create(t1), Action::Update(t2)) => {
t1.calendar_href == t2.calendar_href
}
(Action::Update(t1), Action::Update(t2)) => {
t1.calendar_href == t2.calendar_href
}
(Action::Create(t1), Action::Delete(t2)) => {
t1.calendar_href == t2.calendar_href
}
(Action::Update(t1), Action::Delete(t2)) => {
t1.calendar_href == t2.calendar_href
}
(Action::Create(t1), Action::Create(t2)) => {
t1.calendar_href == t2.calendar_href
}
_ => false,
};
if same_calendar {
match (prev, &action) {
(Action::Create(prev_t), Action::Update(t)) => {
let mut merged_t = t.clone();
merged_t.inherit_metadata_if_pending(prev_t);
compacted[idx] = Some(Action::Create(merged_t));
merged = true;
}
(Action::Update(prev_t), Action::Update(t)) => {
let mut merged_t = t.clone();
merged_t.inherit_metadata_if_pending(prev_t);
compacted[idx] = Some(Action::Update(merged_t));
merged = true;
}
(Action::Create(_), Action::Delete(_)) => {
compacted[idx] = None;
uid_map.remove(&uid);
merged = true;
}
(Action::Update(prev_t), Action::Delete(t)) => {
let mut merged_t = t.clone();
merged_t.inherit_metadata_if_pending(prev_t);
compacted[idx] = Some(Action::Delete(merged_t));
merged = true;
}
(Action::Create(prev_t), Action::Create(t)) => {
// Merge duplicates: keep the newer version (last wins)
let mut merged_t = t.clone();
merged_t.inherit_metadata_if_pending(prev_t);
compacted[idx] = Some(Action::Create(merged_t));
merged = true;
}
_ => {}
}
}
}
if !merged {
compacted.push(Some(action));
uid_map.insert(uid, compacted.len() - 1);
}
}
self.queue = compacted.into_iter().flatten().collect();
}
/// Apply journaled actions to an existing task list for a given calendar.
///
/// This merges creates/updates/deletes/moves into `tasks` in-memory so the
/// caller can present or operate on the final state prior to syncing.
pub fn apply_to_tasks(ctx: &dyn AppContext, tasks: &mut Vec<Task>, calendar_href: &str) {
let journal = Self::load(ctx);
// Helper for robust matching of URLs and paths (ignoring trailing slashes and host differences)
let urls_match = |a: &str, b: &str| -> bool {
strip_host(a).trim_end_matches('/') == strip_host(b).trim_end_matches('/')
};
let mut pending_uids = HashSet::new();
for action in &journal.queue {
match action {
Action::Create(t) | Action::Update(t)
if urls_match(&t.calendar_href, calendar_href) =>
{
pending_uids.insert(t.uid.clone());
}
Action::Move(t, target) if urls_match(target, calendar_href) => {
pending_uids.insert(t.uid.clone());
}
_ => {}
}
}
// For remote calendars, drop entries without an etag unless they are pending in the journal.
if !calendar_href.starts_with("local://") {
tasks.retain(|t| !t.etag.is_empty() || pending_uids.contains(&t.uid));
}
if journal.is_empty() {
return;
}
let mut task_map: HashMap<String, Task> =
tasks.drain(..).map(|t| (t.uid.clone(), t)).collect();
for action in journal.queue {
match action {
Action::Create(t) => {
if urls_match(&t.calendar_href, calendar_href) {
task_map.insert(t.uid.clone(), t);
}
}
Action::Update(t) => {
if urls_match(&t.calendar_href, calendar_href) {
task_map.insert(t.uid.clone(), t);
}
}
Action::Delete(t) => {
if urls_match(&t.calendar_href, calendar_href) {
task_map.remove(&t.uid);
}
}
Action::Move(t, new_href) => {
if urls_match(&t.calendar_href, calendar_href) {
task_map.remove(&t.uid);
} else if urls_match(&new_href, calendar_href) {
let mut moved_task = t;
moved_task.calendar_href = new_href;
task_map.insert(moved_task.uid.clone(), moved_task);
}
}
}
}
*tasks = task_map.into_values().collect();
}
}