-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
715 lines (605 loc) · 25.3 KB
/
main.py
File metadata and controls
715 lines (605 loc) · 25.3 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
from __future__ import annotations
import atexit
import csv
import json
import os
import re
import shutil
import subprocess
import sys
import time
from datetime import datetime
from pathlib import Path
from typing import Optional
import psutil
from PySide6 import QtCore, QtGui, QtWidgets
IS_WINDOWS = sys.platform.startswith("win")
IS_LINUX = sys.platform.startswith("linux")
if IS_WINDOWS:
import winreg
import win32gui
import win32process
def get_app_dir() -> Path:
"""Directory for external files (settings.json). Next to the executable."""
if hasattr(sys, "frozen"): # PyInstaller
return Path(sys.executable).resolve().parent
return Path(__file__).resolve().parent # Development
def get_data_dir() -> Path:
"""Directory for bundled assets (font.ttf, icon.ico)."""
if hasattr(sys, "_MEIPASS"): # PyInstaller bundles to _MEIPASS
return Path(sys._MEIPASS)
return Path(__file__).resolve().parent # Development
APP_DIR = get_app_dir()
DATA_DIR = get_data_dir()
SETTINGS_PATH = APP_DIR / "settings.json"
FONT_PATH = DATA_DIR / "font.ttf"
ICON_PATH = DATA_DIR / "icon.ico"
LOCK_PATH = APP_DIR / ".lock"
DEFAULT_SETTINGS = {"pos": [24, 24], "opacity": 0.5, "font_size": 22, "save_csv": False, "wait_period": 20.0}
CSV_PATH = APP_DIR / "queue_log.csv"
TF2_PROCESS_NAMES = ["tf_win64.exe"] if IS_WINDOWS else ["tf_linux64", "hl2_linux"]
QUEUE_START_PATTERN = re.compile(
r"^\[PartyClient\] (?:Requesting queue for|Entering queue for match group) .*Casual Match\b"
r"|^\[ReliableMsg\] PartyQueueForMatch started\b"
)
MATCH_FOUND_PATTERN = re.compile(
r"^\[PartyClient\] Leaving queue for match group .*Casual Match\b"
r"|^\[ReliableMsg\] AcceptLobbyInvite\b"
r"|^Lobby created\s*$"
r"|^Differing lobby received\.",
re.IGNORECASE,
)
MAP_PATTERN = re.compile(r"^Map:\s*([A-Za-z0-9_]+)")
def load_settings() -> dict:
if SETTINGS_PATH.exists():
try:
return {**DEFAULT_SETTINGS, **json.loads(SETTINGS_PATH.read_text())}
except Exception:
pass
return DEFAULT_SETTINGS.copy()
def save_settings(settings: dict) -> None:
try:
SETTINGS_PATH.write_text(json.dumps(settings, indent=2))
except Exception:
pass
def ensure_settings_file() -> None:
if not SETTINGS_PATH.exists():
save_settings(DEFAULT_SETTINGS)
def save_queue_to_csv(duration_seconds: float, map_name: Optional[str]) -> None:
"""Append queue data to CSV file."""
try:
file_exists = CSV_PATH.exists()
with open(CSV_PATH, "a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
if not file_exists:
writer.writerow(["timestamp", "duration_seconds", "duration_formatted", "map"])
writer.writerow([
datetime.now().isoformat(timespec="seconds"),
f"{duration_seconds:.3f}",
format_mmss_mmm(duration_seconds),
map_name or ""
])
except Exception:
pass
_xdotool_warned = False
def is_tf2_running() -> bool:
try:
names = {name.lower() for name in TF2_PROCESS_NAMES}
for proc in psutil.process_iter(["name"]):
name = (proc.info.get("name") or "").lower()
if name in names:
return True
except Exception:
pass
return False
def _warn_xdotool_missing() -> None:
global _xdotool_warned
if _xdotool_warned:
return
_xdotool_warned = True
print("Warning: xdotool not found. Overlay visibility will follow TF2 process.", file=sys.stderr)
def _get_focused_pid() -> Optional[int]:
try:
result = subprocess.run(
["xdotool", "getwindowfocus", "getwindowpid"],
capture_output=True,
text=True,
check=True,
timeout=0.25,
)
return int(result.stdout.strip())
except (subprocess.TimeoutExpired, ValueError, OSError):
return None
except Exception:
return None
def is_tf2_focused() -> bool:
if IS_WINDOWS:
try:
hwnd = win32gui.GetForegroundWindow()
if not hwnd:
return False
_, pid = win32process.GetWindowThreadProcessId(hwnd)
return psutil.Process(pid).name().lower() in {n.lower() for n in TF2_PROCESS_NAMES}
except Exception:
return False
if shutil.which("xdotool") is None:
_warn_xdotool_missing()
return is_tf2_running()
pid = _get_focused_pid()
if not pid:
return is_tf2_running()
try:
return psutil.Process(pid).name().lower() in {n.lower() for n in TF2_PROCESS_NAMES}
except Exception:
return is_tf2_running()
def get_steam_path() -> Optional[Path]:
if IS_WINDOWS:
for root, subkey, value in [
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Valve\Steam", "InstallPath"),
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Valve\Steam", "InstallPath"),
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Valve\Steam", "SteamPath"),
]:
try:
key = winreg.OpenKey(root, subkey)
val, _ = winreg.QueryValueEx(key, value)
winreg.CloseKey(key)
p = Path(val)
if p.exists() and (p / "steam.exe").exists():
return p
except OSError:
continue
for p in [
Path(r"C:\Program Files (x86)\Steam"),
Path(r"C:\Program Files\Steam"),
Path(r"D:\Steam"),
Path(r"D:\SteamLibrary"),
Path(r"E:\Steam"),
Path(r"E:\SteamLibrary"),
]:
if p.exists() and (p / "steam.exe").exists():
return p
return None
if IS_LINUX:
candidates = [
Path.home() / ".local" / "share" / "Steam",
Path.home() / ".steam" / "steam",
]
for p in candidates:
if p.exists() and (p / "steamapps").exists():
return p
return None
return None
def get_library_folders(steam_path: Path) -> list[Path]:
libs = [steam_path]
vdf_path = steam_path / "steamapps" / "libraryfolders.vdf"
if not vdf_path.exists():
return libs
try:
text = vdf_path.read_text(encoding="utf-8", errors="ignore")
strings = re.findall(r'"([^"]*)"', text)
for i, s in enumerate(strings):
if s.lower() == "path" and i + 1 < len(strings):
p = Path(strings[i + 1])
if p.exists() and p not in libs:
libs.append(p)
except Exception:
pass
return libs
def find_tf2_tf_dir() -> Optional[Path]:
steam_path = get_steam_path()
if not steam_path:
return None
for lib in get_library_folders(steam_path):
tf_dir = lib / "steamapps" / "common" / "Team Fortress 2" / "tf"
if tf_dir.exists():
return tf_dir
return None
def clear_console_log(log_path: Path) -> None:
try:
with open(log_path, "w", encoding="utf-8", errors="ignore"):
pass
except Exception:
pass
class ConsoleLogFollower:
def __init__(self, path: Path):
self.path = path
self.f = None
self._last_size = 0
def open(self) -> None:
self.f = open(self.path, "r", encoding="utf-8", errors="ignore")
self.f.seek(0, os.SEEK_END)
try:
self._last_size = self.path.stat().st_size
except OSError:
self._last_size = 0
def close(self) -> None:
if self.f:
try:
self.f.close()
except Exception:
pass
self.f = None
def poll_lines(self, max_lines: int = 250) -> list[str]:
try:
if self.f is None:
self.open()
try:
current_size = self.path.stat().st_size
if current_size < self._last_size:
self.close()
self.open()
self._last_size = current_size
except OSError:
pass
lines = []
for _ in range(max_lines):
pos = self.f.tell()
line = self.f.readline()
if not line:
self.f.seek(pos, os.SEEK_SET)
break
lines.append(line.rstrip("\n"))
return lines
except (OSError, IOError):
self.close()
return []
def format_mmss_mmm(seconds: float) -> str:
seconds = max(0.0, min(seconds, 99 * 3600 + 99 * 60 + 99.9))
total_ms = int(seconds * 1000.0)
total_secs = total_ms // 1000
hours, mins, secs = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60
ms = total_ms % 1000
if hours > 0:
return f"{hours:02d}:{mins:02d}:{secs:02d}.{ms // 100}"
return f"{mins:02d}:{secs:02d}.{ms:03d}"
_cached_app_icon: Optional[QtGui.QIcon] = None
def get_app_icon() -> QtGui.QIcon:
global _cached_app_icon
if _cached_app_icon is not None:
return _cached_app_icon
if ICON_PATH.exists():
_cached_app_icon = QtGui.QIcon(str(ICON_PATH))
else:
pix = QtGui.QPixmap(64, 64)
pix.fill(QtCore.Qt.GlobalColor.transparent)
p = QtGui.QPainter(pix)
p.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing)
p.setBrush(QtGui.QColor(26, 26, 30, 255))
p.setPen(QtGui.QPen(QtGui.QColor(255, 255, 255, 170), 2))
p.drawRoundedRect(8, 8, 48, 48, 12, 12)
p.setPen(QtGui.QPen(QtGui.QColor(255, 255, 255, 220), 3))
p.drawLine(22, 34, 32, 44)
p.drawLine(32, 44, 46, 24)
p.end()
_cached_app_icon = QtGui.QIcon(pix)
return _cached_app_icon
class SettingsDialog(QtWidgets.QDialog):
def __init__(self, overlay: "OverlayWindow", parent=None):
super().__init__(parent)
self.overlay = overlay
self.settings = overlay.settings.copy()
self.setWindowTitle("Settings")
self.setWindowIcon(get_app_icon())
self.setFixedWidth(300)
layout = QtWidgets.QVBoxLayout(self)
layout.setSpacing(12)
# Opacity
opacity_group = QtWidgets.QGroupBox("Opacity")
opacity_layout = QtWidgets.QHBoxLayout(opacity_group)
self.opacity_slider = QtWidgets.QSlider(QtCore.Qt.Orientation.Horizontal)
self.opacity_slider.setRange(10, 100)
self.opacity_slider.setValue(int(self.settings["opacity"] * 100))
self.opacity_label = QtWidgets.QLabel(f"{int(self.settings['opacity'] * 100)}%")
self.opacity_label.setFixedWidth(40)
self.opacity_slider.valueChanged.connect(self._on_opacity_change)
opacity_layout.addWidget(self.opacity_slider)
opacity_layout.addWidget(self.opacity_label)
layout.addWidget(opacity_group)
# Font Size
font_group = QtWidgets.QGroupBox("Font Size")
font_layout = QtWidgets.QHBoxLayout(font_group)
self.font_slider = QtWidgets.QSlider(QtCore.Qt.Orientation.Horizontal)
self.font_slider.setRange(14, 40)
self.font_slider.setValue(int(self.settings["font_size"]))
self.font_label = QtWidgets.QLabel(f"{int(self.settings['font_size'])}pt")
self.font_label.setFixedWidth(40)
self.font_slider.valueChanged.connect(self._on_font_change)
font_layout.addWidget(self.font_slider)
font_layout.addWidget(self.font_label)
layout.addWidget(font_group)
# Position
pos_group = QtWidgets.QGroupBox("Position (X, Y)")
pos_layout = QtWidgets.QHBoxLayout(pos_group)
self.pos_x = QtWidgets.QSpinBox()
self.pos_x.setRange(0, 3840)
self.pos_x.setValue(self.settings["pos"][0])
self.pos_y = QtWidgets.QSpinBox()
self.pos_y.setRange(0, 2160)
self.pos_y.setValue(self.settings["pos"][1])
pos_layout.addWidget(QtWidgets.QLabel("X:"))
pos_layout.addWidget(self.pos_x)
pos_layout.addWidget(QtWidgets.QLabel("Y:"))
pos_layout.addWidget(self.pos_y)
layout.addWidget(pos_group)
# Save to CSV
self.csv_checkbox = QtWidgets.QCheckBox("Save queue data to CSV")
self.csv_checkbox.setChecked(self.settings.get("save_csv", False))
self.csv_checkbox.setToolTip("When enabled, saves queue time and map to queue_log.csv")
layout.addWidget(self.csv_checkbox)
# Wait Period
wait_group = QtWidgets.QGroupBox("Wait Period (Seconds)")
wait_layout = QtWidgets.QHBoxLayout(wait_group)
self.wait_spin = QtWidgets.QSpinBox()
self.wait_spin.setRange(0, 120)
self.wait_spin.setValue(int(self.settings.get("wait_period", 20.0)))
self.wait_spin.setToolTip("Delay before saving to CSV to allow map detection.")
wait_layout.addWidget(self.wait_spin)
layout.addWidget(wait_group)
# Buttons
btn_layout = QtWidgets.QHBoxLayout()
self.save_btn = QtWidgets.QPushButton("Save")
self.cancel_btn = QtWidgets.QPushButton("Cancel")
self.save_btn.clicked.connect(self._save)
self.cancel_btn.clicked.connect(self.reject)
btn_layout.addStretch()
btn_layout.addWidget(self.save_btn)
btn_layout.addWidget(self.cancel_btn)
layout.addLayout(btn_layout)
def _on_opacity_change(self, value: int):
self.opacity_label.setText(f"{value}%")
self.overlay.setWindowOpacity(value / 100.0)
def _on_font_change(self, value: int):
self.font_label.setText(f"{value}pt")
def _save(self):
self.settings["opacity"] = self.opacity_slider.value() / 100.0
self.settings["font_size"] = self.font_slider.value()
self.settings["pos"] = [self.pos_x.value(), self.pos_y.value()]
self.settings["save_csv"] = self.csv_checkbox.isChecked()
self.settings["wait_period"] = float(self.wait_spin.value())
self.overlay.settings = self.settings
self.overlay.setWindowOpacity(self.settings["opacity"])
self.overlay.move(*self.settings["pos"])
self.overlay.timer_label.setFont(self.overlay._font(self.settings["font_size"] + 10, True))
self.overlay.adjustSize()
save_settings(self.settings)
self.accept()
def reject(self):
# Restore original opacity on cancel
self.overlay.setWindowOpacity(self.overlay.settings["opacity"])
super().reject()
class OverlayWindow(QtWidgets.QWidget):
_STATUS_STYLES = {
"IDLE": "QLabel#StatusPill { padding: 4px 10px; border-radius: 999px; color: rgba(255,255,255,230); background-color: rgba(120,120,120,95); border: 1px solid rgba(255,255,255,45); min-width: 110px; }",
"QUEUEING": "QLabel#StatusPill { padding: 4px 10px; border-radius: 999px; color: rgba(255,255,255,230); background-color: rgba(255,193,7,100); border: 1px solid rgba(255,255,255,45); min-width: 110px; }",
"MATCH FOUND": "QLabel#StatusPill { padding: 4px 10px; border-radius: 999px; color: rgba(255,255,255,230); background-color: rgba(76,175,80,100); border: 1px solid rgba(255,255,255,45); min-width: 110px; }",
}
def __init__(self, log_path: Path):
super().__init__()
self.settings = load_settings()
self.status = "IDLE"
self._last_status = ""
self.queue_start_perf: Optional[float] = None
self.last_match_found_seconds = 0.0
self.map_name: Optional[str] = None
self.follower = ConsoleLogFollower(log_path)
self.setObjectName("Root")
self.setWindowTitle("TF2 Queue Timer")
self.setWindowIcon(get_app_icon())
self.setWindowFlags(
QtCore.Qt.WindowType.FramelessWindowHint
| QtCore.Qt.WindowType.Tool
| QtCore.Qt.WindowType.WindowStaysOnTopHint
)
self.setAttribute(QtCore.Qt.WidgetAttribute.WA_TranslucentBackground, True)
self.setAttribute(QtCore.Qt.WidgetAttribute.WA_ShowWithoutActivating, True)
self.setWindowOpacity(float(self.settings["opacity"]))
self.move(*self.settings["pos"])
self._load_font()
self._build_ui()
self.poll_timer = QtCore.QTimer(self)
self.poll_timer.timeout.connect(self._on_poll_tick)
self.poll_timer.start(100)
self.ui_timer = QtCore.QTimer(self)
self.ui_timer.timeout.connect(self._update_ui)
self.proc_timer = QtCore.QTimer(self)
self.proc_timer.timeout.connect(self._sync_visibility)
self.proc_timer.start(500)
self._sync_visibility()
self._pending_csv_duration: Optional[float] = None
def _load_font(self):
self.font_family = None
if FONT_PATH.exists():
font_id = QtGui.QFontDatabase.addApplicationFont(str(FONT_PATH))
families = QtGui.QFontDatabase.applicationFontFamilies(font_id)
if families:
self.font_family = families[0]
def _font(self, size: int, bold: bool = False) -> QtGui.QFont:
f = QtGui.QFont(self.font_family or "Segoe UI")
f.setPointSize(size)
f.setBold(bold)
f.setStyleStrategy(QtGui.QFont.StyleStrategy.PreferAntialias)
return f
def _build_ui(self):
self.card = QtWidgets.QFrame(self)
self.card.setObjectName("Card")
shadow = QtWidgets.QGraphicsDropShadowEffect(self.card)
shadow.setBlurRadius(24)
shadow.setOffset(0, 10)
shadow.setColor(QtGui.QColor(0, 0, 0, 110))
self.card.setGraphicsEffect(shadow)
root = QtWidgets.QVBoxLayout(self)
root.setContentsMargins(0, 0, 0, 0)
root.addWidget(self.card)
layout = QtWidgets.QVBoxLayout(self.card)
layout.setContentsMargins(14, 12, 14, 12)
layout.setSpacing(10)
header = QtWidgets.QHBoxLayout()
header.setSpacing(10)
self.title_label = QtWidgets.QLabel("Queue Timer")
self.title_label.setFont(self._font(11, True))
self.title_label.setObjectName("Title")
self.status_pill = QtWidgets.QLabel("IDLE")
self.status_pill.setFont(self._font(10, True))
self.status_pill.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
self.status_pill.setObjectName("StatusPill")
header.addWidget(self.title_label, 1)
header.addWidget(self.status_pill, 0)
layout.addLayout(header)
self.timer_label = QtWidgets.QLabel("--:--.---")
self.timer_label.setFont(self._font(int(self.settings["font_size"]) + 10, True))
self.timer_label.setObjectName("Timer")
self.timer_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignLeft)
layout.addWidget(self.timer_label)
self.map_label = QtWidgets.QLabel("Map: —")
self.map_label.setFont(self._font(11, False))
self.map_label.setObjectName("Meta")
layout.addWidget(self.map_label)
self.setStyleSheet("""
QFrame#Card { background-color: rgba(18,18,20,165); border: 1px solid rgba(255,255,255,40); border-radius: 14px; }
QLabel#Title { color: rgba(255,255,255,220); }
QLabel#Timer { color: rgba(255,255,255,240); }
QLabel#Meta { color: rgba(255,255,255,175); }
QLabel#StatusPill { padding: 4px 10px; border-radius: 999px; color: rgba(255,255,255,230); background-color: rgba(120,120,120,95); border: 1px solid rgba(255,255,255,45); min-width: 110px; }
""")
self._update_ui()
def _sync_visibility(self):
if is_tf2_focused():
if not self.isVisible():
self.show()
self.raise_()
elif self.isVisible():
self.hide()
def _on_poll_tick(self):
for line in self.follower.poll_lines():
self._handle_line(line)
def _handle_line(self, line: str):
m = MAP_PATTERN.search(line)
if m:
self.map_name = m.group(1)
self._update_ui()
return
if QUEUE_START_PATTERN.search(line):
self.status = "QUEUEING"
self.queue_start_perf = time.perf_counter()
self.last_match_found_seconds = 0.0
self.map_name = None
self._update_timers()
return
if self.status == "QUEUEING" and self.queue_start_perf and MATCH_FOUND_PATTERN.search(line):
self.status = "MATCH FOUND"
self.last_match_found_seconds = time.perf_counter() - self.queue_start_perf
self.queue_start_perf = None
self._update_timers()
if self.settings.get("save_csv", False):
self._pending_csv_duration = self.last_match_found_seconds
wait_ms = int(self.settings.get("wait_period", 20.0) * 1000)
QtCore.QTimer.singleShot(wait_ms, self._save_pending_csv)
def _save_pending_csv(self):
"""Save CSV after delay to allow map name detection."""
if self._pending_csv_duration is not None:
# Only save if we have a valid map name
if self.map_name:
save_queue_to_csv(self._pending_csv_duration, self.map_name)
self._pending_csv_duration = None
def _update_timers(self):
if self.status == "QUEUEING":
self.poll_timer.setInterval(50)
if not self.ui_timer.isActive():
self.ui_timer.start(16)
else:
self.poll_timer.setInterval(100)
if self.ui_timer.isActive():
self.ui_timer.stop()
self._update_ui()
def _elapsed_seconds(self) -> float:
if self.status == "QUEUEING" and self.queue_start_perf:
return time.perf_counter() - self.queue_start_perf
if self.status == "MATCH FOUND":
return self.last_match_found_seconds
return 0.0
def _update_ui(self):
self.timer_label.setText("--:--.---" if self.status == "IDLE" else format_mmss_mmm(self._elapsed_seconds()))
if self.status != self._last_status:
self.status_pill.setText(self.status)
self.status_pill.setStyleSheet(self._STATUS_STYLES[self.status])
self._last_status = self.status
self.map_label.setText(f"Map: {self.map_name}" if self.map_name else "Map: —")
self.adjustSize()
def reset_timer(self):
self.status = "IDLE"
self.queue_start_perf = None
self.last_match_found_seconds = 0.0
self.map_name = None
self._update_timers()
self._update_ui()
def show_settings(self):
dialog = SettingsDialog(self)
dialog.exec()
def build_tray(app: QtWidgets.QApplication, window: OverlayWindow) -> QtWidgets.QSystemTrayIcon:
tray = QtWidgets.QSystemTrayIcon(app)
tray.setIcon(get_app_icon())
tray.setToolTip("TF2 Queue Timer Overlay")
menu = QtWidgets.QMenu()
menu.addAction("Settings...").triggered.connect(window.show_settings)
menu.addAction("Reset Timer").triggered.connect(window.reset_timer)
menu.addSeparator()
menu.addAction("Quit").triggered.connect(app.quit)
tray.setContextMenu(menu)
tray.show()
return tray
def acquire_lock() -> bool:
try:
if LOCK_PATH.exists():
try:
old_pid = int(LOCK_PATH.read_text().strip())
if psutil.pid_exists(old_pid):
try:
proc = psutil.Process(old_pid)
if "python" in proc.name().lower() or "tf2queuetimer" in proc.name().lower():
return False
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
except (ValueError, OSError):
pass
LOCK_PATH.write_text(str(os.getpid()))
return True
except Exception:
return True
def release_lock() -> None:
try:
if LOCK_PATH.exists() and int(LOCK_PATH.read_text().strip()) == os.getpid():
LOCK_PATH.unlink()
except Exception:
pass
def main():
if not acquire_lock():
app = QtWidgets.QApplication([])
app.setWindowIcon(get_app_icon())
QtWidgets.QMessageBox.warning(None, "TF2 Queue Timer", "Another instance is already running.\nCheck your system tray.")
sys.exit(0)
atexit.register(release_lock)
ensure_settings_file()
tf_dir = find_tf2_tf_dir()
if not tf_dir:
app = QtWidgets.QApplication([])
app.setWindowIcon(get_app_icon())
QtWidgets.QMessageBox.critical(None, "TF2 Queue Timer", "Could not find TF2 installation.\nMake sure TF2 is installed via Steam.")
sys.exit(1)
log_path = tf_dir / "console.log"
if not log_path.exists():
app = QtWidgets.QApplication([])
app.setWindowIcon(get_app_icon())
QtWidgets.QMessageBox.warning(None, "TF2 Queue Timer",
f"TF2 console.log was not found.\n\nAdd -condebug to TF2 launch options:\nSteam → Library → TF2 → Properties → Launch Options\n\nExpected: {tf_dir}\\console.log")
sys.exit(1)
clear_console_log(log_path)
app = QtWidgets.QApplication([])
app.setWindowIcon(get_app_icon())
app.setQuitOnLastWindowClosed(False)
window = OverlayWindow(log_path)
window.hide()
tray = build_tray(app, window)
QtCore.QTimer.singleShot(400, lambda: tray.showMessage("TF2 Queue Timer started", "Running in the system tray.\nRight-click the tray icon for options.", QtWidgets.QSystemTrayIcon.MessageIcon.Information, 6000) if tray.supportsMessages() else None)
sys.exit(app.exec())
if __name__ == "__main__":
main()