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
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
// Copyright (C) 2018-2025 Daniel Mueller <deso@posteo.net>
// SPDX-License-Identifier: GPL-3.0-or-later

use std::cell::Cell;
use std::cell::RefCell;
use std::cmp::max;
use std::cmp::min;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::collections::HashSet;
use std::io::BufWriter;
use std::io::Result;
use std::io::Write;
use std::ops::Add;
use std::ops::Sub;

use termion::color::Bg;
use termion::color::Fg;
use termion::cursor::Goto;
use termion::cursor::Hide;
use termion::cursor::Show;
use termion::terminal_size;

use gui::BBox;
use gui::Cap;
use gui::Id;
use gui::Object;
use gui::Renderable;
use gui::Renderer;
use gui::Widget as _;

use crate::colors::Color;
use crate::colors::Colors;
use crate::tasks::Task;
use crate::text;
use crate::text::Cursor;
use crate::text::DisplayWidth as _;
use crate::text::Width;
use crate::LINE_END;

use super::detail_dialog::DetailDialog;
use super::detail_dialog::DetailDialogData;
use super::event::Ids;
use super::in_out::InOut;
use super::in_out::InOutArea;
use super::tab_bar::TabBar;
use super::tag_dialog::SetUnsetTag;
use super::tag_dialog::TagDialog;
use super::task_list_box::TaskListBox;
use super::termui::TermUi;

const TASK_LIST_MARGIN_X: u16 = 3;
const TASK_LIST_MARGIN_Y: u16 = 2;
const TASK_SPACE: u16 = 2;
const TAG_SPACE: u16 = 2;
const TAB_TITLE_WIDTH: u16 = 30;
const DETAIL_DIALOG_MIN_W: u16 = 40;
const DETAIL_DIALOG_MIN_H: u16 = 20;
const DETAIL_DIALOG_MARGIN_X: u16 = 2;
const DETAIL_DIALOG_MARGIN_Y: u16 = 1;
const TAG_DIALOG_MARGIN_X: u16 = 2;
const TAG_DIALOG_MARGIN_Y: u16 = 1;
const TAG_DIALOG_MIN_W: u16 = 40;
const TAG_DIALOG_MIN_H: u16 = 20;

const SAVED_TEXT: &str = " Saved ";
const SEARCH_TEXT: &str = " Search ";
const ERROR_TEXT: &str = " Error ";
const INPUT_TEXT: &str = " > ";


/// Calculate the desired starting position of a window, given a cursor
/// that is always meant to be covered by `<return value> + size`.
///
/// This functionality forms the basis for all our sliding windows over
/// a set of entities (such as tasks, tags, ...).
fn window_start<T, U>(start: T, size: U, cursor: T) -> T
where
  T: Copy + Ord + Add<U, Output = T> + Sub<U, Output = T>,
  U: Copy + From<usize>,
{
  // If the cursor is in front of the window it marks the start of the
  // window. If it is past the end of the window, the window's start is
  // adjusted such that the cursor ends up being the very last element
  // in it.
  if cursor <= start {
    cursor
  } else if cursor >= start + size {
    cursor - size + U::from(1)
  } else {
    start
  }
}


/// Align string centrally in the given `width` or cut it off if it is too long.
fn align_center(string: impl Into<String>, width: usize) -> String {
  let mut string = string.into();
  let length = string.len();

  match length.cmp(&width) {
    Ordering::Greater => {
      // Note: May underflow if width < 3. That's not really a supported
      //       use case, though, so we ignore it here.
      string.replace_range(width - 3..length, "...");
    },
    Ordering::Less => {
      let pad_right = (width - length) / 2;
      let pad_left = width - length - pad_right;

      let pad_right = " ".repeat(pad_right);
      let pad_left = " ".repeat(pad_left);

      string.insert_str(0, &pad_right);
      string.push_str(&pad_left);
    },
    Ordering::Equal => (),
  }

  string
}

/// Clip a string according to the active bounding box.
///
/// # Notes
/// The `x` and `y` coordinates are interpreted to be relative to the
/// bounding box's origin.
fn clip(x: u16, y: u16, string: &str, bbox: BBox) -> &str {
  let w = bbox.w;
  let h = bbox.h;

  if y < h {
    text::clip(string, Width::from(usize::from(w.saturating_sub(x))))
  } else {
    ""
  }
}


/// A writer that clips writes according to a bounding box (typically
/// representing a widget) as well as the terminal size.
struct ClippingWriter<W>
where
  W: Write,
{
  /// The writer in use.
  writer: RefCell<W>,
  /// The currently active bounding box.
  bbox: Cell<BBox>,
  /// The size of the terminal, cached for each render pass (i.e., for
  /// everything between [`pre_render`] and [`post_render`]).
  terminal_size: Cell<Option<(u16, u16)>>,
}

impl<W> ClippingWriter<W>
where
  W: Write,
{
  /// Create a new `ClippingWriter` object.
  fn new(writer: W) -> Self {
    Self {
      writer: RefCell::new(writer),
      bbox: Default::default(),
      terminal_size: Default::default(),
    }
  }

  /// Set the `BBox` to restrict the rendering area to.
  fn restrict(&self, bbox: BBox) {
    self.bbox.set(bbox)
  }

  fn current_bbox(&self) -> BBox {
    let bbox = self.bbox.get();
    // SANITY: This function is only ever called when rendering, in
    //         which case our invariant dictates that the terminal size
    //         is set.
    let tsize = self.terminal_size.get().unwrap();
    BBox {
      x: bbox.x,
      y: bbox.y,
      w: min(bbox.w, tsize.0.saturating_sub(bbox.x)),
      h: min(bbox.h, tsize.1.saturating_sub(bbox.y)),
    }
  }

  /// Write a string to the terminal.
  fn write<S>(&self, x: u16, y: u16, fg: Color, bg: Color, string: S) -> Result<()>
  where
    S: AsRef<str>,
  {
    let string = clip(x, y, string.as_ref(), self.current_bbox());
    if !string.is_empty() {
      // Specified coordinates are always relative to the bounding box
      // set. Termion works with an origin at (1,1). We fudge that by
      // adjusting all coordinates accordingly.
      let x = self.bbox.get().x + x + 1;
      let y = self.bbox.get().y + y + 1;

      write!(
        self.writer.borrow_mut(),
        "{}{}{}{}",
        Goto(x, y),
        Fg(fg.as_term_color()),
        Bg(bg.as_term_color()),
        string,
      )?
    }
    Ok(())
  }

  /// Fill the rest of a line with the given color.
  fn fill_line(&self, x: u16, y: u16, w: u16, color: Color) -> Result<()> {
    // A string of 200 spaces.
    static SPACES: &str = concat!(
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
      "          ",
    );

    let bbox = self.current_bbox();
    let w = min(bbox.w.saturating_sub(x), w);
    let x = bbox.x + x + 1;
    let y = bbox.y + y + 1;

    let mut x = x;
    let mut w = w;
    while w > 0 {
      let cells = min(SPACES.len(), w.into());
      // SANITY: We will always get a valid slice here, because `cells`
      //         is guaranteed to be less `SPACES.len()` and more than
      //         1.
      let s = SPACES.get(..cells).unwrap();
      let () = write!(
        self.writer.borrow_mut(),
        "{}{}{}{}",
        Goto(x, y),
        Fg(color.as_term_color()),
        Bg(color.as_term_color()),
        s,
      )?;

      x += cells as u16;
      w -= cells as u16;
    }
    Ok(())
  }

  /// Move the cursor to the given position.
  fn goto(&self, x: u16, y: u16) -> Result<()> {
    let x = self.bbox.get().x + x + 1;
    let y = self.bbox.get().y + y + 1;
    write!(self.writer.borrow_mut(), "{}", Goto(x, y))
  }

  /// Flush everything written so far.
  fn flush(&self) -> Result<()> {
    self.writer.borrow_mut().flush()
  }

  /// Hide the cursor.
  fn hide(&self) -> Result<()> {
    write!(self.writer.borrow_mut(), "{Hide}")
  }

  /// Show the cursor.
  fn show(&self) -> Result<()> {
    write!(self.writer.borrow_mut(), "{Show}")
  }
}


/// A struct containing rendering related widget data with an offset.
#[derive(Default)]
struct OffsetData {
  pub offset: usize,
}


/// Retrieve the number of tasks that fit in the given `BBox`.
fn displayable_tasks(bbox: BBox) -> usize {
  ((bbox.h.saturating_sub(TASK_LIST_MARGIN_Y)) / TASK_SPACE) as usize
}

/// Retrieve the number of tags that fit in the given `BBox`.
fn displayable_tags(bbox: BBox) -> usize {
  ((bbox.h.saturating_sub(2 * TAG_DIALOG_MARGIN_Y)) / TAG_SPACE) as usize
}

/// Retrieve the number of tabs that fit in the given `BBox`.
fn displayable_tabs(width: u16) -> usize {
  (width / TAB_TITLE_WIDTH) as usize
}


/// A renderer outputting to a terminal.
pub struct TermRenderer<W>
where
  W: Write,
{
  /// Our actual writer.
  writer: ClippingWriter<BufWriter<W>>,
  /// A mapping from widget ID to a widget-specific offset indicating
  /// where to start rendering.
  data: RefCell<HashMap<Id, OffsetData>>,
  /// The colors to use.
  colors: Colors,
  /// An optional set of `Id` objects of widgets to render. If `None`,
  /// all widgets will be rendered.
  to_render: Option<HashSet<Id>>,
  /// The widget currently being rendered.
  ///
  /// This attribute is set as part of a `render` call and enables
  /// incremental redrawing.
  rendering: Cell<Option<Id>>,
}

impl<W> TermRenderer<W>
where
  W: Write,
{
  /// Create a new `TermRenderer` object.
  pub fn new(writer: W, colors: Colors) -> Result<Self> {
    // Compared to termbox termion suffers from flickering when clearing
    // the entire screen as it lacks any double buffering capabilities
    // and uses an escape sequence for the clearing. One proposed
    // solution is to use a io::BufWriter. Tests have shown that it does
    // not change much but conceptually it makes sense to use it
    // nevertheless -- so this is what we do. For a broader discussion
    // of this issue see https://github.com/ticki/termion/issues/105.
    let writer = ClippingWriter::new(BufWriter::new(writer));

    Ok(TermRenderer {
      writer,
      data: Default::default(),
      colors,
      to_render: None,
      rendering: Cell::new(None),
    })
  }

  /// Tell the renderer which widgets to render in the next
  /// [`render`][Self::render] call.
  pub(crate) fn set_ids(&mut self, ids: Option<Ids>) {
    self.to_render = ids.map(HashSet::from);
  }

  fn query_terminal_size() -> (u16, u16) {
    match terminal_size() {
      Ok(size) => size,
      Err(err) => panic!("Retrieving terminal size failed: {err}"),
    }
  }

  /// Render a `TermUi`.
  fn render_term_ui(&self, _ui: &TermUi, _bbox: BBox) -> Result<()> {
    Ok(())
  }

  /// Render a `TabBar`.
  fn render_tab_bar(&self, tab_bar: &TabBar, cap: &dyn Cap, bbox: BBox) -> Result<()> {
    let mut map = self.data.borrow_mut();
    let data = map.entry(tab_bar.id()).or_default();

    let mut x = 1;
    let w = bbox.w.saturating_sub(1);

    // TODO: We have some amount of duplication with the logic used to
    //       render a TaskListBox. Deduplicate?
    // TODO: This logic (and the task rendering, although for it the
    //       consequences are less severe) is not correct in the face of
    //       terminal resizes. If the width of the terminal is increased
    //       the offset would need to be adjusted. Should/can this be
    //       fixed?
    let tabs = tab_bar.iter(cap).len();
    let count = displayable_tabs(w.saturating_sub(1));
    let selection = tab_bar.selection(cap);
    let offset = window_start(data.offset, count, selection);

    if offset > 0 {
      let fg = self.colors.more_tasks_fg;
      let bg = self.colors.more_tasks_bg;
      self.writer.write(0, 0, fg, bg, "<")?;
    } else {
      let fg = self.colors.unselected_tab_fg;
      let bg = self.colors.unselected_tab_bg;
      self.writer.write(0, 0, fg, bg, " ")?;
    }

    if tabs > offset + count {
      let fg = self.colors.more_tasks_fg;
      let bg = self.colors.more_tasks_bg;
      self.writer.write(w, 0, fg, bg, ">")?;
    } else {
      let fg = self.colors.unselected_tab_fg;
      let bg = self.colors.unselected_tab_bg;
      self.writer.write(w, 0, fg, bg, " ")?;
    }

    for (i, tab) in tab_bar.iter(cap).enumerate().skip(offset).take(count) {
      let (fg, bg) = if i == selection {
        (self.colors.selected_tab_fg, self.colors.selected_tab_bg)
      } else {
        (self.colors.unselected_tab_fg, self.colors.unselected_tab_bg)
      };

      let title = align_center(tab.clone(), TAB_TITLE_WIDTH as usize - 4);
      let padded = format!("  {title}  ");
      self.writer.write(x, 0, fg, bg, padded)?;

      x += TAB_TITLE_WIDTH;
    }

    if x < w {
      let pad = " ".repeat((w - x) as usize);
      let fg = self.colors.unselected_tab_fg;
      let bg = self.colors.unselected_tab_bg;
      self.writer.write(x, 0, fg, bg, pad)?
    }

    data.offset = offset;
    Ok(())
  }

  /// Render a full line of the [`TaskListBox`], containing a task.
  fn render_task_list_line(
    &self,
    task: &Task,
    tagged: bool,
    selected: bool,
    y: u16,
    w: u16,
  ) -> Result<()> {
    let (state, state_fg, state_bg) = if !tagged {
      (
        "[ ]",
        self.colors.task_not_started_fg,
        self.colors.task_not_started_bg,
      )
    } else {
      ("[X]", self.colors.task_done_fg, self.colors.task_done_bg)
    };

    let (task_fg, task_bg) = if selected {
      (self.colors.selected_task_fg, self.colors.selected_task_bg)
    } else {
      (
        self.colors.unselected_task_fg,
        self.colors.unselected_task_bg,
      )
    };

    let mut x = 0;
    let () = self
      .writer
      .fill_line(0, y, TASK_LIST_MARGIN_X, self.colors.unselected_task_bg)?;
    x += TASK_LIST_MARGIN_X;

    self.writer.write(x, y, state_fg, state_bg, state)?;
    x += state.len() as u16;

    let details = if task.details().is_empty() {
      "   "
    } else {
      " * "
    };
    self.writer.write(
      x,
      y,
      self.colors.unselected_task_fg,
      self.colors.unselected_task_bg,
      details,
    )?;

    x += details.len() as u16;
    self.writer.write(x, y, task_fg, task_bg, task.summary())?;

    x += task.summary().display_width().as_usize() as u16;
    let () = self
      .writer
      .fill_line(x, y, w, self.colors.unselected_task_bg)?;
    Ok(())
  }

  /// Render a `TaskListBox`.
  fn render_task_list_box(&self, task_list: &TaskListBox, cap: &dyn Cap, bbox: BBox) -> Result<()> {
    let mut map = self.data.borrow_mut();
    let data = map.entry(task_list.id()).or_default();

    let mut cursor = None;

    let view = task_list.view(cap);
    let count = displayable_tasks(bbox);
    let selection = task_list.selection(cap);
    let offset = window_start(data.offset, count, selection);

    let () = view.iter(|iter| {
      let mut tasks = iter.enumerate().skip(offset).take(count);

      (0..bbox.h).try_for_each(|y| {
        if y < TASK_LIST_MARGIN_Y
          || y > bbox.h - TASK_LIST_MARGIN_Y
          || (y - TASK_LIST_MARGIN_Y) % TAG_SPACE != 0
        {
          self
            .writer
            .fill_line(0, y, bbox.w, self.colors.unselected_task_bg)
        } else if let Some((i, task)) = tasks.next() {
          let tagged = task_list
            .toggle_tag(cap)
            .map(|toggle_tag| task.has_tag(&toggle_tag))
            .unwrap_or(false);

          let () = self.render_task_list_line(task, tagged, i == selection, y, bbox.w)?;

          if i == selection && cap.is_focused(task_list.id()) {
            cursor = Some((TASK_LIST_MARGIN_X + 6, y));
          }
          Ok(())
        } else {
          self
            .writer
            .fill_line(0, y, bbox.w, self.colors.unselected_task_bg)
        }
      })
    })?;

    // Set the cursor to the first character of the selected item. This
    // allows for more convenient copying of the currently selected task
    // with programs such as tmux.
    if let Some((x, y)) = cursor {
      self.writer.goto(x, y)?;
    }

    // We need to adjust the offset we use in order to be able to give
    // the correct impression of a sliding selection window.
    data.offset = offset;
    Ok(())
  }

  /// Render a full line of the dialog, containing a tag.
  fn render_detail_dialog_line<'s>(
    &self,
    line: Option<&'s str>,
    y: u16,
    w: u16,
  ) -> Result<(Width, Option<&'s str>)> {
    let fg = self.colors.detail_dialog_fg;
    let bg = self.colors.detail_dialog_bg;

    let mut x = 0;
    // Fill initial margin before content.
    let () = self
      .writer
      .fill_line(x, y, DETAIL_DIALOG_MARGIN_X, self.colors.detail_dialog_bg)?;
    x += DETAIL_DIALOG_MARGIN_X;

    let (width, rest) = if let Some(line) = line {
      let (line, rest) = text::wrap(
        line,
        Width::from(usize::from(w.saturating_sub(2 * DETAIL_DIALOG_MARGIN_X))),
      );
      let width = line.display_width();
      let () = self.writer.write(x, y, fg, bg, line)?;
      (width, rest)
    } else {
      (Width::from(0), None)
    };

    x += width.as_usize() as u16;

    // Fill the remainder of the line.
    let () = self
      .writer
      .fill_line(x, y, w, self.colors.detail_dialog_bg)?;
    Ok((width, rest))
  }

  /// Render a `DetailDialog`.
  fn render_detail_dialog(
    &self,
    detail_dialog: &DetailDialog,
    cap: &dyn Cap,
    bbox: BBox,
  ) -> Result<()> {
    let data = detail_dialog.data::<DetailDialogData>(cap);
    let details = data.details();
    let mut lines = details.as_str().split(LINE_END);
    let mut line = None;
    let mut selection = details.cursor();
    let mut cursor = None;

    (0..bbox.h).try_for_each(|y| {
      if y < DETAIL_DIALOG_MARGIN_Y || y >= bbox.h - DETAIL_DIALOG_MARGIN_Y {
        self
          .writer
          .fill_line(0, y, bbox.w, self.colors.detail_dialog_bg)
      } else {
        let (rendered, rest) =
          self.render_detail_dialog_line(line.or_else(|| lines.next()), y, bbox.w)?;

        if cursor.is_none() {
          if Cursor::at_start() + rendered >= selection {
            cursor = Some((
              selection + Width::from(usize::from(DETAIL_DIALOG_MARGIN_X)),
              y,
            ));
          } else {
            selection -= rendered;
          }

          if rest.is_none() {
            // If there is no rest then we need to account for the line
            // break that we split at.
            selection -= LINE_END.display_width();
          }
        }

        line = rest;
        Ok(())
      }
    })?;

    if let Some((x, y)) = cursor {
      let () = self.writer.goto(x.as_usize() as _, y)?;
      let () = self.writer.show()?;
    } else if cfg!(debug_assertions) {
      panic!("no cursor set")
    }
    Ok(())
  }

  /// Render a full line of the dialog, containing a tag.
  fn render_tag_dialog_tag_line(
    &self,
    tag: &SetUnsetTag,
    y: u16,
    w: u16,
    selected: bool,
  ) -> Result<()> {
    let set = tag.is_set();
    let (state, state_fg, state_bg) = if set {
      (
        "[X]",
        self.colors.tag_dialog_tag_set_fg,
        self.colors.tag_dialog_tag_set_bg,
      )
    } else {
      (
        "[ ]",
        self.colors.tag_dialog_tag_unset_fg,
        self.colors.tag_dialog_tag_unset_bg,
      )
    };

    let (tag_fg, tag_bg) = if selected {
      (
        self.colors.tag_dialog_selected_tag_fg,
        self.colors.tag_dialog_selected_tag_bg,
      )
    } else {
      (self.colors.tag_dialog_fg, self.colors.tag_dialog_bg)
    };

    let mut x = 0;
    // Fill initial margin before state indication.
    let () = self
      .writer
      .fill_line(x, y, TAG_DIALOG_MARGIN_X, self.colors.tag_dialog_bg)?;
    x += TAG_DIALOG_MARGIN_X;

    let () = self.writer.write(x, y, state_fg, state_bg, state)?;
    x += state.len() as u16;

    let () = self.writer.fill_line(x, y, 1, self.colors.tag_dialog_bg)?;
    x += 1;

    let () = self.writer.write(x, y, tag_fg, tag_bg, tag.name())?;

    // Fill the remainder of the line.
    let () = self
      .writer
      .fill_line(x + tag.name().len() as u16, y, w, self.colors.tag_dialog_bg)?;
    Ok(())
  }

  /// Render a `TagDialog`.
  fn render_tag_dialog(&self, tag_dialog: &TagDialog, cap: &dyn Cap, bbox: BBox) -> Result<()> {
    let mut map = self.data.borrow_mut();
    let data = map.entry(tag_dialog.id()).or_default();

    let count = displayable_tags(bbox);
    let selection = tag_dialog.selection(cap);
    let offset = window_start(data.offset, count, selection);

    let mut tags = tag_dialog.tags(cap).iter().enumerate().skip(offset);

    (0..bbox.h).try_for_each(|y| {
      if y < TAG_DIALOG_MARGIN_Y
        || y >= bbox.h - TAG_DIALOG_MARGIN_Y
        || (y - TAG_DIALOG_MARGIN_Y) % TAG_SPACE != 0
      {
        self
          .writer
          .fill_line(0, y, bbox.w, self.colors.tag_dialog_bg)
      } else if let Some((i, tag)) = tags.next() {
        self.render_tag_dialog_tag_line(tag, y, bbox.w, i == selection)
      } else {
        self
          .writer
          .fill_line(0, y, bbox.w, self.colors.tag_dialog_bg)
      }
    })?;

    if cap.is_focused(tag_dialog.id()) {
      let x = TAG_DIALOG_MARGIN_X + 4;
      let y = TAG_DIALOG_MARGIN_Y + (selection as u16 * TAG_SPACE);
      self.writer.goto(x, y)?;
    }

    data.offset = offset;
    Ok(())
  }

  /// Render an `InOutArea`.
  fn render_input_output(&self, in_out: &InOutArea, cap: &dyn Cap, bbox: BBox) -> Result<()> {
    let mut x = 0;
    let y = bbox.h - 1;

    let (prefix, fg, bg, string) = match in_out.state(cap) {
      InOut::Saved => (
        SAVED_TEXT,
        self.colors.in_out_success_fg,
        self.colors.in_out_success_bg,
        None,
      ),
      InOut::Search(ref s) => (
        SEARCH_TEXT,
        self.colors.in_out_status_fg,
        self.colors.in_out_status_bg,
        Some(s.as_ref()),
      ),
      InOut::Error(ref e) => (
        ERROR_TEXT,
        self.colors.in_out_error_fg,
        self.colors.in_out_error_bg,
        Some(e.as_ref()),
      ),
      InOut::Input(ref text) => (
        INPUT_TEXT,
        self.colors.in_out_success_fg,
        self.colors.in_out_success_bg,
        Some(text.as_str()),
      ),
      InOut::Clear => {
        // This is a tiny bit of an unclean solution, but essentially we
        // do not want to keep any offset data around between editing
        // cycles. If we apply an offset previously stored for an overly
        // long task and then start editing a different task that easily
        // fits on the screen, the result will look strange. The correct
        // thing is to clear any offset data, but ideally there would be
        // a cleaner way to go about that than relying on us entering
        // the `Clear` state in between editing of different tasks.
        let _ = self.data.borrow_mut().remove(&in_out.id());
        let () = self
          .writer
          .fill_line(x, y, bbox.w, self.colors.in_out_string_bg)?;
        return Ok(())
      },
    };

    let () = self.writer.write(x, y, fg, bg, prefix)?;
    x += prefix.len() as u16;

    let () = self
      .writer
      .fill_line(x, y, 1, self.colors.in_out_string_bg)?;
    x += 1;

    let cursor = if let Some(string) = string {
      let fg = self.colors.in_out_string_fg;
      let bg = self.colors.in_out_string_bg;

      if let InOut::Input(text) = in_out.state(cap) {
        debug_assert!(cap.is_focused(in_out.id()));

        let mut map = self.data.borrow_mut();
        let data = map.entry(in_out.id()).or_default();

        // Calculate the number of displayable characters we have
        // available after the "prefix".
        let count = Width::from(bbox.w.saturating_sub(x) as usize);
        let cursor = text.cursor();
        let offset = window_start(
          text.cursor_start() + Width::from(data.offset),
          count,
          cursor,
        );
        let string = text.substr(offset..);

        data.offset = offset.as_usize();

        let () = self.writer.write(x, y, fg, bg, string)?;
        let cursor = x + cursor.as_usize() as u16 - offset.as_usize() as u16;

        x += string.display_width().as_usize() as u16;
        Some(cursor)
      } else {
        let () = self.writer.write(x, y, fg, bg, string)?;
        x += string.display_width().as_usize() as u16;
        None
      }
    } else {
      None
    };

    let () = self
      .writer
      .fill_line(x, y, bbox.w, self.colors.in_out_string_bg)?;

    if let Some(x) = cursor {
      let () = self.writer.goto(x, y)?;
      let () = self.writer.show()?;
    }
    Ok(())
  }

  fn render_widget(
    &self,
    widget: &dyn Renderable,
    cap: &dyn Cap,
    bbox: BBox,
    render: bool,
  ) -> Result<BBox> {
    let () = self.writer.restrict(bbox);

    if let Some(ui) = widget.downcast_ref::<TermUi>() {
      if render {
        let () = self.render_term_ui(ui, bbox)?;
      }
      Ok(bbox)
    } else if let Some(detail_dialog) = widget.downcast_ref::<DetailDialog>() {
      // We want the dialog box displayed in the center and not filling
      // up the entire screen.
      let w = max(DETAIL_DIALOG_MIN_W, bbox.w / 2);
      let h = max(DETAIL_DIALOG_MIN_H, bbox.h / 2);
      let x = w / 2;
      let y = h / 2;

      let bbox = BBox { x, y, w, h };

      if render {
        let () = self.writer.restrict(bbox);
        let () = self.render_detail_dialog(detail_dialog, cap, bbox)?;
      }
      Ok(bbox)
    } else if let Some(tag_dialog) = widget.downcast_ref::<TagDialog>() {
      // We want the dialog box displayed in the center and not filling
      // up the entire screen.
      let w = max(TAG_DIALOG_MIN_W, bbox.w / 2);
      let h = max(TAG_DIALOG_MIN_H, bbox.h / 2);
      let x = w / 2;
      let y = h / 2;

      let bbox = BBox { x, y, w, h };

      if render {
        let () = self.writer.restrict(bbox);
        let () = self.render_tag_dialog(tag_dialog, cap, bbox)?;
      }
      Ok(bbox)
    } else if let Some(in_out) = widget.downcast_ref::<InOutArea>() {
      if render {
        let () = self.render_input_output(in_out, cap, bbox)?;
      }
      Ok(bbox)
    } else if let Some(tab_bar) = widget.downcast_ref::<TabBar>() {
      if render {
        let () = self.render_tab_bar(tab_bar, cap, bbox)?;
      }

      // Account for the one line the tab bar occupies at the top and
      // another one to have some space at the bottom to the input/output
      // area.
      let bbox = BBox {
        y: bbox.y.saturating_add(1),
        h: bbox.h.saturating_sub(2),
        ..bbox
      };
      Ok(bbox)
    } else if let Some(task_list) = widget.downcast_ref::<TaskListBox>() {
      if render {
        let () = self.render_task_list_box(task_list, cap, bbox)?;
      }
      Ok(bbox)
    } else {
      panic!("Widget {widget:?} is unknown to the renderer")
    }
  }

  fn widget_id(widget: &dyn Renderable) -> Id {
    if let Some(ui) = widget.downcast_ref::<TermUi>() {
      ui.id()
    } else if let Some(detail_dialog) = widget.downcast_ref::<DetailDialog>() {
      detail_dialog.id()
    } else if let Some(tag_dialog) = widget.downcast_ref::<TagDialog>() {
      tag_dialog.id()
    } else if let Some(in_out) = widget.downcast_ref::<InOutArea>() {
      in_out.id()
    } else if let Some(tab_bar) = widget.downcast_ref::<TabBar>() {
      tab_bar.id()
    } else if let Some(task_list) = widget.downcast_ref::<TaskListBox>() {
      task_list.id()
    } else {
      panic!("Widget {widget:?} is unknown to the renderer")
    }
  }
}

impl<W> Renderer for TermRenderer<W>
where
  W: Write,
{
  fn renderable_area(&self) -> BBox {
    // SANITY: The renderable area should only ever be queried between
    //         `pre_render` and `post_render`, in which case a
    //         renderable area should always be available.
    let tsize = self.writer.terminal_size.get().unwrap();

    BBox {
      x: 0,
      y: 0,
      w: tsize.0,
      h: tsize.1,
    }
  }

  fn pre_render(&self) {
    let () = self
      .writer
      .terminal_size
      .set(Some(Self::query_terminal_size()));

    // Always hide the cursor before rendering, to prevent various
    // related artifacts from showing up. Widgets may opt for setting
    // and enabling the cursor as one of their last actions.
    let result = self.writer.hide();

    if let Err(err) = result {
      panic!("Pre-render failed: {err}");
    }
  }

  fn render(&self, widget: &dyn Renderable, cap: &dyn Cap, bbox: BBox) -> BBox {
    let render = if let Some(to_render) = &self.to_render {
      if self.rendering.get().is_none() {
        let id = Self::widget_id(widget);
        if to_render.contains(&id) {
          let () = self.rendering.set(Some(id));
          true
        } else {
          false
        }
      } else {
        true
      }
    } else {
      true
    };

    let result = self.render_widget(widget, cap, bbox, render);
    match result {
      Ok(b) => b,
      Err(err) => panic!("Rendering failed: {err}"),
    }
  }

  fn render_done(&self, widget: &dyn Renderable, _cap: &dyn Cap, _bbox: BBox) {
    if let Some(rendering) = self.rendering.get() {
      let id = Self::widget_id(widget);

      // If we just finished rendering the widget we set out to render, we
      // can clear the corresponding ID marker.
      if rendering == id {
        self.rendering.set(None)
      }
    }
  }

  fn post_render(&self) {
    let result = self.writer.flush();
    if let Err(err) = result {
      panic!("Post-render failed: {err}");
    }

    let () = self.writer.terminal_size.set(None);
  }
}

impl<W> Drop for TermRenderer<W>
where
  W: Write,
{
  fn drop(&mut self) {
    // We should never panic in a destructor so don't unwrap and just
    // swallow the result. We are done anyway.
    let _result = self.writer.show();
  }
}


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

  #[cfg(feature = "nightly")]
  use unstable_test::Bencher;


  /// Check that we can centrally align a string properly using
  /// `align_center`.
  #[test]
  fn align_string() {
    assert_eq!(align_center("", 0), "");
    assert_eq!(align_center("", 1), " ");
    assert_eq!(align_center("", 8), "        ");
    assert_eq!(align_center("a", 1), "a");
    assert_eq!(align_center("a", 2), "a ");
    assert_eq!(align_center("a", 3), " a ");
    assert_eq!(align_center("a", 4), " a  ");
    assert_eq!(align_center("hello", 20), "       hello        ");
  }

  /// Make sure that `align_center` crops a string as necessary.
  #[test]
  fn crop_string() {
    assert_eq!(align_center("hello", 4), "h...");
    assert_eq!(align_center("hello", 5), "hello");
    assert_eq!(align_center("that's a test", 8), "that'...");
  }

  /// Check that we ca properly clip a string using `clip`.
  #[test]
  fn clip_string() {
    let bbox = BBox {
      x: 0,
      y: 0,
      w: 0,
      h: 0,
    };
    assert_eq!(clip(0, 0, "hello", bbox), "");
    assert_eq!(clip(1, 0, "foobar", bbox), "");
    assert_eq!(clip(1, 1, "baz?", bbox), "");

    let bbox = BBox {
      x: 10,
      y: 16,
      w: 6,
      h: 1,
    };
    assert_eq!(clip(0, 0, "hello", bbox), "hello");
    assert_eq!(clip(0, 0, "hello you", bbox), "hello ");

    // The position of the bounding box should not matter.
    for x in 0..5 {
      for y in 0..3 {
        let bbox = BBox { x, y, w: 5, h: 3 };
        assert_eq!(clip(0, 2, "inside", bbox), "insid");
        assert_eq!(clip(0, 3, "outside", bbox), "");

        assert_eq!(clip(1, 2, "inside", bbox), "insi");
        assert_eq!(clip(2, 0, "inside", bbox), "ins");
        assert_eq!(clip(2, 3, "outside", bbox), "");
      }
    }
  }

  /// Benchmark the rendering of the UI.
  // TODO: This is quite a monstrosity with all the setup code and there
  //       is duplication/overlap with respect to the example and other
  //       code paths. We should really streamline that.
  #[cfg(feature = "nightly")]
  #[ignore = "test requires fully functional TTY"]
  #[bench]
  fn bench_ui_rendering(b: &mut Bencher) {
    use std::ffi::OsString;
    use std::io::stdout;

    use gui::Ui;
    use tempfile::TempDir;
    use termion::raw::IntoRawMode as _;
    use termion::screen::IntoAlternateScreen as _;
    use tokio::runtime::Builder;

    use crate::test::default_tasks_and_tags;
    use crate::ui::Renderer as TermUiRenderer;
    use crate::ui::UiData as TermUiData;
    use crate::DirCap;
    use crate::TaskState;
    use crate::UiConfig;
    use crate::UiState;

    let rt = Builder::new_current_thread().build().unwrap();

    let () = rt.block_on(async {
      let (ui_config, task_state) = default_tasks_and_tags();

      let task_state = TaskState::with_serde(task_state).unwrap();
      let tasks_dir = TempDir::new().unwrap();
      let mut tasks_root_cap = DirCap::for_dir(tasks_dir.path().to_path_buf())
        .await
        .unwrap();
      let () = task_state.save(&mut tasks_root_cap).await.unwrap();

      let ui_config = UiConfig::with_serde(ui_config, &task_state).unwrap();
      let ui_config_dir = TempDir::new().unwrap();
      let ui_config_file_name = OsString::from("notnow.json");
      let ui_config_path = (
        ui_config_dir.path().to_path_buf(),
        ui_config_file_name.clone(),
      );
      let mut ui_config_dir_cap = DirCap::for_dir(ui_config_dir.path().to_path_buf())
        .await
        .unwrap();
      let ui_config_dir_write_guard = ui_config_dir_cap.write().await.unwrap();
      let mut ui_config_file_cap = ui_config_dir_write_guard.file_cap(&ui_config_file_name);
      let () = ui_config.save(&mut ui_config_file_cap).await.unwrap();

      let ui_state_dir = TempDir::new().unwrap();
      let ui_state_file_name = OsString::from("ui-state.json");
      let ui_state_path = (ui_state_dir.path().to_path_buf(), ui_state_file_name);
      let tasks_root = tasks_dir.path().to_path_buf();

      let task_state = TaskState::load(&tasks_root).await.unwrap();
      let ui_config_file = ui_config_path.0.join(&ui_config_path.1);
      let ui_state_file = ui_state_path.0.join(&ui_state_path.1);
      let ui_config = UiConfig::load(&ui_config_file, &task_state).await.unwrap();
      let UiConfig {
        colors,
        toggle_tag,
        views,
      } = ui_config;

      let ui_state = UiState::load(&ui_state_file).await.unwrap();

      let ui_config_dir_cap = DirCap::for_dir(ui_config_path.0).await.unwrap();
      let ui_config_file = ui_config_path.1;

      let ui_state_dir_cap = DirCap::for_dir(ui_state_path.0).await.unwrap();
      let ui_state_file = ui_state_path.1;

      let tasks_root_cap = DirCap::for_dir(tasks_root).await.unwrap();

      let (ui, _) = Ui::new(
        || {
          Box::new(TermUiData::new(
            tasks_root_cap,
            task_state,
            (ui_config_dir_cap, ui_config_file),
            (ui_state_dir_cap, ui_state_file),
            colors,
            toggle_tag,
          ))
        },
        |id, cap| Box::new(TermUi::new(id, cap, views, ui_state)),
      );

      let screen = stdout()
        .lock()
        .into_raw_mode()
        .unwrap()
        .into_alternate_screen()
        .unwrap();
      let renderer = TermUiRenderer::new(screen, colors).unwrap();

      let () = b.iter(|| {
        let () = ui.render(&renderer);
      });
    });
  }
}