toodoux 0.4.1

A modern task management tool
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
//! Initiate the configuration file creation when not present.

use colored::{Color as Col, ColoredString, Colorize};
use core::fmt::Formatter;
use serde::{
  de::{self, Visitor},
  Deserialize, Serialize,
};
use std::{
  fmt, fs,
  ops::Deref,
  path::{Path, PathBuf},
  str::FromStr,
};

use crate::error::Error;

#[derive(Debug, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct Config {
  pub main: MainConfig,
  pub colors: ColorConfig,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(default)]
pub struct MainConfig {
  /// Editor to use for interactive editing.
  ///
  /// If absent, default to `$EDITOR`. If neither the configuration or `$EDITOR` is set,
  /// interactive editing is disabled.
  interactive_editor: Option<String>,

  /// Path to the folder containing all the tasks.
  tasks_file: PathBuf,

  /// Name of the “TODO” state.
  todo_alias: String,

  /// Name of the “ONGOING” state.
  wip_alias: String,

  /// Name of the “DONE” state.
  done_alias: String,

  /// Name of the “CANCELLED” state.
  cancelled_alias: String,

  /// “UID” column name.
  uid_col_name: String,

  /// “Age” column name.
  age_col_name: String,

  /// “Spent” column name.
  spent_col_name: String,

  /// “Prio” column name.
  prio_col_name: String,

  /// “Project” column name.
  project_col_name: String,

  /// “Tags” column name.
  tags_col_name: String,

  /// “Status” column name.
  status_col_name: String,

  /// “Description” column name.
  description_col_name: String,

  /// Should we display empty columns?
  display_empty_cols: bool,

  /// Maximum number of warping lines of task description before breaking it (and adding the ellipsis character).
  max_description_lines: usize,

  /// "Number of notes” column name."
  notes_nb_col_name: String,

  /// Display tags in listings.
  display_tags_listings: bool,

  /// Show the previous notes when adding a new note.
  ///
  /// This option allows to show all the previously recorded notes for a given task as a header of the current note.
  /// The note history will be automatically discarded and will not appear in the new note.
  previous_notes_help: bool,
}

impl Default for MainConfig {
  fn default() -> Self {
    Self {
      interactive_editor: None,
      tasks_file: dirs::config_dir().unwrap().join("toodoux"),
      todo_alias: "TODO".to_owned(),
      wip_alias: "WIP".to_owned(),
      done_alias: "DONE".to_owned(),
      cancelled_alias: "CANCELLED".to_owned(),
      uid_col_name: "UID".to_owned(),
      age_col_name: "Age".to_owned(),
      spent_col_name: "Spent".to_owned(),
      prio_col_name: "Prio".to_owned(),
      project_col_name: "Project".to_owned(),
      tags_col_name: "Tags".to_owned(),
      status_col_name: "Status".to_owned(),
      description_col_name: "Description".to_owned(),
      notes_nb_col_name: "Notes".to_owned(),
      display_empty_cols: false,
      max_description_lines: 2,
      display_tags_listings: true,
      previous_notes_help: true,
    }
  }
}

impl MainConfig {
  #[allow(dead_code)]
  pub fn new(
    interactive_editor: impl Into<Option<String>>,
    tasks_file: impl Into<PathBuf>,
    todo_alias: impl Into<String>,
    wip_alias: impl Into<String>,
    done_alias: impl Into<String>,
    cancelled_alias: impl Into<String>,
    uid_col_name: impl Into<String>,
    age_col_name: impl Into<String>,
    spent_col_name: impl Into<String>,
    prio_col_name: impl Into<String>,
    project_col_name: impl Into<String>,
    tags_col_name: impl Into<String>,
    status_col_name: impl Into<String>,
    description_col_name: impl Into<String>,
    notes_nb_col_name: impl Into<String>,
    display_empty_cols: bool,
    max_description_lines: usize,
    display_tags_listings: bool,
    previous_notes_help: bool,
  ) -> Self {
    Self {
      interactive_editor: interactive_editor.into(),
      tasks_file: tasks_file.into(),
      todo_alias: todo_alias.into(),
      wip_alias: wip_alias.into(),
      done_alias: done_alias.into(),
      cancelled_alias: cancelled_alias.into(),
      uid_col_name: uid_col_name.into(),
      age_col_name: age_col_name.into(),
      spent_col_name: spent_col_name.into(),
      prio_col_name: prio_col_name.into(),
      project_col_name: project_col_name.into(),
      tags_col_name: tags_col_name.into(),
      status_col_name: status_col_name.into(),
      description_col_name: description_col_name.into(),
      notes_nb_col_name: notes_nb_col_name.into(),
      display_empty_cols,
      max_description_lines,
      display_tags_listings,
      previous_notes_help,
    }
  }
}

impl Config {
  #[allow(dead_code)]
  pub fn new(main: MainConfig, colors: ColorConfig) -> Self {
    Config { main, colors }
  }

  fn get_config_path() -> Result<PathBuf, Error> {
    log::trace!("getting configuration root path from the environment");
    let home = dirs::config_dir().ok_or(Error::NoConfigDir)?;
    let path = Path::new(&home).join("toodoux");

    Ok(path)
  }

  pub fn from_dir(path: impl AsRef<Path>) -> Result<Option<Self>, Error> {
    let path = path.as_ref().join("config.toml");

    log::trace!("reading configuration from {}", path.display());
    if path.is_file() {
      let content = fs::read_to_string(&path).map_err(Error::CannotOpenFile)?;
      let parsed = toml::from_str(&content).map_err(Error::CannotDeserializeFromTOML)?;
      Ok(Some(parsed))
    } else {
      Ok(None)
    }
  }

  pub fn root_dir(&self) -> &Path {
    &self.main.tasks_file
  }

  pub fn config_toml_path(&self) -> PathBuf {
    self.main.tasks_file.join("config.toml")
  }

  pub fn interactive_editor(&self) -> Option<&str> {
    self.main.interactive_editor.as_deref()
  }

  pub fn tasks_path(&self) -> PathBuf {
    self.main.tasks_file.join("tasks.json")
  }

  pub fn todo_alias(&self) -> &str {
    &self.main.todo_alias
  }

  pub fn wip_alias(&self) -> &str {
    &self.main.wip_alias
  }

  pub fn done_alias(&self) -> &str {
    &self.main.done_alias
  }

  pub fn cancelled_alias(&self) -> &str {
    &self.main.cancelled_alias
  }

  pub fn uid_col_name(&self) -> &str {
    &self.main.uid_col_name
  }

  pub fn age_col_name(&self) -> &str {
    &self.main.age_col_name
  }

  pub fn spent_col_name(&self) -> &str {
    &self.main.spent_col_name
  }

  pub fn prio_col_name(&self) -> &str {
    &self.main.prio_col_name
  }

  pub fn project_col_name(&self) -> &str {
    &self.main.project_col_name
  }

  pub fn tags_col_name(&self) -> &str {
    &self.main.tags_col_name
  }

  pub fn status_col_name(&self) -> &str {
    &self.main.status_col_name
  }

  pub fn description_col_name(&self) -> &str {
    &self.main.description_col_name
  }

  pub fn notes_nb_col_name(&self) -> &str {
    &self.main.notes_nb_col_name
  }

  pub fn display_empty_cols(&self) -> bool {
    self.main.display_empty_cols
  }

  pub fn max_description_lines(&self) -> usize {
    self.main.max_description_lines
  }

  pub fn display_tags_listings(&self) -> bool {
    self.main.display_tags_listings
  }

  pub fn previous_notes_help(&self) -> bool {
    self.main.previous_notes_help
  }

  pub fn get() -> Result<Option<Self>, Error> {
    let path = Self::get_config_path()?;
    Self::from_dir(path)
  }

  pub fn create(path: Option<&Path>) -> Result<Self, Error> {
    let default_config = Self::default();
    let tasks_file = path.map_or_else(Self::get_config_path, |p| Ok(p.to_owned()))?;

    let main = MainConfig {
      tasks_file,
      ..default_config.main
    };
    let config = Self {
      main,
      ..default_config
    };

    log::trace!("creating new configuration:\n{:#?}", config);

    Ok(config)
  }

  pub fn save(&self) -> Result<(), Error> {
    let root_dir = self.root_dir();
    fs::create_dir_all(root_dir).map_err(Error::CannotSave)?;

    let serialized = toml::to_string_pretty(self).map_err(Error::CannotSerializeToTOML)?;
    fs::write(self.config_toml_path(), serialized).map_err(Error::CannotSave)?;

    Ok(())
  }
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum StyleAttribute {
  Bold,
  Dimmed,
  Underline,
  Reversed,
  Italic,
  Blink,
  Hidden,
  Strikethrough,
}

impl StyleAttribute {
  /// Apply this style attribute to the input colored string.
  fn apply_style(&self, s: ColoredString) -> ColoredString {
    match self {
      StyleAttribute::Bold => s.bold(),
      StyleAttribute::Dimmed => s.dimmed(),
      StyleAttribute::Underline => s.underline(),
      StyleAttribute::Reversed => s.reversed(),
      StyleAttribute::Italic => s.italic(),
      StyleAttribute::Blink => s.blink(),
      StyleAttribute::Hidden => s.hidden(),
      StyleAttribute::Strikethrough => s.strikethrough(),
    }
  }
}

#[derive(Debug, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct ColorConfig {
  pub description: TaskDescriptionColorConfig,
  pub status: TaskStatusColorConfig,
  pub priority: PriorityColorConfig,
  pub show_header: ShowHeaderColorConfig,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct TaskDescriptionColorConfig {
  pub ongoing: Highlight,
  pub todo: Highlight,
  pub done: Highlight,
  pub cancelled: Highlight,
}

impl Default for TaskDescriptionColorConfig {
  fn default() -> Self {
    Self {
      ongoing: Highlight {
        foreground: Some(Color(Col::Black)),
        background: Some(Color(Col::BrightGreen)),
        style: vec![],
      },
      todo: Highlight {
        foreground: Some(Color(Col::BrightWhite)),
        background: Some(Color(Col::Black)),
        style: vec![],
      },
      done: Highlight {
        foreground: Some(Color(Col::BrightBlack)),
        background: Some(Color(Col::Black)),
        style: vec![StyleAttribute::Dimmed],
      },
      cancelled: Highlight {
        foreground: Some(Color(Col::BrightBlack)),
        background: Some(Color(Col::Black)),
        style: vec![StyleAttribute::Dimmed, StyleAttribute::Strikethrough],
      },
    }
  }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct TaskStatusColorConfig {
  pub ongoing: Highlight,
  pub todo: Highlight,
  pub done: Highlight,
  pub cancelled: Highlight,
}

impl Default for TaskStatusColorConfig {
  fn default() -> Self {
    Self {
      ongoing: Highlight {
        foreground: Some(Color(Col::Green)),
        background: None,
        style: vec![StyleAttribute::Bold],
      },
      todo: Highlight {
        foreground: Some(Color(Col::Magenta)),
        background: None,
        style: vec![StyleAttribute::Bold],
      },
      done: Highlight {
        foreground: Some(Color(Col::BrightBlack)),
        background: None,
        style: vec![StyleAttribute::Dimmed],
      },
      cancelled: Highlight {
        foreground: Some(Color(Col::BrightRed)),
        background: None,
        style: vec![StyleAttribute::Dimmed],
      },
    }
  }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct PriorityColorConfig {
  pub low: Highlight,
  pub medium: Highlight,
  pub high: Highlight,
  pub critical: Highlight,
}

impl Default for PriorityColorConfig {
  fn default() -> Self {
    Self {
      low: Highlight {
        foreground: Some(Color(Col::BrightBlack)),
        background: None,
        style: vec![StyleAttribute::Dimmed],
      },
      medium: Highlight {
        foreground: Some(Color(Col::Blue)),
        background: None,
        style: vec![],
      },
      high: Highlight {
        foreground: Some(Color(Col::Red)),
        background: None,
        style: vec![],
      },
      critical: Highlight {
        foreground: Some(Color(Col::Black)),
        background: Some(Color(Col::BrightRed)),
        style: vec![],
      },
    }
  }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct ShowHeaderColorConfig(Highlight);

impl Default for ShowHeaderColorConfig {
  fn default() -> Self {
    Self(Highlight {
      foreground: Some(Color(Col::BrightBlack)),
      background: None,
      style: vec![],
    })
  }
}

impl Deref for ShowHeaderColorConfig {
  type Target = Highlight;

  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

/// Highlight definition.
///
/// Contains foreground and background colors as well as the style to use.
#[derive(Debug, Deserialize, Serialize)]
pub struct Highlight {
  /// Foreground color.
  ///
  /// Leaving it empty implies using the default foreground color of your terminal
  pub foreground: Option<Color>,

  /// Background color.
  ///
  /// Leaving it empty implies using the default background color of your terminal
  pub background: Option<Color>,

  /// Style attributes to use.
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub style: Vec<StyleAttribute>,
}

impl Highlight {
  /// Apply the highlight to an input string.
  pub fn highlight(&self, input: impl AsRef<str>) -> HighlightedString {
    let mut colored: ColoredString = input.as_ref().into();

    if let Some(foreground) = &self.foreground {
      colored = colored.color(foreground.0);
    }

    if let Some(background) = &self.background {
      colored = colored.on_color(background.0);
    }

    for s in &self.style {
      colored = s.apply_style(colored);
    }

    HighlightedString(colored)
  }
}

/// Highlighted string — i.e. all color information and styles have been applied.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HighlightedString(ColoredString);

impl fmt::Display for HighlightedString {
  fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
    self.0.fmt(f)
  }
}

/// a wrapper around colored::Color in order to implement serialization
#[derive(Debug, PartialEq)]
pub struct Color(pub Col);

impl Color {
  /// Parse a [`Color`] from a hexadecimal string.
  ///
  /// Supports two simple formats (uppercase / lowercase supported in either case):
  ///
  /// - `#rrggbb`. Example: `#34f1c8`.
  /// - `#rgb`, which desugars to repeating each channel once. Example: `#3fc`.
  pub fn from_hex(hex: impl AsRef<str>) -> Option<Color> {
    let hex = hex.as_ref();
    let bytes = hex.as_bytes();
    let (mut r, mut g, mut b);

    if hex.len() == 4 && bytes[0] == b'#' {
      // triplet form (#rgb)
      let mut h = u16::from_str_radix(&hex[1..], 16).ok()?;

      b = (h & 0xf) as _;
      b += b << 4;

      h >>= 4;
      g = (h & 0xf) as _;
      g += g << 4;

      h >>= 4;
      r = (h & 0xf) as _;
      r += r << 4;
    } else if hex.len() == 7 && bytes[0] == b'#' {
      // #rrggbb form
      let mut h = u32::from_str_radix(&hex[1..], 16).ok()?;

      b = (h & 0xff) as _;

      h >>= 8;
      g = (h & 0xff) as _;

      h >>= 8;
      r = (h & 0xff) as _;
    } else {
      return None;
    }

    Some(Color(Col::TrueColor { r, g, b }))
  }
}

impl<'de> Deserialize<'de> for Color {
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: serde::Deserializer<'de>,
  {
    struct ColorVisitor;

    const EXPECTING: &str = "a color name or hexadecimal color";

    impl Visitor<'_> for ColorVisitor {
      type Value = Color;

      fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter.write_str(EXPECTING)
      }

      fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
      where
        E: de::Error,
      {
        // try to use from_str to get color; if this doesn't work we try to parse it as hex
        Col::from_str(value)
          .ok()
          .map(Color)
          .or_else(|| Color::from_hex(value))
          .ok_or_else(|| {
            // in the case we were unable to parse either a color name or hexadecimal color, we emit a serde error
            E::invalid_value(de::Unexpected::Str(value), &EXPECTING)
          })
      }
    }

    deserializer.deserialize_str(ColorVisitor)
  }
}

impl Serialize for Color {
  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  where
    S: serde::Serializer,
  {
    // this is a bit of a hack in order to extend the life time of a string
    // so we can return a ref to it from a match
    let true_color;
    // this is a reversed version of colored::Color::from_str()
    // with hex added
    let clr = match self.0 {
      Col::Black => "black",
      Col::Red => "red",
      Col::Green => "green",
      Col::Yellow => "yellow",
      Col::Blue => "blue",
      Col::Magenta => "magenta",
      Col::Cyan => "cyan",
      Col::White => "white",
      Col::BrightBlack => "bright black",
      Col::BrightRed => "bright red",
      Col::BrightGreen => "bright green",
      Col::BrightYellow => "bright yellow",
      Col::BrightBlue => "bright blue",
      Col::BrightMagenta => "bright magenta",
      Col::BrightCyan => "bright cyan",
      Col::BrightWhite => "bright white",
      Col::TrueColor { r, g, b } => {
        true_color = format!("#{:02x}{:02x}{:02x}", r, g, b);
        &true_color
      }
    };

    serializer.serialize_str(clr)
  }
}

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

  #[test]
  fn color_hex() {
    assert_eq!(
      Color::from_hex("#123"),
      Some(Color(Col::TrueColor {
        r: 0x11,
        g: 0x22,
        b: 0x33
      }))
    );

    assert_eq!(
      Color::from_hex("#112234"),
      Some(Color(Col::TrueColor {
        r: 0x11,
        g: 0x22,
        b: 0x34
      }))
    );
  }

  #[test]
  fn color_colored_name() {
    let c = Color(Col::White);
    assert_tokens(&c, &[Token::Str("white")])
  }

  #[test]
  fn apply_color_options() {
    // with color
    {
      let expected = HighlightedString("test".on_black().white().bold());
      let opts = Highlight {
        background: Some(Color(Col::Black)),
        foreground: Some(Color(Col::White)),
        style: vec![StyleAttribute::Bold],
      };
      assert_eq!(expected, opts.highlight("test"));
    }

    // only styles
    {
      let expected = HighlightedString("test".italic().bold());
      let opts = Highlight {
        background: None,
        foreground: None,
        style: vec![StyleAttribute::Bold, StyleAttribute::Italic],
      };
      assert_eq!(expected, opts.highlight("test"));
    }
  }
}