-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtui.py
More file actions
746 lines (657 loc) · 30.2 KB
/
Copy pathtui.py
File metadata and controls
746 lines (657 loc) · 30.2 KB
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
"""Curses TUI for the TaskManager CLI (Phase 4: scrolling, resize, polish).
A full-screen alternative to the line REPL in `tasks`. It renders the active
category as a browsable list, opens a detail screen for a task, shows a help
overlay, and performs every mutation the old REPL could: add, edit title, set
status, add/remove note, change category, move, finish, and delete, all via
single keypresses through input/confirm/pick overlays. As of Phase 4 the list
and detail-note regions scroll to keep the selection visible, the layout
recomputes on terminal resize, selection/scroll anchors are re-clamped after
every change, and long text truncates with `…` so nothing crashes on a tiny or
overflowing screen. Styling (labels, colors, glyphs) is reused from render.py
rather than re-derived, mapped once onto curses color pairs.
`run(tm)` is the only public entry point. It returns 0 on a clean exit, or
None when the TUI can't run (non-TTY / curses unavailable) so the caller can
fall back to the old REPL.
"""
import sys
import curses
import curses.textpad
from render import STYLE, _status_color, _RAMP_256, _BOX
from tasks import MODES, LIST, SHORTTERM, LONGTERM, WAIT, BACKLOG, UP, DOWN, FIRST, LAST
from devlogger import devlog
# The six color names used by render.STYLE / render._status_color, mapped to
# curses base colors. init_pair numbers are assigned in _init_colors().
_COLOR_NAMES = ['green', 'blue', 'yellow', 'magenta', 'cyan', 'red']
_COLOR_CURSES = {
'green': curses.COLOR_GREEN,
'blue': curses.COLOR_BLUE,
'yellow': curses.COLOR_YELLOW,
'magenta': curses.COLOR_MAGENTA,
'cyan': curses.COLOR_CYAN,
'red': curses.COLOR_RED,
}
# Fallback rainbow ramp for the gradient border when the terminal can't address
# all 256 xterm colors: the six base colors in ROYGCBV order so it still reads
# as a rainbow. render._RAMP_256 is the smooth 256-color version, used when
# available; both are consumed by _init_colors / _hue_attr.
_RAMP_8 = ['red', 'yellow', 'green', 'cyan', 'blue', 'magenta']
_PAIRS = {} # color name -> fg init_pair number
_PILLS = {} # color name -> status-pill init_pair number
_RAMP = [] # init_pair numbers along the rainbow
_HINT = '↑↓ move · ←→ cat · ↵ open · a add · e edit · d done · x del · ? help · q quit'
_DETAIL_HINT = ('↑↓ task · ⇧↑↓ note · e edit · s status · S clear · n note · '
'N del-note · t type · m move · d done · x del · ? help · b back')
# Keybindings shown in the help overlay. Module-level so it can be extended in
# one place. Each entry is (keys, description).
_HELP_KEYS = [
('↑ ↓ / k j', 'move selection (list) / switch task (detail)'),
('← → / h l', 'switch category'),
('⇧ ↑ ↓ / PgUp PgDn', 'select note (detail)'),
('↵ Enter', 'open task detail'),
('b / Esc', 'back to list (from detail)'),
('a', 'add a task'),
('e', 'edit title'),
('s / S', 'set / clear status'),
('n / N', 'add / remove note'),
('t', 'change category'),
('m', 'move within category'),
('d', 'finish (done) task'),
('x', 'delete task'),
('q', 'quit (list) / back (detail)'),
('?', 'toggle this help'),
]
# 't' (change type) menu order and 'm' (move) targets, mirroring the REPL
# (`_interactive_task` t/m handlers and `tasks._WHERE`).
_TYPE_MENU = [SHORTTERM, WAIT, LONGTERM, BACKLOG]
_MOVE_OPTIONS = ['up', 'down', 'top', 'bottom']
_MOVE_MAP = {
'up': ('direction', UP),
'down': ('direction', DOWN),
'top': ('new_slot', FIRST),
'bottom': ('new_slot', LAST),
}
class _State:
"""Tiny UI state: which category is shown, which row is selected, which
screen ('list' or 'detail') is active, and whether help is overlaid."""
def __init__(self, tm):
self.mode = tm.mode
self.selected = 0
self.screen = 'list'
self.show_help = False
self.scroll_offset = 0 # list view: index of first visible task
self.note_sel = 0 # detail view: index of the highlighted note
self.note_scroll = 0 # detail view: index of first visible note
self.note_capacity = 0 # detail view: visible note rows (for paging)
def _init_colors():
"""Allocate the curses color pairs the TUI draws with: one foreground pair
per render color name, one status-pill pair (dark text on the color) per
name, and a rainbow ramp for the gradient border. The ramp uses render's
256-color hue ring when the terminal can address it, else the six base
colors cycled (so the border still reads as a rainbow on 8-color terminals).
No-op when the terminal lacks color support; every _attr/_hue/_pill helper
then returns 0 and the UI degrades to monochrome."""
_PAIRS.clear()
_PILLS.clear()
_RAMP.clear()
if not curses.has_colors():
return
curses.start_color()
try:
curses.use_default_colors()
bg = -1
except curses.error:
bg = curses.COLOR_BLACK
pair = 1
for name in _COLOR_NAMES: # foreground-over-default category colors
curses.init_pair(pair, _COLOR_CURSES[name], bg)
_PAIRS[name] = pair
pair += 1
for name in _COLOR_NAMES: # status pills: dark text on the color
try:
curses.init_pair(pair, curses.COLOR_BLACK, _COLOR_CURSES[name])
except curses.error:
break
_PILLS[name] = pair
pair += 1
ramp = _RAMP_256 if curses.COLORS >= 256 else [_COLOR_CURSES[n] for n in _RAMP_8]
for cnum in ramp: # rainbow ramp for the gradient border
if pair >= curses.COLOR_PAIRS:
break
try:
curses.init_pair(pair, cnum, bg)
except curses.error:
break
_RAMP.append(pair)
pair += 1
def _attr(name):
"""curses attribute for a render color name; 0 if falsy/unsupported."""
if not name:
return 0
pair = _PAIRS.get(name)
return curses.color_pair(pair) if pair else 0
def _hue_attr(frac):
"""curses attribute for hue fraction `frac` in [0, 1] along the rainbow ramp,
the curses analogue of render._hue. Wraps like render's hue wheel (1.0 -> the
first color) and returns 0 when color/the ramp is unavailable."""
if not _RAMP:
return 0
return curses.color_pair(_RAMP[int(frac * len(_RAMP)) % len(_RAMP)])
def _pill_attr(status):
"""curses attribute for a status pill -- dark text on the status color, the
curses analogue of render._status_tag. Falls back to the plain status
foreground color (or 0) when pills/color are unavailable."""
name = _status_color(status)
pair = _PILLS.get(name)
return curses.color_pair(pair) if pair else _attr(name)
def _add(stdscr, y, x, text, attr, maxx, ellipsis=False):
"""Draw `text` at (y, x) clipped to the screen width; return the new x.
addnstr is bounded (and the last cell is never written) so edge writes can't
raise; the call is also wrapped defensively for very small terminals. With
`ellipsis`, text too long for the line is truncated with a trailing `…`
instead of hard-clipped, so titles/status/hints degrade cleanly."""
maxy, _ = stdscr.getmaxyx()
if y < 0 or y >= maxy or x < 0:
return x
avail = maxx - 1 - x # never write the last column
if avail <= 0:
return x
if ellipsis and len(text) > avail:
text = text[:max(0, avail - 1)] + '…'
try:
stdscr.addnstr(y, x, text, avail, attr)
except curses.error:
return x
return x + min(len(text), avail)
def _clamp(state, items):
"""Keep `selected` inside the current list and the scroll anchor sane after
a list shrinks (delete/finish/category switch) or the terminal resizes. The
per-screen draw refines the scroll window once it knows the visible height;
this just guarantees nothing is left pointing past the end."""
n = len(items)
state.selected = min(max(0, state.selected), max(0, n - 1))
state.scroll_offset = max(0, min(state.scroll_offset, state.selected))
if state.note_scroll < 0:
state.note_scroll = 0
def _prompt(stdscr, label, default=''):
"""One-line text input in a centered bordered window. Returns the trimmed
string, or None if the user cancels (Esc, or an empty entry). When `default`
is given it's shown in the label as `[default]` and a non-empty entry
replaces it (REPL-style) -- an empty entry cancels, leaving it unchanged.
Replaces the `input()` the REPL uses, which can't run inside curses."""
if default:
label = '%s [%s]' % (label, default)
maxy, maxx = stdscr.getmaxyx()
if maxy < 4 or maxx < 14: # no room for the bordered input window
return None
width = min(maxx - 2, max(40, len(label) + 4))
width = max(width, 12)
height = 4
y = max(0, (maxy - height) // 2)
x = max(0, (maxx - width) // 2)
win = curses.newwin(height, width, y, x)
win.keypad(True)
win.border()
win.addnstr(1, 2, label, width - 4, curses.A_BOLD)
win.refresh()
editw = curses.newwin(1, width - 4, y + 2, x + 2)
box = curses.textpad.Textbox(editw, insert_mode=True)
cancelled = [False]
def validate(ch):
if ch in (curses.KEY_ENTER, 10, 13):
return 7 # Ctrl-G: terminate the edit
if ch == 27: # Esc: cancel
cancelled[0] = True
return 7
if ch in (curses.KEY_BACKSPACE, 127, 8):
return 8 # Ctrl-H: backspace
return ch
curses.curs_set(1)
try:
text = box.edit(validate)
except curses.error:
text = ''
curses.curs_set(0)
stdscr.touchwin()
stdscr.refresh()
if cancelled[0]:
return None
text = text.strip()
return text or None
def _confirm(stdscr, message):
"""Draw `message + ' (y/N)'` on the bottom line; return True only on y/Y."""
maxy, maxx = stdscr.getmaxyx()
stdscr.move(maxy - 1, 0)
stdscr.clrtoeol()
_add(stdscr, maxy - 1, 0, message + ' (y/N)', curses.A_BOLD, maxx)
stdscr.refresh()
key = stdscr.getch()
return key in (ord('y'), ord('Y'))
def _pick(stdscr, title, options):
"""Single-key numbered chooser in a centered bordered window. Returns the
chosen index, or None on cancel (Esc/q). Used by 'change type' and 'move'."""
maxy, maxx = stdscr.getmaxyx()
if maxy < 4 or maxx < 14: # no room for the bordered chooser window
return None
rows = ['%d %s' % (i + 1, o) for i, o in enumerate(options)]
inner = max([len(title)] + [len(r) for r in rows])
width = min(maxx - 2, inner + 4)
width = max(width, 12)
height = min(maxy, len(rows) + 4)
y = max(0, (maxy - height) // 2)
x = max(0, (maxx - width) // 2)
win = curses.newwin(height, width, y, x)
win.keypad(True)
win.border()
win.addnstr(1, 2, title, width - 4, curses.A_BOLD)
for i, r in enumerate(rows):
if 2 + i >= height - 1:
break
win.addnstr(2 + i, 2, r, width - 4)
win.refresh()
result = None
while True:
key = win.getch()
if key in (27, ord('q'), ord('Q')):
break
if ord('1') <= key <= ord('9'):
choice = key - ord('1')
if choice < len(options):
result = choice
break
stdscr.touchwin()
stdscr.refresh()
return result
def _handle_action(stdscr, tm, state, key, items, n):
"""Perform an editing keypress shared by the list and detail screens. Acts
on the selected task (`state.selected`). Returns True if `key` was an action
(consumed), False otherwise. Mutators that move a task out of its slot/list
(t/m/d/x) drop back to the list screen; the main loop re-clamps `selected`."""
mode = state.mode
idx = state.selected
if key in (ord('a'), ord('A')):
text = _prompt(stdscr, 'task:')
if text:
tm.append_task(text, mode=mode)
state.selected = len(tm.lists[mode][LIST]) - 1
return True
if not n: # the rest need a selected task
return False
task = items[idx]
if key == ord('e'):
title = _prompt(stdscr, 'new title:', default=task.title)
if title:
tm.set_title(idx, title, mode=mode)
return True
if key == ord('s'):
status = _prompt(stdscr, 'status:', default=task.status)
if status:
tm.set_status(idx, status, mode=mode)
return True
if key == ord('S'): # clear status (no prompt)
if task.status:
tm.set_status(idx, '', mode=mode)
return True
if key == ord('n'):
note = _prompt(stdscr, 'note:')
if note:
tm.add_note(idx, note, mode=mode)
return True
if key == ord('N'):
if task.notes:
which = _pick(stdscr, 'remove note:', task.notes)
if which is not None:
tm.remove_note(idx, which, mode=mode)
return True
if key == ord('t'):
pick = _pick(stdscr, 'new type:', _TYPE_MENU)
if pick is not None and _TYPE_MENU[pick] != mode:
tm.change_type(idx, _TYPE_MENU[pick], mode=mode)
state.screen = 'list' # index shifted to another list
return True
if key == ord('m'):
pick = _pick(stdscr, 'move:', _MOVE_OPTIONS)
if pick is not None:
kind, value = _MOVE_MAP[_MOVE_OPTIONS[pick]]
tm.move_task(idx, mode=mode, **{kind: value})
state.screen = 'list' # slot may have shifted
return True
if key == ord('d'):
if _confirm(stdscr, 'Finish "%s"' % task.title):
finished = tm.finish_task(idx, mode=mode)
devlog('Finished task: %s' % finished.title)
state.screen = 'list'
return True
if key == ord('x'):
if _confirm(stdscr, 'Delete "%s"' % task.title):
tm.delete_task(idx, mode=mode)
state.screen = 'list'
return True
return False
def _draw_frame(stdscr, y0, x0, h, w, title_left=None, title_right=None,
fill=False):
"""Draw a single-line box with a rainbow-gradient border at (y0, x0) sized
h x w, and return (iy, ix, ih, iw): the interior origin and size for content.
Border chars are hue-colored across the width on the top/bottom rules and
down the height on the side bars -- the curses analogue of render._box's
rainbow frame (_rule_paint / _side_paint). `title_left`/`title_right` are
(text, attr) pairs embedded in the top rule, padded so the gradient doesn't
run into the text. With `fill`, interior rows are blanked first so the box
reads as a solid overlay (used by the help panel). Callers size the frame to
avoid the screen's last column, which curses can't safely write."""
maxy, maxx = stdscr.getmaxyx()
iy, ix, ih, iw = y0 + 1, x0 + 2, h - 2, w - 4
if h < 2 or w < 2:
return (iy, ix, max(0, ih), max(0, iw))
tl, tr, bl, br, hbar, vbar = _BOX
# top and bottom rules, hue by column so the gradient flows left-to-right
for x in range(x0, x0 + w):
a = _hue_attr((x - x0) / max(1, w - 1))
top_ch = tl if x == x0 else tr if x == x0 + w - 1 else hbar
bot_ch = bl if x == x0 else br if x == x0 + w - 1 else hbar
_add(stdscr, y0, x, top_ch, a, maxx)
_add(stdscr, y0 + h - 1, x, bot_ch, a, maxx)
# side bars, hue by row so the frame is one continuous gradient
for y in range(y0 + 1, y0 + h - 1):
a = _hue_attr((y - y0) / max(1, h - 1))
if fill:
_add(stdscr, y, x0 + 1, ' ' * (w - 2), 0, maxx)
_add(stdscr, y, x0, vbar, a, maxx)
_add(stdscr, y, x0 + w - 1, vbar, a, maxx)
# embed titles over the top rule (right first, so the left clip can stop short)
left_clip = x0 + w - 1
if title_right:
text, attr = title_right
s = ' %s ' % text
tx = x0 + w - 2 - len(s)
if tx > x0 + 4:
_add(stdscr, y0, tx, s, attr, x0 + w - 1)
left_clip = tx
if title_left:
text, attr = title_left
_add(stdscr, y0, x0 + 2, ' %s ' % text, attr, left_clip, ellipsis=True)
return (iy, ix, ih, iw)
def _draw_list(stdscr, tm, state):
"""Render the active category: header, the visible window of numbered rows
(selected row reversed), and a footer with the other categories' counts plus
a key hint. When the list is taller than the screen it scrolls to keep the
selected row visible, and the header shows a `[first-last / total]` marker."""
maxy, maxx = stdscr.getmaxyx()
label, col, glyph = STYLE[state.mode]
items = tm.lists[state.mode][LIST]
n = len(items)
# Interior geometry (mirrors _draw_frame): one blank top line, the task
# window, then the two footer lines (other-category counts + key hint).
iy, ix = 1, 2
right = maxx - 3 # interior right clip (before the bar)
top = iy
other_row = maxy - 3
hint_row = maxy - 2
capacity = max(0, other_row - top)
# Scroll-into-view: nudge the window so `selected` sits inside it, then clamp
# to the list bounds. (Central _clamp already kept selected/offset >= 0.)
if capacity and n:
if state.selected < state.scroll_offset:
state.scroll_offset = state.selected
elif state.selected >= state.scroll_offset + capacity:
state.scroll_offset = state.selected - capacity + 1
state.scroll_offset = max(0, min(state.scroll_offset, max(0, n - capacity)))
else:
state.scroll_offset = 0
# Title row (in the rainbow border): list name on the left, active category
# label/glyph on the right with a scroll-position marker when it scrolls.
cat = '%s %s' % (glyph, label)
if capacity and n > capacity:
last = min(n, state.scroll_offset + capacity)
cat += ' [%d-%d / %d]' % (state.scroll_offset, last - 1, n)
_draw_frame(stdscr, 0, 0, maxy, maxx - 1,
title_left=(str(tm.active_list), curses.A_BOLD),
title_right=(cat, _attr(col) | curses.A_BOLD))
if not n:
_add(stdscr, top, ix + 1, '(no tasks)', curses.A_DIM, right)
else:
iw = right - ix
for i in range(state.scroll_offset, min(n, state.scroll_offset + capacity)):
task = items[i]
row = top + (i - state.scroll_offset)
selected = i == state.selected
if selected: # category-tinted highlight bar
base = _attr(col) | curses.A_REVERSE
_add(stdscr, row, ix, ' ' * iw, base, right)
else:
base = 0
x = _add(stdscr, row, ix, ' %d ' % i, base, right)
x = _add(stdscr, row, x, task.title, base, right, ellipsis=True)
if task.status: # gap, then a colored pill (even on the bar)
x = _add(stdscr, row, x, ' ', base, right)
_add(stdscr, row, x, ' %s ' % task.status,
_pill_attr(task.status), right, ellipsis=True)
# Footer: other categories with counts, then a dim key hint.
others = ['%s (%d)' % (STYLE[m][0].lower(), len(tm.lists[m][LIST]))
for m in MODES if m != state.mode]
_add(stdscr, other_row, ix, 'other: ' + ' '.join(others), curses.A_DIM,
right, ellipsis=True)
_add(stdscr, hint_row, ix, _HINT, curses.A_DIM, right, ellipsis=True)
def _draw_detail(stdscr, task, index, mode, state):
"""Render a single task's detail screen (curses port of
render.render_task_detail): title, status, category, notes, footer hint.
Title/status/category stay pinned; one note is highlighted (the note
cursor, moved with Shift+Up/Down and PgUp/PgDn) and the notes region
scrolls to keep it visible, with a `[note sel / max]` marker."""
maxy, maxx = stdscr.getmaxyx()
label, col, glyph = STYLE[mode]
# Interior geometry (mirrors _draw_frame). Title/status/category stay pinned;
# notes scroll within [note_top, hint_row); the footer owns the last interior row.
iy, ix = 1, 2
right = maxx - 3
note_top = iy + 5
hint_row = maxy - 2
capacity = max(0, hint_row - note_top)
state.note_capacity = capacity # let the key loop page by a screenful
notes = task.notes
# Keep the highlighted note in range, then scroll the window so it stays
# visible (scroll-into-view, mirroring the list view's selection clamp).
if notes:
state.note_sel = max(0, min(state.note_sel, len(notes) - 1))
if capacity:
if state.note_sel < state.note_scroll:
state.note_scroll = state.note_sel
elif state.note_sel >= state.note_scroll + capacity:
state.note_scroll = state.note_sel - capacity + 1
state.note_scroll = max(0, min(state.note_scroll, max(0, len(notes) - capacity)))
else:
state.note_scroll = 0
else:
state.note_sel = state.note_scroll = 0
# Active category on the right of the rainbow border, with a marker showing
# which note is selected when there's more than one.
cat = '%s %s' % (glyph, label)
if notes and len(notes) > 1:
cat += ' [note %d / %d]' % (state.note_sel, len(notes) - 1)
_draw_frame(stdscr, 0, 0, maxy, maxx - 1,
title_left=('task %d' % index, curses.A_BOLD),
title_right=(cat, _attr(col) | curses.A_BOLD))
# Title: ▸ in the category color, '[idx] title' in bold.
x = _add(stdscr, iy, ix, '%s ' % glyph, _attr(col) | curses.A_BOLD, right)
_add(stdscr, iy, x, '[%d] %s' % (index, task.title), curses.A_BOLD, right,
ellipsis=True)
# status (colored pill)
x = _add(stdscr, iy + 2, ix, 'status: ', 0, right)
if task.status:
_add(stdscr, iy + 2, x, ' %s ' % task.status, _pill_attr(task.status),
right, ellipsis=True)
else:
_add(stdscr, iy + 2, x, '(none)', curses.A_DIM, right)
# category
x = _add(stdscr, iy + 3, ix, 'category: ', 0, right)
_add(stdscr, iy + 3, x, '%s %s' % (glyph, label.lower()), _attr(col), right)
# notes (the selected note row is reverse-highlighted)
if notes:
_add(stdscr, iy + 4, ix, 'notes:', 0, right)
for i in range(state.note_scroll, min(len(notes), state.note_scroll + capacity)):
row = note_top + (i - state.note_scroll)
selected = i == state.note_sel
base = curses.A_REVERSE if selected else 0
if selected: # full-width highlight bar across the interior
_add(stdscr, row, ix, ' ' * (right - ix), curses.A_REVERSE, right)
x = _add(stdscr, row, ix, '%d ' % i,
base if selected else curses.A_DIM, right)
_add(stdscr, row, x, notes[i], base, right, ellipsis=True)
else:
x = _add(stdscr, iy + 4, ix, 'notes: ', 0, right)
_add(stdscr, iy + 4, x, '(none)', curses.A_DIM, right)
_add(stdscr, hint_row, ix, _DETAIL_HINT, curses.A_DIM, right, ellipsis=True)
def _draw_help(stdscr):
"""Draw the help overlay: a top-left panel with a rainbow-gradient border
listing the keybindings in _HELP_KEYS, drawn as a solid overlay over whatever
screen is active (`fill`). Any key dismisses it. 'help' rides in the top rule."""
maxy, maxx = stdscr.getmaxyx()
keyw = max(len(k) for k, _ in _HELP_KEYS)
rows = ['%-*s %s' % (keyw, k, d) for k, d in _HELP_KEYS]
inner = max(len(' help '), max(len(r) for r in rows))
width = min(inner + 4, maxx - 1) # '│ ' ... ' │'
height = min(len(rows) + 2, maxy) # top rule (with title), rows, bottom rule
iy, ix, ih, iw = _draw_frame(stdscr, 0, 0, height, width,
title_left=('help', curses.A_BOLD), fill=True)
for i, r in enumerate(rows):
if i >= ih:
break
_add(stdscr, iy + i, ix, r, 0, ix + iw, ellipsis=True)
if height < maxy:
_add(stdscr, height, 0, 'press any key', curses.A_DIM, maxx - 1)
# Shift+Arrow CSI sequences (ESC [ 1 ; 2 X). The default xterm-256color keymap
# doesn't fold these into KEY_SR/KEY_SF, and this Python's curses lacks
# define_key, so _read_key decodes the bytes itself and yields the synthetic
# KEY_S* codes the loop already understands.
_CSI_SHIFT = {
'[1;2A': curses.KEY_SR, # Shift+Up
'[1;2B': curses.KEY_SF, # Shift+Down
'[1;2D': curses.KEY_SLEFT, # Shift+Left
'[1;2C': curses.KEY_SRIGHT, # Shift+Right
}
def _read_key(stdscr):
"""getch() plus a tiny decoder for the Shift+Arrow escape sequences above.
Most terminals' ncurses fold them into KEY_SR/KEY_SF directly (returned as
is); for the ones that don't, a bare ESC (27) triggers a non-blocking drain
of the follow-on bytes, and a recognized CSI sequence yields the matching
KEY_S* code. An unrecognized/empty sequence still reads as a real Esc."""
key = stdscr.getch()
if key != 27:
return key
stdscr.nodelay(True)
seq = ''
try:
for _ in range(6):
c = stdscr.getch()
if c == -1:
break
seq += chr(c)
if seq in _CSI_SHIFT:
return _CSI_SHIFT[seq]
finally:
stdscr.nodelay(False)
return 27 # real Esc (or an unrecognized sequence)
def _main_loop(stdscr, tm):
"""The curses event loop: draw, read a key, dispatch, until quit."""
curses.curs_set(0)
stdscr.keypad(True)
# Shorten the Esc hold-off (default ~1s): makes a lone Esc respond promptly
# and keeps _read_key's escape-sequence drain quick. Shift+Arrow bursts
# arrive whole, so the shorter delay doesn't truncate them.
try:
curses.set_escdelay(25)
except (curses.error, AttributeError):
pass
_init_colors()
state = _State(tm)
while True:
items = tm.lists[state.mode][LIST]
n = len(items)
# Re-clamp selection/scroll for the current category every iteration, so
# a shrunk list (delete/finish/switch) or a resize never leaves them
# pointing past the end. The per-screen draw refines the scroll window.
_clamp(state, items)
stdscr.erase()
if state.screen == 'detail' and n:
_draw_detail(stdscr, items[state.selected], state.selected,
state.mode, state)
else:
state.screen = 'list' # empty category can't stay in detail
_draw_list(stdscr, tm, state)
if state.show_help:
_draw_help(stdscr)
stdscr.refresh()
key = _read_key(stdscr)
# A resize just needs a redraw from the new geometry; don't let it
# dismiss the help overlay or reach an action handler.
if key == curses.KEY_RESIZE:
continue
# Help overlay swallows the next keypress to dismiss itself.
if state.show_help:
state.show_help = False
continue
if key == ord('?'):
state.show_help = True
continue
if state.screen == 'detail':
page = max(1, state.note_capacity)
if key in (curses.KEY_UP, ord('k')): # previous task (reset note cursor)
state.selected = max(0, state.selected - 1)
state.note_sel = state.note_scroll = 0
elif key in (curses.KEY_DOWN, ord('j')): # next task (reset note cursor)
state.selected = min(n - 1, state.selected + 1) if n else 0
state.note_sel = state.note_scroll = 0
elif key == curses.KEY_SR: # Shift+Up: select previous note
state.note_sel = max(0, state.note_sel - 1)
elif key == curses.KEY_SF: # Shift+Down: select next note
state.note_sel += 1 # (draw clamps to range)
elif key == curses.KEY_PPAGE: # PgUp: jump a screenful of notes
state.note_sel = max(0, state.note_sel - page)
elif key == curses.KEY_NPAGE: # PgDn: jump a screenful of notes
state.note_sel += page # (draw clamps to range)
elif key == ord('N'): # delete the highlighted note
task = items[state.selected] if n else None
if task and task.notes and _confirm(
stdscr, 'Delete note %d' % state.note_sel):
tm.remove_note(state.selected, state.note_sel, mode=state.mode)
elif key in (curses.KEY_LEFT, ord('h'), ord('b'), ord('B'),
ord('q'), ord('Q'), 27): # back to list; 27 = Esc
state.screen = 'list'
else:
_handle_action(stdscr, tm, state, key, items, n)
continue
# list screen
if key in (curses.KEY_UP, ord('k')):
state.selected = max(0, state.selected - 1)
elif key in (curses.KEY_DOWN, ord('j')):
state.selected = min(n - 1, state.selected + 1) if n else 0
elif key in (curses.KEY_LEFT, ord('h')):
state.mode = MODES[(MODES.index(state.mode) - 1) % len(MODES)]
tm.set_mode(state.mode)
state.selected = 0
elif key in (curses.KEY_RIGHT, ord('l'), ord('\t')):
state.mode = MODES[(MODES.index(state.mode) + 1) % len(MODES)]
tm.set_mode(state.mode)
state.selected = 0
elif key in (curses.KEY_ENTER, ord('\n'), ord('\r')):
if n:
state.screen = 'detail'
state.note_sel = state.note_scroll = 0
elif key in (ord('q'), ord('Q'), 27): # 27 = Esc
return
else:
_handle_action(stdscr, tm, state, key, items, n)
def run(tm):
"""Run the curses TUI. Returns 0 on a clean exit -- including Ctrl-C, which
quits quietly like 'q' rather than surfacing a traceback -- or None if the
TUI can't run (non-TTY / curses unavailable) so the caller can fall back.
curses.wrapper restores the terminal before any exception propagates here,
so the screen is already sane by the time we catch."""
if not sys.stdout.isatty():
return None
try:
curses.wrapper(_main_loop, tm)
except curses.error:
return None
except KeyboardInterrupt:
pass # Ctrl-C: exit cleanly, same as quitting
return 0