-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathctf_timer.py
More file actions
1317 lines (1162 loc) · 48.3 KB
/
Copy pathctf_timer.py
File metadata and controls
1317 lines (1162 loc) · 48.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
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
#!/usr/bin/env python3
"""
Ouroboros: CTF Tracker
A minimalist, brutal timer for CTF players to enforce detachment.
Built with CustomTkinter. Audio via native Linux players (paplay/aplay).
"""
import customtkinter as ctk
import os
import sys
import tkinter as tk
import wave
import struct
import math
import tempfile
import random
import time
from datetime import datetime
from typing import List, Tuple, Optional
from PIL import Image
# ============== CONFIG / COLORS ==============
BG = "#121212"
TEXT_MUTED = "#888888"
TEXT_LIGHT = "#e5e5e5"
ACCENT_BLUE = "#2563eb" # Flag Captured
ACCENT_AMBER = "#d97706" # +5 Min (orange)
ACCENT_CRIMSON = "#b91c1c" # Timeout / harsh (crimson)
ACCENT_GHOST = "#6b7280" # Drop & Flag
SIDEBAR_BG = "#1a1a1a"
ENTRY_BG = "#1f1f1f"
EGO_LINES: List[str] = [
"Sunk cost mathematically loses to breadth. Drop it.",
"The server returned False. It is not personal. Move on.",
"Your ego is burning the clock. Next category.",
"You are evaluating a bad assumption. Leave it in the Ghosts list.",
]
def get_asset_path(filename: str) -> str:
"""Return absolute path to asset, works in script mode and PyInstaller onefile."""
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
base = sys._MEIPASS
else:
base = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base, "assets", filename)
class CTFTimerApp(ctk.CTk):
def __init__(self):
# className is critical: sets the initial WM_CLASS so Linux dock/launcher
# never sees the default "Tk" (even briefly). Must be first thing.
super().__init__(className="Ouroboros")
# Set app class name and title *immediately* after creation.
# className= on the CTk() constructor + repeated tk.call is the permanent
# way to get "Ouroboros" (not "Tk") for Fedora/GNOME dock + .desktop matching.
try:
self.tk.call("tk", "appname", "Ouroboros")
self.tk.call("wm", "title", self._w, "Ouroboros: CTF Tracker")
self.title("Ouroboros: CTF Tracker")
self.wm_iconname("Ouroboros: CTF Tracker")
except Exception:
pass
# Force Tk scaling as early as possible (helps on some Linux setups)
try:
scale = float(os.environ.get("CTF_TIMER_SCALE", "1.35"))
self.tk.call("tk", "scaling", scale)
except Exception:
pass
# Auto-choose a good initial window size based on screen for best timer display
# (avoids tiny font or cutoff on launch/fullscreen scenarios)
self.update_idletasks()
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
width = max(920, min(int(screen_width * 0.65), 1400))
height = max(580, min(int(screen_height * 0.70), 900))
x = (screen_width - width) // 2
y = (screen_height - height) // 2
self.geometry(f"{width}x{height}+{x}+{y}")
self.minsize(920, 580)
self.configure(fg_color=BG)
# Set window icon using bundled logo (True = default for WM)
try:
icon_path = get_asset_path("ouroboros_logo_128.png")
if os.path.exists(icon_path):
icon = tk.PhotoImage(file=icon_path)
self.iconphoto(True, icon)
self._icon_ref = icon # keep reference
except Exception:
pass
# Extra sets right after icon (belt and suspenders)
try:
self.tk.call("tk", "appname", "Ouroboros")
self.tk.call("wm", "title", self._w, "Ouroboros: CTF Tracker")
self.title("Ouroboros: CTF Tracker")
except Exception:
pass
# Re-apply aggressively at multiple points after mapping (this is what finally
# defeats any race where WM sees "Tk" on first realize). These cover most DEs.
self.after_idle(self._force_wm_class)
self.after(0, self._force_wm_class)
self.after(50, self._force_wm_class)
self.after(120, self._force_wm_class)
self.after(300, self._force_wm_class)
self.after(700, self._force_wm_class)
# State
self.default_seconds: int = 20 * 60
self.remaining_seconds: int = 20 * 60
self.initial_seconds: int = 20 * 60
self.problem_start_time: Optional[float] = None
self.is_running: bool = False
self.extension_used: bool = False
self.current_target: str = ""
self.kills: List[Tuple[str, str]] = [] # (name, "MM:SS")
self.ghosts: List[Tuple[str, str]] = [] # (name, "MM:SS")
self.buzzer_path: Optional[str] = None
self._tick_job: Optional[str] = None
self.timed_out: bool = False
self._blink_job: Optional[str] = None
self.current_overlay = None
self._ensure_buzzer()
self._ensure_success_sound()
self._ensure_drop_sound()
self._ensure_plus5_sound()
self._ensure_start_sound()
# UI Setup
self._setup_ui()
# Force correct title late (CTk unconditionally does self.title("CTk") inside its __init__)
self.title("Ouroboros: CTF Tracker")
self.tk.call("wm", "title", self._w, "Ouroboros: CTF Tracker")
# Close handler for persistence
self.protocol("WM_DELETE_WINDOW", self.on_closing)
# Initial state
self._update_timer_display()
self._update_action_buttons()
self._refresh_sidebar()
# Dynamic timer font on resize
self._resize_job = None
self.bind("<Configure>", self._on_window_configure)
self.after(150, self._resize_timer_font)
# Extra late title force (CTk can be stubborn)
self.after(400, lambda: self.title("Ouroboros: CTF Tracker"))
def _force_wm_class(self):
"""Aggressively force correct WM_CLASS (via className ctor) + title.
Called many times so it sticks after CustomTkinter init and window mapping.
This + build auto-install permanently fixes "Tk" + poor icon on Fedora."""
try:
self.tk.call("tk", "appname", "Ouroboros")
self.tk.call("wm", "title", self._w, "Ouroboros: CTF Tracker")
self.title("Ouroboros: CTF Tracker")
self.wm_iconname("Ouroboros: CTF Tracker")
except Exception:
pass
def _on_window_configure(self, event):
if event.widget == self:
if self._resize_job:
self.after_cancel(self._resize_job)
self._resize_job = self.after(120, self._resize_timer_font)
def _resize_timer_font(self):
"""Scale the big timer font based on the actual timer container size for perfect fit and centering."""
if not hasattr(self, 'timer_frame') or not self.timer_frame.winfo_exists():
return
if getattr(self, 'timed_out', False) and self.remaining_seconds <= 0:
return # keep quote font during timeout
try:
tw = self.timer_frame.winfo_width()
th = self.timer_frame.winfo_height()
if tw < 50 or th < 50:
return
# Find largest size where "10:00" (5 chars) fits with margin using actual font metrics.
# This prevents cutoff/overflow on resize or full screen.
font_size = 20
for sz in range(min(180, int(th * 0.65)), 19, -1):
f = tk.font.Font(family="monospace", size=sz, weight="bold")
text_w = f.measure("10:00")
text_h = sz * 1.2
if text_w < tw * 0.88 and text_h < th * 0.75:
font_size = sz
break
self.timer_label.configure(
font=ctk.CTkFont(family="monospace", size=font_size, weight="bold")
)
except Exception:
pass
# ------------------- UI BUILD -------------------
def _setup_ui(self):
# Main grid: left controls + center timer | right sidebar
self.grid_columnconfigure(0, weight=3, minsize=520)
self.grid_columnconfigure(1, weight=2, minsize=320)
self.grid_rowconfigure(0, weight=1)
# ===== LEFT / MAIN CONTENT =====
main = ctk.CTkFrame(self, fg_color=BG, corner_radius=0)
main.grid(row=0, column=0, sticky="nsew", padx=(16, 8), pady=16)
main.grid_columnconfigure(0, weight=1)
# Give the timer (row 6) the majority of vertical space
main.grid_rowconfigure(5, weight=1)
# Top branding: logo + title side by side
top_branding = ctk.CTkFrame(main, fg_color="transparent")
top_branding.grid(row=0, column=0, sticky="w", pady=(0, 2))
try:
logo_path = get_asset_path("ouroboros_logo_128.png")
if os.path.exists(logo_path):
pil = Image.open(logo_path)
ctk_img = ctk.CTkImage(light_image=pil, dark_image=pil, size=(42, 42))
logo_lbl = ctk.CTkLabel(top_branding, image=ctk_img, text="")
logo_lbl.grid(row=0, column=0, padx=(0, 8))
self._logo_ref = ctk_img # prevent GC
except Exception:
pass
header = ctk.CTkLabel(
top_branding,
text="OUROBOROS — CTF TRACKER",
font=ctk.CTkFont(family="monospace", size=16, weight="bold"),
text_color=TEXT_LIGHT
)
header.grid(row=0, column=1, sticky="w")
# Mode selector
mode_frame = ctk.CTkFrame(main, fg_color="transparent")
mode_frame.grid(row=1, column=0, sticky="ew", pady=(0, 10))
mode_frame.grid_columnconfigure((0, 1), weight=1)
self.mode_var = ctk.StringVar(value="20:00")
self.mode_btn_20 = ctk.CTkButton(
mode_frame,
text="STANDARD\n20:00",
font=ctk.CTkFont(family="monospace", size=13, weight="bold"),
fg_color="#1f2937",
hover_color="#374151",
text_color=TEXT_LIGHT,
corner_radius=6,
height=52,
command=lambda: self._set_mode(20)
)
self.mode_btn_20.grid(row=0, column=0, padx=(0, 6), sticky="ew")
self.mode_btn_10 = ctk.CTkButton(
mode_frame,
text="BLITZ\n10:00",
font=ctk.CTkFont(family="monospace", size=13, weight="bold"),
fg_color="#1f2937",
hover_color="#374151",
text_color=TEXT_LIGHT,
corner_radius=6,
height=52,
command=lambda: self._set_mode(10)
)
self.mode_btn_10.grid(row=0, column=1, padx=(6, 0), sticky="ew")
self._highlight_mode()
# Target input
target_label = ctk.CTkLabel(
main,
text="CURRENT TARGET",
font=ctk.CTkFont(family="monospace", size=11),
text_color=TEXT_MUTED
)
target_label.grid(row=2, column=0, sticky="w", pady=(8, 2))
entry_row = ctk.CTkFrame(main, fg_color="transparent")
entry_row.grid(row=3, column=0, sticky="ew", pady=(0, 8))
entry_row.grid_columnconfigure(0, weight=1)
self.target_entry = ctk.CTkEntry(
entry_row,
placeholder_text="Enter target name or category",
font=ctk.CTkFont(family="monospace", size=13),
fg_color=ENTRY_BG,
border_color="#333333",
text_color=TEXT_LIGHT,
height=38
)
self.target_entry.grid(row=0, column=0, sticky="ew", padx=(0, 6))
self.target_entry.bind("<Return>", lambda e: self.start_timer())
clear_btn = ctk.CTkButton(
entry_row,
text="✕",
width=38,
height=38,
font=ctk.CTkFont(size=14),
fg_color="#222222",
hover_color="#3f3f3f",
text_color=TEXT_MUTED,
command=lambda: (self.target_entry.delete(0, "end"), self.target_entry.focus())
)
clear_btn.grid(row=0, column=1, sticky="e")
# Start button
self.start_btn = ctk.CTkButton(
main,
text="START TIMER",
font=ctk.CTkFont(family="monospace", size=15, weight="bold"),
fg_color="#111111",
hover_color="#1f2937",
text_color="#22c55e",
border_width=2,
border_color="#22c55e",
height=44,
command=self.start_timer
)
self.start_btn.grid(row=4, column=0, sticky="ew", pady=(0, 16))
# Timer display
timer_frame = ctk.CTkFrame(main, fg_color=SIDEBAR_BG, corner_radius=8)
timer_frame.grid(row=5, column=0, sticky="nsew", pady=(4, 12))
timer_frame.grid_columnconfigure(0, weight=1)
timer_frame.grid_rowconfigure(0, weight=1)
timer_frame.grid_rowconfigure(1, weight=0) # active label small
# Temporary font; will be resized dynamically to fit
self.timer_label = ctk.CTkLabel(
timer_frame,
text="20:00",
font=ctk.CTkFont(family="monospace", size=40, weight="bold"),
text_color=TEXT_MUTED,
justify="center",
anchor="center"
)
self.timer_label.grid(row=0, column=0, sticky="nsew")
self.timer_frame = timer_frame # for resize calculations
self.timer_frame.bind("<Configure>", lambda e: self.after(80, self._resize_timer_font))
# Active problem display
self.active_label = ctk.CTkLabel(
timer_frame,
text="",
font=ctk.CTkFont(family="monospace", size=13),
text_color=ACCENT_BLUE
)
self.active_label.grid(row=1, column=0, pady=(0, 10))
# Action buttons
actions = ctk.CTkFrame(main, fg_color="transparent")
actions.grid(row=6, column=0, sticky="ew")
actions.grid_columnconfigure((0, 1, 2), weight=1)
self.flag_btn = ctk.CTkButton(
actions,
text="FLAG CAPTURED",
font=ctk.CTkFont(family="monospace", size=13, weight="bold"),
fg_color=ACCENT_BLUE,
hover_color="#1d4ed8",
text_color="white",
height=46,
command=self.flag_captured
)
self.flag_btn.grid(row=0, column=0, padx=(0, 6), sticky="ew")
self.plus5_btn = ctk.CTkButton(
actions,
text="+5 MIN",
font=ctk.CTkFont(family="monospace", size=13, weight="bold"),
fg_color=ACCENT_AMBER,
hover_color="#b45309",
text_color="white",
height=46,
command=self.add_five_minutes
)
self.plus5_btn.grid(row=0, column=1, padx=6, sticky="ew")
self.drop_btn = ctk.CTkButton(
actions,
text="DROP & FLAG",
font=ctk.CTkFont(family="monospace", size=13, weight="bold"),
fg_color=ACCENT_GHOST,
hover_color="#4b5563",
text_color="white",
height=46,
command=self.drop_and_flag
)
self.drop_btn.grid(row=0, column=2, padx=(6, 0), sticky="ew")
# Bottom bar: always on top + status
bottom = ctk.CTkFrame(main, fg_color="transparent")
bottom.grid(row=7, column=0, sticky="ew", pady=(14, 0))
self.topmost_var = ctk.BooleanVar(value=False)
self.topmost_btn = ctk.CTkButton(
bottom,
text="",
width=30,
height=18,
fg_color="#4b5563", # off
hover_color="#6b7280",
command=self._toggle_topmost
)
self.topmost_btn.grid(row=0, column=0, sticky="w", padx=(0, 5))
if self.topmost_var.get():
self.topmost_btn.configure(fg_color=ACCENT_AMBER)
self.status_label = ctk.CTkLabel(
bottom,
text="",
font=ctk.CTkFont(size=10),
text_color=TEXT_MUTED
)
self.status_label.grid(row=0, column=1, sticky="e")
# ===== RIGHT SIDEBAR =====
sidebar = ctk.CTkFrame(self, fg_color=SIDEBAR_BG, corner_radius=8)
sidebar.grid(row=0, column=1, sticky="nsew", padx=(8, 16), pady=16)
sidebar.grid_rowconfigure(1, weight=1)
sidebar.grid_rowconfigure(3, weight=1)
sidebar.grid_columnconfigure(0, weight=1)
# Kills header
kills_header = ctk.CTkLabel(
sidebar,
text="KILLS",
font=ctk.CTkFont(family="monospace", size=12, weight="bold"),
text_color=ACCENT_BLUE
)
kills_header.grid(row=0, column=0, sticky="w", padx=12, pady=(10, 4))
self.kills_box = ctk.CTkTextbox(
sidebar,
font=ctk.CTkFont(family="monospace", size=12),
fg_color="#111111",
text_color=TEXT_LIGHT,
border_color="#222222",
wrap="none"
)
self.kills_box.grid(row=1, column=0, sticky="nsew", padx=10, pady=(0, 8))
self.kills_box.configure(state="disabled")
# Strikethrough tag
self.kills_box._textbox.tag_config(
"strike",
overstrike=True,
foreground="#666666"
)
# Ghosts header
ghosts_header = ctk.CTkLabel(
sidebar,
text="GHOSTS",
font=ctk.CTkFont(family="monospace", size=12, weight="bold"),
text_color=ACCENT_GHOST
)
ghosts_header.grid(row=2, column=0, sticky="w", padx=12, pady=(6, 4))
self.ghosts_box = ctk.CTkTextbox(
sidebar,
font=ctk.CTkFont(family="monospace", size=12),
fg_color="#111111",
text_color=TEXT_LIGHT,
border_color="#222222",
wrap="none"
)
self.ghosts_box.grid(row=3, column=0, sticky="nsew", padx=10, pady=(0, 10))
self.ghosts_box.configure(state="disabled")
# Sidebar footer actions
side_footer = ctk.CTkFrame(sidebar, fg_color="transparent")
side_footer.grid(row=4, column=0, sticky="ew", padx=10, pady=(0, 10))
side_footer.grid_columnconfigure(0, weight=1)
export_btn = ctk.CTkButton(
side_footer,
text="EXPORT SESSION",
font=ctk.CTkFont(family="monospace", size=11),
fg_color="#222222",
hover_color="#333333",
text_color=TEXT_MUTED,
height=30,
command=self.export_session
)
export_btn.grid(row=0, column=0, sticky="ew")
def _highlight_mode(self):
if self.default_seconds == 20 * 60:
self.mode_btn_20.configure(fg_color=ACCENT_BLUE, text_color="white")
self.mode_btn_10.configure(fg_color="#1f2937", text_color=TEXT_LIGHT)
else:
self.mode_btn_10.configure(fg_color=ACCENT_AMBER, text_color="white")
self.mode_btn_20.configure(fg_color="#1f2937", text_color=TEXT_LIGHT)
def _set_mode(self, minutes: int):
if self.is_running:
return
self.default_seconds = minutes * 60
self.remaining_seconds = self.default_seconds
self._update_timer_display()
self._highlight_mode()
def _toggle_topmost(self):
val = not self.topmost_var.get()
self.topmost_var.set(val)
self.attributes("-topmost", val)
if val:
self.topmost_btn.configure(fg_color=ACCENT_AMBER) # orange on
else:
self.topmost_btn.configure(fg_color="#4b5563") # off gray
# ------------------- TIMER CORE -------------------
def _update_timer_display(self, force_color: Optional[str] = None):
if getattr(self, 'timed_out', False) and self.remaining_seconds <= 0:
return # quote is shown in timer area during timeout
text = self._format_time(self.remaining_seconds)
color = force_color or (ACCENT_CRIMSON if self.remaining_seconds <= 0 and not self.is_running else TEXT_MUTED)
self.timer_label.configure(text=text, text_color=color)
def _format_time(self, secs: int) -> str:
m = max(0, secs) // 60
s = max(0, secs) % 60
return f"{m:02d}:{s:02d}"
def _start_blink(self):
"""Start blinking the 00:00 after timeout."""
if getattr(self, 'timed_out', False):
self._blink_state = True
if self._blink_job:
self.after_cancel(self._blink_job)
self._do_blink()
def _do_blink(self):
if not getattr(self, 'timed_out', False) or self.remaining_seconds != 0:
return
color = ACCENT_CRIMSON if getattr(self, '_blink_state', True) else "#555555"
self.timer_label.configure(text_color=color)
self._blink_state = not getattr(self, '_blink_state', True)
self._blink_job = self.after(500, self._do_blink)
def _get_monospace_font(self, size: int):
"""Try common programming fonts that exist on most Linux systems."""
candidates = [
"JetBrains Mono",
"Fira Code",
"DejaVu Sans Mono",
"Liberation Mono",
"Source Code Pro",
"monospace",
"Courier New",
"Courier",
]
for fam in candidates:
try:
f = ctk.CTkFont(family=fam, size=size, weight="bold")
return f
except Exception:
continue
return ctk.CTkFont(size=size, weight="bold")
def _update_action_buttons(self):
running = self.is_running
post_timeout = getattr(self, 'timed_out', False) and bool(self.current_target)
can_act = running or post_timeout
# Start button
if running:
self.start_btn.configure(state="disabled", text="RUNNING")
else:
self.start_btn.configure(state="normal", text="START TIMER")
# Action buttons: allow after timeout too (user can still flag/drop/+5)
state = "normal" if can_act else "disabled"
self.flag_btn.configure(state=state)
self.drop_btn.configure(state=state)
# +5 if can act and not used (even post-timeout)
if can_act and not self.extension_used:
self.plus5_btn.configure(state="normal")
else:
self.plus5_btn.configure(state="disabled")
# Mode buttons disabled while running or post-timeout (active problem)
mstate = "disabled" if can_act else "normal"
self.mode_btn_20.configure(state=mstate)
self.mode_btn_10.configure(state=mstate)
# Target entry: only lock while actively running; allow edit post-timeout to start fresh if desired
if running:
self.target_entry.configure(state="disabled")
else:
self.target_entry.configure(state="normal")
def _set_active_display(self, text: str = ""):
self.active_label.configure(text=text)
def start_timer(self):
if self.is_running:
return
target = self.target_entry.get().strip()
if not target:
self.status_label.configure(text="Enter a target name to start", text_color=ACCENT_AMBER)
self.after(1800, lambda: self.status_label.configure(text=""))
return
# If abandoning a timed-out problem by starting new, auto-ghost it
if getattr(self, 'timed_out', False) and self.current_target:
elapsed = self._get_elapsed_seconds()
time_str = self._format_time(elapsed)
self.ghosts.append((self.current_target, f"{time_str} timeout"))
self._refresh_sidebar()
# Capture
self.current_target = target
self.initial_seconds = self.default_seconds
self.remaining_seconds = self.default_seconds
self.problem_start_time = time.time()
self.extension_used = False
self.is_running = True
self.timed_out = False
if self._blink_job:
self.after_cancel(self._blink_job)
self._blink_job = None
if getattr(self, 'current_overlay', None):
try:
self.current_overlay.destroy()
except Exception:
pass
self.current_overlay = None
self._set_active_display(f"▶ {self.current_target}")
self._update_timer_display()
self._update_action_buttons()
self.status_label.configure(text="")
# Play start sound
self._play_start_sound()
# Start ticking
self._schedule_tick()
def _schedule_tick(self):
if self._tick_job:
self.after_cancel(self._tick_job)
self._tick_job = self.after(1000, self._tick)
def _tick(self):
if not self.is_running:
return
self.remaining_seconds -= 1
self._update_timer_display()
if self.remaining_seconds <= 0:
self._handle_timeout()
return
self._schedule_tick()
def stop_timer(self, clear_current: bool = True):
self.is_running = False
if self._tick_job:
self.after_cancel(self._tick_job)
self._tick_job = None
if self._blink_job:
self.after_cancel(self._blink_job)
self._blink_job = None
self.timed_out = False
if self.current_overlay:
try:
self.current_overlay.destroy()
except Exception:
pass
self.current_overlay = None
# Reset visual timer to current mode default for next run
self.remaining_seconds = self.default_seconds
self._update_timer_display()
self._update_action_buttons()
if clear_current:
self._clear_current_problem()
def _clear_current_problem(self):
self.current_target = ""
self.target_entry.delete(0, "end")
self._set_active_display("")
self.extension_used = False
self.problem_start_time = None
self.timed_out = False
if self._blink_job:
self.after_cancel(self._blink_job)
self._blink_job = None
if self.current_overlay:
try:
self.current_overlay.destroy()
except Exception:
pass
self.current_overlay = None
# ------------------- ACTIONS -------------------
def add_five_minutes(self):
if not (self.is_running or getattr(self, 'timed_out', False)) or self.extension_used:
return
was_post_timeout = not self.is_running and getattr(self, 'timed_out', False)
self.remaining_seconds += 5 * 60
self.extension_used = True
self.timed_out = False
if self._blink_job:
self.after_cancel(self._blink_job)
self._blink_job = None
if was_post_timeout:
self.is_running = True
self._schedule_tick()
self._update_timer_display()
self._update_action_buttons()
self._play_plus5_sound()
self.status_label.configure(text="+5 added (locked for this problem)", text_color=ACCENT_AMBER)
self.after(1600, lambda: self.status_label.configure(text="") if not (self.is_running or self.timed_out) else None)
# Auto close the timeout banner if user takes action
if getattr(self, 'current_overlay', None):
try:
self.current_overlay.destroy()
except Exception:
pass
self.current_overlay = None
def flag_captured(self):
if not (self.is_running or getattr(self, 'timed_out', False)):
return
name = self.current_target
elapsed = self._get_elapsed_seconds()
time_str = self._format_time(elapsed)
self.kills.append((name, time_str))
self._refresh_sidebar()
# Play positive success sound (Mario-style)
self._play_success_sound()
self.timed_out = False
if self._blink_job:
self.after_cancel(self._blink_job)
self._blink_job = None
self.stop_timer(clear_current=True)
self._update_timer_display() # reset color
# Auto close the timeout banner if user takes action
if getattr(self, 'current_overlay', None):
try:
self.current_overlay.destroy()
except Exception:
pass
self.current_overlay = None
def drop_and_flag(self):
if not (self.is_running or getattr(self, 'timed_out', False)):
return
name = self.current_target
elapsed = self._get_elapsed_seconds()
time_str = self._format_time(elapsed)
self.ghosts.append((name, time_str))
self._refresh_sidebar()
# Play drop sound
self._play_drop_sound()
self.timed_out = False
if self._blink_job:
self.after_cancel(self._blink_job)
self._blink_job = None
self.stop_timer(clear_current=True)
self._update_timer_display()
# Auto close the timeout banner if user takes action
if getattr(self, 'current_overlay', None):
try:
self.current_overlay.destroy()
except Exception:
pass
self.current_overlay = None
def _get_elapsed_seconds(self) -> int:
if self.problem_start_time:
return max(0, int(time.time() - self.problem_start_time))
# Fallback to initial - remaining (less accurate if +5 used)
return max(0, self.initial_seconds - self.remaining_seconds)
# ------------------- TIMEOUT / EGO DROP -------------------
def _handle_timeout(self):
self.is_running = False
if self._tick_job:
self.after_cancel(self._tick_job)
self._tick_job = None
# Visual: show quote in the timer area (where timer is displayed)
self.remaining_seconds = 0
self.timed_out = True
quote = random.choice(EGO_LINES)
# Make sure full quote is visible: wrap to box width, readable size
tw = self.timer_frame.winfo_width() or 500
self.timer_label.configure(
text=quote,
text_color=ACCENT_CRIMSON,
font=ctk.CTkFont(family="monospace", size=15, weight="bold"),
wraplength=tw - 30
)
self._update_action_buttons()
# Play sound
self._play_buzzer()
# Show the overlay banner (non-modal, does not block action buttons)
self._show_ego_overlay()
def _show_ego_overlay(self):
# Do NOT disable action buttons (flag, +5, drop) -- user can use them with banner visible
# Only disable start/modes/entry
self.start_btn.configure(state="disabled")
self.target_entry.configure(state="disabled")
self.mode_btn_20.configure(state="disabled")
self.mode_btn_10.configure(state="disabled")
overlay = ctk.CTkToplevel(self)
overlay.overrideredirect(True)
overlay.attributes("-topmost", True)
overlay.configure(fg_color=BG)
self.current_overlay = overlay
# Top banner attached to this app window (small height so it doesn't cover action buttons)
# Scaled for HiDPI. Stays until manually closed.
scale = float(os.environ.get("CTF_TIMER_SCALE", "1.35"))
popup_width = int(self.winfo_width() * 0.95)
popup_height = int(80 * scale)
self.update_idletasks()
app_x = self.winfo_x()
app_y = self.winfo_y()
overlay.geometry(f"{popup_width}x{popup_height}+{app_x}+{app_y}")
# Use inner frame for better alignment/padding
inner = ctk.CTkFrame(overlay, fg_color=BG)
inner.pack(expand=True, fill="both", padx=20, pady=10)
# Content - minimal, no quote (quote shown in main timer area below)
title = ctk.CTkLabel(
inner,
text="⏱ TIME'S UP",
font=ctk.CTkFont(family="monospace", size=22, weight="bold"),
text_color=ACCENT_CRIMSON
)
title.pack(pady=(0, 4))
sub = ctk.CTkLabel(
inner,
text="4 second circuit breaker active.",
font=ctk.CTkFont(family="monospace", size=13),
text_color=TEXT_LIGHT
)
sub.pack(pady=(0, 8))
# Manual close only - no auto after
def finish(overlay_widget):
try:
overlay_widget.destroy()
except Exception:
pass
self.current_overlay = None
self._set_all_controls_disabled(False)
# set back to 00:00 in timer area
self.timer_label.configure(
text="00:00",
text_color=ACCENT_CRIMSON,
font=ctk.CTkFont(family="monospace", size=60, weight="bold") # will be resized
)
self._start_blink()
# restore correct per-state button enables (post-timeout allows actions)
self._update_action_buttons()
# Do NOT reset or clear target.
# Timer stays at 00:00 (blinking), user can still Drop/Flag/+5 the current one.
# Close button for manual dismiss (popup does not auto close)
close_btn = ctk.CTkButton(
inner,
text="✕ Close / Continue",
font=ctk.CTkFont(family="monospace", size=12),
fg_color=ACCENT_CRIMSON,
hover_color="#8b0000", # darker crimson
command=lambda o=overlay: finish(o)
)
close_btn.pack()
# No grab_set: non-modal, user can interact with main window buttons below the banner
def _set_all_controls_disabled(self, disabled: bool):
state = "disabled" if disabled else "normal"
for btn in (self.start_btn, self.flag_btn, self.plus5_btn, self.drop_btn,
self.mode_btn_20, self.mode_btn_10):
btn.configure(state=state)
self.target_entry.configure(state=state)
self.topmost_btn.configure(state=state)
# ------------------- SIDEBAR -------------------
def _refresh_sidebar(self):
# Kills
self.kills_box.configure(state="normal")
self.kills_box.delete("1.0", "end")
for name, t in self.kills:
# Show both the markdown-style strikethrough text + real overstrike tag
line = f"~~{name} ({t})~~\n"
self.kills_box.insert("end", line)
last_line_start = self.kills_box.index("end-2l")
last_line_end = self.kills_box.index("end-1l")
try:
self.kills_box._textbox.tag_add("strike", last_line_start, last_line_end)
except Exception:
pass # fallback to the ~~ visual only
self.kills_box.configure(state="disabled")
# Ghosts
self.ghosts_box.configure(state="normal")
self.ghosts_box.delete("1.0", "end")
for name, t in self.ghosts:
self.ghosts_box.insert("end", f"{name} ({t})\n")
self.ghosts_box.configure(state="disabled")
# ------------------- PERSISTENCE -------------------
def export_session(self):
if not self.kills and not self.ghosts:
self.status_label.configure(text="Nothing to export yet", text_color=TEXT_MUTED)
self.after(1400, lambda: self.status_label.configure(text=""))
return
date_str = datetime.now().strftime("%Y-%m-%d")
filename = f"ctf_session_{date_str}.md"
try:
with open(filename, "w", encoding="utf-8") as f:
f.write(f"# CTF Session — {date_str}\n\n")
f.write("**Ouroboros: CTF Tracker Log**\n\n")
f.write("## KILLS (Solved)\n\n")
if self.kills:
for name, t in self.kills:
f.write(f"- ~~{name} ({t})~~\n")
else:
f.write("_None_\n")
f.write("\n## GHOSTS (Flagged / Unsolved)\n\n")
if self.ghosts:
for name, t in self.ghosts:
f.write(f"- {name} ({t})\n")
else:
f.write("_None_\n")
f.write("\n---\n")
f.write(f"Generated by Ouroboros CTF Tracker on {datetime.now().isoformat(timespec='seconds')}\n")
self.status_label.configure(text=f"Exported → {filename}", text_color=ACCENT_BLUE)
self.after(2200, lambda: self.status_label.configure(text=""))
except Exception as e:
self.status_label.configure(text=f"Export failed: {e}", text_color=ACCENT_CRIMSON)
def on_closing(self):
try:
self.export_session()
except Exception:
pass
self.destroy()
# ------------------- AUDIO -------------------
def _ensure_buzzer(self):
self.buzzer_path = os.path.join(tempfile.gettempdir(), "ouroboros_ctf_buzzer.wav")
if not os.path.exists(self.buzzer_path):
self._generate_buzzer(self.buzzer_path)
def _generate_buzzer(self, path: str):
"""Generate a harsh, jarring multi-beep buzzer (stdlib only). ~4.5s"""
framerate = 44100
# ~4.5s total: many short harsh bursts
with wave.open(path, "w") as wf:
wf.setparams((1, 2, framerate, 0, "NONE", "not compressed"))
samples = []
freqs = [980, 1240, 920, 1350] # harsh alternating