Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
527 lines (484 loc) · 19 KB
/
Copy pathmain.py
File metadata and controls
527 lines (484 loc) · 19 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
import curses
import os
import json
import sys
from re import T
from typing import cast
from task import Task, TaskManager, serialize_task
from envutils import ADict
EVENTS = [
"next task",
"prev task",
"quit",
"force quit",
"toggle task",
"help menu",
"rename task",
"add task",
"delete task",
"force delete task",
"save tasks",
"move task",
"special:arrow pressed",
"command",
"trash menu",
]
settings = ADict(
keybindings={
"q": ["quit"],
"Q": ["force quit"],
" ": ["toggle task"],
"h": ["help menu"],
"r": ["rename task"],
"a": ["add task"],
"d": ["delete task"],
"D": ["force delete task"],
"s": ["save tasks"],
"t": ["trash menu"],
":": ["command"],
"e": ["command"],
10: ["move task"],
"f": ["move task"],
"j": ["next task"],
"k": ["prev task"],
curses.KEY_DOWN: ["next task", "special:arrow pressed"],
curses.KEY_UP: ["prev task", "special:arrow pressed"],
},
use_colors=True,
show_old_name_mode="next to", # ["shadow", "next to", "none"]
show_help_message=True,
show_current_mode=True,
prompt_unsaved=True,
prompt_delete=True,
show_index=True,
info=ADict(
description=True,
created_at=True,
modified_at=True,
)
)
class Application:
def __init__(self) -> None:
self.rename_mode = False
self.move_mode = False
self.command_mode = False
self.trash_mode = False
self.save_path = os.path.join(os.path.expanduser("~"),".config/tertask/tasks.json")
self.load()
self.custom_message = ""
self.custom_type = "info"
def load(self) -> None:
save_exists = os.path.exists(self.save_path)
self.create_folder_if_missing(os.path.dirname(self.save_path))
self.tm = TaskManager()
if save_exists:
data = self.open_json(self.save_path)
self.tm.load_serialized_tasks(data)
def save(self) -> None:
with open(self.save_path, "w") as f:
f.truncate(0)
f.write(json.dumps([serialize_task(task) for task in self.tm._tasks]))
def keyevent(self, key: str | int) -> list[str]:
for skey in settings.keybindings:
actions_to_return = []
for actions in settings.keybindings[skey]:
is_int = isinstance(skey, int)
if is_int and key == skey: actions_to_return.append(actions)
if not is_int and key == ord(skey): actions_to_return.append(actions)
if actions_to_return: return actions_to_return
return [""]
def show_help(self, page: int=1) -> None:
self.stdscr.clear()
self.stdscr.addstr(1, 2, " Help Menu - Press 'q' to return ", curses.A_BOLD | curses.A_REVERSE)
self.stdscr.addstr(2, 2, " (c)ommands, (k)eybindings ", curses.A_BOLD)
mode = "Help"
if page == 1: mode = "Help — Commands"
if page == 2: mode = "Help — Keybindings"
if settings.show_current_mode: self.add_string(mode, self.width - (len(mode)+1), self.height - 1, curses.color_pair(4), move=False)
if page == 1:
text = [
" : — Open command line",
" ---------------------------------------",
" q — quit",
" q! — quit without saving",
" w — save tasks",
" wq — save tasks and quit",
" export <file> — export tasks to file",
" rename | rn <name...> — rename task",
" delete | del | d <task id> — delete task",
" describe | desc <desc...> — set task description",
" run <python code> — run python code",
" move mode | mm — move task",
" a | add — add task",
" h | help — show this help menu",
" recover | rev <task id> — recover a deleted task",
" burn <task id> — delete a task forever",
]
self.stdscr.addstr(4, 2, " Commands: ", curses.A_BOLD)
self.stdscr.addstr(5, 4, "\n ".join(text))
elif page == 2:
for idx, (key, action) in enumerate(settings.keybindings.items(), start=4):
rebindings = {
" ": "Space",
258: "↓",
259: "↑",
10: "⏎",
}
if key in rebindings:
key = rebindings[key]
self.stdscr.addstr(idx, 4, f"{str(key).ljust(10, ' ')}| {" - ".join(action)}")
key = self.stdscr.getch()
if key == ord("q"):
return
elif key == ord("c"):
self.show_help(1)
elif key == ord("k"):
self.show_help(2)
else:
self.show_help()
def render(self, only_render: bool=False) -> None:
self.stdscr.clear()
# Trash menu
if self.trash_mode:
self.stdscr.addstr(1, 2, " Trash Menu - Press 't' to return ", curses.A_BOLD | curses.A_REVERSE)
if not self.tm.deleted_tasks:
self.stdscr.addstr(2, 2, "No deleted tasks available.")
else:
self.stdscr.addstr(2, 2, "use :recover <task id> to recover a task or :burn <task id> to delete a task forever")
for idx, task in enumerate(self.tm.deleted_tasks):
task = cast(Task, task) # convert to Task object
x = 2
y = 3 + idx
is_completed_attr = curses.color_pair(2) if task.completed else curses.A_NORMAL
self.draw_task(x, y, task, attr=is_completed_attr)
self.add_string(f"{task.index} {task.mark} {task.title} — {task.description:20}", x, y, curses.color_pair(3))
return
# Task list
for idx, task in enumerate(self.tm.tasks):
task = cast(Task, task) # convert to Task object
x = 2
y = 2 + idx
is_completed_attr = curses.color_pair(2) if task.completed else curses.A_NORMAL
if idx == self.tm.selected:
if self.rename_mode and not only_render:
self.render(only_render=True)
new_name = ""
if settings.show_old_name_mode == "next to":
new_name = self.input(x, y, f"{task.mark} {task.title} → ", curses.color_pair(1))
elif settings.show_old_name_mode == "shadow":
self.add_string(f"{task.mark} {task.title}", x, y, curses.color_pair(5))
new_name = self.input(x, y, f"{task.mark} ", curses.color_pair(3))
elif settings.show_old_name_mode == "none":
self.add_string(" " * len(f"{task.mark} {task.title}"), x, y, curses.color_pair(5))
new_name = self.input(x, y, f"{task.mark} ", curses.color_pair(3))
if new_name: task.title = new_name
self.rename_mode = False
self.render()
break
elif self.move_mode and not only_render:
self.render(only_render=True)
self.add_string(f" ↕ {task.mark} {task.title}", x, y, curses.color_pair(1))
key = self.stdscr.getch()
actions = self.check_keys(key, whitelist=["next task", "prev task", "special:arrow pressed", "move task"], use_whitelist=True)
move_dir = 1 if "next task" in actions else -1
if "special:arrow pressed" in actions:
self.tm.move_task(self.tm.selected, self.tm.selected + move_dir)
self.move_mode = "move task" not in actions
self.render()
break
else:
self.draw_task(x, y, task, selected=True)
if not settings.use_colors:
self.draw_task(x, y, task, selected=True, attr=curses.A_REVERSE)
string = f"{task.mark} {task.title}"
if settings.show_index:
string += f" == {task.index}"
self.add_string(string, x, y, curses.color_pair(3))
else: self.draw_task(x, y, task, attr=is_completed_attr)
if len(self.tm.tasks) == 0:
# if no tasks exist
first_keybind_add_task = [keybind for keybind in settings.keybindings if settings.keybindings[keybind] == "add task"][0]
self.stdscr.addstr(2, 2, f"No tasks available. Press '{first_keybind_add_task}' to add a new task.")
# Top bar
title = " TerTask - 'h' for help ".ljust(self.width, " ")
if not settings.show_help_message:
title = " TerTask ".ljust(self.width, " ")
self.stdscr.addstr(0, 0, title, curses.A_BOLD)
self.stdscr.addstr(1, 0, "─" * self.width)
color = curses.color_pair(1)
if self.custom_type == "info": color = curses.color_pair(3)
elif self.custom_type == "warning": color = curses.color_pair(4)
elif self.custom_type == "error": color = curses.color_pair(6)
self.stdscr.addstr(0, self.width - len(self.custom_message) - 1, self.custom_message, color)
# Bottom bar
mode = "Normal"
if self.rename_mode: mode = "Rename"
elif self.move_mode: mode = "Move"
elif self.command_mode: mode = "Command"
elif self.trash_mode: mode = "Trash"
if settings.show_current_mode: self.add_string(mode, self.width - (len(mode)+1), self.height - 1, curses.color_pair(4), move=False)
# Description panel
self.stdscr.addstr(self.height - 7, 0, "─" * self.width)
if settings.info.description:
self.stdscr.addstr(self.height - 6, 2, "Description: ")
self.stdscr.addstr(self.height - 5, 2, self.tm.current_task.description)
# Footer with created/modified info
if settings.info.created_at: self.stdscr.addstr(self.height - 3, 2, f"Created: {self.tm.current_task.created_at} ")
if settings.info.modified_at: self.stdscr.addstr(self.height - 2, 2, f"Modified: {self.tm.current_task.modified_at} ")
def main_loop(self, stdscr: curses.window) -> None:
self.stdscr = stdscr
self.run_control_sequence(f"\x1b[\x36 q")
curses.curs_set(0)
curses.start_color()
curses.use_default_colors()
self.stdscr.keypad(True)
self.render()
# Colors
if settings.use_colors:
curses.init_pair(1, 208, -1) # edit mode
curses.init_pair(2, curses.COLOR_GREEN, -1) # Completed task
curses.init_pair(3, curses.COLOR_BLUE, -1) # Selected task
curses.init_pair(4, 208, -1) # message
curses.init_pair(5, 238, -1) # shadow
curses.init_pair(6, 196, -1) # red
else:
curses.init_pair(1, curses.COLOR_WHITE, -1) # edit mode
curses.init_pair(2, 238, -1) # Completed task
curses.init_pair(3, curses.COLOR_WHITE, -1) # Selected task
curses.init_pair(4, curses.COLOR_WHITE, -1) # message
curses.init_pair(5, 235, -1) # shadow
curses.init_pair(6, curses.COLOR_WHITE, -1) # red
try:
while True:
self.tm.max_items = self.height - 9
self.render()
key = self.stdscr.getch()
self.custom_message = ""
self.custom_type = "info"
whitelist = []
use_whitelist = True if self.rename_mode or self.move_mode else False
if self.rename_mode:
whitelist = ["rename task"]
if self.move_mode:
whitelist = ["move task"]
actions = self.check_keys(key, whitelist=whitelist, use_whitelist=use_whitelist)
self.handle_actions(actions)
except Exception as e:
print("Unexpected error:", e)
print("Do you want to save your tasks? (Y/n) ", end="")
if input().lower() != "n": self.save()
def handle_actions(self, actions: list[str], extended: bool=False, only_extended: bool=False) -> None:
for action in actions:
if not only_extended:
if action == "rename task":
self.rename_mode = True
elif action == "move task":
self.move_mode = True
elif action == "prev task":
self.tm.prev()
elif action == "next task":
self.tm.next()
elif action == "quit":
if not self.has_saved_tasks() and settings.prompt_unsaved:
if self.prompt(2, self.height - 1, "You have unsaved tasks. Do you want to save them? (Y/n) ", curses.color_pair(1), True).lower() != "n": self.save()
exit(0)
elif action == "force quit":
self.save()
exit(0)
elif action == "toggle task":
self.tm.current_task.toggle()
elif action == "add task":
self.tm.add("New Task")
self.tm.select_task(-1)
self.rename_mode = True
elif action == "delete task":
if settings.prompt_delete:
if self.prompt(2, self.height - 1, "Are you sure? (y/N) ", curses.color_pair(1), True).lower() != "y": break
self.tm.delete_current_task()
elif action == "force delete task":
self.tm.delete_current_task()
elif action == "save tasks":
self.custom_message = "Saved tasks..."
self.save()
elif action == "command":
self.command_mode = True
self.render(only_render=True)
cmd = self.input(2, self.height - 1, ": ", curses.color_pair(1), -1, placeholder="help - to open help menu")
self.handle_actions([cmd], True, True)
self.command_mode = False
elif action == "help menu":
self.show_help()
elif action == "trash menu":
self.trash_mode = not self.trash_mode
self.tm.selected = 0
self.render()
if extended:
actions = action.split(" ")
action = actions[0]
match action:
case "q":
if not self.has_saved_tasks() and settings.prompt_unsaved:
if self.prompt(2, self.height - 1, "You have unsaved tasks. Are you sure? (y/N) ", curses.color_pair(1), True).lower() != "y": break
exit(0)
case "q!":
exit(0)
case "w":
self.save()
self.custom_message = "Saved tasks..."
case "wq" | "qw":
self.save()
exit(0)
case "export":
if len(actions) == 2:
self.custom_message = "Exporting tasks..."
self.custom_type = "info"
with open(actions[1], "w") as f:
f.truncate(0)
f.write(json.dumps([serialize_task(task) for task in self.tm._tasks]))
else:
self.custom_type = "error"
self.custom_message = "Error: missing argument -> :export <file>"
case "rename" | "rn":
if len(actions) > 1:
self.custom_message = f"Renamed task '{self.tm.current_task.title}' to '{" ".join(actions[1:])}'."
self.custom_type = "info"
self.tm.current_task.title = " ".join(actions[1:])
else:
self.custom_type = "error"
self.custom_message = "Error: missing argument -> :rename <new name...>"
case "delete" | "d" | "del":
if len(actions) > 1:
self.custom_message = f"Deleted task '{self.tm.get(int(actions[1])).title}'."
self.custom_type = "info"
self.tm.delete_task(int(actions[1]))
else:
self.custom_message = f"Deleted task '{self.tm.current_task.title}'."
self.custom_type = "info"
self.tm.delete_current_task()
case "move mode" | "mm":
self.move_mode = True
case "a" | "add":
if len(actions) > 1:
self.custom_message = f"Added task '{' '.join(actions[1:])}'"
self.custom_type = "info"
self.tm.add(" ".join(actions[1:]))
self.tm.select_task(-1)
else:
self.custom_message = f"Added task 'New Task'"
self.custom_type = "info"
self.tm.add("New Task")
self.tm.select_task(-1)
self.rename_mode = True
case "":
pass
case "h" | "help":
self.show_help()
case "describe" | "desc":
if len(actions) > 1:
self.custom_message = f"Set Description for Task."
self.custom_type = "info"
self.tm.current_task.description = " ".join(actions[1:])
else:
self.custom_type = "error"
self.custom_message = "Error: missing argument -> :describe <new description...>"
case "run":
if len(actions) > 1:
self.custom_message = f"Executed Python Code."
self.custom_type = "info"
def info(*args: str): self.custom_message = " ".join([str(arg) for arg in args])
try:
exec(" ".join(actions[1:]), {"tasks": self.tm.tasks, "deleted_tasks": self.tm.deleted_tasks, "current_task": self.tm.current_task, "tm": self.tm, "info": info, "delete": self.tm._remove, "tasks_len": len(self.tm.tasks.copy())})
except Exception as e:
self.custom_type = "error"
self.custom_message = f"Error: {e}"
else:
self.custom_type = "error"
self.custom_message = "Error: missing argument -> :run <python code...>"
case "recover" | "rev":
try:
task_id = int(actions[1])
for task in self.tm.deleted_tasks:
if task.index == task_id:
task.restore()
self.tm._index_tasks()
self.render()
return
self.custom_type = "error"
self.custom_message = "Task not found"
except (IndexError, ValueError):
self.custom_type = "error"
self.custom_message = "Invalid task ID"
case "burn":
try:
task_id = int(actions[1])
for idx, task in enumerate(self.tm._tasks):
if task.index == task_id:
self.tm._tasks.pop(idx)
self.render()
return
self.custom_type = "error"
self.custom_message = "Task not found"
except (IndexError, ValueError):
self.custom_type = "error"
self.custom_message = "Invalid task ID"
return
case _:
self.custom_type = "error"
self.custom_message = "Error: unknown command"
def check_keys(self, key: int, blacklist: list[str]=[], whitelist: list[str]=[], use_whitelist: bool=False) -> list[str]:
actions = []
for action in EVENTS:
is_not_disabled = (action not in blacklist) if not use_whitelist else (action in whitelist)
actions.append(action) if action in self.check_key(key, action, is_not_disabled) else None
return actions if len(actions) != 0 else [] # return empty list if no actions are found
def request_input(self) -> None:
curses.curs_set(2)
curses.echo()
def stop_input(self) -> None:
curses.curs_set(0)
curses.noecho()
def run_control_sequence(self, sequence: str) -> None:
os.write(sys.stdout.fileno(), bytes(sequence, 'utf-8'))
def draw_task(self, x: int, y: int, task: Task, selected: bool=False, attr: int=curses.A_NORMAL) -> None:
self.stdscr.addstr(y, x, f"{task.mark} {str(task.title)}", curses.color_pair(3) | attr if selected else attr)
def check_key(self, key: int, action: str, is_not_disabled: bool) -> list[str]:
return self.keyevent(key) if (action in self.keyevent(key) and is_not_disabled) else [""]
def create_folder_if_missing(self, path: str) -> None:
if not os.path.exists(path): os.makedirs(path)
def open_json(self, path: str) -> list[dict]:
with open(path, "r") as f:
return json.load(f)
def has_saved_tasks(self) -> bool:
old_tasks = self.open_json(self.save_path)
new_tasks = [serialize_task(task) for task in self.tm._tasks]
return str(old_tasks) == str(new_tasks)
def input(self, x: int, y: int, prompt_string: str, attr: int, starting_offset: int=0, offset: int=3, prompt_attr: int=curses.A_NORMAL, placeholder: str="", placeholder_attr: int|None=None) -> str:
self.add_string(prompt_string, x, y, attr)
self.request_input()
self.stdscr.attron(prompt_attr)
if placeholder_attr is None: placeholder_attr = curses.color_pair(5)
self.add_string(placeholder, x + len(prompt_string) + starting_offset, y, placeholder_attr, offset)
answer = self.stdscr.getstr(y, x + len(prompt_string) + starting_offset, self.width - len(prompt_string) - offset).decode("utf-8")
self.stdscr.attroff(prompt_attr)
self.stop_input()
return answer
def prompt(self, x: int, y: int, prompt_string: str, attr: int, use_char: bool=False, starting_offset: int=0) -> str:
if use_char: return self.inputch(x, y, prompt_string, attr, starting_offset)
return self.input(x, y, prompt_string, attr, starting_offset)
def inputch(self, x: int, y: int, prompt_string: str, attr: int, starting_offset: int=0) -> str:
self.add_string(prompt_string, x, y, attr)
self.request_input()
answer = self.stdscr.getch(y, x + len(prompt_string) + starting_offset)
self.stop_input()
return chr(answer)
def add_string(self, string: str, x: int, y: int, attr: int=curses.A_NORMAL, offset: int=0, move: bool=True) -> None:
self.stdscr.addstr(y, x, string, attr)
if move: self.stdscr.move(y, x + len(string) + offset)
self.stdscr.refresh()
@property
def height(self) -> int: return self.stdscr.getmaxyx()[0]
@property
def width(self) -> int: return self.stdscr.getmaxyx()[1]
if __name__ == "__main__":
app = Application()
curses.wrapper(app.main_loop)