-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkday_timer.py
More file actions
603 lines (499 loc) · 24.8 KB
/
workday_timer.py
File metadata and controls
603 lines (499 loc) · 24.8 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
import datetime
import logging
import os
import random
import sys
import requests # Add import for HTTP requests
import win32gui
import win32con
import multiprocessing
import threading
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QPixmap, QFont, QIcon, QIntValidator
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QMessageBox, QPushButton, QVBoxLayout, QHBoxLayout, QDialog, QSystemTrayIcon, QMenu, QAction, QLineEdit, QProgressBar
from config import (START_TIME_FILE, isFLEXIBLE, ICON_FILE, IMAGE_DIRECTORY, DEFAULT_TIMER_IMAGE,
WINDOW_POSITION_X, WINDOW_POSITION_Y, WINDOW_SIZE_WIDTH, WINDOW_SIZE_HEIGHT,
DIALOG_POSITION_X, DIALOG_POSITION_Y, DIALOG_SIZE_WIDTH, DIALOG_SIZE_HEIGHT,
FLEXIBLE_MODE_FILE)
# Configure logging
logging.basicConfig(
filename='app.log', # Log file name
level=logging.DEBUG, # Only record logs at DEBUG level and above
format='%(asctime)s - %(levelname)s - %(message)s' # Log format
)
def get_last_start_time():
"""Reads the last start time from the config file. Returns None if not found."""
try:
with open(START_TIME_FILE, "r") as f:
lines = f.readlines()
if lines:
last_line = lines[-1].strip()
try:
return datetime.datetime.strptime(last_line, "%Y-%m-%d %H:%M:%S.%f")
except ValueError:
print("Warning: Invalid date format in config file. Using current time.")
return None
else:
return None
except FileNotFoundError:
return None
def write_start_time(start_time):
"""Writes the start time to the config file."""
try:
with open(START_TIME_FILE, "a") as f:
f.write(start_time.strftime("%Y-%m-%d %H:%M:%S.%f") + "\n")
except Exception as e:
print(f"Error writing to config file: {e}")
class WorkdayTimer(QWidget):
def __init__(self, app):
super().__init__()
self.app = app
self.init_ui()
current_time = datetime.datetime.now()
last_start_time = get_last_start_time()
is_first_start = False
if last_start_time is None or last_start_time.date() != current_time.date():
# First start of the day
print("First start of the day.")
is_first_start = True
write_start_time(current_time)
last_start_time = current_time
# Subtract 90 seconds
last_start_time = last_start_time - datetime.timedelta(seconds=92) # < 94 95 100
if not isFLEXIBLE:
# Get current time
now = datetime.datetime.now()
# Create a time object representing 9 AM
morning_nine = datetime.time(9, 0)
# Combine current date with 9 AM time
last_start_time = datetime.datetime.combine(now.date(), morning_nine)
# Round down to the nearest minute
last_start_time = last_start_time.replace(second=0, microsecond=0)
self.timer_expiry = last_start_time + datetime.timedelta(hours=8.5)
delay = (self.timer_expiry - datetime.datetime.now()).total_seconds()
self.timer_type = delay
self.reminder_timer = QTimer(self)
self.reminder_timer.timeout.connect(self.show_reminder)
self.reminder_timer.setSingleShot(True) # Only run once
self.reminder_timer.start(int(delay * 1000)) # 8.5 hours in milliseconds
timer_expiry2 = last_start_time + datetime.timedelta(hours=7.5)
delay2 = (timer_expiry2 - datetime.datetime.now()).total_seconds()
self.reminder_timer2 = QTimer()
self.reminder_timer2.timeout.connect(self.show_job_record_warning)
self.reminder_timer.setSingleShot(True) # Only run once
self.reminder_timer2.start(int(delay2 * 1000)) # 8.5 hours in milliseconds
if is_first_start:
self.show_checkin_reminder()
# Create system tray icon
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(QIcon(ICON_FILE)) # Replace with your own icon file
# Create menu for open and exit
self.menu = QMenu()
# Create action to open window
open_action = QAction("Open", self)
open_action.triggered.connect(self.moveAvatar)
self.menu.addAction(open_action)
# Create action to toggle flexible mode
self.flexible_action = QAction(f"Flexible Mode: {'On' if isFLEXIBLE else 'Off'}", self)
self.flexible_action.setCheckable(True)
self.flexible_action.setChecked(isFLEXIBLE)
self.flexible_action.triggered.connect(self.toggle_flexible_mode)
self.menu.addAction(self.flexible_action)
# Create action for custom timer
custom_timer_action = QAction("Custom Timer", self)
custom_timer_action.triggered.connect(self.show_custom_timer_dialog)
self.menu.addAction(custom_timer_action)
# Add an update action to the tray menu
update_action = QAction("Update Application", self)
update_action.triggered.connect(self.update_application)
self.menu.addAction(update_action)
# Create action to exit program
exit_action = QAction("Exit", self)
exit_action.triggered.connect(self.exit_app)
self.menu.addAction(exit_action)
# Set menu to system tray icon
self.tray_icon.setContextMenu(self.menu)
# Show system tray icon
self.tray_icon.show()
# Connect tray icon click event
self.tray_icon.activated.connect(self.icon_activated)
# Set up global keyboard hook for Enter key
self.setup_keyboard_hook()
def init_ui(self):
try:
self.countdown_label = QLabel(self)
# Enable key press events
self.setFocusPolicy(Qt.StrongFocus)
self.countdown_label.setPixmap(QPixmap(DEFAULT_TIMER_IMAGE).scaled(60, 60, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation))
except FileNotFoundError:
QMessageBox.critical(self, "Error", "Timer icon not found. Please check the path.")
sys.exit(1)
self.display_timer = QTimer(self)
self.display_timer.timeout.connect(self.update_timer_display)
self.display_timer.start(100)
self.time_label = QLabel('Countdown: {}'.format(0), self)
self.time_label.setAlignment(Qt.AlignCenter)
self.setParent(None)
self.setGeometry(WINDOW_POSITION_X, WINDOW_POSITION_Y, WINDOW_SIZE_WIDTH, WINDOW_SIZE_HEIGHT)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool | Qt.WindowStaysOnTopHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.show()
def mousePressEvent(self, event):
self.offset = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton:
self.move(event.globalPos() - self.offset)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
self.toggle_qq_window()
def update_timer_display(self):
# Display image
seconds = self.reminder_timer.remainingTime() / 1000.0
# Add display for custom timer remaining time
custom_timer_seconds = 0
if hasattr(self, 'custom_timer') and self.custom_timer and self.custom_timer.isActive():
custom_timer_seconds = self.custom_timer.remainingTime() / 1000.0
if self.timer_type - seconds > 60:
self.timer_type = seconds
# Define image directory
image_directory = IMAGE_DIRECTORY
# List all image files in directory
all_images = [f for f in os.listdir(image_directory) if f.endswith(('.png', '.jpg', '.jpeg'))]
# Randomly select an image
if all_images: # Make sure there are images in the directory
random_image = random.choice(all_images)
image_path = os.path.join(image_directory, random_image)
self.countdown_label.setPixmap(QPixmap(image_path).scaled(60, 60, Qt.KeepAspectRatio, Qt.SmoothTransformation))
# Update display text with both timer information
display_text = ' : {:.0f} ✔ {}\n'.format(seconds, self.timer_expiry.minute)
if custom_timer_seconds > 0:
display_text += ' : {:.0f}s'.format(custom_timer_seconds)
self.time_label.setText(display_text)
self.time_label.adjustSize()
self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool | Qt.WindowStaysOnTopHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.show()
def show_checkin_reminder(self):
job_record_reminder_dialog = QMessageBox()
job_record_reminder_dialog.setWindowFlags(Qt.WindowStaysOnTopHint)
job_record_reminder_dialog.setWindowTitle("Microsoft Visual Studio")
reminder_message = """checkin"""
job_record_reminder_dialog.setText(reminder_message)
job_record_reminder_dialog.setIcon(QMessageBox.Critical)
job_record_reminder_dialog.addButton(QMessageBox.Close)
job_record_reminder_dialog.setGeometry(700, 500, 900, 700)
job_record_reminder_dialog.exec_()
def show_reminder(self):
reminder_dialog = QMessageBox()
reminder_dialog.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
reminder_dialog.setWindowTitle("Microsoft Visual Studio")
reminder_message = """Reminder:
- 1. Clock out
- 2. Turn off AC, water dispenser, windows, computer
- 3. Write work log
-- """
if not isFLEXIBLE:
reminder_message = """ Need to shutdown """
reminder_dialog.setText(reminder_message)
reminder_dialog.setIcon(QMessageBox.Information)
# Add Shutdown Button
shutdown_button = QPushButton("Shutdown")
shutdown_button.clicked.connect(self.shutdown_computer)
reminder_dialog.addButton(shutdown_button, QMessageBox.ActionRole)
reminder_dialog.addButton(QMessageBox.Ignore)
reminder_dialog.setMinimumSize(400, 200)
desktop = QApplication.desktop()
x = (desktop.width() - reminder_dialog.width()) // 2
y = (desktop.height() - reminder_dialog.height()) // 2
reminder_dialog.setGeometry(x, y, reminder_dialog.width(), reminder_dialog.height())
reminder_dialog.setGeometry(DIALOG_POSITION_X, DIALOG_POSITION_Y, DIALOG_SIZE_WIDTH, DIALOG_SIZE_HEIGHT)
font = QFont()
font.setPointSize(12)
reminder_dialog.setFont(font)
reminder_dialog.exec()
def show_job_record_warning(self):
reminder_dialog = QMessageBox()
reminder_dialog.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
reminder_dialog.setWindowTitle("Work Record Reminder")
reminder_dialog.setText("Please remember to record your work progress!")
reminder_dialog.setIcon(QMessageBox.Information)
reminder_dialog.addButton(QMessageBox.Ok)
reminder_dialog.exec()
def moveAvatar(self):
self.show()
self.raise_()
self.activateWindow()
def exit_app(self):
# Stop keyboard listener before exiting
import keyboard
keyboard.unhook_all()
self.app.quit()
def closeEvent(self, event):
event.ignore()
def icon_activated(self, reason):
if reason == QSystemTrayIcon.Trigger:
self.moveAvatar()
def toggle_flexible_mode(self):
"""Toggle flexible mode and save the state to file"""
is_flexible = self.flexible_action.isChecked()
try:
with open(FLEXIBLE_MODE_FILE, "w") as f:
f.write(str(is_flexible).lower())
global isFLEXIBLE
isFLEXIBLE = is_flexible
QMessageBox.information(self, "Mode Changed", "Flexible mode has been " + ("enabled" if is_flexible else "disabled") + ".\nPlease restart the application for the changes to take effect.")
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to save flexible mode: {e}")
self.flexible_action.setChecked(not is_flexible)
def show_custom_timer_dialog(self):
dialog = QDialog(self)
dialog.setWindowTitle("Custom Timer")
dialog.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.Tool)
layout = QVBoxLayout()
# Create input field
input_label = QLabel("Enter minutes:")
input_field = QLineEdit()
input_field.setAlignment(Qt.AlignCenter)
input_field.setFont(QFont("Arial", 20))
input_field.setText("0")
input_field.setValidator(QIntValidator(0, 999999))
layout.addWidget(input_label)
layout.addWidget(input_field)
# Create quick select buttons layout
quick_select_layout = QVBoxLayout()
# First row - 1 to 5 minutes
row1_layout = QHBoxLayout()
for i in range(1, 6):
btn = QPushButton(str(i))
btn.clicked.connect(lambda checked, num=i: self.add_minutes(input_field, num))
row1_layout.addWidget(btn)
quick_select_layout.addLayout(row1_layout)
# Second row - 6 to 10 minutes
row2_layout = QHBoxLayout()
for i in range(6, 11):
btn = QPushButton(str(i))
btn.clicked.connect(lambda checked, num=i: self.add_minutes(input_field, num))
row2_layout.addWidget(btn)
quick_select_layout.addLayout(row2_layout)
# Third row - 15, 20, 30 minutes
row3_layout = QHBoxLayout()
for minutes in [15, 20, 30]:
btn = QPushButton(f"{minutes}")
btn.clicked.connect(lambda checked, num=minutes: self.add_minutes(input_field, num))
row3_layout.addWidget(btn)
quick_select_layout.addLayout(row3_layout)
# Fourth row - 40, 60, 90 minutes
row4_layout = QHBoxLayout()
for minutes in [40, 60, 90]:
btn = QPushButton(f"{minutes}")
btn.clicked.connect(lambda checked, num=minutes: self.add_minutes(input_field, num))
row4_layout.addWidget(btn)
quick_select_layout.addLayout(row4_layout)
# Fifth row - 120, 180, 240 minutes
row5_layout = QHBoxLayout()
for minutes in [120, 180, 240]:
btn = QPushButton(f"{minutes}")
btn.clicked.connect(lambda checked, num=minutes: self.add_minutes(input_field, num))
row5_layout.addWidget(btn)
quick_select_layout.addLayout(row5_layout)
# Add clear button
clear_button = QPushButton("Clear")
clear_button.clicked.connect(lambda: input_field.setText("0"))
quick_select_layout.addWidget(clear_button)
layout.addLayout(quick_select_layout)
# Create OK and Cancel buttons
button_box = QHBoxLayout()
ok_button = QPushButton("OK")
cancel_button = QPushButton("Cancel")
def start_custom_timer():
try:
minutes = int(input_field.text())
if minutes > 0:
self.start_custom_countdown(minutes)
dialog.accept()
else:
QMessageBox.warning(dialog, "Invalid Input", "Please enter a positive number.")
except ValueError:
QMessageBox.warning(dialog, "Invalid Input", "Please enter a valid number.")
ok_button.clicked.connect(start_custom_timer)
cancel_button.clicked.connect(dialog.reject)
button_box.addWidget(ok_button)
button_box.addWidget(cancel_button)
layout.addLayout(button_box)
dialog.setLayout(layout)
dialog.exec_()
def add_minutes(self, input_field, minutes):
try:
current = int(input_field.text())
input_field.setText(str(current + minutes))
except ValueError:
input_field.setText(str(minutes))
def start_custom_countdown(self, minutes):
if hasattr(self, 'custom_timer'):
self.custom_timer.stop()
self.custom_timer = QTimer(self)
self.custom_timer.timeout.connect(lambda: self.show_custom_timer_reminder())
self.custom_timer.setSingleShot(True)
self.custom_timer.start(minutes * 60 * 1000)
def show_custom_timer_reminder(self):
reminder_dialog = QMessageBox()
reminder_dialog.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
reminder_dialog.setWindowTitle("Custom Timer")
reminder_dialog.setText("Custom timer countdown finished!")
reminder_dialog.setIcon(QMessageBox.Information)
reminder_dialog.addButton(QMessageBox.Ok)
reminder_dialog.exec_()
def setup_keyboard_hook(self):
"""Set up a global keyboard hook to listen for Enter key press using multiprocessing"""
import keyboard
def on_enter_key(event):
if event.event_type == keyboard.KEY_DOWN and event.name == 'enter':
self.toggle_qq_window()
# Register the hook in a separate thread
self.keyboard_listener_thread = threading.Thread(target=self._start_keyboard_listener, daemon=True)
self.keyboard_listener_thread.start()
def _start_keyboard_listener(self):
"""Start the keyboard listener in a separate thread"""
import keyboard
def on_enter_key(event):
if event.event_type == keyboard.KEY_DOWN and event.name == 'enter':
# Use wx.CallAfter equivalent for Qt
self.toggle_qq_window()
# Start the keyboard listener
keyboard.hook(on_enter_key)
# Keep the thread alive
try:
keyboard.wait()
except KeyboardInterrupt:
pass
def toggle_qq_window(self):
"""Toggle visibility of windows with 'QQ..exe' in the title"""
def window_enum_callback(hwnd, extra):
if "QQ..exe" in win32gui.GetWindowText(hwnd):
# Check if window is visible
if win32gui.IsWindowVisible(hwnd):
win32gui.ShowWindow(hwnd, win32con.SW_HIDE)
else:
win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
win32gui.EnumWindows(window_enum_callback, None)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
self.toggle_qq_window()
def shutdown_computer(self):
# **WARNING: Use with EXTREME caution!** Add robust confirmation dialog before implementing.
try:
os.system("shutdown /s /t 1") #Windows shutdown command, adjust for other OS.
except Exception as e:
QMessageBox.critical(self, "Error", f"Shutdown failed: {e}")
def update_application(self):
"""Download the latest executable from GitHub and replace the current one."""
try:
github_url = "https://github.com/uuvccc/WorkDayTimer/releases/latest/download/WorkDayTimer.exe"
# Determine if running as executable or script
local_exe_path = sys.argv[0]
is_running_as_exe = local_exe_path.endswith('.exe')
if not is_running_as_exe:
# When running as script, download to current directory
local_exe_path = os.path.join(os.getcwd(), "WorkDayTimer.exe")
reply = QMessageBox.question(self, "Update Confirmation",
"Application is running as a Python script.\n"
"The executable will be downloaded to the current directory.\n"
f"Download location: {local_exe_path}\n"
"Do you want to continue?")
if reply == QMessageBox.No:
return
# Create a temporary file for the new version
import tempfile
temp_dir = tempfile.gettempdir()
temp_exe_path = os.path.join(temp_dir, "WorkDayTimer_new.exe")
# Create progress dialog
progress_dialog = QDialog(None) # Changed from QDialog(self) to QDialog(None)
progress_dialog.setWindowTitle("Downloading Update")
progress_dialog.setWindowFlags(Qt.WindowStaysOnTopHint)
progress_dialog.setModal(True)
progress_dialog.resize(300, 100)
layout = QVBoxLayout()
label = QLabel("Downloading update...")
layout.addWidget(label)
progress_bar = QProgressBar()
progress_bar.setRange(0, 100)
layout.addWidget(progress_bar)
progress_dialog.setLayout(layout)
progress_dialog.show()
QApplication.processEvents() # Ensure dialog is displayed
response = requests.get(github_url, stream=True)
if response.status_code == 200:
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
with open(temp_exe_path, "wb") as exe_file:
if total_size == 0:
# If content-length header is missing, set a default size for progress bar
progress_bar.setRange(0, 0) # Indeterminate progress bar
label.setText("Downloading update... (size unknown)")
QApplication.processEvents()
for chunk in response.iter_content(chunk_size=1024):
if chunk:
exe_file.write(chunk)
downloaded_size += len(chunk)
if total_size > 0:
progress = int((downloaded_size / total_size) * 100)
progress_bar.setValue(progress)
label.setText(f"Downloading update... {progress}%")
QApplication.processEvents() # Update UI
else:
# Update UI even when we don't know the total size
label.setText(f"Downloading update... {downloaded_size} bytes")
QApplication.processEvents()
progress_dialog.close()
if not is_running_as_exe:
# If running as script, just move the downloaded file to current directory
import shutil
shutil.move(temp_exe_path, local_exe_path)
QMessageBox.information(self, "Update Complete",
f"Executable downloaded successfully!\n"
f"Location: {local_exe_path}\n"
f"Run this file to start the application as an executable.")
return
# Create an updater script that will run after this application closes
# Place the updater script in the same directory as the executable
updater_script = os.path.join(os.path.dirname(local_exe_path), "updater.bat")
with open(updater_script, "w") as f:
f.write(f"""@echo off
timeout /t 2 /nobreak >nul
taskkill /f /im WorkDayTimer.exe 2>nul
del "{local_exe_path}"
move "{temp_exe_path}" "{local_exe_path}"
:: Set the PATH to include system and user DLL directories
set "PATH=%PATH%;C:\\Windows\\System32;C:\\Windows\\SysWOW64"
cd /d "{os.path.dirname(local_exe_path)}"
start "" "{os.path.basename(local_exe_path)}"
del "%~f0"
""")
# Launch the updater script and exit the current application
import subprocess
# Set environment variables to help find DLLs
env = os.environ.copy()
env['PATH'] = env.get('PATH', '') + r';C:\Windows\System32;C:\Windows\SysWOW64'
subprocess.Popen(updater_script, shell=True, env=env)
self.exit_app()
else:
progress_dialog.close()
QMessageBox.critical(self, "Update Failed", f"Failed to download the update. HTTP Status Code: {response.status_code}")
except Exception as e:
if 'progress_dialog' in locals() and progress_dialog:
progress_dialog.close()
QMessageBox.critical(self, "Update Error", f"An error occurred during the update: {e}")
if __name__ == '__main__':
try:
app = QApplication(sys.argv)
workday_timer = WorkdayTimer(app)
sys.exit(app.exec_())
except Exception as e:
error_message = f"An error occurred: {e}"
print(error_message)
logging.error(error_message) # Write error message to log
self.tray_icon.setContextMenu(self.menu)
self.tray_icon.show()
self.tray_icon.activated.connect(self.icon_activated)
# Initialize custom countdown timer
self.custom_timer = None