-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRCR
More file actions
2271 lines (1964 loc) · 96.3 KB
/
Copy pathRCR
File metadata and controls
2271 lines (1964 loc) · 96.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
"""
RCR v0.5 — RuleFlow Chain Runner (Cross-Platform)
Graphical front-end for: rulest_v2.py -> concentrator.py -> ranker.py
Fully compatible with Windows 10+ and Linux (X11/Wayland).
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
import subprocess
import threading
import os
import sys
import glob
import shlex
import re
import queue
import time
import gc
import hashlib
from dataclasses import dataclass
from typing import Optional, List, Tuple, Callable, Dict
from collections import defaultdict
# ── Platform bootstrap ─────────────────────────────────────────────────────
def _set_dpi_awareness() -> None:
"""Enable DPI awareness on Windows so the GUI renders correctly on
high-DPI displays (4K monitors, laptops with scaling > 100%)."""
if sys.platform == "win32":
try:
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1) # type: ignore[attr-defined]
except Exception:
try:
ctypes.windll.user32.SetProcessDPIAware() # type: ignore[attr-defined]
except Exception:
pass
_set_dpi_awareness()
# On Windows, force UTF-8 for stdin/stdout/stderr so that rule files,
# wordlists and log output containing non-ASCII characters are handled
# identically to Linux.
if sys.platform == "win32":
import io
if sys.stdout.encoding != "utf-8":
try:
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
except Exception:
pass
# SCRIPT_DIR must resolve correctly whether we are running from source or
# from a frozen PyInstaller/pex bundle.
if getattr(sys, "frozen", False):
SCRIPT_DIR = os.path.dirname(sys.executable)
else:
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
APP_TITLE = "RCR - RuleFlow Chain Runner"
# ── Cross-platform font resolution ─────────────────────────────────────────
if sys.platform == "win32":
FONT_UI = "Segoe UI"
FONT_MONO = "Consolas"
else:
# Linux / macOS fallbacks. Tkinter will degrade gracefully if the
# first choice is missing, but DejaVu is present on almost all distros.
FONT_UI = "DejaVu Sans"
FONT_MONO = "DejaVu Sans Mono"
def ui_font(size: int = 10, weight: str = "normal") -> Tuple[str, int, str]:
return (FONT_UI, size, weight)
def mono_font(size: int = 9) -> Tuple[str, int]:
return (FONT_MONO, size)
# ── Theme ──────────────────────────────────────────────────────────────────
@dataclass(frozen=True)
class Theme:
name: str = "dark"
bg: str = "#0f1115"
surface: str = "#181a20"
card: str = "#1e2128"
elevated: str = "#252830"
border: str = "#2f333c"
fg: str = "#e4e6eb"
fg2: str = "#8b909e"
accent: str = "#58a6ff"
accent_hover: str = "#79b8ff"
success: str = "#3fb950"
warning: str = "#d29922"
danger: str = "#f85149"
info: str = "#a371f7"
log_bg: str = "#0d0f14"
DARK_THEME = Theme(
name="dark",
bg="#0f1115", surface="#181a20", card="#1e2128", elevated="#252830",
border="#2f333c", fg="#e4e6eb", fg2="#8b909e", accent="#58a6ff",
accent_hover="#79b8ff", success="#3fb950", warning="#d29922",
danger="#f85149", info="#a371f7", log_bg="#0d0f14",
)
LIGHT_THEME = Theme(
name="light",
bg="#f4f5f7", surface="#ffffff", card="#ffffff", elevated="#eef1f5",
border="#d7dbe1", fg="#1b1e24", fg2="#5b6270", accent="#2563eb",
accent_hover="#3b76ea", success="#1a7f37", warning="#9a6700",
danger="#cf222e", info="#7c3aed", log_bg="#fbfbfc",
)
class _ThemeProxy:
"""Lets the rest of the codebase keep using `THEME.xxx` unmodified while
the active palette can be swapped at runtime (dark/light mode)."""
def __init__(self, initial: Theme):
object.__setattr__(self, "_current", initial)
@property
def current(self) -> Theme:
return self._current # type: ignore[has-type]
def set(self, theme: Theme):
object.__setattr__(self, "_current", theme)
def __getattr__(self, item):
return getattr(self._current, item) # type: ignore[has-type]
THEME = _ThemeProxy(DARK_THEME)
# ── ANSI → tkinter mapping ─────────────────────────────────────────────────
# Palette used when the log panel has a dark background (default).
ANSI_COLOURS_DARK = {
"30": "#2f333c", "31": "#f85149", "32": "#3fb950", "33": "#d29922",
"34": "#58a6ff", "35": "#bc8cff", "36": "#39c5cf", "37": "#e4e6eb",
"90": "#6e7681", "91": "#ff7b72", "92": "#7ee787", "93": "#ffa657",
"94": "#79b8ff", "95": "#d2a8ff", "96": "#56d4dd", "97": "#ffffff",
}
# Palette used when the log panel has a light background — the dark palette's
# near-white/pastel tones (e.g. codes 37/97/90/94/95/96) are almost invisible
# on a light background, so these are darkened/saturated for contrast.
ANSI_COLOURS_LIGHT = {
"30": "#1b1e24", "31": "#cf222e", "32": "#1a7f37", "33": "#9a6700",
"34": "#2563eb", "35": "#8250df", "36": "#0969a2", "37": "#57606a",
"90": "#6e7681", "91": "#c4262e", "92": "#116329", "93": "#7d4e00",
"94": "#1d4ed8", "95": "#6639ba", "96": "#0c6b8e", "97": "#1b1e24",
}
ANSI_RE = re.compile(r'\x1b\[([0-9;]*)m')
def active_ansi_colours() -> dict:
"""Returns the ANSI colour palette matching the currently active theme."""
return ANSI_COLOURS_LIGHT if THEME.current.name == "light" else ANSI_COLOURS_DARK
def strip_ansi(text: str) -> str:
return ANSI_RE.sub("", text)
def parse_ansi_segments(text: str) -> List[Tuple[str, Optional[str]]]:
"""Split text into (chunk, colour_hex) segments."""
colours = active_ansi_colours()
segments = []
pos = 0
current_fg = None
for m in ANSI_RE.finditer(text):
if m.start() > pos:
segments.append((text[pos:m.start()], current_fg))
codes = m.group(1).split(";") if m.group(1) else ["0"]
for code in codes:
if code in ("0", ""):
current_fg = None
elif code in colours:
current_fg = colours[code]
pos = m.end()
if pos < len(text):
segments.append((text[pos:], current_fg))
return segments
# tqdm (and similar) progress bars are rendered by the *external* tool with
# whatever width it decides on, which varies with description length, digit
# counts in the counters, etc. — making the log look ragged/uneven. Since we
# can't change how those tools draw their bars, we detect the "NN%|<bar>|"
# segment and re-render just that portion at a fixed width, so every bar in
# the log (regardless of which stage or tool produced it) lines up evenly.
_TQDM_BAR_RE = re.compile(r'(\d{1,3})%\|([^|]*)\|')
PROGRESS_BAR_WIDTH = 30
def normalize_progress_bars(text: str) -> str:
def _replace(m: "re.Match") -> str:
try:
pct = max(0, min(100, int(m.group(1))))
except ValueError:
return m.group(0)
filled = round(PROGRESS_BAR_WIDTH * pct / 100)
bar = "█" * filled + " " * (PROGRESS_BAR_WIDTH - filled)
return f"{pct}%|{bar}|"
return _TQDM_BAR_RE.sub(_replace, text)
# ── Theme switching (light / dark) ─────────────────────────────────────────
_TK_COLOR_OPTIONS = (
"bg", "background", "fg", "foreground",
"activebackground", "activeforeground", "disabledforeground",
"highlightbackground", "highlightcolor",
"insertbackground", "selectbackground", "selectforeground",
"troughcolor", "selectcolor",
)
def _theme_color_map(old: Theme, new: Theme) -> dict:
fields = ("bg", "surface", "card", "elevated", "border", "fg", "fg2",
"accent", "accent_hover", "success", "warning", "danger", "info")
return {getattr(old, f): getattr(new, f) for f in fields}
def _retheme_widget(widget, color_map: dict):
for opt in _TK_COLOR_OPTIONS:
try:
cur = widget.cget(opt)
except Exception:
continue
if cur in color_map:
try:
widget.configure(**{opt: color_map[cur]})
except Exception:
pass
# ModernButton caches its own hover/base colours outside of tk's option
# database, so those need to be remapped too or hovering will revert them.
base_bg = getattr(widget, "_base_bg", None)
if base_bg in color_map:
widget._base_bg = color_map[base_bg]
hover_bg = getattr(widget, "_hover_bg", None)
if hover_bg in color_map:
widget._hover_bg = color_map[hover_bg]
def _retheme_tree(widget, color_map: dict):
_retheme_widget(widget, color_map)
try:
children = widget.winfo_children()
except Exception:
children = []
for child in children:
_retheme_tree(child, color_map)
OOM_PATTERNS = re.compile(
r"memoryerror|out of memory|bad_alloc|allocation failed|"
r"failed to allocate|cl_mem|clerror|memory allocation failed|"
r"gpu memory allocation failed|killed\b",
re.IGNORECASE,
)
# ==============================================================================
# CONCENTRATOR-COMPATIBLE RULE HELPERS (copied from concentrator.py)
# ==============================================================================
_NEVER_PRODUCE_OPS = frozenset({'M', '4', '6', 'X', '<', '>', '!', '/', '(', ')', '=', '%', 'Q'})
_OPERATOR_ARGS: Dict[str, List[str]] = {
':': [], 'l': [], 'u': [], 'c': [], 'C': [], 't': [], 'r': [], 'd': [], 'f': [],
'{': [], '}': [], '[': [], ']': [], 'q': [], 'k': [], 'K': [], 'E': [],
'T': ['num'], 'p': ['num'], 'D': ['num'], 'z': ['num'], 'Z': ['num'], "'": ['num'],
'+': ['num'], '-': ['num'], '.': ['num'], ',': ['num'], 'L': ['num'], 'R': ['num'],
'y': ['num'], 'Y': ['num'], '<': ['num'], '>': ['num'], '_': ['num'],
'x': ['num', 'num'], 'O': ['num', 'num'], '*': ['num', 'num'],
'$': ['char'], '^': ['char'], '@': ['char'], 'e': ['char'],
's': ['char', 'char'],
'i': ['num', 'char'], 'o': ['num', 'char'], '3': ['num', 'char'],
}
def _build_token_regex() -> re.Pattern:
patterns = []
for op, args in _OPERATOR_ARGS.items():
escaped = re.escape(op)
arg_pat = ''.join('[0-9A-Z]' if a == 'num' else '[ -~]' for a in args)
patterns.append(escaped + arg_pat)
patterns.sort(key=len, reverse=True)
return re.compile('|'.join(patterns))
_TOKEN_REGEX = _build_token_regex()
def _has_banned_op(rule: str) -> bool:
tokens = _TOKEN_REGEX.findall(rule)
return any(t[0] in _NEVER_PRODUCE_OPS for t in tokens)
def _i36(s: str) -> int:
return int(s, 36)
def is_valid_hashcat_rule(rule: str) -> bool:
if _has_banned_op(rule):
return False
if not rule.strip():
return False
pos = 0
cnt = 0
n = len(rule)
def is_digit(c: str) -> bool:
return ('0' <= c <= '9') or ('A' <= c <= 'Z')
while pos < n:
c = rule[pos]
if c == ' ':
pos += 1
continue
if c in ('p', 'z', 'Z'):
cnt += 1
pos += 1
if pos < n and is_digit(rule[pos]):
pos += 1
continue
if c in (':', 'l', 'u', 'c', 'C', 't', 'r', 'd', 'f', 'q', 'k', 'K',
'E', '{', '}', '[', ']'):
pos += 1
cnt += 1
continue
if c in ('T', 'D', 'L', 'R', '+', '-', '.', ',', "'", 'y', 'Y', '_'):
pos += 1
if pos >= n or not is_digit(rule[pos]):
return False
pos += 1
cnt += 1
continue
if c in ('i', 'o', '3'):
pos += 1
if pos >= n or not is_digit(rule[pos]):
return False
pos += 1
if pos >= n:
return False
pos += 1
cnt += 1
continue
if c in ('x', '*', 'O'):
pos += 1
if pos >= n or not is_digit(rule[pos]):
return False
pos += 1
if pos >= n or not is_digit(rule[pos]):
return False
pos += 1
cnt += 1
continue
if c == 's':
pos += 1
if pos + 1 >= n:
return False
pos += 2
cnt += 1
continue
if c in ('@', 'e', '$', '^'):
pos += 1
if pos >= n:
return False
pos += 1
cnt += 1
continue
return False
return 1 <= cnt <= 255
# ── Simplified RuleEngine (from concentrator) ────────────────────────────────
class _RuleEngine:
def __init__(self, rules: List[str]) -> None:
self._token_lists = [_TOKEN_REGEX.findall(r) for r in rules]
self.memorized = ''
def apply(self, string: str) -> str:
word = string
self.memorized = ''
for tokens in self._token_lists:
for token in tokens:
try:
word = self._dispatch(token, word)
except Exception:
pass
return word
def _dispatch(self, token: str, word: str) -> str:
op = token[0]
args = token[1:]
if op == ':':
return word
elif op == 'l':
return word.lower()
elif op == 'u':
return word.upper()
elif op == 'c':
return word.capitalize()
elif op == 'C':
return word.capitalize().swapcase()
elif op == 't':
return word.swapcase()
elif op == 'T':
n = _i36(args[0])
if n >= len(word):
return word
return word[:n] + word[n].swapcase() + word[n + 1:]
elif op == 'r':
return word[::-1]
elif op == 'd':
return word + word
elif op == 'p':
if not args:
return word
return word * (_i36(args[0]) + 1)
elif op == 'f':
return word + word[::-1]
elif op == '{':
return (word[1:] + word[0]) if word else word
elif op == '}':
return (word[-1] + word[:-1]) if word else word
elif op == '$':
return word + args[0]
elif op == '^':
return args[0] + word
elif op == '[':
return word[1:]
elif op == ']':
return word[:-1]
elif op == 'D':
n = _i36(args[0])
return word[:n] + word[n + 1:] if n < len(word) else word
elif op == 'x':
n, m = _i36(args[0]), _i36(args[1])
if n < 0 or m < 0:
return word
return word[n:n + m]
elif op == 'O':
n, m = _i36(args[0]), _i36(args[1])
if n < 0 or m < 0 or n >= len(word):
return word
return word[:n] + word[n + m:]
elif op == 'i':
pos = min(_i36(args[0]), len(word))
return word[:pos] + args[1] + word[pos:]
elif op == 'o':
pos = _i36(args[0])
return word[:pos] + args[1] + word[pos + 1:] if pos < len(word) else word
elif op == "'":
return word[:_i36(args[0])]
elif op == 's':
return word.replace(args[0], args[1])
elif op == '@':
return word.replace(args[0], '')
elif op == 'z':
n = _i36(args[0])
return word[0] * n + word if word else ''
elif op == 'Z':
n = _i36(args[0])
return word + word[-1] * n if word else ''
elif op == 'q':
return ''.join(c * 2 for c in word)
elif op == 'E':
out = []
cap = True
for ch in word:
if cap and ch.islower():
out.append(ch.upper())
elif not cap and ch.isupper():
out.append(ch.lower())
else:
out.append(ch)
cap = (ch == ' ')
return ''.join(out)
elif op == 'e':
sep = args[0]
out = []
cap = True
for ch in word:
if cap and ch.islower():
out.append(ch.upper())
elif not cap and ch.isupper():
out.append(ch.lower())
else:
out.append(ch)
cap = (ch == sep)
return ''.join(out)
else:
return word
# ── Memory Monitor ─────────────────────────────────────────────────────────
class MemoryMonitor:
def __init__(self, threshold_mb: float = 6144.0):
self.threshold_mb = threshold_mb
self._have_psutil = False
try:
import psutil
self._have_psutil = True
self._psutil = psutil
self._self_proc = psutil.Process()
except ImportError:
self._psutil = None
self._self_proc = None
self._child_pid: Optional[int] = None
def set_child_pid(self, pid: Optional[int]):
self._child_pid = pid
def current_mb(self) -> float:
if not self._have_psutil:
return 0.0
total = 0.0
try:
total += self._self_proc.memory_info().rss
except Exception:
pass
if self._child_pid:
try:
p = self._psutil.Process(self._child_pid)
total += p.memory_info().rss
for c in p.children(recursive=True):
try:
total += c.memory_info().rss
except Exception:
pass
except Exception:
pass
return total / (1024 * 1024)
def is_under_pressure(self) -> bool:
return self.current_mb() > self.threshold_mb
def format(self) -> str:
mb = self.current_mb()
if not self._have_psutil:
return "n/a (psutil not installed)"
if mb > 1024:
return f"{mb/1024:.2f} GB"
return f"{mb:.0f} MB"
# ── Bounded Log Queue ──────────────────────────────────────────────────────
class BoundedLogQueue:
def __init__(self, maxsize: int = 4000):
self._queue: queue.Queue = queue.Queue(maxsize=maxsize)
self._dropped = 0
self._lock = threading.Lock()
def put(self, item, block: bool = False, timeout: float = 0.1) -> bool:
try:
self._queue.put(item, block=block, timeout=timeout)
return True
except queue.Full:
with self._lock:
self._dropped += 1
return False
def get_nowait(self):
return self._queue.get_nowait()
def clear_dropped(self) -> int:
with self._lock:
d = self._dropped
self._dropped = 0
return d
# ── Process Wrapper ────────────────────────────────────────────────────────
class ManagedProcess:
def __init__(self):
self._proc: Optional[subprocess.Popen] = None
self._terminated = False
self._lock = threading.Lock()
self._queue: queue.Queue = queue.Queue()
self._reader_thread: Optional[threading.Thread] = None
@property
def pid(self) -> Optional[int]:
return self._proc.pid if self._proc else None
def start(self, cmd: List[str], cwd: str, env: dict) -> bool:
with self._lock:
if self._proc is not None:
return False
try:
popen_kwargs = {
"stdin": subprocess.DEVNULL,
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"bufsize": 0,
"cwd": cwd,
"env": env,
}
# On Windows, running from a tkinter GUI without a console
# attached will cause every subprocess to spawn a visible CMD
# window. CREATE_NO_WINDOW suppresses that.
if sys.platform == "win32":
popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW # type: ignore[attr-defined]
self._proc = subprocess.Popen(cmd, **popen_kwargs)
self._terminated = False
self._queue = queue.Queue()
self._reader_thread = threading.Thread(target=self._reader_loop, daemon=True)
self._reader_thread.start()
return True
except Exception as e:
print(f"Failed to start process: {e}", file=sys.stderr)
return False
def _reader_loop(self, chunk_size: int = 4096):
if self._proc is None or self._proc.stdout is None:
self._queue.put(None)
return
buf = ""
decoder_leftover = b""
while True:
if self._terminated:
break
try:
raw = self._proc.stdout.read(chunk_size)
except (OSError, ValueError):
break
if not raw:
break
raw = decoder_leftover + raw
try:
text = raw.decode("utf-8")
decoder_leftover = b""
except UnicodeDecodeError as e:
text = raw[:e.start].decode("utf-8", errors="replace")
decoder_leftover = raw[e.start:]
buf += text
while True:
idx_n = buf.find("\n")
idx_r = buf.find("\r")
if idx_n == -1 and idx_r == -1:
break
if idx_n != -1 and idx_r != -1:
idx = min(idx_n, idx_r)
elif idx_n != -1:
idx = idx_n
else:
idx = idx_r
piece = buf[:idx]
buf = buf[idx + 1:]
if idx == idx_r and buf.startswith("\n"):
buf = buf[1:]
self._queue.put(("line", piece))
if buf:
self._queue.put(("line", buf))
self._queue.put(None)
def iter_events(self, timeout: float = 0.3, chunk_size: int = 4096):
while True:
if self._terminated:
break
try:
item = self._queue.get(timeout=timeout)
except queue.Empty:
if self._proc is not None and self._proc.poll() is not None:
while True:
try:
item = self._queue.get_nowait()
except queue.Empty:
return
if item is None:
return
continue
if item is None:
break
yield item
def terminate(self, wait: float = 3.0) -> None:
with self._lock:
self._terminated = True
if self._proc is None:
return
try:
self._proc.terminate()
try:
self._proc.wait(timeout=0.5)
except subprocess.TimeoutExpired:
# On Windows, killing the parent often leaves orphaned
# child processes (e.g. Python multiprocessing workers).
# If psutil is available, walk the tree and kill them.
if sys.platform == "win32":
try:
import psutil
parent = psutil.Process(self._proc.pid)
for child in parent.children(recursive=True):
try:
child.kill()
except psutil.NoSuchProcess:
pass
except Exception:
pass
self._proc.kill()
self._proc.wait(timeout=wait)
except Exception:
pass
finally:
if self._proc and self._proc.stdout:
try:
self._proc.stdout.close()
except Exception:
pass
self._proc = None
@property
def returncode(self) -> Optional[int]:
with self._lock:
if self._proc is None:
return None
return self._proc.poll()
# ── UI Helpers ───────────────────────────────────────────────────────────────
class ModernButton(tk.Button):
def __init__(self, master, text="", command=None, variant="primary",
font=None, padx=None, pady=None, **kw):
self.variant = variant
colors = {
"primary": (THEME.accent, "#0a0a0a", THEME.accent_hover),
"danger": (THEME.danger, "#0a0a0a", "#ff7b72"),
"secondary": (THEME.surface, THEME.fg, THEME.elevated),
"ghost": (THEME.bg, THEME.fg2, THEME.surface),
}
bg, fg, hover_bg = colors.get(variant, colors["primary"])
btn_font = font or ui_font(10, "bold" if variant == "primary" else "normal")
btn_padx = padx if padx is not None else 14
btn_pady = pady if pady is not None else 7
super().__init__(
master, text=text, command=command,
bg=bg, fg=fg, activebackground=hover_bg, activeforeground=fg,
disabledforeground="#5c6270",
relief="flat", bd=0, cursor="hand2",
font=btn_font, padx=btn_padx, pady=btn_pady,
**kw
)
if variant != "primary":
self.config(highlightbackground=THEME.border, highlightthickness=1)
self._hover_bg = hover_bg
self._base_bg = bg
self.bind("<Enter>", self._on_enter)
self.bind("<Leave>", self._on_leave)
def _on_enter(self, _event=None):
if self.cget("state") != "disabled":
self.config(bg=self._hover_bg)
def _on_leave(self, _event=None):
if self.cget("state") != "disabled":
self.config(bg=self._base_bg)
class Section(tk.Frame):
def __init__(self, master, title: str, **kw):
super().__init__(
master, bg=THEME.card,
highlightbackground=THEME.border, highlightthickness=1,
padx=14, pady=10, **kw
)
tk.Label(
self, text=title, bg=THEME.card, fg=THEME.accent,
font=ui_font(10, "bold")
).pack(anchor="w", pady=(0, 8))
self.body = tk.Frame(self, bg=THEME.card)
self.body.pack(fill="both", expand=True)
class Expander(tk.Frame):
def __init__(self, master, title: str, subtitle: str = "", start_open: bool = False, **kw):
super().__init__(
master, bg=THEME.card,
highlightbackground=THEME.border, highlightthickness=1, **kw
)
self._open = tk.BooleanVar(value=start_open)
head = tk.Frame(self, bg=THEME.card, cursor="hand2")
head.pack(fill="x", padx=12, pady=8)
self._arrow = tk.Label(head, text="▸", bg=THEME.card, fg=THEME.accent,
font=ui_font(10, "bold"), width=2)
self._arrow.pack(side="left")
titles = tk.Frame(head, bg=THEME.card)
titles.pack(side="left", fill="x", expand=True)
tk.Label(titles, text=title, bg=THEME.card, fg=THEME.fg,
font=ui_font(10, "bold"), anchor="w").pack(fill="x")
if subtitle:
tk.Label(titles, text=subtitle, bg=THEME.card, fg=THEME.fg2,
font=ui_font(8), anchor="w").pack(fill="x")
self.body = tk.Frame(self, bg=THEME.card, padx=12, pady=10)
for w in (head, self._arrow, titles):
w.bind("<Button-1>", self._toggle)
for child in titles.winfo_children():
child.bind("<Button-1>", self._toggle)
if start_open:
self.body.pack(fill="x")
self._arrow.config(text="▾")
def _toggle(self, _=None):
if self._open.get():
self.body.pack_forget()
self._arrow.config(text="▸")
else:
self.body.pack(fill="x")
self._arrow.config(text="▾")
self._open.set(not self._open.get())
class FilePicker(tk.Frame):
def __init__(self, master, label: str, **kw):
super().__init__(master, bg=THEME.card, **kw)
tk.Label(self, text=label, bg=THEME.card, fg=THEME.fg2,
font=ui_font(9), width=18, anchor="w").pack(side="left")
self.var = tk.StringVar()
self.entry = tk.Entry(
self, textvariable=self.var, bg=THEME.surface, fg=THEME.fg,
insertbackground=THEME.accent, relief="flat", bd=0,
highlightbackground=THEME.border, highlightthickness=1,
font=mono_font()
)
self.entry.pack(side="left", fill="x", expand=True, padx=(0, 8), ipady=4)
ModernButton(self, text="Browse", command=self._browse, variant="secondary").pack(side="left")
def _browse(self):
p = filedialog.askopenfilename()
if p:
self.var.set(p)
def get(self) -> str:
return self.var.get().strip()
def set(self, value: str):
self.var.set(value)
class ModernSlider(tk.Frame):
def __init__(self, master, label: str, from_: float, to: float,
resolution: float, default: float, is_float: bool = False,
unit: str = "", **kw):
super().__init__(master, bg=THEME.card, **kw)
self.is_float = is_float
tk.Label(self, text=label, bg=THEME.card, fg=THEME.fg2,
font=ui_font(9), width=24, anchor="w").pack(side="left")
self.var = tk.DoubleVar(value=default)
self.scale = tk.Scale(
self, variable=self.var, from_=from_, to=to, resolution=resolution,
orient="horizontal", bg=THEME.card, fg=THEME.fg, troughcolor=THEME.surface,
highlightthickness=0, showvalue=False, bd=0,
activebackground=THEME.accent, length=150, command=self._on_scale
)
self.scale.pack(side="left", padx=(0, 8))
self.entry_var = tk.StringVar(value=self._fmt(default))
self.entry = tk.Entry(
self, textvariable=self.entry_var, bg=THEME.surface, fg=THEME.accent,
insertbackground=THEME.accent, relief="flat", bd=0,
highlightbackground=THEME.border, highlightthickness=1,
font=mono_font(), width=9, justify="right"
)
self.entry.pack(side="left")
self.entry.bind("<FocusOut>", self._on_entry)
self.entry.bind("<Return>", self._on_entry)
if unit:
tk.Label(self, text=unit, bg=THEME.card, fg=THEME.fg2,
font=ui_font(8)).pack(side="left", padx=(4, 0))
def _fmt(self, v) -> str:
v = float(v)
return f"{v:.1f}" if self.is_float else str(int(v))
def _on_scale(self, v):
self.entry_var.set(self._fmt(v))
def _on_entry(self, _=None):
try:
v = float(self.entry_var.get())
sc_from = float(self.scale.cget("from"))
sc_to = float(self.scale.cget("to"))
v = max(sc_from, min(v, sc_to))
self.var.set(v)
self.entry_var.set(self._fmt(v))
except ValueError:
self.entry_var.set(self._fmt(self.var.get()))
def get(self) -> float:
try:
return float(self.entry_var.get())
except ValueError:
return float(self.var.get())
def set(self, v: float):
sc_from = float(self.scale.cget("from"))
sc_to = float(self.scale.cget("to"))
v = max(sc_from, min(v, sc_to))
self.var.set(v)
self.scale.set(v)
self.entry_var.set(self._fmt(v))
class ModeCard(tk.Frame):
def __init__(self, master, title: str, subtitle: str, value: str,
selected: bool = False, command: Optional[Callable] = None, **kw):
super().__init__(
master, bg=THEME.elevated if selected else THEME.card,
highlightbackground=THEME.accent if selected else THEME.border,
highlightthickness=2 if selected else 1,
padx=12, pady=8, cursor="hand2", **kw
)
self.value = value
self.command = command
tk.Label(self, text=title, bg=self.cget("bg"),
fg=THEME.accent if selected else THEME.fg,
font=ui_font(10, "bold")).pack(anchor="w")
tk.Label(self, text=subtitle, bg=self.cget("bg"), fg=THEME.fg2,
font=ui_font(8), justify="left").pack(anchor="w", pady=(3, 0))
for w in [self] + list(self.winfo_children()):
w.bind("<Button-1>", lambda _e: self.command and self.command(self.value))
def set_selected(self, selected: bool):
bg = THEME.elevated if selected else THEME.card
fg = THEME.accent if selected else THEME.fg
self.config(bg=bg, highlightbackground=THEME.accent if selected else THEME.border,
highlightthickness=2 if selected else 1)
for child in self.winfo_children():
child.config(bg=bg)
if isinstance(child, tk.Label) and "bold" in str(child.cget("font")):
child.config(fg=fg)
class StageCheck(tk.Frame):
"""A checkbox widget for toggling pipeline stages with a description."""
def __init__(self, master, label: str, description: str, variable: tk.BooleanVar,
command: Optional[Callable] = None, **kw):
super().__init__(master, bg=THEME.card, **kw)
self.variable = variable
self.command = command
self.cb = tk.Checkbutton(
self, text=label, variable=variable, bg=THEME.card, fg=THEME.fg,
selectcolor=THEME.surface, activebackground=THEME.card,
activeforeground=THEME.fg, font=ui_font(10, "bold"),
command=self._on_toggle
)
self.cb.pack(anchor="w")
tk.Label(self, text=description, bg=THEME.card, fg=THEME.fg2,
font=ui_font(8), justify="left", anchor="w").pack(anchor="w", padx=(24, 0))
def _on_toggle(self):
if self.command:
self.command()
# ── Main Application ─────────────────────────────────────────────────────────
# Log display is kept unbounded per user preference — the queue that feeds
# it is unbounded too (see BoundedLogQueue(maxsize=0) below), so no output is
# ever dropped or trimmed, either on screen or in the mirrored log file.
class RCRApp(tk.Tk):
def __init__(self):
super().__init__()
self.title(APP_TITLE)
# ── Window / taskbar icon ─────────────────────────────────────────
try:
icon_path = os.path.join(SCRIPT_DIR, "rcr_icon_128.png")
if os.path.exists(icon_path):
self._icon_img = tk.PhotoImage(file=icon_path)
self.iconphoto(True, self._icon_img)
except Exception:
pass
self.configure(bg=THEME.bg)