-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.py
More file actions
executable file
·561 lines (478 loc) · 21.5 KB
/
Copy pathtimer.py
File metadata and controls
executable file
·561 lines (478 loc) · 21.5 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
#!/usr/bin/python3
"""Tray app and CLI on top of worklog.py / store.py."""
import os
import re
from datetime import date, datetime, timedelta
import store
import worklog
# GtkStatusIcon (MATE's Notification Area applet) renders hover tooltips and
# Pango markup; the AppIndicator backend renders neither. Overridable via env.
os.environ.setdefault("PYSTRAY_BACKEND", "gtk")
# Pin GTK 3 up front: gi otherwise defaults to GTK 4, but this app's widgets
# (and pystray's gtk backend) are GTK 3. require_version only records the
# constraint, so the CLI paths that never import Gtk stay display-free.
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
# Tango palette, medium row first then the light row for overflow. Cycled per
# distinct task so each task keeps one colour across the bar and the legend.
TANGO = [
(0x34, 0x65, 0xa4), # sky blue
(0x73, 0xd2, 0x16), # chameleon
(0xf5, 0x79, 0x00), # orange
(0x75, 0x50, 0x7b), # plum
(0xcc, 0x00, 0x00), # scarlet
(0xc1, 0x7d, 0x11), # chocolate
(0xed, 0xd4, 0x00), # butter
(0x72, 0x9f, 0xcf), # sky blue light
(0x8a, 0xe2, 0x34), # chameleon light
(0xfc, 0xaf, 0x3e), # orange light
(0xad, 0x7f, 0xa8), # plum light
]
def task_colors(tasks):
"""Map each distinct task name to a Tango RGB triple (0..1), in first-seen
order so the bar and legend agree."""
seen = dict.fromkeys(tasks)
return {task: tuple(c / 255 for c in TANGO[i % len(TANGO)])
for i, task in enumerate(seen)}
def project_code(task):
"""Two-letter project prefix of a task token (e.g. 'di-321' -> 'DI'), or
None for tokens without such a code (a plain word like 'unfolder')."""
code = worklog.project(task) if task else ""
return code.upper() if len(code) == 2 and code.isalpha() else None
# Ubuntu ships as one variable font, so ask for its Bold instance.
_UBUNTU_FONT = "/usr/share/fonts/truetype/ubuntu/Ubuntu[wdth,wght].ttf"
def _label_font(dc, text, box):
"""Largest Ubuntu Bold font whose rendering of `text` fits within `box`
pixels square."""
from PIL import ImageFont
for pt in range(box, 6, -1):
font = ImageFont.truetype(_UBUNTU_FONT, pt)
font.set_variation_by_name("Bold")
l, t, r, b = dc.textbbox((0, 0), text, font=font)
if r - l <= box and b - t <= box:
return font
return font
def create_image(is_running=False, code=None):
from PIL import Image, ImageDraw
size = 16
fg = "#dfdbd2ff"
red = "#f00"
# Panel foreground is hard to extract from the tray, so use a fixed near-white.
label = "#f7f7f7"
image = Image.new('RGBA', (2*size, 2*size), "#0000")
dc = ImageDraw.Draw(image)
if is_running:
bbox = [(2, 2), (2*size-4, 2*size-4)]
dc.ellipse(bbox, fill=red)
if code:
cx = (bbox[0][0] + bbox[1][0]) / 2
cy = (bbox[0][1] + bbox[1][1]) / 2
# Fit the icon boundary, not the circle: the label may overflow the
# red disc but must stay inside the 2*size canvas.
box = 2*size - 2
dc.text((cx, cy), code, fill=label, anchor="mm",
font=_label_font(dc, code, box))
else:
triangle = [(size // 2, 0), (size // 2, 2*size), (3 * size // 2, size)]
dc.polygon(triangle, fill=fg)
image = image.resize((size, size))
return image
def pretty_duration(minutes):
minutes = int(minutes)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
if not days:
return f"{hours}:{minutes:02}"
return f"{days}d {hours:02}:{minutes:02}"
def elapsed_minutes(segment, now=None):
now = now or datetime.now()
return (now - segment.start).total_seconds() // 60
def current_journal():
return worklog.parse(store.read())
def all_journal():
return worklog.parse("\n".join(store.read_all()))
def running_segment(journal):
"""The open segment, but only if it is running today; else None.
An open segment left over from an earlier day is a data problem, not a
running task.
"""
segment = journal.open_segment
if segment and segment.start.date() == date.today():
return segment
return None
def start_label(default_task):
"""Idle tooltip when nothing runs: the most recent task, or a note that
there is none."""
return f"Start {default_task}" if default_task else "No recent task"
def tooltip(segment, default_task=None):
"""Plain-text tray title / fallback: task and elapsed on the first line,
the inline comment on the second."""
if segment is None:
return start_label(default_task)
head = f"{segment.task} ({pretty_duration(elapsed_minutes(segment))})"
return f"{head}\n{segment.comment}" if segment.comment else head
def tooltip_markup(segment, default_task=None):
"""Pango markup for the hover tooltip: bold task and elapsed on the first
line, the inline comment on the second."""
from gi.repository import GLib
esc = GLib.markup_escape_text
if segment is None:
return f"<b>{esc(start_label(default_task))}</b>"
head = esc(f"{segment.task} ({pretty_duration(elapsed_minutes(segment))})")
return f"<b>{head}</b>\n{esc(segment.comment)}" if segment.comment else f"<b>{head}</b>"
def today_summary(journal, now=None):
"""Today's tasks as (task, minutes) pairs, one per task, in first-seen
order; the running task counts up to `now`. Matches the timeline's order."""
now = now or datetime.now()
totals = {}
for start, end, _running, task in worklog.day_intervals(journal, date.today(), now):
totals[task] = totals.get(task, 0) + (end - start).total_seconds() // 60
return list(totals.items())
class EditorWindow:
"""A plain text editor over the current month's worklog file.
The window loads the whole file so the user sees the full context of
earlier work. On a left click it seeds a fresh 'HH:MM ' line under today's
header and drops the cursor there for quick entry; when opened for a fired
reminder (focus_time set) it shows the file untouched and lands the cursor
on that scheduled entry instead. Closing the window saves the buffer back
to disk; an untouched scaffold is discarded.
"""
def __init__(self, on_close, focus_time=None):
from gi.repository import Gtk, GLib
self.on_close = on_close
self.day = date.today()
self.window = Gtk.Window(title="Worklog")
self.window.set_default_size(720, 640)
self.textview = Gtk.TextView()
css = Gtk.CssProvider()
css.load_from_data(b"textview { font-family: serif; }")
self.textview.get_style_context().add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
self.textview.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
self.textview.set_left_margin(8)
self.textview.set_right_margin(8)
self.timeline = Gtk.DrawingArea(height_request=57)
self.timeline.connect('draw', self._draw_timeline)
scroll = Gtk.ScrolledWindow()
scroll.add(self.textview)
column = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
column.pack_start(self.timeline, False, False, 0)
column.pack_start(scroll, True, True, 0)
self.window.add(column)
self.original = store.read(self.day)
if focus_time is None:
# Left click: seed a fresh line to type into.
text, cursor = worklog.prepare_entry(self.original, self.day, datetime.now())
else:
# A fired reminder: show the file as-is and land on the entry that
# came due, never seeding a second line that would duplicate it.
text = self.original
cursor = worklog.locate_entry(text, focus_time)
if cursor is None:
cursor = len(text)
buf = self.textview.get_buffer()
buf.set_text(text)
buf.place_cursor(buf.get_iter_at_offset(cursor))
buf.connect('changed', lambda _b: self.timeline.queue_draw())
self.textview.connect('button-press-event', self._on_click)
self.window.connect('delete-event', self._on_delete)
self.window.connect('key-press-event', self._on_key)
self.window.show_all()
self.window.present()
if focus_time is not None:
self.window.set_urgency_hint(True)
# Scroll the target line into view only once the view has a size.
GLib.idle_add(self.textview.scroll_to_mark, buf.get_insert(), 0.0, True, 0.0, 1.0)
# Keep the running span growing on screen while the window sits open.
self._tick = GLib.timeout_add_seconds(20, self._redraw_timeline)
def _redraw_timeline(self):
self.timeline.queue_draw()
return True
_MARKER_H = 15
_BAR_H = 20
_LEGEND_ROW_H = 18
_PAD_X = 8
def _draw_timeline(self, area, cr):
from gi.repository import Gtk, Pango, PangoCairo
width = area.get_allocated_width()
pad = self._PAD_X
inner = max(width - 2 * pad, 1)
intervals = worklog.day_intervals(worklog.parse(self._buffer_text()), self.day, datetime.now())
colors = task_colors(task for *_, task in intervals)
fg = self.textview.get_style_context().get_color(Gtk.StateFlags.NORMAL)
midnight = datetime(self.day.year, self.day.month, self.day.day)
def hour_floor(dt):
return dt.replace(minute=0, second=0, microsecond=0)
start = midnight + timedelta(hours=8)
end = midnight + timedelta(hours=18)
if intervals:
first = min(s for s, *_ in intervals)
last = max(e for _, e, *_ in intervals)
start = min(start, hour_floor(first))
end = max(end, hour_floor(last))
span = max((end - start).total_seconds(), 3600)
def x_of(dt):
return pad + (dt - start).total_seconds() / span * inner
layout = PangoCairo.create_layout(cr)
layout.set_font_description(Pango.FontDescription("Sans 8"))
def text(s, x, y, align_center=False):
layout.set_text(s, -1)
if align_center:
w = layout.get_pixel_size().width
x = min(max(x - w / 2, 0), width - w)
cr.move_to(x, y)
PangoCairo.show_layout(cr, layout)
marker_y = 0
bar_y = self._MARKER_H
legend_y = bar_y + self._BAR_H + 4
# Hourly grid across the bar; every third hour gets a labelled marker.
hour = start
while hour <= end:
x = round(x_of(hour))
heavy = hour.hour % 3 == 0
cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.22 if heavy else 0.12)
cr.rectangle(x, bar_y, 1, self._BAR_H)
cr.fill()
if heavy:
cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.6)
text(f"{hour.hour}:00", x, marker_y, align_center=True)
hour += timedelta(hours=1)
# Colored task bars; the running one keeps its colour but gets an outline.
inset = 2
for begin, finish, running, task in intervals:
left = x_of(begin)
right = x_of(finish)
r, g, b = colors[task]
cr.set_source_rgba(r, g, b, 0.9)
cr.rectangle(left, bar_y + inset, max(right - left, 1), self._BAR_H - 2 * inset)
cr.fill()
if running:
cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.85)
cr.set_line_width(1)
cr.rectangle(round(left) + 0.5, bar_y + inset + 0.5,
max(round(right - left), 1), self._BAR_H - 2 * inset - 1)
cr.stroke()
# Legend: a colour chip and name per task, wrapping across rows.
chip = 10
gap = 6
x, y = pad, legend_y
for task, (r, g, b) in colors.items():
layout.set_text(task, -1)
label_w = layout.get_pixel_size().width
item_w = chip + 4 + label_w
if x > pad and x + item_w > width - pad:
x = pad
y += self._LEGEND_ROW_H
cr.set_source_rgb(r, g, b)
cr.rectangle(x, y + 3, chip, chip)
cr.fill()
cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.85)
text(task, x + chip + 4, y)
x += item_w + gap
needed = int(y + self._LEGEND_ROW_H)
if area.get_allocated_height() < needed:
area.set_size_request(-1, needed)
def present(self):
self.window.present()
def _buffer_text(self):
buf = self.textview.get_buffer()
return buf.get_text(buf.get_start_iter(), buf.get_end_iter(), True)
def _save(self):
text = worklog.strip_trailing_scaffold(self._buffer_text())
if text != worklog.strip_trailing_scaffold(self.original):
store.write_text(text, self.day)
def _on_delete(self, *_):
from gi.repository import GLib
GLib.source_remove(self._tick)
self._save()
self.on_close()
return False
_CHECKBOX_RE = re.compile(r"\[[ xX]\]")
def _on_click(self, textview, event):
"""Toggle a '[ ]'/'[x]' checkbox when the click lands on its inner half.
The clickable zone runs from the middle of '[' to the middle of ']',
tested against the glyphs' real pixel rectangles rather than the iter
the click snaps to -- so clicks past a line end or below the last line
(which snap onto a checkbox) do not toggle it.
"""
from gi.repository import Gdk, Gtk
if event.type != Gdk.EventType.BUTTON_PRESS or event.button != 1:
return False
bx, by = textview.window_to_buffer_coords(Gtk.TextWindowType.TEXT, int(event.x), int(event.y))
buf = textview.get_buffer()
clicked = textview.get_iter_at_location(bx, by).iter
start = buf.get_iter_at_line(clicked.get_line())
end = start.copy()
end.forward_to_line_end()
base = start.get_offset()
line = buf.get_text(start, end, True)
for m in self._CHECKBOX_RE.finditer(line):
box = buf.get_iter_at_offset(base + m.start())
open_rect = textview.get_iter_location(box)
close_rect = textview.get_iter_location(buf.get_iter_at_offset(base + m.end() - 1))
x0 = open_rect.x + open_rect.width / 2
x1 = close_rect.x + close_rect.width / 2
if x0 <= bx <= x1 and open_rect.y <= by < open_rect.y + open_rect.height:
fill = buf.get_iter_at_offset(base + m.start() + 1)
fill_end = buf.get_iter_at_offset(base + m.start() + 2)
buf.delete(fill, fill_end)
buf.insert(buf.get_iter_at_offset(base + m.start() + 1), ' ' if m.group()[1] != ' ' else 'x')
return True
return False
def _on_key(self, _widget, event):
from gi.repository import Gdk
if event.keyval == Gdk.KEY_Escape:
self.window.close()
return True
ctrl = event.state & Gdk.ModifierType.CONTROL_MASK
if ctrl and event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter):
self.window.close()
return True
return False
class App:
def __init__(self):
from pystray import Icon, Menu
self._file_token = store.stat_token()
self.editor = None
# Only entries that fall due after launch fire; past reminders in the
# file are history, not alarms to replay on every start.
self._reminder_watermark = datetime.now()
self._load_journal()
running = running_segment(self.journal)
# A callable menu so the right-click popup reflects the running task and
# today's totals as they change; tick() rebuilds the handle each second.
code = project_code(running.task) if running else None
self.icon = Icon("timer", create_image(running is not None, code), menu=Menu(self._menu_items))
def _menu_items(self):
from pystray import Menu, MenuItem
running = running_segment(self.journal)
# Left click still opens the editor via this default item; visible=False
# keeps it out of the right-click popup, which the user wants trimmed.
yield MenuItem("Open worklog", self.open_editor, default=True, visible=False)
if running:
elapsed = pretty_duration(elapsed_minutes(running))
yield MenuItem(f"Stop {running.task} ({elapsed})", self.stop_task)
else:
yield MenuItem("No running task", None, enabled=False)
yield Menu.SEPARATOR
summary = today_summary(self.journal)
if summary:
for task, minutes in summary:
yield MenuItem(f"{task} {pretty_duration(minutes)}", None, enabled=False)
else:
yield MenuItem("No tasks today", None, enabled=False)
def _load_journal(self):
text = store.read()
self.journal = worklog.parse(text)
self._entry_times = worklog.entry_times(text)
def reload(self):
self._file_token = store.stat_token()
self._load_journal()
self.refresh_presentation()
def refresh_presentation(self):
running = running_segment(self.journal)
default_task = None if running else next(iter(self.journal.recent_tasks(1)), None)
self.icon.icon = create_image(running is not None, project_code(running.task) if running else None)
self.icon.title = tooltip(running, default_task)
status_icon = getattr(self.icon, '_status_icon', None)
if status_icon is not None:
status_icon.set_tooltip_markup(tooltip_markup(running, default_task))
def tick(self):
# One periodic source, double duty: re-read only when the file changed
# on disk, but always advance the running task's elapsed display.
if store.stat_token() != self._file_token:
self.reload()
else:
self.refresh_presentation()
# Rebuild the popup so the stop item and today's totals stay current;
# the menu is a callable, so this just refreshes the built handle.
self.icon.update_menu()
self.check_reminders()
return True
def check_reminders(self):
"""Open the editor for any scheduled entry whose time has arrived.
The watermark walks forward every tick, so only entries still in the
future when last seen ever fire -- a note logged at the current time
never triggers itself. While the editor is open the entry is already
on screen, so we let the watermark pass it without reopening.
"""
now = datetime.now()
if self.editor is None:
due = [t for t in self._entry_times if self._reminder_watermark < t <= now]
if due:
self._open_editor(max(due))
self._reminder_watermark = now
def open_editor(self, icon=None, item=None):
# Menu callbacks may fire off the GTK main loop; build the window there.
from gi.repository import GLib
GLib.idle_add(self._open_editor)
def _open_editor(self, focus_time=None):
if self.editor is not None:
self.editor.present()
else:
self.editor = EditorWindow(on_close=self._editor_closed, focus_time=focus_time)
return False
def _editor_closed(self):
self.editor = None
self.reload()
def stop_task(self, icon=None, item=None):
if running_segment(self.journal):
store.append_lines([worklog.stop_line(datetime.now())])
self.reload()
def run(self):
from gi.repository import GLib
GLib.timeout_add(1000, self.tick)
self.icon.run()
def print_segments(segments):
for s in sorted(segments, key=lambda s: s.start):
duration = pretty_duration((s.end - s.start).total_seconds() // 60) if s.end else "running"
print(f" {s.start:%Y-%m-%d %H:%M} +{duration} {s.comment}")
def cmd_task(token):
journal = all_journal()
segments = journal.by_task().get(token, [])
print(token, pretty_duration(journal.total_minutes(segments)))
print_segments(segments)
def cmd_project(prefix=None):
journal = all_journal()
by_task = journal.by_task()
if prefix is None:
prefixes = sorted({worklog.project(token) for token in by_task})
for p in prefixes:
print(p)
return
for token in sorted(by_task):
if worklog.project(token) == prefix:
segments = by_task[token]
print(token, pretty_duration(journal.total_minutes(segments)))
print_segments(segments)
def parse_period(arg, period_start):
"""The start date for a period arg, or None if arg is not a valid period."""
try:
return period_start(arg)
except ValueError:
return None
def _load_stat_module():
import importlib.util
from pathlib import Path
spec = importlib.util.spec_from_file_location("worklog_stat", Path(__file__).with_name("stat.py"))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
if __name__ == "__main__":
from sys import argv
stat_report = _load_stat_module()
match argv[1:]:
case ["--task", token]:
cmd_task(token)
case ["--project"]:
cmd_project()
case ["--project", prefix]:
cmd_project(prefix)
case [period] if (start := parse_period(period, stat_report.period_start)) is not None:
stat_report.main(start)
case [period, prefix] if (start := parse_period(period, stat_report.period_start)) is not None:
stat_report.main(start, prefix)
case []:
App().run()
case _:
print("usage: ./timer.py [--task <token> | --project [prefix] | day|week|month|year|YYYY-MM-DD [project]]")