notnow 0.3.10

A terminal based task and TODO management software.
Documentation
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
// Copyright (C) 2017-2025 Daniel Mueller <deso@posteo.net>
// SPDX-License-Identifier: GPL-3.0-or-later

use std::rc::Rc;

use anyhow::anyhow;
use anyhow::Result;

use crate::ser::view::TagLit as SerTagLit;
use crate::ser::view::View as SerView;
use crate::ser::ToSerde;
use crate::tags::Tag;
use crate::tags::Templates;
use crate::tasks::Task;
use crate::tasks::TaskIter;
use crate::tasks::Tasks;


/// A literal describing whether a tag is negated or not.
#[derive(Clone, Debug)]
enum TagLit {
  Pos(Tag),
  Neg(Tag),
}

impl TagLit {
  /// Retrieve the contained `Tag`.
  fn tag(&self) -> &Tag {
    match self {
      TagLit::Pos(tag) | TagLit::Neg(tag) => tag,
    }
  }

  /// Check whether the literal is a positive one.
  fn is_pos(&self) -> bool {
    match self {
      TagLit::Pos(_) => true,
      TagLit::Neg(_) => false,
    }
  }
}

impl ToSerde for TagLit {
  type Output = SerTagLit;

  /// Convert this object into a serializable one.
  fn to_serde(&self) -> Self::Output {
    match self {
      TagLit::Pos(tag) => SerTagLit::Pos(tag.to_serde()),
      TagLit::Neg(tag) => SerTagLit::Neg(tag.to_serde()),
    }
  }
}


/// An object providing filtered iteration over an iterator of tasks.
#[derive(Clone, Debug)]
pub struct Filter<'tasks> {
  iter: TaskIter<'tasks>,
  lits: &'tasks [Vec<TagLit>],
}

impl<'tasks> Filter<'tasks> {
  /// Create a new `Filter` wrapping an iterator and filtering using the given set of literals.
  fn new(iter: TaskIter<'tasks>, lits: &'tasks [Vec<TagLit>]) -> Self {
    Self { iter, lits }
  }

  /// Check if one of the given tags matches the available ones.
  fn matches<'tag, I>(lits: &[TagLit], avail_tags: &I) -> bool
  where
    I: Iterator<Item = &'tag Tag> + Clone,
  {
    // Iterate over disjunctions and check if any of them matches.
    for lit in lits {
      let tag = lit.tag();
      let must_exist = lit.is_pos();

      if avail_tags.clone().any(|x| x == tag) == must_exist {
        return true
      }
    }
    false
  }

  /// Check if the given `tags` match this view's requirements.
  fn matched_by<'tag, I>(&self, avail_tags: &I) -> bool
  where
    I: Iterator<Item = &'tag Tag> + Clone,
  {
    // Iterate over conjunctions; all of them need to match.
    for req_lits in self.lits {
      // We could create a set for faster inclusion checks instead of
      // passing in an iterator. However, typically tasks only use a
      // small set of tags and so the allocation overhead is assumed to
      // be higher than the iteration cost we incur right now.
      if !Self::matches(req_lits, avail_tags) {
        return false
      }
    }
    true
  }
}

impl<'tasks> Iterator for Filter<'tasks> {
  type Item = &'tasks Rc<Task>;

  /// Advance the iterator yielding the next matching task or None.
  fn next(&mut self) -> Option<Self::Item> {
    // TODO: Should really be a for loop or even just a .find()
    //       invocation, however, both versions do not compile due to
    //       borrowing/ownership conflicts.
    loop {
      match self.iter.next() {
        Some(task) => {
          if task.tags(|iter| self.matched_by(&iter)) {
            return Some(task)
          }
        },
        None => return None,
      }
    }
  }
}

impl DoubleEndedIterator for Filter<'_> {
  fn next_back(&mut self) -> Option<Self::Item> {
    loop {
      match self.iter.next_back() {
        Some(task) => {
          if task.tags(|iter| self.matched_by(&iter)) {
            return Some(task)
          }
        },
        None => return None,
      }
    }
  }
}


/// A builder object to create a `View`.
// Strictly speaking the builder contains the same members as the actual
// `View` object and, hence, could be merged into it easily. However,
// the API would be rather unnatural and non-obvious. A `View` is
// supposed to be something that does not change over its lifetime.
pub struct ViewBuilder {
  tasks: Rc<Tasks>,
  lits: Vec<Vec<TagLit>>,
}

impl ViewBuilder {
  /// Create a new `ViewBuilder` object.
  pub fn new(tasks: Rc<Tasks>) -> ViewBuilder {
    Self {
      tasks,
      lits: Default::default(),
    }
  }

  /// Add a new conjunction containing the given literal to the view.
  #[cfg(test)]
  fn and_lit(mut self, lit: TagLit) -> ViewBuilder {
    // An AND always starts a new vector of ORs.
    self.lits.push(vec![lit]);
    self
  }

  /// Add a new conjunction containing the given tag to the view.
  ///
  /// Note that ANDed tags always associate with previously ANDed ones.
  /// That is, if you ORed a tag before you won't be able to OR any more
  /// tags to that same tag after a tag was ANDed in. E.g.,
  ///
  /// view
  ///  .or(tag1)  // `and` or `or` act equivalently for the first tag
  ///  .and(tag2)
  ///  .or(tag3)
  ///  .and(tag4)
  ///
  /// Is equivalent to tag1 && (tag2 || tag3) && tag4.
  #[cfg(test)]
  pub fn and(self, tag: impl Into<Tag>) -> ViewBuilder {
    self.and_lit(TagLit::Pos(tag.into()))
  }

  /// Add a new conjunction containing the given tag in negated form to
  /// the view.
  ///
  /// Please see `View::and` for more details on how ANDed tags
  /// associate with one another and with ORed ones.
  #[cfg(test)]
  pub fn and_not(self, tag: impl Into<Tag>) -> ViewBuilder {
    self.and_lit(TagLit::Neg(tag.into()))
  }

  /// Add a new literal to the last disjunction.
  #[cfg(test)]
  fn or_lit(mut self, lit: TagLit) -> ViewBuilder {
    let last = self.lits.pop();
    match last {
      Some(mut last) => {
        last.push(lit);
        self.lits.push(last);
      },
      None => self.lits.push(vec![lit]),
    };
    self
  }

  /// Add a new tag to the last disjunction.
  ///
  /// Please see `View::and` for more details on how ORed tags
  /// associate with one another and with ANDed ones.
  #[cfg(test)]
  pub fn or(self, tag: impl Into<Tag>) -> ViewBuilder {
    self.or_lit(TagLit::Pos(tag.into()))
  }

  /// Add a new tag in negated form to the last disjunction.
  ///
  /// Please see `View::and` for more details on how ORed tags
  /// associate with one another and with ANDed ones.
  #[cfg(test)]
  pub fn or_not(self, tag: impl Into<Tag>) -> ViewBuilder {
    self.or_lit(TagLit::Neg(tag.into()))
  }

  /// Build the final `View` instance.
  pub fn build(self, name: impl Into<String>) -> View {
    View {
      name: name.into(),
      tasks: self.tasks,
      lits: self.lits,
    }
  }
}


/// An object representing a particular view onto a `Tasks` object.
///
/// Ultimately a `View` is conceptually an iterator over a set of `Task`
/// objects. However, there are crucial differences to ordinary
/// iterators.
/// 1) Where an normal iterator requires a true reference to the
///    underlying collection, a `View` relieves that restriction.
/// 2) Iteration is internal instead of external to reduce the
///    likelihood of borrowing conflicts.
#[derive(Clone, Debug)]
pub struct View {
  /// The name of the view.
  // TODO: This attribute does not really belong in here. Once we have
  //       the necessary infrastructure for storing it elsewhere it
  //       should be removed from this struct.
  name: String,
  /// A reference to the `Tasks` object we use for retrieving the set of
  /// available tasks.
  tasks: Rc<Tasks>,
  /// Tags are stored in Conjunctive Normal Form, meaning we have a
  /// large AND (all elements in the outer vector) of ORs (all the
  /// elements in the inner vector).
  lits: Vec<Vec<TagLit>>,
}

impl View {
  /// Create a new `View` object from a serializable one.
  pub fn with_serde(view: SerView, templates: &Rc<Templates>, tasks: Rc<Tasks>) -> Result<Self> {
    let mut and_lits = Vec::with_capacity(view.lits.len());
    for lits in view.lits.into_iter() {
      let mut or_lits = Vec::with_capacity(lits.len());
      for lit in lits.into_iter() {
        let tag = templates
          .instantiate(lit.id())
          .ok_or_else(|| anyhow!("encountered invalid tag ID {}", lit.id()))?;
        let lit = match lit {
          SerTagLit::Pos(_) => TagLit::Pos(tag),
          SerTagLit::Neg(_) => TagLit::Neg(tag),
        };
        or_lits.push(lit);
      }

      and_lits.push(or_lits);
    }

    Ok(Self {
      name: view.name,
      tasks,
      lits: and_lits,
    })
  }

  /// Invoke a user-provided function on an iterator over the tasks
  /// represented by this view.
  #[inline]
  pub fn iter<F, R>(&self, mut f: F) -> R
  where
    F: FnMut(Filter<'_>) -> R,
  {
    self.tasks.iter(|iter| f(Filter::new(iter, &self.lits)))
  }

  /// Retrieve an iterator over all tags of the positive literals in
  /// this `View`.
  pub fn positive_tag_iter(&self) -> impl Iterator<Item = &Tag> {
    self.lits.iter().flat_map(|disjunctions| {
      disjunctions.iter().filter_map(|literal| match literal {
        TagLit::Pos(tag) => Some(tag),
        TagLit::Neg(..) => None,
      })
    })
  }

  /// Check whether the view is empty or not.
  #[cfg(test)]
  pub fn is_empty(&self) -> bool {
    self.iter(|mut iter| iter.next().is_none())
  }

  /// Retrieve the view's name.
  pub fn name(&self) -> &str {
    &self.name
  }
}

impl ToSerde for View {
  type Output = SerView;

  /// Convert this view into a serializable one.
  fn to_serde(&self) -> Self::Output {
    let lits = self
      .lits
      .iter()
      .map(|lits| lits.iter().map(ToSerde::to_serde).collect())
      .collect();

    SerView {
      name: self.name.clone(),
      lits,
      // We always set the value to false here. This way, if on-disk
      // state still uses the deprecated format, we will force a save.
      deprecated: false,
    }
  }
}


#[cfg(test)]
mod tests {
  use super::*;

  use crate::ser::tags::Templates as SerTemplates;
  use crate::ser::tasks::Tasks as SerTasks;
  use crate::tags::Templates;
  use crate::test::make_tasks;
  use crate::test::make_tasks_with_tags;
  use crate::test::COMPLETE_TAG;


  /// Create a view with the given number of tasks in it.
  fn make_view(count: usize) -> View {
    let tasks = Tasks::with_serde_tasks(make_tasks(count));
    let tasks = Rc::new(tasks.unwrap());
    let view = ViewBuilder::new(tasks).build("test");
    view
  }

  fn make_tagged_tasks(count: usize) -> (Rc<Templates>, Rc<Tasks>) {
    let (_, templates, tasks) = make_tasks_with_tags(count);
    let templates = Rc::new(Templates::with_serde(SerTemplates(templates)).unwrap());
    let tasks = SerTasks::from(tasks);
    let tasks = Tasks::with_serde(tasks, Rc::clone(&templates)).unwrap();
    let tasks = Rc::new(tasks);

    (templates, tasks)
  }


  /// Check that we can identify an empty `View`.
  #[test]
  fn is_empty() {
    assert!(make_view(0).is_empty());
    assert!(!make_view(1).is_empty());
  }

  /// Make sure that we can retrieve an iterator over all positive tag
  /// literals in a `View`.
  #[test]
  fn pos_tag_iteration() {
    fn pos_tags(view: &View) -> Vec<String> {
      view
        .positive_tag_iter()
        .map(|tag| tag.name().to_string())
        .collect::<Vec<_>>()
    }

    let (templates, tasks) = make_tagged_tasks(20);

    let view = ViewBuilder::new(Rc::clone(&tasks)).build("test");
    assert_eq!(pos_tags(&view), Vec::<String>::new());

    let view = ViewBuilder::new(Rc::clone(&tasks))
      .and(templates.instantiate_from_name(COMPLETE_TAG))
      .build("test");
    assert_eq!(pos_tags(&view), vec![COMPLETE_TAG]);

    let view = ViewBuilder::new(Rc::clone(&tasks))
      .and(templates.instantiate_from_name("tag1"))
      .and_not(templates.instantiate_from_name("tag2"))
      .build("test");
    assert_eq!(pos_tags(&view), vec!["tag1"]);

    let view = ViewBuilder::new(Rc::clone(&tasks))
      .and(templates.instantiate_from_name("tag1"))
      .or(templates.instantiate_from_name("tag2"))
      .build("test");
    assert_eq!(pos_tags(&view), vec!["tag1", "tag2"]);

    let view = ViewBuilder::new(Rc::clone(&tasks))
      .and(templates.instantiate_from_name("tag3"))
      .or(templates.instantiate_from_name("tag1"))
      .and_not(templates.instantiate_from_name("tag2"))
      .build("test");
    assert_eq!(pos_tags(&view), vec!["tag3", "tag1"]);

    let view = ViewBuilder::new(Rc::clone(&tasks))
      .or(templates.instantiate_from_name("tag3"))
      .or(templates.instantiate_from_name("tag2"))
      .or(templates.instantiate_from_name("tag5"))
      .build("test");
    assert_eq!(pos_tags(&view), vec!["tag3", "tag2", "tag5"]);

    let view = ViewBuilder::new(tasks)
      .and(templates.instantiate_from_name("tag3"))
      .and(templates.instantiate_from_name("tag2"))
      .and(templates.instantiate_from_name("tag5"))
      .build("test");
    assert_eq!(pos_tags(&view), vec!["tag3", "tag2", "tag5"]);
  }

  /// Check that we can correctly filter all completed tasks.
  #[test]
  fn filter_completions() {
    let (templates, tasks) = make_tagged_tasks(16);
    let complete_tag = templates.instantiate_from_name(COMPLETE_TAG);
    let view = ViewBuilder::new(tasks)
      .and(complete_tag.clone())
      .build("test");

    let () = view.iter(|mut iter| {
      let () = iter
        .clone()
        .for_each(|task| assert!(task.has_tag(&complete_tag)));

      assert_eq!(iter.next().unwrap().summary(), "2");
      assert_eq!(iter.next().unwrap().summary(), "4");
      assert_eq!(iter.next().unwrap().summary(), "6");
      assert_eq!(iter.next().unwrap().summary(), "8");
      assert_eq!(iter.next().unwrap().summary(), "10");
      assert_eq!(iter.next().unwrap().summary(), "12");
      assert_eq!(iter.next().unwrap().summary(), "14");
      assert_eq!(iter.next().unwrap().summary(), "16");
      assert!(iter.next().is_none());
    });
  }

  #[test]
  fn filter_no_completions() {
    let (templates, tasks) = make_tagged_tasks(16);
    let complete_tag = templates.instantiate_from_name(COMPLETE_TAG);
    let view = ViewBuilder::new(tasks)
      .and_not(complete_tag.clone())
      .build("test");

    view.iter(|mut iter| {
      let () = iter
        .clone()
        .for_each(|task| assert!(!task.has_tag(&complete_tag)));

      assert_eq!(iter.next().unwrap().summary(), "1");
      assert_eq!(iter.next().unwrap().summary(), "3");
      assert_eq!(iter.next().unwrap().summary(), "5");
      assert_eq!(iter.next().unwrap().summary(), "7");
      assert_eq!(iter.next().unwrap().summary(), "9");
      assert_eq!(iter.next().unwrap().summary(), "11");
      assert_eq!(iter.next().unwrap().summary(), "13");
      assert_eq!(iter.next().unwrap().summary(), "15");
      assert!(iter.next().is_none());
    })
  }

  #[test]
  fn filter_tag1_and_tag2() {
    let (templates, tasks) = make_tagged_tasks(20);
    let tag1 = templates.instantiate_from_name(templates.iter().nth(1).unwrap().name());
    let tag2 = templates.instantiate_from_name(templates.iter().nth(2).unwrap().name());
    let view = ViewBuilder::new(tasks).and(tag1).and(tag2).build("test");

    let () = view.iter(|mut iter| {
      assert_eq!(iter.next().unwrap().summary(), "11");
      assert_eq!(iter.next().unwrap().summary(), "12");
      assert_eq!(iter.next().unwrap().summary(), "15");
      assert_eq!(iter.next().unwrap().summary(), "16");
      assert_eq!(iter.next().unwrap().summary(), "19");
      assert_eq!(iter.next().unwrap().summary(), "20");
      assert!(iter.next().is_none());
    });
  }

  #[test]
  fn filter_tag3_or_tag1() {
    let (templates, tasks) = make_tagged_tasks(20);
    let tag1 = templates.instantiate_from_name(templates.iter().nth(1).unwrap().name());
    let tag3 = templates.instantiate_from_name(templates.iter().nth(3).unwrap().name());
    let view = ViewBuilder::new(tasks).or(tag3).or(tag1).build("test");

    let () = view.iter(|mut iter| {
      assert_eq!(iter.next().unwrap().summary(), "5");
      assert_eq!(iter.next().unwrap().summary(), "6");
      assert_eq!(iter.next().unwrap().summary(), "7");
      assert_eq!(iter.next().unwrap().summary(), "8");
      assert_eq!(iter.next().unwrap().summary(), "11");
      assert_eq!(iter.next().unwrap().summary(), "12");
      assert_eq!(iter.next().unwrap().summary(), "13");
      assert_eq!(iter.next().unwrap().summary(), "14");
      assert_eq!(iter.next().unwrap().summary(), "15");
      assert_eq!(iter.next().unwrap().summary(), "16");
      assert_eq!(iter.next().unwrap().summary(), "19");
      assert_eq!(iter.next().unwrap().summary(), "20");
      assert!(iter.next().is_none());
    });
  }

  #[test]
  fn filter_tag1_and_complete_or_tag4() {
    let (templates, tasks) = make_tagged_tasks(20);
    let complete_tag = templates.instantiate_from_name(COMPLETE_TAG);
    let tag1 = templates.instantiate_from_name(templates.iter().nth(1).unwrap().name());
    let tag4 = templates.instantiate_from_name(templates.iter().nth(4).unwrap().name());
    let view = ViewBuilder::new(tasks)
      .and(tag1)
      .and(complete_tag)
      .or(tag4)
      .build("test");

    let () = view.iter(|mut iter| {
      assert_eq!(iter.next().unwrap().summary(), "6");
      assert_eq!(iter.next().unwrap().summary(), "8");
      assert_eq!(iter.next().unwrap().summary(), "12");
      assert_eq!(iter.next().unwrap().summary(), "16");
      assert_eq!(iter.next().unwrap().summary(), "19");
      assert_eq!(iter.next().unwrap().summary(), "20");
      assert!(iter.next().is_none());
    });
  }

  #[test]
  fn filter_tag2_and_not_complete() {
    let (templates, tasks) = make_tagged_tasks(20);
    let complete_tag = templates.instantiate_from_name(COMPLETE_TAG);
    let tag2 = templates.instantiate_from_name(templates.iter().nth(2).unwrap().name());
    let view = ViewBuilder::new(tasks)
      .and_not(tag2)
      .and_not(complete_tag)
      .build("test");

    let () = view.iter(|mut iter| {
      assert_eq!(iter.next().unwrap().summary(), "1");
      assert_eq!(iter.next().unwrap().summary(), "3");
      assert_eq!(iter.next().unwrap().summary(), "5");
      assert_eq!(iter.next().unwrap().summary(), "7");
      assert_eq!(iter.next().unwrap().summary(), "13");
      assert_eq!(iter.next().unwrap().summary(), "17");
      assert!(iter.next().is_none());
    });
  }

  #[test]
  fn filter_tag2_or_not_complete_and_tag3() {
    let (templates, tasks) = make_tagged_tasks(20);
    let complete_tag = templates.instantiate_from_name(COMPLETE_TAG);
    let tag2 = templates.instantiate_from_name(templates.iter().nth(2).unwrap().name());
    let tag3 = templates.instantiate_from_name(templates.iter().nth(3).unwrap().name());
    let view = ViewBuilder::new(tasks)
      .or_not(tag2)
      .or_not(complete_tag)
      .and(tag3)
      .build("test");

    let () = view.iter(|mut iter| {
      assert_eq!(iter.next().unwrap().summary(), "13");
      assert_eq!(iter.next().unwrap().summary(), "14");
      assert_eq!(iter.next().unwrap().summary(), "15");
      assert_eq!(iter.next().unwrap().summary(), "19");
      assert!(iter.next().is_none());
    });
  }
}