-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
693 lines (517 loc) · 17.5 KB
/
main.py
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
import json
from dataclasses import dataclass, asdict
import datetime
import dacite
import curses
from curses import wrapper
from curses.textpad import Textbox, rectangle
from enum import IntEnum
import sys
import copy
import asyncio
from desktop_notifier import DesktopNotifier
#test
offset = 0
class Window(IntEnum):
main = 0
templates = 1
class ColumnType(IntEnum):
description = 0
start = 1
requested_time = 2
assigned_time = 3
@dataclass
class SubSlot:
start: int
reqtime: int
assigned: int
fixed_time: bool
fixed_length: bool
description: str
@dataclass
class Slot:
start: int
reqtime: int
assigned: int
fixed_time: bool
fixed_length: bool
description: str
subslots: list[SubSlot]
@dataclass
class Template:
name: str
total_time: int
start: int
slots: list[Slot]
@dataclass
class Day:
date: str
total_time: int
start: int
slots: list[Slot]
@dataclass
class SlotBlock:
startindex: int
endindex: int
blocklength: int
fixedtime: int
reqtime: int
ratio: float
@dataclass
class Config:
default_minutes: int
desclimit: int
autosave: bool
@dataclass
class Mainclass:
config: Config
days: list[Day]
@dataclass
class Row:
selected: int
previous: int
current: int
bottom: int
@dataclass
class Column:
selected: int
maxindex = len(ColumnType) - 1
def current_minutes() -> int:
now = datetime.datetime.now()
return now.hour * 60 + now.minute
def min_to_time(mins: int) -> str:
hrs = mins // 60
mins = mins - hrs * 60
hrs = str(hrs).rjust(2, "0")
mins = str(mins).rjust(2, "0")
return f"{hrs}:{mins}"
def intput(prompt: str, lower=float("-inf"), upper=float("inf"))-> int:
assert isinstance(prompt, str)
while True:
try:
value = int(input(prompt))
except:
print("invalid int")
continue
if not lower <= value <= upper:
print("input out of bounds")
continue
return value
def calibrate_subslots(subslots, start, end):
pass
def get_slotblocks(slots, end):
slotblocks = []
for index, slot in enumerate(slots):
if not index or slot.fixed_time:
slotblock = SlotBlock(index, 0, 0, 0, 0, 0)
if slot.fixed_length:
slotblock.fixedtime += slot.reqtime
else:
slotblock.reqtime += slot.reqtime
is_finalslot = index + 1 == len(slots)
if is_finalslot or (nextslot := slots[index+1]).fixed_time:
blockstart = slots[slotblock.startindex].start
blockend = end if is_finalslot else nextslot.start
slotblock.endindex = index + 1
slotblock.blocklength = blockend - blockstart
slotblock.ratio = (slotblock.blocklength - slotblock.fixedtime) / slotblock.reqtime
slotblocks.append(slotblock)
return slotblocks
def calibrate_slots(day):
slots = day.slots
slots[0].start = day.start
end_of_day = day.total_time + day.start
slotblocks = get_slotblocks(slots, end_of_day)
for slotblock in slotblocks:
starttime = slots[slotblock.startindex].start
for i in range(slotblock.startindex, slotblock.endindex):
slot = slots[i]
slot.start = starttime
slot.assigned = slot.reqtime if slot.fixed_length else int(slot.reqtime * slotblock.ratio)
starttime = slot.start + slot.assigned
for slot in slots:
if slot.subslots:
calibrate_subslots(slot.subslots, slot.start, slot.start + slot.assigned)
def newslots(day, index):
newslot = Slot(-1, mainclass.config.default_minutes, -1, False, False, "___", [])
day.slots.insert(index + 1, newslot)
def template_to_day(template: Template, today)-> Day:
newslot = Slot(
template.start,
1,
-1,
False,
False,
"___",
)
newday = Day(
today,
template.total_time,
template.start,
[Slot(
0,
reqtime,
0,
False,
False,
"...",
[],
)]
)
return newday
def fetch_current_day(mainclass: Mainclass, offset=0) -> Day:
today = str((datetime.datetime.now() + datetime.timedelta(days=offset)).date())
for day in mainclass.days:
print(day.date, today)
if day.date == today:
return day
newday = Day(
today,
16*60,
450,
[Slot(
0,
1,
0,
False,
False,
"...",
[],
)]
)
mainclass.days.append(newday)
return newday
def get_cols(slot):
lim = mainclass.config.desclimit
desc = slot.description.ljust(lim," ")[:lim]
if desc[-1] != " ":
desc = desc[:-3:] + "..."
start = min_to_time(slot.start).ljust(8, " ")
req = str(slot.reqtime).ljust(4," ")
ass = str(slot.assigned).ljust(4, " ")
return desc, start, req, ass
def edit_description(screen, day, index):
desc = []
screen.move(index+1, 0)
while True:
try:
keypressed = screen.getkey()
except:
continue
if keypressed == "\n":
day.slots[index].description = ''.join(desc)
return
elif keypressed in ('KEY_BACKSPACE', '\b', '\x7f'):
if not desc: continue
y, x = screen.getyx()
screen.move(index+1, x-1)
screen.addstr(" ")
screen.move(index+1, x-1)
desc.pop()
elif keypressed.isalnum() or keypressed == " ":
screen.addstr(keypressed)
desc.append(keypressed)
else:
screen.addstr(keypressed)
def edit_requested_time(screen, day, index, column, num):
while True:
match (keypressed := screen.getkey()):
case '\n':
day.slots[index].reqtime = int(num)
if column == ColumnType.assigned_time:
day.slots[index].fixed_length = True
return
case 'KEY_EXIT':
return
case _:
if keypressed.isnumeric():
num += keypressed
def int_format_time(num):
if len(num) == 3:
hrs = int(num[0])
mins = int(num[1::])
else:
hrs = int(num[:2:])
mins = int(num[2::])
return hrs * 60 + mins
def debuglol(screen, var):
var = str(var)
screen.move(0,0)
screen.addstr(var)
screen.getch()
def edit_start_time(screen, day, index, num):
while True:
keypressed = screen.getkey()
if keypressed.isnumeric():
num += keypressed
if len(num) == 4:
day.slots[index].start = int_format_time(num)
return
if keypressed == '\n':
if len(num) == 3:
day.slots[index].start = int_format_time(num)
return
return
if keypressed == 'KEY_EXIT':
return
def save_to_file(mainclass):
with open('db.json', 'w') as fp:
json.dump(asdict(mainclass), fp)
async def not_func(msg: tuple[str, str]):
notify = DesktopNotifier()
title, message = msg
n = await notify.send(title=title + message, message=" ")
await asyncio.sleep(10) # wait a bit before clearing notification
await notify.clear(n) # removes the notification
await notify.clear_all() # removes all notifications for this app
def view_rows(screen, day, row, column):
screen.clear()
screen.addstr("viewing day " + str(day.date))
slot_qty = row.bottom + 1
line_index = 0
for row_index, _row in enumerate(day.slots):
screen.move(line_index + 1, 0)
for col_index, _column in enumerate(get_cols(day.slots[row_index])):
attributes = 0
if col_index == ColumnType.start and _row.fixed_time == True:
attributes |= curses.A_BOLD
if col_index == ColumnType.requested_time and _row.fixed_length == True:
attributes |= curses.A_BOLD
if row_index == row.selected and col_index == column.selected:
attributes |= curses.A_STANDOUT
screen.addstr(_column, attributes)
if slot_qty >= line_index + 1 and offset == 0:
if _row.start <= current_minutes():
if line_index + 1 == slot_qty or current_minutes() < day.slots[line_index + 1].start:
screen.addstr("🕑")
row.current = row_index
if _row.subslots:
for subslot in _row.subslots:
line_index += 1
screen.move(line_index + 1, 0)
screen.addstr(" ↳ ")
for i, x in enumerate(get_cols(subslot)):
if not i:
x = x[:-5:]
screen.addstr(x)
line_index += 1
screen.refresh()
curses.curs_set(0)
def split(screen, day, row):
if not (somevar := screen.getkey()).isnumeric():
return
somevar = int(somevar)
reqtime = day.slots[row].reqtime // somevar
for _ in range(somevar):
newslot = Slot(
0,
reqtime,
0,
False,
False,
"...",
[],
)
day.slots[row].subslots.append(newslot)
def handle_main_keys(screen, row, column):
global selected_day
global offset
change = True
selected_slot = selected_day.slots[row.selected]
try:
keypressed = screen.getkey()
except Exception as e:
if row.previous is not None and row.previous != row.current:
msg = "Start new task!: ", selected_day.slots[row.current].description
asyncio.run(not_func(msg))
row.previous = row.current
return
match keypressed:
case "KEY_DOWN" | "j":
if row.selected != row.bottom:
row.selected += 1
change = False
case "KEY_UP" | "k":
if row.selected != 0:
row.selected -= 1
change = False
case "KEY_LEFT" | "h":
if column.selected != 0:
column.selected -= 1
change = False
case "KEY_RIGHT" | "l":
if column.selected != column.maxindex:
column.selected += 1
change = False
# insert new slot
case "i":
newslots(selected_day, row.selected)
row.selected += 1
row.bottom += 1
calibrate_slots(selected_day)
# supposedly insert slot above current
case "I":
newslots(selected_day, row.selected)
row.selected += 1
row.bottom += 1
calibrate_slots(selected_day)
# begin task now
case "b":
selected_slot.start = current_minutes()
selected_slot.fixed_time = True
selected_day.slots[row.selected - 1].fixed_length = False
calibrate_slots(selected_day)
# duplicate task
case "d":
row.selected += 1
row.bottom += 1
newslot = copy.deepcopy(selected_slot)
selected_day.slots.insert(row.selected, newslot)
calibrate_slots(selected_day)
case "D":
halftime = selected_day.slots[row.selected].reqtime // 2
copiedslot = copy.deepcopy(selected_day.slots[row.selected])
selected_day.slots[row.selected].reqtime = halftime
copiedslot.reqtime = halftime
copiedslot.fixed_time = False
selected_day.slots.insert(row.selected, copiedslot)
row.selected += 1
row.bottom +=1
calibrate_slots(selected_day)
case "s":
save_to_file(mainclass)
# go to current slot by time
case "e":
row.selected = row.current
case "t":
pass
# fill time or something
case "z":
selected_day.slots[row.selected].reqtime = selected_day.slots[row.selected].assigned
case "x":
split(screen, selected_day, row.selected)
case "r":
if row.selected:
prevslot = selected_day.slots[row.selected - 1]
if not (prevslot.fixed_time and selected_slot.fixed_time):
selected_day.slots[row.selected], selected_day.slots[row.selected - 1] = selected_day.slots[row.selected - 1], selected_day.slots[row.selected]
row.selected -= 1
calibrate_slots(selected_day)
case "f":
if row.selected != len(selected_day.slots) - 1:
nextslot = selected_day.slots[row.selected + 1]
if not (nextslot.fixed_time and selected_slot.fixed_time):
selected_day.slots[row.selected], selected_day.slots[row.selected + 1] = selected_day.slots[row.selected + 1], selected_day.slots[row.selected]
row.selected += 1
calibrate_slots(selected_day)
case "m":
offset += 1
selected_day = fetch_current_day(mainclass, offset=offset)
row.bottom = len(selected_day.slots) - 1
row.selected = 0
calibrate_slots(selected_day)
case "n":
offset -= 1
selected_day = fetch_current_day(mainclass, offset=offset)
row.bottom = len(selected_day.slots) - 1
row.selected = 0
calibrate_slots(selected_day)
case "M":
offset += 7
selected_day = fetch_current_day(mainclass, offset=offset)
row.bottom = len(selected_day.slots) - 1
row.selected = 0
calibrate_slots(selected_day)
case "N":
offset -= 7
selected_day = fetch_current_day(mainclass, offset=offset)
row.bottom = len(selected_day.slots) - 1
row.selected = 0
calibrate_slots(selected_day)
case "KEY_DC":
del selected_day.slots[row.selected]
row.bottom -= 1
if row.bottom == -1:
newslots(selected_day, 0)
row.selected = 0
row.bottom = 0
if row.selected == row.bottom + 1:
row.selected -= 1
selected_day.slots[row.selected].fixed_length = False
calibrate_slots(selected_day)
case "KEY_HOME" | "KEY_PPAGE":
row.selected = 0
case "KEY_END" | "KEY_NPAGE":
row.selected = row.bottom
case "\n": # enter-key
match column.selected:
case ColumnType.assigned_time | ColumnType.requested_time:
if not (row.selected == row.bottom and selected_slot.fixed_time):
selected_slot.fixed_length = not selected_slot.fixed_length
case ColumnType.start:
selected_slot.fixed_time = not selected_slot.fixed_time
selected_day.slots[row.selected - 1].fixed_length = False
case ColumnType.description:
edit_description(screen, selected_day, row.selected)
calibrate_slots(selected_day)
case wildcard:
if wildcard.isnumeric():
match column.selected:
case ColumnType.requested_time | ColumnType.assigned_time:
edit_requested_time(screen, selected_day, row.selected, column.selected, wildcard)
calibrate_slots(selected_day)
case ColumnType.start:
edit_start_time(screen, selected_day, row.selected, wildcard)
if row.selected:
selected_day.slots[row.selected].fixed_time = True
selected_day.slots[row.selected - 1].fixed_length = False
else:
selected_day.start = selected_day.slots[row.selected].start
calibrate_slots(selected_day)
if change and mainclass.config.autosave:
save_to_file(mainclass)
def view_main(stdscr, mainclass):
# global selected_day
column = Column(0)
row = Row(0, None, None, 0)
row.bottom = len(selected_day.slots) - 1
stdscr.clear()
curses.halfdelay(150)
while True:
view_rows (stdscr, selected_day, row, column)
handle_main_keys(stdscr, row, column)
filename = 'db.json'
content = """{
"config": {
"default_minutes": 30,
"desclimit": 30,
"autosave": true
},
"days": []
}
"""
try:
with open(filename, 'x') as file:
file.write(content)
print(f"Created a new file: {filename}")
except FileExistsError:
print(f"File {filename} already exists.")
loaded_dict = {}
try:
with open('db.json') as f:
loaded_dict = json.load(f) # Use json.load instead of json.loads in a loop
mainclass = dacite.from_dict(data_class=Mainclass, data=loaded_dict)
print("maybe no exception!")
except SyntaxError as e:
print("exception!!!", e)
sys.exit(e)
def main(stdscr):
window = Window.main
while True:
match window:
case Window.main:
window = view_main(stdscr, mainclass)
case Window.templates:
sys.exit("template test")
selected_day = fetch_current_day(mainclass)
wrapper(main)