-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkTimerApp.py
More file actions
1013 lines (826 loc) · 44.1 KB
/
WorkTimerApp.py
File metadata and controls
1013 lines (826 loc) · 44.1 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
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
import traceback
import os
import sys
import time
import datetime
import re
import tkinter as tk
from tkinter import filedialog, simpledialog
import pystray
from pystray import MenuItem as item, Icon
from PIL import Image
import threading
import base64
import io
# Base64 encoded icon data (PNG format)
CHILL_ICON = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAX0lEQVR4nGPU0FD9z0ABYMEmeP36LayKNTXV8BtwHaoRm0Jc8owwL4AkcWnEZhBMLRMDhYCJVNtBAKQW5h0mqriAEsA0TAzQRApVuqcDRuTMRFFSxqYQHWAzGKsBpAAA13krZK9ro5MAAAAASUVORK5CYII="
WORK_ICON = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAhElEQVR4nM2S0Q3AIAhElbiKDew/DE07TBsTaZCgtfGn71OOO1EiYr7CAsk7ZD5cMdE2NuDa6Al79SgjlKIu7Hw2zUi5MRJtsim20Z5rowJ46W8UrYwDM+kjDYRF4F8GaF7Yw/0FUq86w3APsCaMFknzbKI4y416ybbeGFihxTN2Db5wA1dOPWheOcEiAAAAAElFTkSuQmCC"
# Log everything from the start
with open("error_log.txt", "w") as f:
f.write("Debugging started:\n")
# Function to log to the error log file
def log_to_file(message):
with open("error_log.txt", "a") as f:
f.write(f"{message}\n")
try:
class WorkTimerApp:
def __init__(self, root):
self.root = root
self.root.title("Work Timer")
# Get screen dimensions
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
# Get the window dimensions
window_width = 175 # Adjust as necessary
window_height = 85 # Adjust as necessary
# Calculate the x and y position to place the window at the bottom right
x_position = (
screen_width - window_width - 10
) # 10 pixels margin from the right
y_position = (
screen_height - window_height - 60
) # 60 pixels margin from the bottom
# Set the window's position and size
self.root.geometry(
f"{window_width}x{window_height}+{x_position}+{y_position}"
)
self.root.overrideredirect(True) # Remove window frame
self.root.configure(bg="#2E2E2E") # Dark background
self.root.attributes("-topmost", True) # Keep window on top
# Make window draggable
self.root.bind("<ButtonPress-1>", self.start_move)
self.root.bind("<B1-Motion>", self.do_move)
self.logged_sessions_today = set()
config_file = os.path.expanduser("~/.work_timer_config")
self.log_directory = None
if os.path.exists(config_file):
with open(config_file, "r") as f:
saved_directory = f.read().strip()
if os.path.exists(saved_directory):
self.log_directory = saved_directory
else:
self.select_save_location()
else:
self.select_save_location()
if not self.log_directory:
print("No save location selected. Exiting...")
root.quit()
return
with open(config_file, "w") as f:
f.write(self.log_directory)
os.makedirs(self.log_directory, exist_ok=True)
self.project_name = tk.StringVar()
self.project_name.set("Default Project")
self.load_last_project()
self.timer_running = False
self.start_time = None
self.elapsed_time = tk.StringVar()
self.elapsed_time.set("00:00:00")
self.daily_totals = {}
self.log_file = self.get_current_week_log_filename()
self.load_existing_logs() # Recalculate totals from the log file
self.weekly_total = datetime.timedelta(0)
self.sessions_today = set()
self.session_logged = (
False # Flag to track if the current session has been logged
)
self.create_widgets()
self.create_tray_icon()
# Schedule periodic log updates every minute (60000ms)
self.update_log_periodically()
def create_widgets(self):
# Frame for organizing widgets
frame = tk.Frame(self.root, bg="#2E2E2E", bd=2, relief="ridge")
frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# "Project:" label and text entry in the same row (row 0)
tk.Label(frame, text="Project:", fg="white", bg="#2E2E2E").grid(
row=0, column=0, padx=5, pady=5, sticky="e"
)
self.project_entry = tk.Entry(
frame,
textvariable=self.project_name,
width=15,
bg="#3C3C3C",
fg="white",
insertbackground="white",
)
self.project_entry.grid(row=0, column=1, padx=5, pady=5)
# Start/Stop button and timer display in the same row (row 1)
self.start_stop_button = tk.Button(
frame,
text="Start",
command=self.toggle_timer,
bg="#444",
fg="white",
relief="raised",
)
self.start_stop_button.grid(row=1, column=0, padx=5, pady=5)
# Timer label in the same row (row 1), aligned to the right side of the cell (column 1)
tk.Label(
frame,
textvariable=self.elapsed_time,
font=("Arial", 14),
fg="white",
bg="#2E2E2E",
).grid(
row=1, column=1, padx=5, pady=5, sticky="w"
) # Align to the left of the cell
# Set column weights for better resizing and preventing overflow
frame.grid_columnconfigure(0, weight=1, minsize=50)
frame.grid_columnconfigure(1, weight=3, minsize=50)
def start_move(self, event):
if event.widget not in [self.project_entry, self.start_stop_button]:
self.x = event.x_root - self.root.winfo_x()
self.y = event.y_root - self.root.winfo_y()
def do_move(self, event):
if event.widget not in [self.project_entry, self.start_stop_button]:
self.root.geometry(f"+{event.x_root - self.x}+{event.y_root - self.y}")
def stop_move(self, event):
pass # Prevent moving while interacting with widgets
def toggle_timer(self):
if self.timer_running:
self.stop_timer()
self.tray_icon.icon = self.not_working_icon
else:
self.start_timer()
self.tray_icon.icon = self.working_icon
def create_log_file(self):
"""Ensures that the log file for the current week exists and is initialized."""
# Get the current date and week start
now = datetime.datetime.now()
week_start = now - datetime.timedelta(days=now.weekday())
# Define the log file path
log_file = os.path.join(
self.log_directory, f"work_hours_{week_start.strftime('%d-%m-%Y')}.txt"
)
# Check if the log file already exists
if not os.path.exists(log_file):
# If the file doesn't exist, create a new one
try:
with open(log_file, "w") as f:
# Write a header or initialization message
f.write(
"Work Hours Log - Week Starting: "
+ week_start.strftime("%d-%m-%Y")
+ "\n"
)
f.write("---------------------------------------------------\n")
print(f"New log file created: {log_file}")
except Exception as e:
print(f"Error creating log file: {e}")
else:
print(f"Log file already exists: {log_file}")
# After creating or finding the log file, call write_day_log to ensure today's log entry is there
today_date = now.strftime("%d/%m/%Y") # Format today’s date
self.write_day_log(log_file, today_date) # Call write_day_log here
return log_file # Return the log file path
def update_log_periodically(self):
"""Update the log file every minute to preserve the current session in case of a crash."""
print(
f"Checking timer state: Running: {self.timer_running}, Start Time: {self.start_time}"
) # Debug
if not self.timer_running or not self.start_time:
print(
"Skipping log update, either timer is not running or no start time."
) # Debug
return
# Update the log file with the current session
# The update_log_file method already checks for duplicates
print("Updating log file with current session...")
self.update_log_file()
# Schedule the next update after 60 seconds, but only if the timer is still running
if self.timer_running:
self.root.after(60000, self.update_log_periodically)
def update_log_file(self):
"""Update the log file with the current session, updating an existing entry if possible."""
if not self.timer_running or not self.start_time:
return
# Set the flag to indicate this session has been logged
self.session_logged = True
current_time = time.time()
start_time_dt = datetime.datetime.fromtimestamp(self.start_time).replace(
second=0, microsecond=0
)
end_time_dt = datetime.datetime.fromtimestamp(current_time).replace(
second=0, microsecond=0
)
session_start_time = start_time_dt.strftime("%H:%M")
session_end_time = end_time_dt.strftime("%H:%M")
session_duration = self.format_time(end_time_dt - start_time_dt)
project_name = self.project_name.get()
# New log entry
log_entry = f"- {session_start_time} - {session_end_time} (Project: {project_name}) ({session_duration})"
log_file = self.get_current_week_log_filename()
try:
if not os.path.exists(log_file):
self.create_log_file()
# Read the current log file
with open(log_file, "r") as f:
lines = f.readlines()
# Find today's date in the log file
today_date = datetime.datetime.now().strftime("%d/%m/%Y")
date_index = -1
next_date_index = len(lines)
# Find today's date and the next date (if any)
for i, line in enumerate(lines):
if line.strip() == today_date:
date_index = i
# Now find the next date or end of file
for j in range(i + 1, len(lines)):
if re.match(r"\d{2}/\d{2}/\d{4}", lines[j].strip()):
next_date_index = j
break
break
# If we didn't find today's date, add it to the end
if date_index < 0:
lines.append(f"\n{today_date}\n")
date_index = len(lines) - 1
next_date_index = len(lines)
# Find all session entries for today
today_sessions = []
for i in range(date_index + 1, next_date_index):
line = lines[i].strip()
if line.startswith("-"):
# Check if this is for the current session (same start time)
if f"- {session_start_time} -" in line:
# Found an existing entry for this session, update it
today_sessions.append((i, log_entry))
print(f"Updated existing session entry: {log_entry}")
else:
# Keep the existing session
today_sessions.append((i, line))
# If we didn't find an existing entry for this session, add it
if not any(
f"- {session_start_time} -" in entry for _, entry in today_sessions
):
today_sessions.append((-1, log_entry))
print(f"Added new session entry: {log_entry}")
# Sort sessions by start time (oldest first)
today_sessions.sort(
key=lambda x: (
re.search(r"- (\d{2}:\d{2}) -", x[1]).group(1)
if re.search(r"- (\d{2}:\d{2}) -", x[1])
else ""
)
)
# Rebuild the file with sorted sessions
new_lines = lines[
: date_index + 1
] # Everything up to and including today's date
# Add all sessions in order
for _, session in today_sessions:
new_lines.append(session + "\n")
# Add everything after today's sessions
if next_date_index < len(lines):
new_lines.extend(lines[next_date_index:])
# Write the updated lines back to the log file
with open(log_file, "w") as f:
f.writelines(new_lines)
print(f"Log updated: {log_file}")
except Exception as e:
print(f"Error updating log file: {e}")
traceback.print_exc() # Print the full traceback for debugging
def stop_timer(self, end_time=None):
"""Stop the timer and log the session."""
print("Stopping timer...")
self.timer_running = False
end_time = end_time if end_time else time.time()
end_time_dt = datetime.datetime.fromtimestamp(end_time)
# Round down to the nearest minute
end_time_dt = end_time_dt.replace(second=0, microsecond=0)
end_time = end_time_dt.timestamp() # Convert back to timestamp
# Calculate session duration
duration = self.calculate_duration(self.start_time, end_time)
# Only log the session if it hasn't been logged by update_log_file
if not self.session_logged:
self.log_time(duration, end_time)
else:
print("Session already logged by update_log_file, skipping log_time")
# Reset the button and elapsed time display
self.start_stop_button.config(text="Start")
self.elapsed_time.set("00:00:00") # Reset display
# Get the log file for the current week
now = datetime.datetime.now()
week_start = now - datetime.timedelta(days=now.weekday())
log_file = os.path.join(
self.log_directory,
f"work_hours_{week_start.strftime('%d-%m-%Y')}.txt",
)
# Update daily and weekly totals **only when stopping the session**
today_date = now.strftime("%d/%m/%Y")
self.update_daily_total(log_file, today_date, duration)
self.update_weekly_total(log_file)
print("Session logged and updated.")
def start_timer(self, start_time=None):
self.timer_running = True
self.start_time = start_time if start_time else time.time()
self.session_logged = (
False # Reset the session_logged flag when starting a new timer
)
log_file = self.get_current_week_log_filename()
print(f"Timer started. Log file: {log_file}")
self.start_stop_button.config(text="Stop")
self.update_elapsed_time()
self.update_log_periodically()
def update_elapsed_time(self):
if self.timer_running:
now = datetime.datetime.now()
# Check if it's 23:59:59 (last second of the day)
if now.hour == 23 and now.minute == 59 and now.second == 59:
print("🔔 Split session at 23:59:59!")
# Get the current log file before midnight
current_log_file = self.get_current_week_log_filename()
current_date = now.strftime("%d/%m/%Y")
# Stop the current session at 23:59:59
end_of_day = datetime.datetime.combine(
now.date(), datetime.time(23, 59, 59)
)
self.stop_timer(
end_time=end_of_day.timestamp()
) # Log the old session
# Update daily and weekly totals for the current day
self.update_daily_total(
current_log_file, current_date, datetime.timedelta(0)
)
self.update_weekly_total(current_log_file)
# Check if we're transitioning from Sunday to Monday (new week)
tomorrow = now.date() + datetime.timedelta(days=1)
if tomorrow.weekday() == 0: # Monday is 0
print("🔔 New week starting! Creating new log file.")
# The current log file already has the correct totals from stop_timer and our updates above
# The new log file will be created when we start the timer below
# or when get_current_week_log_filename is called with the new date
# Start a new session at 00:00:00 (midnight of the new day)
midnight = datetime.datetime.combine(
tomorrow, datetime.time(0, 0, 0)
)
# Create a new log entry for the new day before starting the timer
tomorrow_date = tomorrow.strftime("%d/%m/%Y")
new_log_file = self.get_current_week_log_filename() # This might be a new file if it's a new week
self.write_day_log(new_log_file, tomorrow_date)
# Start the new timer
self.start_timer(
start_time=midnight.timestamp()
) # Log the new session
# Reset daily total for the new day
self.daily_totals = {midnight.date(): datetime.timedelta(0)}
print(f"🔔 Started new session at midnight for {tomorrow_date}")
# Update elapsed time
elapsed = time.time() - self.start_time
self.elapsed_time.set(time.strftime("%H:%M:%S", time.gmtime(elapsed)))
self.root.after(1000, self.update_elapsed_time)
def calculate_duration(self, start, end):
# Duration in seconds
delta = end - start
return datetime.timedelta(seconds=delta)
def log_time(self, duration, end_time):
now = datetime.datetime.now()
week_start = now - datetime.timedelta(days=now.weekday())
log_file = os.path.join(
self.log_directory, f"work_hours_{week_start.strftime('%d-%m-%Y')}.txt"
)
# Convert timestamps to datetime objects
start_time_dt = datetime.datetime.fromtimestamp(self.start_time)
end_time_dt = datetime.datetime.fromtimestamp(end_time)
# Round start and end times down to the nearest minute
start_time_dt = start_time_dt.replace(second=0, microsecond=0)
end_time_dt = end_time_dt.replace(second=0, microsecond=0)
# Calculate duration using the rounded times (not the original times)
rounded_duration = end_time_dt - start_time_dt
# Format session log entry
session_start_time = start_time_dt.strftime("%H:%M")
session_end_time = end_time_dt.strftime("%H:%M")
session_duration = self.format_time(rounded_duration)
log_entry = f"- {session_start_time} - {session_end_time} (Project: {self.project_name.get()}) ({session_duration})"
# Ensure the log file exists
if not os.path.exists(log_file):
with open(log_file, "w") as f:
f.write(
f"Hours Worked\nWeek commencing {week_start.strftime('%d/%m/%Y')}\n"
)
today_date = now.strftime("%d/%m/%Y")
self.write_day_log(log_file, today_date)
# Check for duplicates before writing
try:
with open(log_file, "r") as f:
lines = [line.strip() for line in f.readlines()]
existing_sessions = {
line.strip() for line in lines if line.startswith("-")
}
if log_entry in existing_sessions:
print(
"Duplicate session detected in log_time, skipping log update."
)
return
# Append the session log only if it's not a duplicate
with open(log_file, "a") as f:
f.write(f"{log_entry}\n")
print(f"Session logged: {log_entry}")
except Exception as e:
print(f"Error logging time: {e}")
def update_daily_total(self, log_file, current_date, duration):
"""Updates the daily total time worked by parsing session times for the current day from the log file."""
try:
print(f"\n\n==== UPDATING DAILY TOTAL FOR {current_date} ====")
# Read the current lines in the log file
with open(log_file, "r") as f:
lines = f.readlines()
# Print all lines for debugging
print("\nLog file contents:")
for i, line in enumerate(lines):
print(f"{i}: '{line.strip()}'")
# Initialize the total time for the day
total_today = datetime.timedelta(0)
# Find the date line index
date_line_index = -1
for i, line in enumerate(lines):
line = line.strip()
if line == current_date:
date_line_index = i
print(f"Found exact date match at line {i}: '{line}'")
break
elif current_date in line and not line.startswith("-"):
date_line_index = i
print(f"Found partial date match at line {i}: '{line}'")
break
# If we found the date, find the next date or end of file
next_date_index = len(lines)
if date_line_index >= 0:
for i in range(date_line_index + 1, len(lines)):
line = lines[i].strip()
if re.match(r"\d{2}/\d{2}/\d{4}", line):
next_date_index = i
print(f"Found next date at line {i}: '{line}'")
break
elif line.startswith("Total hours this week:"):
next_date_index = i
print(f"Found weekly total at line {i}: '{line}'")
break
# Calculate the total using only lines between the date line and the next date
for i in range(date_line_index + 1, next_date_index):
line = lines[i].strip()
if line.startswith("-"): # Session entry
session_time = self.extract_session_time(line)
if session_time:
total_today += session_time
print(
f"Line {i}: Added {self.format_time(session_time)} to daily total"
)
print(f"Final daily total: {self.format_time(total_today)}")
# If today's date wasn't found in the log, add it
if date_line_index < 0:
self.write_day_log(log_file, current_date)
date_line_index = len(lines) - 1 # Assume it was added at the end
next_date_index = len(lines)
# Rebuild the file with the daily total in the correct place
new_lines = []
# Add everything up to the current date section
new_lines.extend(lines[: date_line_index + 1])
# Add all session entries for the current date
session_lines = []
for i in range(date_line_index + 1, next_date_index):
line = lines[i].strip()
if line.startswith("-") or not line: # Session entry or blank line
session_lines.append(lines[i])
new_lines.extend(session_lines)
# Add the daily total after the session entries
if session_lines:
if not session_lines[-1].strip(): # If last line is blank
new_lines.append(
f"Total today: {self.format_time(total_today)}\n\n"
)
else:
new_lines.append(
f"\nTotal today: {self.format_time(total_today)}\n\n"
)
else:
new_lines.append(
f"\nTotal today: {self.format_time(total_today)}\n\n"
)
# Add everything after the current date section
if next_date_index < len(lines):
new_lines.extend(lines[next_date_index:])
# Write the updated lines back into the log file
with open(log_file, "w") as f:
f.writelines(new_lines)
print(
f"Total today updated in {log_file}: {self.format_time(total_today)}"
)
print("==== DAILY TOTAL UPDATE COMPLETE ====\n\n")
except Exception as e:
print(f"Error updating daily total: {e}")
traceback.print_exc() # Print the full traceback for debugging
def extract_session_time(self, line):
"""Extracts the duration of a session from the log line."""
# Example line: "- 21:46 - 21:48 (Project: Default Project) (0h 2m)"
try:
print(f"Extracting time from line: {line}")
# Look for the last parenthesized expression which should contain the duration
match = re.search(r"\(([^)]+)\)$", line.strip())
if match:
time_str = match.group(1)
print(f"Found time string: {time_str}")
# Use regex to extract hours and minutes
hours_match = re.search(r"(\d+)h", time_str)
minutes_match = re.search(r"(\d+)m", time_str)
hours = int(hours_match.group(1)) if hours_match else 0
minutes = int(minutes_match.group(1)) if minutes_match else 0
duration = datetime.timedelta(hours=hours, minutes=minutes)
print(f"Extracted duration: {self.format_time(duration)}")
return duration
else:
# If we can't find the duration at the end, try to extract it from the time range
time_range_match = re.search(
r"- (\d{2}:\d{2}) - (\d{2}:\d{2})", line
)
if time_range_match:
start_time_str = time_range_match.group(1)
end_time_str = time_range_match.group(2)
# Parse the time strings
start_hour, start_minute = map(int, start_time_str.split(":"))
end_hour, end_minute = map(int, end_time_str.split(":"))
# Calculate duration in minutes
start_minutes = start_hour * 60 + start_minute
end_minutes = end_hour * 60 + end_minute
# Handle cases where the session crosses midnight
if end_minutes < start_minutes:
# For sessions that cross midnight, we need to be careful
# If the start time is close to midnight (after 23:00)
# and end time is close to 00:00, it's likely crossing midnight
if start_hour >= 23 and end_hour < 1:
end_minutes += 24 * 60 # Add a day's worth of minutes
# Otherwise, it might be a different kind of session (like spanning a whole day)
# In this case, calculate the duration normally
duration_minutes = end_minutes - start_minutes
# Ensure we never have negative durations
if duration_minutes < 0:
print(f"Warning: Negative duration detected: {duration_minutes} minutes")
print(f" Start: {start_hour}:{start_minute}, End: {end_hour}:{end_minute}")
# In case of negative duration, assume it's a short session
duration_minutes = abs(duration_minutes)
duration = datetime.timedelta(minutes=duration_minutes)
print(
f"Extracted duration from time range: {self.format_time(duration)}"
)
return duration
print(f"No time format found in line: {line}")
return datetime.timedelta(0)
except Exception as e:
print(f"Error extracting session time from '{line}': {e}")
traceback.print_exc() # Print the full traceback for debugging
return datetime.timedelta(0) # Return zero on error
def update_weekly_total(self, log_file):
"""Updates the total work time for the current week in the log file by parsing all session entries."""
try:
# Read the current lines in the log file
with open(log_file, "r") as f:
lines = f.readlines()
# Remove any previous weekly total if it exists
lines = [line for line in lines if "Total hours this week:" not in line]
# Initialize the weekly total
weekly_total = datetime.timedelta(0)
# Calculate directly from all session entries in the file
print("Calculating weekly total from all session entries...")
for line in lines:
line = line.strip()
if line.startswith("-"): # Session entry
session_time = self.extract_session_time(line)
if session_time:
weekly_total += session_time
print(
f"Added to weekly total: {self.format_time(session_time)}"
)
print(
f"Final weekly total calculation: {self.format_time(weekly_total)}"
)
# Add the weekly total at the end of the log file
lines.append(
f"\nTotal hours this week: {self.format_time(weekly_total)}\n"
)
# Write the updated lines back into the log file
with open(log_file, "w") as f:
f.writelines(lines)
print(
f"Weekly total updated in {log_file}: {self.format_time(weekly_total)}"
)
except Exception as e:
print(f"Error updating weekly total: {e}")
def get_current_week_log_filename(self):
today = datetime.date.today()
week_start = today - datetime.timedelta(days=today.weekday())
return os.path.join(
self.log_directory, f"work_hours_{week_start.strftime('%d-%m-%Y')}.txt"
)
def find_log_file(self):
"""Finds the log file based on the most recent 'Week commencing' entry or defaults to the current week."""
log_dir = self.log_directory # Use the actual log directory
today = datetime.date.today()
if not log_dir:
print("Log directory not set. Skipping log search.")
return None
# Get the start of the current week (Monday)
week_start = today - datetime.timedelta(days=today.weekday())
# Expected filename format
expected_filename = f"work_hours_{week_start.strftime('%d-%m-%Y')}.txt"
log_path = os.path.join(log_dir, expected_filename)
# Check if the log file exists
if os.path.exists(log_path):
return log_path # Found log file
# If log file doesn't exist, call create_log_file to ensure it's created
print(
f"Log file not found: {log_path}. Creating a new log file using create_log_file."
)
# Call create_log_file to handle log file creation
return (
self.create_log_file()
) # This will return the log file path after ensuring it's created
def load_existing_logs(self):
"""Load existing logs if the file exists, otherwise skip."""
log_file = self.find_log_file()
if not log_file:
return # Skip if no log file
try:
with open(log_file, "r") as file:
current_day = None
current_day_duration = datetime.timedelta(0)
for line in file:
line = line.strip()
if "Week commencing" in line:
continue # Ignore header lines
elif "Total today:" in line:
continue # Ignore summary lines
elif line.startswith("-"):
# Parse time durations from each session entry
match = re.search(r"\((\d+h \d+m)\)", line)
if match:
session_duration = match.group(1)
session_td = self.parse_time(session_duration)
current_day_duration += session_td
# Store the total for today
today_date = datetime.datetime.now().strftime("%d/%m/%Y")
self.daily_totals[today_date] = current_day_duration
except Exception as e:
print(f"Error loading logs: {e}")
def write_day_log(self, log_file, today_date):
"""Adds a new day entry to the log file if it doesn't already exist."""
print(f"write_day_log called for {today_date}")
try:
# Read the current log file
with open(log_file, "r") as f:
lines = f.readlines()
# Check if today's date already exists in the file
date_exists = False
for line in lines:
if line.strip() == today_date:
date_exists = True
break
# If today's date doesn't exist, add it
if not date_exists:
# Find the position to insert the new date
# It should be after any existing dates and their entries,
# but before the weekly total
insert_position = len(lines)
for i in range(len(lines) - 1, -1, -1):
if "Total hours this week:" in lines[i]:
insert_position = i
break
# Insert the new date at the appropriate position
lines.insert(insert_position, f"\n{today_date}\n")
# Write the updated lines back to the file
with open(log_file, "w") as f:
f.writelines(lines)
print(f"Added new date entry for {today_date}")
else:
print(f"Date {today_date} already exists in the log file")
except Exception as e:
print(f"Error in write_day_log: {e}")
# If there's an error, try the simple append method as a fallback
with open(log_file, "a") as f:
f.write(f"\n{today_date}\n")
def parse_time(self, line):
"""Parses a time string like 'Total today: 5h 30m' into a timedelta."""
try:
# Extract the time part after the colon
time_part = line.split(":")[-1].strip()
# Use regex to extract hours and minutes
hours_match = re.search(r"(\d+)h", time_part)
minutes_match = re.search(r"(\d+)m", time_part)
hours = int(hours_match.group(1)) if hours_match else 0
minutes = int(minutes_match.group(1)) if minutes_match else 0
return datetime.timedelta(hours=hours, minutes=minutes)
except Exception as e:
print(f"Error parsing time '{line}': {e}")
return datetime.timedelta(0) # Return zero duration on error
def format_time(self, td):
total_minutes = int(td.total_seconds() // 60)
hours = total_minutes // 60
minutes = total_minutes % 60
return f"{hours}h {minutes}m"
def load_last_project(self):
config_file = os.path.join(self.log_directory, "last_project.txt")
if os.path.exists(config_file):
with open(config_file, "r") as f:
self.project_name.set(f.read().strip())
def select_save_location(self):
self.log_directory = filedialog.askdirectory()
if self.log_directory:
os.makedirs(self.log_directory, exist_ok=True)
def hide_window(self):
self.root.withdraw()
def show_window(self):
self.root.deiconify()
def create_tray_icon(self):
try:
# Try to use base64 encoded icons first
log_to_file("Attempting to load icons from base64 data...")
try:
log_to_file(f"CHILL_ICON length: {len(CHILL_ICON)}")
log_to_file(f"WORK_ICON length: {len(WORK_ICON)}")
# Decode base64 data
log_to_file("Decoding base64 data...")
chill_icon_data = base64.b64decode(CHILL_ICON)
work_icon_data = base64.b64decode(WORK_ICON)
log_to_file(
f"Decoded chill_icon_data length: {len(chill_icon_data)}"
)
log_to_file(f"Decoded work_icon_data length: {len(work_icon_data)}")
# Create BytesIO objects
log_to_file("Creating BytesIO objects...")
chill_bytes = io.BytesIO(chill_icon_data)
work_bytes = io.BytesIO(work_icon_data)
# Open images
log_to_file("Opening images from BytesIO...")
self.not_working_icon = Image.open(chill_bytes)
self.working_icon = Image.open(work_bytes)
log_to_file("Successfully loaded icons from base64 data")
except Exception as e:
log_to_file(f"Error loading icons from base64: {e}")
log_to_file(traceback.format_exc())
# Fall back to loading from files
log_to_file("Falling back to loading icons from files...")
script_dir = os.path.dirname(os.path.abspath(__file__))
chill_path = os.path.join(script_dir, "icons/chill.ico")
work_path = os.path.join(script_dir, "icons/work.ico")
log_to_file(f"Loading chill icon from: {chill_path}")
log_to_file(f"Loading work icon from: {work_path}")
self.not_working_icon = Image.open(chill_path)
self.working_icon = Image.open(work_path)
log_to_file("Successfully loaded icons from files")
log_to_file("Creating tray icon...")
self.tray_icon = Icon(
"work_timer", self.not_working_icon, menu=self.create_tray_menu()
)
log_to_file("Starting tray icon thread...")
threading.Thread(target=self.tray_icon.run, daemon=True).start()
log_to_file("Tray icon thread started")
except Exception as e:
log_to_file(f"Error in create_tray_icon: {e}")
log_to_file(traceback.format_exc())
def create_tray_menu(self):
menu = (
item("Start/Stop", self.toggle_timer),
item("Select File Save Location", self.select_save_location),
item("Show/Hide", self.toggle_gui),
item("View Log", self.open_log_file),
item("Exit", self.exit_app),
)
return menu
def open_log_file(self):
"""Open the current week's log file in the default text editor."""
try:
log_file = self.get_current_week_log_filename()
if os.path.exists(log_file):
# Use the appropriate command based on the OS
if os.name == "nt": # Windows
os.startfile(log_file)
elif os.name == "posix": # macOS and Linux
import subprocess
subprocess.call(
("open", log_file)
if sys.platform == "darwin"
else ("xdg-open", log_file)
)
log_to_file(f"Opening log file: {log_file}")
else:
log_to_file(f"Log file not found: {log_file}")
except Exception as e:
log_to_file(f"Error opening log file: {e}")
log_to_file(traceback.format_exc())
def toggle_gui(self):
if self.root.state() == "withdrawn":
self.show_window()
else:
self.hide_window()
def exit_app(self):
try: