-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
2214 lines (2010 loc) · 92.4 KB
/
Copy pathgui.py
File metadata and controls
2214 lines (2010 loc) · 92.4 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
"""PersonalCleaner — Windows 11 / WinUI 3 style UI (PyQt6).
This is a full rewrite of the interface using PyQt6 with a Fluent / WinUI 3
look (solid neutrals, single blue accent, rounded controls, navigation view
with collapse). The engine (quick_fix.py) is unchanged.
"""
import sys
import os
import base64
import winreg
from datetime import datetime
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
import psutil
import quick_fix as qf
COMMERCIAL = qf.COMMERCIAL
licensing = qf.licensing
MB = 1024 * 1024
# --------------------------------------------------------------------------- #
# Theme tokens (Fluent / Windows 11)
# --------------------------------------------------------------------------- #
LIGHT = {
"app_bg": "#EBEFFF", "surface": "#FFFFFF", "surface_alt": "#E6E9FF",
"nav_bg": "#F8F9FF", "text": "#0B0B0B", "text_secondary": "#4A5568",
"border": "#D6DCFF", "border_strong": "#B8C0E0",
"accent": "#0F6CBD", "accent_hover": "#115EA3", "accent_pressed": "#0C3B5E",
"on_accent": "#FFFFFF", "selected_bg": "#E0EDFF", "hover_bg": "#E8ECFF",
"disabled_bg": "#EEF0FF", "disabled_text": "#94A3B8",
"success": "#0E7A0E", "warning": "#92400E", "error": "#C53030",
}
# System default — keep original 1.2 colors (no background tint, grey #F3F3F3)
SYSTEM = {
"app_bg": "#F3F3F3", "surface": "#FFFFFF", "surface_alt": "#FAFAFA",
"nav_bg": "#F7F7F7", "text": "#1B1B1B", "text_secondary": "#5C5C5C",
"border": "#E0E0E0", "border_strong": "#C8C8C8",
"accent": "#0F6CBD", "accent_hover": "#115EA3", "accent_pressed": "#0C3B5E",
"on_accent": "#FFFFFF", "selected_bg": "#D6E9FB", "hover_bg": "#EDEDED",
"disabled_bg": "#F0F0F0", "disabled_text": "#A0A0A0",
"success": "#107C10", "warning": "#9D5D00", "error": "#C42B1C",
}
DARK = {
"app_bg": "#0F1419", "surface": "#1A202C", "surface_alt": "#1E293B",
"nav_bg": "#111827", "text": "#F8FAFC", "text_secondary": "#94A3B8",
"border": "#1E293B", "border_strong": "#334155",
"accent": "#60A5FA", "accent_hover": "#93C5FD", "accent_pressed": "#3B82F6",
"on_accent": "#0F172A", "selected_bg": "#1E3A5F", "hover_bg": "#334155",
"disabled_bg": "#1E293B", "disabled_text": "#64748B",
"success": "#4ADE80", "warning": "#FDE68A", "error": "#FCA5A5",
}
TOK = dict(LIGHT)
CUR_THEME = "light"
def set_theme(name):
global TOK, CUR_THEME
CUR_THEME = name
if name == "system":
TOK = dict(SYSTEM)
elif name == "dark":
TOK = dict(DARK)
else:
TOK = dict(LIGHT)
def _system_theme():
# Returns "system" so System uses SYSTEM tokens (original 1.2 grey #F3F3F3, no tint)
# Light uses LIGHT (#EBEFFF bluish), Dark uses DARK — so all 3 dropdown options are distinct
try:
with winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize",
) as k:
app_light = winreg.QueryValueEx(k, "AppsUseLightTheme")[0] == 1
return "system"
except Exception:
return "system"
def _res(name):
if getattr(sys, "_MEIPASS", None):
p = os.path.join(sys._MEIPASS, name)
if os.path.exists(p):
return p
return os.path.join(os.path.dirname(os.path.abspath(__file__)), name)
# Checkmark glyph used inside the checked checkbox indicator.
_CHECK_SVG = (
"<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' "
"viewBox='0 0 12 12'><path d='M1.5 6.2 L4.6 9.3 L10.5 2.5' "
"fill='none' stroke='white' stroke-width='2' "
"stroke-linecap='round' stroke-linejoin='round'/></svg>"
)
CHECK_URI = "url(data:image/svg+xml;base64," + base64.b64encode(_CHECK_SVG.encode()).decode() + ")"
QSS = """
QWidget { color: @TEXT@; background: transparent; }
QMainWindow, #Central { background: @APP_BG@; }
QScrollArea { background: transparent; border: none; }
#NavPane { background: @NAV_BG@; border-right: 1px solid @BORDER@; }
#Brand { font-size: 16px; font-weight: 700; color: @TEXT@; }
#NavGroup { font-size: 11px; font-weight: 700; color: @TEXT_SECONDARY@; padding: 10px 14px 4px 14px; }
NavItem { background: transparent; border: none; border-radius: 6px; }
NavItem[selected="true"] { background: @SELECTED_BG@; }
NavItem:hover { background: @HOVER_BG@; }
#NavIcon { font-family: 'Segoe MDL2 Assets'; font-size: 16px; color: @TEXT_SECONDARY@; }
#NavText { font-size: 13px; color: @TEXT@; }
NavItem[selected="true"] #NavIcon { color: @ACCENT@; }
NavItem[selected="true"] #NavText { color: @ACCENT@; font-weight: 600; }
#NavBar { background: @ACCENT@; border-radius: 1px; }
QPushButton { font-family: 'Segoe UI'; font-size: 13px; border-radius: 6px; padding: 9px 18px; border: 1px solid transparent; }
QPushButton[kind="accent"] { background: @ACCENT@; color: @ON_ACCENT@; border: none; }
QPushButton[kind="accent"]:hover { background: @ACCENT_HOVER@; }
QPushButton[kind="accent"]:pressed { background: @ACCENT_PRESSED@; }
QPushButton[kind="accent"]:disabled { background: @DISABLED_BG@; color: @DISABLED_TEXT@; }
QPushButton[kind="default"] { background: @SURFACE@; color: @TEXT@; border: 1px solid @BORDER_STRONG@; }
QPushButton[kind="default"]:hover { background: @HOVER_BG@; }
QPushButton[kind="default"]:pressed { background: @BORDER@; }
QPushButton[kind="default"]:disabled { color: @DISABLED_TEXT@; border-color: @BORDER@; }
QPushButton[kind="subtle"] { background: transparent; color: @TEXT@; border: none; }
QPushButton[kind="subtle"]:hover { background: @HOVER_BG@; }
QPushButton[kind="subtle"]:pressed { background: @BORDER@; }
QPushButton[kind="subtle"]:disabled { color: @DISABLED_TEXT@; }
QPushButton[kind="icon"] { background: transparent; border: none; border-radius: 6px; padding: 0; }
QPushButton[kind="icon"]:hover { background: @HOVER_BG@; }
QPushButton[kind="icon"]:pressed { background: @BORDER@; }
QPushButton:focus { outline: none; }
QMessageBox { background: @SURFACE@; border: 1px solid @BORDER@; }
QMessageBox QLabel { color: @TEXT@; background: transparent; }
QMessageBox QPushButton { min-width: 80px; }
QInputDialog { background: @SURFACE@; border: 1px solid @BORDER@; }
QInputDialog QLabel { color: @TEXT@; }
QInputDialog QLineEdit { background: @SURFACE@; border: 1px solid @BORDER_STRONG@; color: @TEXT@; }
QInputDialog QComboBox { background: @SURFACE@; border: 1px solid @BORDER_STRONG@; }
QInputDialog QPushButton { min-width: 80px; }
#PageTitle { font-size: 26px; font-weight: 700; color: @TEXT@; }
#PageSub { font-size: 13px; color: @TEXT_SECONDARY@; }
#SectionLabel { font-size: 13px; font-weight: 600; color: @TEXT@; }
#Card { background: @SURFACE@; border: 1px solid @BORDER@; border-radius: 10px; }
#CardTitle { font-size: 15px; font-weight: 700; color: @TEXT@; }
#StatIcon { font-family: 'Segoe MDL2 Assets'; font-size: 20px; color: @ACCENT@; }
#StatValue { font-size: 22px; font-weight: 700; color: @TEXT@; }
#StatLabel { font-size: 12px; color: @TEXT_SECONDARY@; }
QPlainTextEdit, QTextEdit { background: @SURFACE@; border: 1px solid @BORDER@; border-radius: 8px; color: @TEXT@; padding: 10px; font-family: 'Segoe UI'; font-size: 12px; }
QPlainTextEdit:focus, QTextEdit:focus { border: 1px solid @ACCENT@; }
QLineEdit, QSpinBox, QTimeEdit { background: @SURFACE@; border: 1px solid @BORDER_STRONG@; border-radius: 6px; padding: 7px 10px; color: @TEXT@; font-size: 13px; }
QLineEdit:focus, QSpinBox:focus, QTimeEdit:focus { border: 1px solid @ACCENT@; }
QLineEdit:read-only { background: @SURFACE_ALT@; color: @TEXT_SECONDARY@; }
QCheckBox { spacing: 10px; color: @TEXT@; font-size: 13px; }
QCheckBox::indicator { width: 18px; height: 18px; border: 1px solid @BORDER_STRONG@; border-radius: 3px; background: @SURFACE@; }
QCheckBox::indicator:hover { border: 1px solid @ACCENT@; }
QCheckBox::indicator:checked { background: @ACCENT@; border: 1px solid @ACCENT@; image: @CHECK@; }
QCheckBox::indicator:disabled { background: @DISABLED_BG@; border: 1px solid @BORDER@; }
QTableWidget { background: @SURFACE@; border: 1px solid @BORDER@; border-radius: 8px; gridline-color: @BORDER@; font-size: 13px; outline: none; }
QTableWidget:focus { outline: none; }
QHeaderView::section { background: @SURFACE_ALT@; color: @TEXT_SECONDARY@; border: none; border-bottom: 1px solid @BORDER@; border-right: 1px solid @BORDER@; padding: 9px 10px; font-weight: 600; }
QTableWidget::item { padding: 7px 10px; border: none; border-right: 1px solid @BORDER@; border-bottom: 1px solid @BORDER@; outline: none; }
QTableWidget::item:selected { background: @SELECTED_BG@; color: @ACCENT@; outline: none; }
QTableWidget::item:selected:focus { background: @ACCENT@; color: @ON_ACCENT@; outline: none; }
QTableWidget::item:focus { border: none; outline: none; }
QMenu { background: @SURFACE@; color: @TEXT@; border: 1px solid @BORDER@; border-radius: 8px; padding: 6px; }
QMenu::item { padding: 8px 22px 8px 14px; border-radius: 4px; background: transparent; color: @TEXT@; }
QMenu::item:selected { background: @SELECTED_BG@; color: @TEXT@; }
QMenu::item:disabled { color: @DISABLED_TEXT@; }
QMenu::separator { height: 1px; background: @BORDER@; margin: 4px 8px; }
QTabWidget::pane { border: none; background: transparent; top: 1px; }
QTabBar::tab { background: transparent; color: @TEXT_SECONDARY@; padding: 12px 18px; border: none; border-bottom: 2px solid transparent; font-size: 13px; }
QTabBar::tab:selected { color: @ACCENT@; border-bottom: 2px solid @ACCENT@; font-weight: 600; }
QTabBar::tab:hover { color: @TEXT@; }
QComboBox { background: @SURFACE@; border: 1px solid @BORDER_STRONG@; border-radius: 6px; padding: 7px 10px; color: @TEXT@; font-size: 13px; }
QComboBox:hover { border: 1px solid @ACCENT@; }
QComboBox::drop-down { border: none; width: 26px; }
QComboBox QAbstractItemView { background: @SURFACE@; border: 1px solid @BORDER@; border-radius: 6px; selection-background-color: @SELECTED_BG@; color: @TEXT@; }
#ToggleLabel { font-size: 13px; color: @TEXT@; }
#OptResult { font-size: 14px; color: @TEXT@; }
#OptResultGood { font-size: 14px; color: @SUCCESS@; font-weight: 600; }
#ProStatus { font-size: 14px; color: @TEXT@; }
#ProStatusGood { font-size: 14px; color: @SUCCESS@; font-weight: 700; }
QScrollBar:vertical { background: transparent; width: 11px; }
QScrollBar::handle:vertical { background: @BORDER_STRONG@; border-radius: 6px; min-height: 30px; }
QScrollBar::handle:vertical:hover { background: @TEXT_SECONDARY@; }
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }
QScrollBar:horizontal { background: transparent; height: 11px; }
QScrollBar::handle:horizontal { background: @BORDER_STRONG@; border-radius: 6px; min-width: 30px; }
QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal { width: 0; }
"""
def _check_png_uri():
"""Draw a white checkmark as a PNG data URI (no SVG plugin needed)."""
try:
from PyQt6.QtGui import QPixmap, QPainter, QPen, QColor
from PyQt6.QtCore import Qt, QBuffer, QIODevice
pm = QPixmap(16, 16)
pm.fill(QColor(0, 0, 0, 0))
p = QPainter(pm)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
pen = QPen(QColor("white"))
pen.setWidth(2)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
p.setPen(pen)
p.drawLine(3, 9, 7, 13)
p.drawLine(7, 13, 13, 4)
p.end()
buf = QBuffer()
buf.open(QIODevice.OpenModeFlag.WriteOnly)
pm.save(buf, "PNG")
data = bytes(buf.data())
return "url(data:image/png;base64," + base64.b64encode(data).decode() + ")"
except Exception:
return "none"
def build_qss():
q = QSS
for k, v in TOK.items():
q = q.replace("@" + k.upper() + "@", v)
q = q.replace("@CHECK@", _check_png_uri())
return q
def apply_theme(app=None):
if app is None:
app = QApplication.instance()
app.setStyleSheet(build_qss())
# --------------------------------------------------------------------------- #
# Custom widgets
# --------------------------------------------------------------------------- #
class StartupTable(QTableWidget):
"""QTableWidget that keeps its column widths at fixed ratios on resize."""
def __init__(self, rows, cols, parent=None):
super().__init__(rows, cols, parent)
self._ratio_cb = None
def resizeEvent(self, e):
super().resizeEvent(e)
if self._ratio_cb:
self._ratio_cb()
class FluentButton(QPushButton):
def __init__(self, text="", kind="accent", parent=None):
super().__init__(text, parent)
self.setProperty("kind", kind)
self.setMinimumHeight(38)
self.setCursor(Qt.CursorShape.PointingHandCursor)
def IconButton(char, tooltip=None, size=36):
b = QPushButton()
b.setFixedSize(size, size)
b.setProperty("kind", "icon")
b.setFont(QFont("Segoe MDL2 Assets", 16))
b.setText(char)
if tooltip:
b.setToolTip(tooltip)
return b
class Card(QFrame):
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("Card")
class NavItem(QWidget):
clicked = pyqtSignal()
def __init__(self, icon, text, parent=None):
super().__init__(parent)
self.setFixedHeight(40)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self._compact = False
self._selected = False
lay = QHBoxLayout(self)
lay.setContentsMargins(12, 0, 12, 0)
lay.setSpacing(12)
self.icon_lbl = QLabel(icon)
self.icon_lbl.setObjectName("NavIcon")
self.icon_lbl.setFont(QFont("Segoe MDL2 Assets", 16))
self.icon_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
lay.addWidget(self.icon_lbl)
self.text_lbl = QLabel(text)
self.text_lbl.setObjectName("NavText")
lay.addWidget(self.text_lbl)
lay.addStretch(1)
self.bar = QFrame(self)
self.bar.setObjectName("NavBar")
self.bar.setFixedWidth(3)
self.bar.setFixedHeight(24)
self.bar.move(0, 8)
self.bar.hide()
def set_selected(self, on):
self._selected = on
self.setProperty("selected", "true" if on else "false")
self.bar.setVisible(on)
acc = TOK["accent"]
tcol = acc if on else TOK["text"]
icol = acc if on else TOK["text_secondary"]
self.text_lbl.setStyleSheet(
f"color: {tcol}; font-weight: {'600' if on else '400'};"
)
self.icon_lbl.setStyleSheet(f"color: {icol};")
self.style().unpolish(self)
self.style().polish(self)
def set_compact(self, on):
self._compact = on
if on:
self.text_lbl.hide()
self.layout().setContentsMargins(24, 0, 24, 0)
else:
self.text_lbl.show()
self.layout().setContentsMargins(12, 0, 12, 0)
def mousePressEvent(self, e):
self.clicked.emit()
super().mousePressEvent(e)
class ToggleTrack(QWidget):
toggled = pyqtSignal(bool)
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedSize(44, 24)
self._checked = False
self._hover = False
def paintEvent(self, e):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
if self._checked:
col = TOK["accent"]
elif self._hover:
col = TOK["hover_bg"]
else:
col = TOK["border_strong"]
p.setBrush(QColor(col))
p.setPen(Qt.PenStyle.NoPen)
p.drawRoundedRect(0, 0, 44, 24, 12, 12)
kx = 23 if self._checked else 4
p.setBrush(QColor("#FFFFFF"))
p.setPen(Qt.PenStyle.NoPen)
p.drawEllipse(kx, 3, 18, 18)
def mousePressEvent(self, e):
self.setChecked(not self._checked)
def enterEvent(self, e):
self._hover = True
self.update()
def leaveEvent(self, e):
self._hover = False
self.update()
def setChecked(self, v):
if self._checked != v:
self._checked = v
self.update()
self.toggled.emit(v)
def isChecked(self):
return self._checked
class ToggleSwitch(QWidget):
def __init__(self, text="", parent=None):
super().__init__(parent)
self.track = ToggleTrack()
lay = QHBoxLayout(self)
lay.setContentsMargins(0, 0, 0, 0)
lay.setSpacing(10)
lay.addWidget(self.track)
if text:
self.label = QLabel(text)
self.label.setObjectName("ToggleLabel")
lay.addWidget(self.label)
self.toggled = self.track.toggled
def setChecked(self, v):
self.track.setChecked(v)
def isChecked(self):
return self.track.isChecked()
class FluentCheckBox(QCheckBox):
"""Checkbox that draws its own indicator so the selected state is always clear."""
def __init__(self, text="", parent=None):
super().__init__(text, parent)
self.setCursor(Qt.CursorShape.PointingHandCursor)
def paintEvent(self, e):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
r = self.rect()
box = QRect(1, (r.height() - 18) // 2, 18, 18)
checked = self.isChecked()
enabled = self.isEnabled()
if not enabled:
p.setBrush(QColor(TOK["disabled_bg"]))
p.setPen(QPen(QColor(TOK["border"])))
elif checked:
p.setBrush(QColor(TOK["accent"]))
p.setPen(QPen(QColor(TOK["accent"])))
else:
p.setBrush(QColor(TOK["surface"]))
p.setPen(QPen(QColor(TOK["border_strong"])))
p.drawRoundedRect(box, 4, 4)
if checked:
pen = QPen(QColor("white"), 2)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
p.setPen(pen)
p.drawLine(box.left() + 5, box.top() + 9, box.left() + 8, box.top() + 12)
p.drawLine(box.left() + 8, box.top() + 12, box.left() + 13, box.top() + 5)
tr = QRect(box.right() + 10, 0, r.width() - box.right() - 12, r.height())
p.setPen(QColor(TOK["text"] if enabled else TOK["disabled_text"]))
p.setFont(self.font())
p.drawText(
tr,
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
self.text(),
)
class Toast(QWidget):
_ICONS = {"success": "\uE73E", "info": "\uE946", "warning": "\uE7BA", "error": "\uE783"}
_COLORS = {"success": "success", "info": "accent", "warning": "warning", "error": "error"}
def __init__(self, parent, text, kind):
super().__init__(parent)
self.setWindowFlags(Qt.WindowType.SubWindow | Qt.WindowType.FramelessWindowHint)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
lay = QHBoxLayout(self)
lay.setContentsMargins(14, 11, 14, 11)
lay.setSpacing(10)
icon = QLabel(self._ICONS.get(kind, "\uE946"))
icon.setFont(QFont("Segoe MDL2 Assets", 14))
c = TOK[self._COLORS.get(kind, "accent")]
icon.setStyleSheet(f"color: {c}")
msg = QLabel(text)
msg.setStyleSheet(f"color: {TOK['text']}")
msg.setWordWrap(True)
lay.addWidget(icon)
lay.addWidget(msg)
self.setStyleSheet(
f"background: {TOK['surface']}; border: 1px solid {TOK['border']}; "
f"border-left: 3px solid {c}; border-radius: 8px;"
)
self.adjustSize()
@classmethod
def notify(cls, parent, text, kind="info", timeout=3200):
t = cls(parent, text, kind)
pr = parent.rect()
t.move(pr.width() - t.width() - 24, pr.height() - t.height() - 24)
t.show()
QTimer.singleShot(timeout, t.deleteLater)
class Splash(QSplashScreen):
def __init__(self, on_done):
self._pix = QPixmap(460, 300)
self._prog = 0
self._on_done = on_done
super().__init__(self._pix, Qt.WindowType.WindowStaysOnTopHint | Qt.WindowType.FramelessWindowHint)
self.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)
screen = QApplication.primaryScreen()
if screen:
self.move(screen.availableGeometry().center() - self.rect().center())
self._draw()
self.show()
self.raise_()
QApplication.processEvents()
self._timer = QTimer(self)
self._timer.timeout.connect(self._tick)
self._timer.start(28)
def _draw(self):
p = QPainter(self._pix)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.fillRect(0, 0, 460, 300, QColor(TOK["app_bg"]))
p.setBrush(QColor(TOK["surface"]))
p.setPen(QPen(QColor(TOK["border"]), 1))
p.drawRoundedRect(30, 30, 400, 240, 14, 14)
ic = QIcon(_res("icon.ico")).pixmap(56, 56)
p.drawPixmap(56, 70, ic)
p.setPen(QColor(TOK["text"]))
p.setFont(QFont("Segoe UI", 20, QFont.Weight.Bold))
p.drawText(124, 96, "Personal Cleaner")
p.setFont(QFont("Segoe UI", 11))
p.setPen(QColor(TOK["text_secondary"]))
p.drawText(124, 120, "Loading...")
# circular loading spinner
cx, cy, rad = 230, 220, 16
p.setPen(QPen(QColor(TOK["border_strong"]), 3))
p.drawEllipse(cx - rad, cy - rad, rad * 2, rad * 2)
pen = QPen(QColor(TOK["accent"]), 3)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
p.setPen(pen)
ang = (self._prog * 13) % 360
p.drawArc(cx - rad, cy - rad, rad * 2, rad * 2, ang * 16, 280 * 16)
self.setPixmap(self._pix)
def _tick(self):
self._prog += 5
if self._prog >= 100:
self._timer.stop()
self._on_done()
self.close()
return
self._draw()
class Worker(QThread):
finished = pyqtSignal(object)
error = pyqtSignal(str)
def __init__(self, fn, *args):
super().__init__()
self.fn = fn
self.args = args
def run(self):
try:
self.finished.emit(self.fn(*self.args))
except Exception as e: # noqa: BLE001
self.error.emit(str(e))
# --------------------------------------------------------------------------- #
# Main application
# --------------------------------------------------------------------------- #
class PCApp(QMainWindow):
def __init__(self):
super().__init__()
self.cfg = qf.load_config()
self._tray = None # init early so closeEvent never sees missing attr
self.setWindowTitle("Personal Cleaner")
self.setWindowIcon(QIcon(_res("icon.ico")))
self.resize(960, 620)
self.setMinimumSize(920, 560)
# Center the window on screen (so it doesn't feel huge on small laptops)
try:
scr = QApplication.primaryScreen()
if scr:
geo = scr.availableGeometry()
x = (geo.width() - self.width()) // 2
y = (geo.height() - self.height()) // 2
self.move(geo.x() + x, geo.y() + y)
except Exception:
pass
self.theme_choice = self.cfg.get("theme", "system")
eff = _system_theme() if self.theme_choice == "system" else self.theme_choice
set_theme(eff)
apply_theme()
self._splash = Splash(self._on_splash_done)
try:
self._splash.show()
self._splash.raise_()
self._splash.activateWindow()
QApplication.processEvents()
except Exception:
pass
self._current = "Dashboard"
self._collapsed = False
self.pages = {}
self.nav_items = {}
self._recolorables = []
self.start_items = []
self._workers = []
self._nav_anim = None
self._ready = False
central = QWidget()
central.setObjectName("Central")
self.setCentralWidget(central)
h = QHBoxLayout(central)
h.setContentsMargins(0, 0, 0, 0)
h.setSpacing(0)
self._build_nav()
QApplication.instance().processEvents()
h.addWidget(self.nav, 0)
self.content = QStackedWidget()
h.addWidget(self.content, 1)
self._build_dashboard()
self._build_clean()
self._build_optimize()
self._build_startup()
self._build_settings()
self._build_pro()
QApplication.instance().processEvents()
self._recolorables.append(self.notif_toggle.track)
# ---- tray icon (hidden-app mode, like Laragon) -------------------- #
# Created after config load; _ensure_tray is the single creator
if self.cfg.get("tray_on_close", False):
try:
self._ensure_tray()
except Exception:
self._tray = None
self.show_page("Dashboard")
QApplication.instance().processEvents()
self._refresh_stats()
QApplication.instance().processEvents()
for i, name in enumerate(
["Dashboard", "Clean", "Optimize", "Startup", "Settings", "Pro"], start=1
):
QShortcut(QKeySequence(f"Ctrl+{i}"), self).activated.connect(
lambda n=name: self.show_page(n)
)
QApplication.instance().processEvents()
self._ready = True
# ---- navigation ------------------------------------------------------ #
def _build_nav(self):
self.nav = QFrame()
self.nav.setObjectName("NavPane")
self.nav.setFixedWidth(260)
lay = QVBoxLayout(self.nav)
lay.setContentsMargins(0, 0, 0, 0)
lay.setSpacing(0)
hdr = QHBoxLayout()
hdr.setContentsMargins(12, 14, 12, 10)
hdr.setSpacing(10)
self.btn_collapse = IconButton("\uE700", "Collapse / expand", 36)
self.btn_collapse.clicked.connect(self._toggle_nav)
self.lbl_brand = QLabel("Personal Cleaner")
self.lbl_brand.setObjectName("Brand")
hdr.addWidget(self.btn_collapse)
hdr.addWidget(self.lbl_brand)
hdr.addStretch(1)
lay.addLayout(hdr)
self.lbl_group_main = QLabel("MAIN")
self.lbl_group_main.setObjectName("NavGroup")
lay.addWidget(self.lbl_group_main)
self._add_nav("Dashboard", "\uE80F", "Dashboard")
self._add_nav("Clean", "\uE74D", "Clean")
self._add_nav("Optimize", "\uE964", "Optimize")
self._add_nav("Startup", "\uE7E8", "Startup")
lay.addStretch(1)
self.lbl_group_app = QLabel("APP")
self.lbl_group_app.setObjectName("NavGroup")
lay.addWidget(self.lbl_group_app)
self._add_nav("Settings", "\uE713", "Settings")
self._add_nav("Pro", "\uE735", "Pro")
lay.addSpacing(10)
def _add_nav(self, name, icon, label):
item = NavItem(icon, label)
item.clicked.connect(lambda n=name: self.show_page(n))
self.nav.layout().addWidget(item)
self.nav_items[name] = item
def show_page(self, name):
page = self.pages.get(name)
if not page:
return
self.content.setCurrentWidget(page)
for n, it in self.nav_items.items():
it.set_selected(n == name)
self._current = name
def _toggle_nav(self):
self._collapsed = not self._collapsed
anim = QVariantAnimation(self)
anim.setDuration(220)
anim.setStartValue(self.nav.width())
anim.setEndValue(64 if self._collapsed else 260)
anim.setEasingCurve(QEasingCurve.Type.OutCubic)
anim.valueChanged.connect(self._on_nav_anim)
anim.start()
self._nav_anim = anim
def _on_nav_anim(self, v):
self.nav.setFixedWidth(int(v))
show = int(v) > 150
self.lbl_brand.setVisible(show)
self.lbl_group_main.setVisible(show)
self.lbl_group_app.setVisible(show)
for it in self.nav_items.values():
if getattr(it, "_compact", False) != self._collapsed:
it.set_compact(self._collapsed)
# ---- page scaffolding ------------------------------------------------ #
def _page(self, title, sub=None):
sc = QScrollArea()
sc.setWidgetResizable(True)
sc.setFrameShape(QFrame.Shape.NoFrame)
root = QWidget()
v = QVBoxLayout(root)
v.setContentsMargins(28, 24, 28, 24)
v.setSpacing(18)
t = QLabel(title)
t.setObjectName("PageTitle")
v.addWidget(t)
if sub:
s = QLabel(sub)
s.setObjectName("PageSub")
v.addWidget(s)
sc.setWidget(root)
return sc, root, v
def _add_page(self, name, widget):
self.content.addWidget(widget)
self.pages[name] = widget
def _stat_card(self, icon, value, label):
card = Card()
card.setMinimumHeight(96)
lay = QVBoxLayout(card)
lay.setContentsMargins(18, 16, 18, 16)
lay.setSpacing(8)
ic = QLabel(icon)
ic.setObjectName("StatIcon")
ic.setFont(QFont("Segoe MDL2 Assets", 20))
val = QLabel(value)
val.setObjectName("StatValue")
lab = QLabel(label)
lab.setObjectName("StatLabel")
lay.addWidget(ic)
lay.addWidget(val)
lay.addWidget(lab)
card.value_label = val
return card
# ---- Dashboard: 4 separate Fluent sections (no mix, no overlap) ---- #
def _build_dashboard(self):
sc, root, v = self._page(
"Dashboard", "Overview of your system cleanliness and quick actions."
)
cards = QHBoxLayout()
cards.setSpacing(16)
self.stat_junk = self._stat_card("\uE74D", "—", "Junk to clean")
self.stat_ram = self._stat_card("\uE945", "—", "Free RAM")
self.stat_start = self._stat_card("\uE7E8", "—", "Startup items")
cards.addWidget(self.stat_junk)
cards.addWidget(self.stat_ram)
cards.addWidget(self.stat_start)
v.addLayout(cards)
# Section 1 — Junk cleanup (own card, own output)
junk_card = Card()
jl = QVBoxLayout(junk_card)
jl.setContentsMargins(18, 14, 18, 14)
jl.setSpacing(10)
jl.addWidget(QLabel("Junk cleanup"))
sub_j = QLabel("Scans temp / WER / Recycle Bin older than 24h. Preview first, then clean.")
sub_j.setObjectName("PageSub")
jl.addWidget(sub_j)
btns_j = QHBoxLayout()
btns_j.setSpacing(10)
self.btn_scan = FluentButton("Scan junk", "accent")
self.btn_scan.setToolTip("Scan temp folders and estimate reclaimable junk (nothing deleted).")
self.btn_scan.clicked.connect(self._scan)
self.btn_clean = FluentButton("Clean junk now", "default")
self.btn_clean.setToolTip("Delete ticked junk categories (see Clean tab).")
self.btn_clean.clicked.connect(self._clean)
self.btn_clean.setEnabled(False)
btns_j.addWidget(self.btn_scan)
btns_j.addWidget(self.btn_clean)
btns_j.addStretch(1)
jl.addLayout(btns_j)
# junk output stays inside this card
self.junk_log = QPlainTextEdit()
self.junk_log.setReadOnly(True)
self.junk_log.setPlaceholderText("Click \"Scan junk\" to preview reclaimable space. Output stays here.")
self.junk_log.setMinimumHeight(90)
jl.addWidget(self.junk_log)
hl_j = QHBoxLayout()
clr_j = FluentButton("Clear", "default")
clr_j.setMinimumHeight(28)
clr_j.clicked.connect(lambda: self.junk_log.clear())
hl_j.addWidget(clr_j)
hl_j.addStretch(1)
jl.addLayout(hl_j)
v.addWidget(junk_card)
# Section 2 — App health (M1, separate output)
health_card = Card()
hl = QVBoxLayout(health_card)
hl.setContentsMargins(18, 14, 18, 14)
hl.setSpacing(10)
hl.addWidget(QLabel("App health"))
sub_h = QLabel("Samples CPU ~1s, checks each app for Not Responding / HIGH MEM / HIGH CPU.")
sub_h.setObjectName("PageSub")
hl.addWidget(sub_h)
btns_h = QHBoxLayout()
btns_h.setSpacing(10)
self.btn_scan_health = FluentButton("Scan app health", "default")
self.btn_scan_health.setToolTip("Check Not Responding / HIGH MEM / HIGH CPU; offer to close.")
self.btn_scan_health.clicked.connect(self._scan_health)
btns_h.addWidget(self.btn_scan_health)
btns_h.addStretch(1)
hl.addLayout(btns_h)
self.health_result = QLabel("Click \"Scan app health\" to check for misbehaving apps.")
self.health_result.setObjectName("PageSub")
self.health_result.setWordWrap(True)
hl.addWidget(self.health_result)
v.addWidget(health_card)
# Section 3 — I1 Activity (real cleaner.log tail)
log_card = Card()
ll = QVBoxLayout(log_card)
ll.setContentsMargins(18, 14, 18, 14)
ll.setSpacing(8)
ll.addWidget(QLabel("Activity log"))
sub_l = QLabel("Tail of cleaner.log on disk (kept ~7 days, 3000 lines cap).")
sub_l.setObjectName("PageSub")
ll.addWidget(sub_l)
self.log = QPlainTextEdit()
self.log.setReadOnly(True)
self.log.setPlaceholderText("Activity from cleaner.log will appear here. Click Refresh below.")
self.log.setMinimumHeight(120)
ll.addWidget(self.log)
hlog = QHBoxLayout()
hlog.setSpacing(10)
clear = FluentButton("Clear display", "default")
clear.setMinimumHeight(28)
clear.clicked.connect(lambda: self.log.clear())
self.btn_refresh_log = FluentButton("Refresh log file", "default")
self.btn_refresh_log.setToolTip("Reload the last 40 lines from cleaner.log on disk.")
self.btn_refresh_log.setMinimumHeight(28)
self.btn_refresh_log.clicked.connect(self._refresh_log)
hlog.addWidget(clear)
hlog.addWidget(self.btn_refresh_log)
hlog.addStretch(1)
ll.addLayout(hlog)
v.addWidget(log_card)
# Section 4 — I2 Background run history (AUTO: parsed)
hist_card = Card()
hl2 = QVBoxLayout(hist_card)
hl2.setContentsMargins(18, 14, 18, 14)
hl2.setSpacing(8)
hl2.addWidget(QLabel("Background run history"))
sub_h2 = QLabel("Parsed from cleaner.log — each silent run (AUTO: freed …).")
sub_h2.setObjectName("PageSub")
hl2.addWidget(sub_h2)
self.hist_table = QTableWidget(0, 4)
self.hist_table.setHorizontalHeaderLabels(["When", "Disk", "RAM", "Hung"])
self.hist_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.hist_table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.hist_table.horizontalHeader().setStretchLastSection(True)
self.hist_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
self.hist_table.verticalHeader().setVisible(False)
self.hist_table.setMinimumHeight(120)
self.hist_table.setShowGrid(False)
hl2.addWidget(self.hist_table)
hhist = QHBoxLayout()
self.btn_refresh_hist = FluentButton("Refresh history", "default")
self.btn_refresh_hist.setMinimumHeight(28)
self.btn_refresh_hist.clicked.connect(self._refresh_history)
hhist.addWidget(self.btn_refresh_hist)
hhist.addStretch(1)
hl2.addLayout(hhist)
v.addWidget(hist_card)
self._add_page("Dashboard", sc)
def _refresh_log(self):
"""I1: tail the real cleaner.log file."""
try:
with open(qf.LOG_FILE, "r", encoding="utf-8", errors="ignore") as fh:
lines = fh.readlines()
tail = lines[-40:] if len(lines) > 40 else lines
self.log.setPlainText("".join(tail) if tail else "(no log yet)")
except Exception as e:
self.log.setPlainText(f"No log yet — {e}")
Toast.notify(self, "No log file yet.", "info")
def _refresh_history(self):
"""I2: parse AUTO: lines into history table."""
import re
try:
with open(qf.LOG_FILE, "r", encoding="utf-8", errors="ignore") as fh:
text = fh.read()
except Exception:
self.hist_table.setRowCount(0)
Toast.notify(self, "No history yet.", "info")
return
pat = re.compile(r"\[(.*?)\] AUTO: freed ([\d.]+) MB disk, ([\d.]+) MB RAM, (\d+) hung")
rows = pat.findall(text)
if not rows:
self.hist_table.setRowCount(0)
return
rows = rows[-20:]
self.hist_table.setRowCount(len(rows))
for i, (when, disk, ram, hung) in enumerate(rows):
self.hist_table.setItem(i, 0, QTableWidgetItem(when))
self.hist_table.setItem(i, 1, QTableWidgetItem(f"{disk} MB"))
self.hist_table.setItem(i, 2, QTableWidgetItem(f"{ram} MB"))
self.hist_table.setItem(i, 3, QTableWidgetItem(hung))
self.hist_table.resizeColumnsToContents()
def _scan_health(self):
"""M1 health: scan_processes + problems_for + offer to close (like CLI run_scan_and_fix)."""
self._set_busy(self.btn_scan_health, "Scanning...")
self.health_result.setText("Sampling CPU ~1s, checking Not Responding / HIGH MEM / HIGH CPU...")
self.health_result.setObjectName("PageSub")
self.health_result.style().unpolish(self.health_result)
self.health_result.style().polish(self.health_result)
def work():
procs, sys_cpu, ncpu = qf.scan_processes()
mem = psutil.virtual_memory()
problems = []
for pd in procs:
if pd["pid"] in qf.IGNORE_PIDS or pd["name"] in qf.IGNORE_NAMES:
continue
tags = qf.problems_for(pd)
if tags:
problems.append((pd, tags))
problems.sort(key=lambda t: (not t[0]["hung"], -t[0]["mem_mb"]))
return problems, sys_cpu, ncpu, mem
def done(res):
self._set_busy(self.btn_scan_health, "Health scan", False)
problems, sys_cpu, ncpu, mem = res
if not problems:
self.health_result.setText(f"No misbehaving apps detected. RAM {mem.percent:.0f}% | CPU {sys_cpu:.0f}% | {ncpu} cores.")
self.health_result.setObjectName("OptResultGood")
self.health_result.style().unpolish(self.health_result)
self.health_result.style().polish(self.health_result)
Toast.notify(self, "No misbehaving apps detected.", "success")
return
# Build textual summary; offer details via dialog
self._pending_health = problems
lines = [f"Found {len(problems)} problem(s) — RAM {mem.percent:.0f}% | CPU {sys_cpu:.0f}%:"]
for pd, tags in problems[:8]:
eligible, reason = qf.is_eligible(pd)
lines.append(f" {pd['name']} (PID {pd['pid']}, {pd['mem_mb']:.0f} MB): {', '.join(tags)} — {'CAN CLOSE' if eligible else reason}")
if len(problems) > 8:
lines.append(f" ... and {len(problems)-8} more")
lines.append("Review in Optimize → Close a stuck app, or click Close selected.")
self.health_result.setText("\n".join(lines))
self.health_result.setObjectName("OptResult")
self.health_result.style().unpolish(self.health_result)
self.health_result.style().polish(self.health_result)
Toast.notify(self, f"Found {len(problems)} problem app(s) — see Optimize → Close a stuck app.", "warning")
self._run_async(work, done)
# ---- Clean ----------------------------------------------------------- #
def _build_clean(self):
sc, root, v = self._page(
"Clean", "Choose what to clean, then preview or run a cleanup."
)
lab = QLabel("Categories")
lab.setObjectName("SectionLabel")
v.addWidget(lab)
grid = QVBoxLayout()
grid.setSpacing(10)
self.clean_boxes = {}
for key, desc in qf.CLEANUP_CATEGORIES:
cb = FluentCheckBox(desc.strip())
cb.setChecked(bool(self.cfg["cleanup"].get(key)))
cb.stateChanged.connect(lambda st, k=key, cb=cb: self._set_cat(k, cb, st))
grid.addWidget(cb)
self.clean_boxes[key] = cb
self._recolorables.append(cb)
v.addLayout(grid)