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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
use failure::ResultExt;
use std::cmp::Ordering;
use std::ffi::OsStr;
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Write;
use std::path::Path;
use crate::terr;
use crate::timer;
use crate::todotxt;
use crate::tsort;
pub const INVALID_ID: usize = 9_999_999_999;
pub const TIMER_TAG: &str = "tmr";
pub const SPENT_TAG: &str = "spent";
pub const TIMER_OFF: &str = "off";
pub type TaskVec = Vec<todotxt::Task>;
pub type TaskSlice = [todotxt::Task];
pub type IDVec = Vec<usize>;
pub type IDSlice = [usize];
pub type ChangedVec = Vec<bool>;
pub type ChangedSlice = [bool];
#[derive(Debug, Clone)]
pub enum Action {
None,
Set,
Delete,
Replace,
Increase,
Decrease,
}
#[derive(Debug, Clone)]
pub struct Conf {
done: bool,
pub subject: Option<String>,
pub priority: u8,
pub priority_act: Action,
pub due: Option<chrono::NaiveDate>,
pub due_act: Action,
pub thr: Option<chrono::NaiveDate>,
pub thr_act: Action,
pub recurrence: Option<todotxt::Recurrence>,
pub recurrence_act: Action,
pub projects: Vec<String>,
pub project_act: Action,
pub contexts: Vec<String>,
pub context_act: Action,
pub auto_create_date: bool,
}
impl Default for Conf {
fn default() -> Conf {
Conf {
subject: None,
done: true,
priority: todotxt::NO_PRIORITY,
priority_act: Action::None,
due: None,
due_act: Action::None,
thr: None,
thr_act: Action::None,
recurrence: None,
recurrence_act: Action::None,
projects: Vec::new(),
project_act: Action::None,
contexts: Vec::new(),
context_act: Action::None,
auto_create_date: false,
}
}
}
pub(crate) fn make_id_vec(sz: usize) -> IDVec {
let mut v: IDVec = Vec::new();
for i in 0..sz {
v.push(i);
}
v
}
pub fn load(filename: &Path) -> Result<TaskVec, terr::TodoError> {
let mut tasks = Vec::new();
if !filename.exists() {
return Ok(tasks);
}
let file = File::open(filename).context(terr::TodoErrorKind::LoadFailed)?;
let now = chrono::Local::now().date().naive_local();
let br = BufReader::new(&file);
for l in br.lines().flatten() {
let t = todotxt::Task::parse(&l, now);
tasks.push(t);
}
Ok(tasks)
}
pub fn save(tasks: &TaskSlice, filename: &Path) -> Result<(), terr::TodoError> {
let tmpname = filename.with_extension(OsStr::new("todo.tmp"));
let mut output = File::create(&tmpname).context(terr::TodoErrorKind::SaveFailed)?;
for t in tasks {
let line = format!("{}\n", t);
if write!(output, "{}", line).is_err() {
return Err(terr::TodoError::from(terr::TodoErrorKind::SaveFailed));
}
}
if fs::rename(tmpname, filename).is_err() {
return Err(terr::TodoError::from(terr::TodoErrorKind::SaveFailed));
}
Ok(())
}
pub fn archive(tasks: &TaskSlice, filename: &Path) -> Result<(), terr::TodoError> {
let mut output = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(&filename)
.context(terr::TodoErrorKind::AppendFailed)?;
for t in tasks {
let line = format!("{}\n", t);
write!(output, "{}", line).context(terr::TodoErrorKind::FileWriteFailed)?;
}
Ok(())
}
pub fn clone_tasks(tasks: &TaskSlice, ids: &IDSlice) -> TaskVec {
let mut v: TaskVec = Vec::new();
for id in ids.iter() {
if *id < tasks.len() {
let t = tasks[*id].clone();
v.push(t);
}
}
v
}
pub fn add(tasks: &mut TaskVec, c: &Conf) -> usize {
let s = match &c.subject {
None => return INVALID_ID,
Some(subj) => subj,
};
let now = chrono::Local::now().date().naive_local();
let mut t = todotxt::Task::parse(s, now);
if c.auto_create_date && t.create_date.is_none() {
t.create_date = Some(chrono::Local::now().date().naive_local());
}
tasks.push(t);
tasks.len() - 1
}
fn done_undone(tasks: &mut TaskVec, ids: Option<&IDVec>, c: &Conf) -> ChangedVec {
if tasks.is_empty() {
return Vec::new();
}
let longvec = make_id_vec(tasks.len());
let id_iter = if let Some(v) = ids { v } else { &longvec };
let mut bools = vec![false; id_iter.len()];
let now = chrono::Local::now().date().naive_local();
for (i, idx) in id_iter.iter().enumerate() {
if *idx >= tasks.len() {
continue;
}
if c.done {
bools[i] = timer::stop_timer(&mut tasks[*idx]);
bools[i] = bools[i] || (&mut tasks[*idx]).complete(now);
} else {
bools[i] = tasks[*idx].uncomplete();
}
}
bools
}
pub fn done(tasks: &mut TaskVec, ids: Option<&IDVec>) -> ChangedVec {
let c = Conf { done: true, ..Default::default() };
done_undone(tasks, ids, &c)
}
pub fn undone(tasks: &mut TaskVec, ids: Option<&IDVec>) -> ChangedVec {
let c = Conf { done: false, ..Default::default() };
done_undone(tasks, ids, &c)
}
pub fn remove(tasks: &mut TaskVec, ids: Option<&IDVec>) -> ChangedVec {
if tasks.is_empty() {
return vec![];
}
let longvec = make_id_vec(tasks.len());
let idlist = if let Some(v) = ids { v } else { &longvec };
let mut bools = vec![false; idlist.len()];
for (i, id) in idlist.iter().enumerate() {
if *id < tasks.len() {
bools[i] = true;
}
}
let mut remained: TaskVec = Vec::new();
for (i, t) in tasks.iter().enumerate() {
let mut found: bool = false;
for id in idlist.iter() {
if *id == i {
found = true;
break;
}
}
if !found {
remained.push(t.clone());
}
}
std::mem::swap(tasks, &mut remained);
bools
}
fn update_priority(task: &mut todotxt::Task, c: &Conf) -> bool {
match c.priority_act {
Action::Set => {
if task.priority != c.priority {
task.priority = c.priority;
return true;
}
}
Action::Delete => {
if task.priority != todotxt::NO_PRIORITY {
task.priority = todotxt::NO_PRIORITY;
return true;
}
}
Action::Increase => {
if task.priority != 0 && task.priority != todotxt::NO_PRIORITY {
task.priority -= 1u8;
return true;
}
}
Action::Decrease => {
if task.priority != todotxt::NO_PRIORITY {
task.priority += 1u8;
return true;
}
}
_ => {}
}
false
}
fn update_due_date(task: &mut todotxt::Task, c: &Conf) -> bool {
match c.due_act {
Action::Set => {
if tsort::cmp_opt_dates(task.due_date, c.due) != Ordering::Equal {
match c.due {
None => task.update_tag_with_value(todotxt::DUE_TAG, ""),
Some(dt) => task.update_tag_with_value(todotxt::DUE_TAG, &todotxt::format_date(dt)),
};
return true;
}
}
Action::Delete => {
if task.due_date.is_some() {
task.update_tag_with_value(todotxt::DUE_TAG, "");
return true;
}
}
_ => {}
}
false
}
fn update_thr_date(task: &mut todotxt::Task, c: &Conf) -> bool {
match c.thr_act {
Action::Set => {
if tsort::cmp_opt_dates(task.threshold_date, c.thr) != Ordering::Equal {
match c.thr {
None => task.update_tag_with_value(todotxt::THR_TAG, ""),
Some(dt) => task.update_tag_with_value(todotxt::THR_TAG, &todotxt::format_date(dt)),
};
return true;
}
}
Action::Delete => {
if task.threshold_date.is_some() {
task.update_tag_with_value(todotxt::THR_TAG, "");
return true;
}
}
_ => {}
}
false
}
fn update_recurrence(task: &mut todotxt::Task, c: &Conf) -> bool {
match c.recurrence_act {
Action::Set => {
if !tsort::equal_opt_rec(&task.recurrence, &c.recurrence) {
if let Some(nr) = &c.recurrence {
let new_rec = format!("{}", nr);
if task.update_tag(&new_rec) && task.finished {
task.uncomplete();
return true;
}
}
}
}
Action::Delete => {
if task.recurrence.is_some() {
task.update_tag_with_value(todotxt::REC_TAG, "");
return true;
}
}
_ => {}
}
false
}
fn update_projects(task: &mut todotxt::Task, c: &Conf) -> bool {
let mut changed = false;
for new_p in &c.projects {
match c.project_act {
Action::Set => {
let old_subj = task.subject.clone();
task.replace_project("", new_p);
changed = old_subj != task.subject;
}
Action::Delete => {
let old_subj = task.subject.clone();
task.replace_project(new_p, "");
changed = old_subj != task.subject;
}
Action::Replace => {
let pair: Vec<&str> = new_p.split_terminator('+').collect();
if pair.len() == 2 && pair[0] != pair[1] && !pair[0].is_empty() && !pair[1].is_empty() {
let old_subj = task.subject.clone();
task.replace_project(pair[0], pair[1]);
changed = old_subj != task.subject;
}
}
_ => {}
}
}
changed
}
fn update_contexts(task: &mut todotxt::Task, c: &Conf) -> bool {
let mut changed = false;
for new_c in &c.contexts {
match c.context_act {
Action::Set => {
let old_subj = task.subject.clone();
task.replace_context("", new_c);
changed = old_subj != task.subject;
}
Action::Delete => {
let old_subj = task.subject.clone();
task.replace_context(new_c, "");
changed = old_subj != task.subject;
}
Action::Replace => {
let pair: Vec<&str> = new_c.split_terminator('@').collect();
if pair.len() == 2 && pair[0] != pair[1] && !pair[0].is_empty() && !pair[1].is_empty() {
let old_subj = task.subject.clone();
task.replace_context(pair[0], pair[1]);
changed = old_subj != task.subject;
}
}
_ => {}
}
}
changed
}
pub fn edit(tasks: &mut TaskVec, ids: Option<&IDVec>, c: &Conf) -> ChangedVec {
if tasks.is_empty() {
return vec![];
}
let longvec = make_id_vec(tasks.len());
let idlist = if let Some(v) = ids { v } else { &longvec };
let now = chrono::Local::now().date().naive_local();
let mut bools = vec![false; idlist.len()];
for (i, idx) in idlist.iter().enumerate() {
let id = *idx;
if id >= tasks.len() {
continue;
}
if let Some(subj) = c.subject.as_ref() {
let mut t = todotxt::Task::parse(subj, now);
if t.create_date.is_none() && tasks[id].create_date.is_some() {
t.create_date = tasks[id].create_date;
}
tasks[id] = t;
bools[i] = true;
break;
}
bools[i] = update_priority(&mut tasks[id], c);
bools[i] |= update_due_date(&mut tasks[id], c);
bools[i] |= update_thr_date(&mut tasks[id], c);
bools[i] |= update_recurrence(&mut tasks[id], c);
bools[i] |= update_projects(&mut tasks[id], c);
bools[i] |= update_contexts(&mut tasks[id], c);
}
bools
}
pub fn start(tasks: &mut TaskVec, ids: Option<&IDVec>) -> ChangedVec {
if tasks.is_empty() {
return vec![];
}
let longvec = make_id_vec(tasks.len());
let idlist = if let Some(v) = ids { v } else { &longvec };
let mut bools = vec![false; idlist.len()];
for (i, idx) in idlist.iter().enumerate() {
let id = *idx;
if id >= tasks.len() {
continue;
}
bools[i] = timer::start_timer(&mut tasks[id]);
}
bools
}
pub fn stop(tasks: &mut TaskVec, ids: Option<&IDVec>) -> ChangedVec {
if tasks.is_empty() {
return vec![];
}
let longvec = make_id_vec(tasks.len());
let idlist = if let Some(v) = ids { v } else { &longvec };
let mut bools = vec![false; idlist.len()];
for (i, idx) in idlist.iter().enumerate() {
let id = *idx;
if id >= tasks.len() {
continue;
}
bools[i] = timer::stop_timer(&mut tasks[id]);
}
bools
}