-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_fix.py
More file actions
2713 lines (2400 loc) · 102 KB
/
Copy pathquick_fix.py
File metadata and controls
2713 lines (2400 loc) · 102 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
"""
quick_fix.py — Windows application-health + junk-cleanup optimizer.
MODES (selected by command-line flag; double-clicking opens the main menu):
(no flag) Main menu (all features).
--settings Open the settings screen directly.
--free-ram Purge the standby list to free cached RAM.
--startup Open the startup-programs manager.
--dry-run Scan + preview cleanup (deletes nothing).
--auto Silent background run for the scheduler: does only the
actions enabled in config, logs everything, no prompts,
no window. Run windowless by Task Scheduler.
--scheduled-restart Task action: restart only if enabled and user is idle.
--install-scheduler Register the on-idle + daily background tasks.
--uninstall-scheduler Remove those scheduled tasks.
SAFETY
* Junk cleanup only touches a hardcoded allowlist of known-temp folders,
only deletes items older than MIN_AGE_HOURS, skips locked/in-use files,
and can never escape the target folder.
* Process termination only happens in interactive mode, always behind a
[y/n] confirmation, never for BLOCKLIST processes.
"""
import argparse
import json
import os
import re
import shutil
import sys
import time
from datetime import datetime, timedelta
try:
import psutil
except ImportError:
print("[FATAL] The 'psutil' package is not installed. Run: pip install psutil")
time.sleep(5)
sys.exit(1)
# Commercial build: if licensing.py is bundled (PersonalCleanerPro.exe), a valid
# license key is required for the Pro/automation features. The free MIT build
# does NOT bundle licensing.py, so it always runs unrestricted.
try:
import licensing
COMMERCIAL = True
except ImportError:
licensing = None
COMMERCIAL = False
# --------------------------------------------------------------------------- #
# Configuration
# --------------------------------------------------------------------------- #
# --- Junk cleanup ----------------------------------------------------------- #
# Only delete items whose most-recent modification is older than this many
# hours. Protects files an application is actively using right now.
MIN_AGE_HOURS = 24
# --- Per-application health thresholds -------------------------------------- #
HEAVY_MEM_MB = 400 # flag HIGH MEMORY at/above this RSS (MB)
CPU_BUSY_PCT = 20.0 # flag HIGH CPU at/above this normalized %
CPU_SAMPLE_SECONDS = 1.0 # CPU sampling window
KILL_HUNG = True # hung, non-blocklisted apps eligible to close
CONFIRM_BEFORE_KILL = True # ask [y/n] before every termination
# --- System context (informational only) ----------------------------------- #
PRESSURE_PERCENT = 80.0
NEAR_LIMIT_RATIO = 0.75
TOP_PROCESS_COUNT = 8
FINAL_PAUSE_SECONDS = 5
# --- Scheduler defaults ----------------------------------------------------- #
TASK_PREFIX = "PersonalCleaner"
DEFAULT_IDLE_MINUTES = 10
DEFAULT_DAILY_TIME = "03:00"
APP_NAME = "PersonalCleaner"
APP_TAGLINE = "Honest Windows Optimizer"
APP_VERSION = "1.3"
# ASCII-art logo (figlet "standard" font), stacked Personal / Cleaner.
BANNER = [
' ____ _',
'| _ \\ ___ _ __ ___ ___ _ __ __ _| |',
"| |_) / _ \\ '__/ __|/ _ \\| '_ \\ / _` | |",
'| __/ __/ | \\__ \\ (_) | | | | (_| | |',
'|_| \\___|_| |___/\\___/|_| |_|\\__,_|_|',
'',
' ____ _',
' / ___| | ___ __ _ _ __ ___ _ __',
"| | | |/ _ \\/ _` | '_ \\ / _ \\ '__|",
'| |___| | __/ (_| | | | | __/ |',
' \\____|_|\\___|\\__,_|_| |_|\\___|_|',
]
# Lightning-bolt emblem (our icon) shown to the left of the logo.
# Tapered: thin tips -> thick kink (row 5, between Personal / Cleaner) -> thin.
EMBLEM = [
'',
'',
' /',
' //',
' ///',
' //////',
' ///',
' //',
' /',
'',
'',
]
# --- Logging ---------------------------------------------------------------- #
# Store settings/log in a FIXED, WRITABLE location so they persist regardless of
# how the app is launched (elevated or not, any account). Prefer beside the exe
# (portable); if that folder is read-only (e.g. exe in Program Files), fall back
# to %LOCALAPPDATA% then the home folder.
def _pick_data_dir() -> str:
candidates = []
if getattr(sys, "frozen", False):
candidates.append(os.path.dirname(sys.executable))
local = os.environ.get("LOCALAPPDATA")
if local:
candidates.append(os.path.join(local, "PersonalCleaner"))
candidates.append(os.path.join(os.path.expanduser("~"), "PersonalCleaner"))
candidates.append(os.getcwd())
for d in candidates:
try:
os.makedirs(d, exist_ok=True)
probe = os.path.join(d, ".pc_write_test")
with open(probe, "w", encoding="utf-8") as fh:
fh.write("ok")
os.remove(probe)
return d
except OSError:
continue
return os.getcwd()
LOG_DIR = _pick_data_dir()
LOG_FILE = os.path.join(LOG_DIR, "cleaner.log")
CONFIG_FILE = os.path.join(LOG_DIR, "config.json")
LOG_RETENTION_DAYS = 7 # keep ~1 week of activity in the log
MAX_LOG_LINES = 3000 # hard safety cap regardless of dates
# The cleanup categories the user can tick. Order = display order.
CLEANUP_CATEGORIES = [
("user_temp", "User temp (%TEMP%, LOCALAPPDATA\\Temp)"),
("windows_temp", "Windows temp (C:\\Windows\\Temp)"),
("wer", "Windows Error Reporting (WER)"),
("recycle_bin", "Recycle Bin"),
]
# Safe default: EVERYTHING unchecked. The background agent cleans nothing until
# the user explicitly ticks categories in --settings.
DEFAULT_CONFIG = {
"cleanup": {key: False for key, _ in CLEANUP_CATEGORIES},
"min_age_hours": MIN_AGE_HOURS,
"memory": {
"trim_on_pressure": False, # opt-in: purge standby list in --auto
"pressure_percent": 85, # ...when RAM usage reaches this %
"purge_standby": True, # the safe trim (cached file data)
"empty_working_sets": False, # aggressive (config-file only); can slow apps
},
"process": {
"auto_close_hung": False, # opt-in: close Not-Responding apps in --auto
"hung_grace_seconds": 20, # must still be hung after this delay
},
"restart": {
"enabled": False, # opt-in: weekly restart when idle
"day": "SUN", # schtasks day code (SUN..SAT)
"time": "04:00", # 24h HH:MM
"idle_minutes": 60, # only restart after this much user idle
"warn_seconds": 120, # warning countdown before restart
},
"notifications": True, # show a toast after each background run
"tray_on_close": False, # hide to tray instead of quitting when X is clicked
"services": {}, # original start modes captured before tuning
}
# Curated, well-known-safe services to defer. (service, friendly, why, target)
# target: "manual" (start on demand) or "disabled". Only ones that EXIST are shown.
SERVICE_TUNING = [
("DiagTrack", "Connected User Experiences & Telemetry",
"Microsoft usage/diagnostics telemetry", "disabled"),
("dmwappushservice", "WAP Push Routing (telemetry)",
"Device-management telemetry", "disabled"),
("RemoteRegistry", "Remote Registry",
"Lets others edit your registry remotely (safer off)", "disabled"),
("RetailDemo", "Retail Demo Service",
"Store demo mode - not needed at home", "disabled"),
("SysMain", "SysMain (Superfetch)",
"Preloads apps into RAM; often unneeded on SSDs", "manual"),
("WSearch", "Windows Search (indexing)",
"Background file indexing", "manual"),
("Fax", "Fax", "Fax service (rarely used)", "manual"),
("MapsBroker", "Downloaded Maps Manager",
"Offline maps updates", "manual"),
("WMPNetworkSvc", "WMP Network Sharing",
"Media streaming to other devices", "manual"),
("lfsvc", "Geolocation Service", "Tracks device location", "manual"),
("XblAuthManager", "Xbox Live Auth Manager",
"Xbox sign-in (only for gaming)", "manual"),
("XblGameSave", "Xbox Live Game Save",
"Xbox cloud saves (only for gaming)", "manual"),
("XboxNetApiSvc", "Xbox Live Networking",
"Xbox networking (only for gaming)", "manual"),
]
# --- Safety lists ----------------------------------------------------------- #
# Processes that must NEVER be killed - doing so crashes Windows (BSOD),
# logs you out, or breaks the desktop / Start menu / taskbar / text input.
# Everything NOT on this list is fair game for the user to close.
BLOCKLIST = {
# --- Kernel / session: killing = BSOD or instant crash ---
"system", "registry", "memory compression",
"smss.exe", "csrss.exe", "wininit.exe", "winlogon.exe",
"services.exe", "lsass.exe", "lsaiso.exe", "svchost.exe",
"fontdrvhost.exe",
# --- Logon / init ---
"logonui.exe", "userinit.exe",
# --- Shell / desktop UI: killing breaks taskbar, Start, desktop, input ---
"explorer.exe", "dwm.exe", "sihost.exe", "ctfmon.exe", "taskhostw.exe",
"shellexperiencehost.exe", "startmenuexperiencehost.exe",
"searchhost.exe", "searchapp.exe", "searchindexer.exe",
"applicationframehost.exe", "textinputhost.exe",
# --- Core services best not force-killed ---
"spoolsv.exe", "wudfhost.exe",
# --- Security (also OS-protected) ---
"msmpeng.exe", "mssense.exe", "securityhealthservice.exe",
"securityhealthsystray.exe",
}
IGNORE_NAMES = {"system idle process"}
IGNORE_PIDS = {0}
# Set True while running interactively (controls the final "press Enter" wait).
INTERACTIVE = False
# The menu manages its own pauses, so it disables the single final wait.
_FINAL_WAIT = True
# --------------------------------------------------------------------------- #
# Colour + logging
# --------------------------------------------------------------------------- #
RED = YELLOW = GREEN = RESET = BOLD = CYAN = ""
def _enable_ansi() -> bool:
try:
import ctypes
kernel32 = ctypes.windll.kernel32
handle = kernel32.GetStdHandle(-11)
mode = ctypes.c_uint32()
if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
return False
return bool(kernel32.SetConsoleMode(handle, mode.value | 0x0004))
except Exception: # noqa: BLE001
return False
def _init_colors() -> None:
global RED, YELLOW, GREEN, RESET, BOLD, CYAN
if _enable_ansi():
RED, YELLOW, GREEN, RESET = "\033[91m", "\033[93m", "\033[92m", "\033[0m"
BOLD, CYAN = "\033[1m", "\033[96m"
def _color(text: str, color: str) -> str:
return f"{color}{text}{RESET}" if color else text
_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
_LOG_TS_RE = re.compile(r"^\[(\d{4})-(\d{2})-(\d{2}) ")
def _rotate_log() -> None:
"""
Keep only the last LOG_RETENTION_DAYS of entries (by their timestamp),
with MAX_LOG_LINES as a hard safety cap. Continuation lines (no timestamp)
stay with their parent entry. Rewrites only if something was dropped.
"""
try:
if not os.path.exists(LOG_FILE):
return
with open(LOG_FILE, "r", encoding="utf-8", errors="ignore") as fh:
lines = fh.readlines()
if not lines:
return
cutoff = (datetime.now() - timedelta(days=LOG_RETENTION_DAYS)).date()
kept, keep_current = [], True
for ln in lines:
m = _LOG_TS_RE.match(ln)
if m:
try:
d = datetime(int(m[1]), int(m[2]), int(m[3])).date()
keep_current = d >= cutoff
except ValueError:
keep_current = True
if keep_current:
kept.append(ln)
if len(kept) > MAX_LOG_LINES:
kept = kept[-MAX_LOG_LINES:]
if len(kept) != len(lines):
with open(LOG_FILE, "w", encoding="utf-8") as fh:
fh.writelines(kept)
except OSError:
pass
def log(msg: str, to_console: bool = True) -> None:
"""Append a timestamped line to the log file (and optionally the console)."""
stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
clean = _ANSI_RE.sub("", msg) # never store colour codes in the log file
try:
os.makedirs(LOG_DIR, exist_ok=True)
with open(LOG_FILE, "a", encoding="utf-8") as fh:
fh.write(f"[{stamp}] {clean}\n")
except OSError:
pass
if to_console:
print(msg)
def _register_aumid() -> None:
"""Register an AppUserModelID so toasts show under a friendly name."""
try:
import winreg
key = r"Software\Classes\AppUserModelId\PersonalCleaner.App"
k = winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, key, 0, winreg.KEY_SET_VALUE)
winreg.SetValueEx(k, "DisplayName", 0, winreg.REG_SZ, "Personal Cleaner")
winreg.CloseKey(k)
except OSError:
pass
def show_toast(title: str, message: str) -> bool:
"""Show a Windows toast notification. Returns True if it was dispatched."""
try:
import subprocess
def esc(s: str) -> str:
return (s.replace("&", "&").replace("<", "<").replace(">", ">")
.replace("'", "'").replace('"', """))
_register_aumid()
xml = ("<toast><visual><binding template=\"ToastGeneric\">"
f"<text>{esc(title)}</text><text>{esc(message)}</text>"
"</binding></visual></toast>")
ps = (
"$ErrorActionPreference='SilentlyContinue';"
"[Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,ContentType=WindowsRuntime]>$null;"
"[Windows.Data.Xml.Dom.XmlDocument,Windows.Data.Xml.Dom,ContentType=WindowsRuntime]>$null;"
f"$x=[Windows.Data.Xml.Dom.XmlDocument]::new();$x.LoadXml('{xml}');"
"$t=[Windows.UI.Notifications.ToastNotification]::new($x);"
"[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('PersonalCleaner.App').Show($t);"
)
res = subprocess.run(
["powershell", "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden",
"-Command", ps],
capture_output=True, text=True, creationflags=0x08000000) # CREATE_NO_WINDOW
return res.returncode == 0
except Exception: # noqa: BLE001
return False
def _mb(num_bytes: float) -> float:
return num_bytes / (1024 * 1024)
def _gb(num_bytes: float) -> float:
return num_bytes / (1024 ** 3)
# --------------------------------------------------------------------------- #
# Junk cleanup
# --------------------------------------------------------------------------- #
def load_config() -> dict:
"""Load settings, merged over defaults. Missing/corrupt file -> defaults."""
cfg = json.loads(json.dumps(DEFAULT_CONFIG)) # deep copy
try:
with open(CONFIG_FILE, "r", encoding="utf-8") as fh:
saved = json.load(fh)
except (OSError, ValueError):
return cfg
if isinstance(saved.get("cleanup"), dict):
for key in cfg["cleanup"]:
if key in saved["cleanup"]:
cfg["cleanup"][key] = bool(saved["cleanup"][key])
if isinstance(saved.get("min_age_hours"), (int, float)):
cfg["min_age_hours"] = saved["min_age_hours"]
if isinstance(saved.get("memory"), dict):
for key in cfg["memory"]:
if key in saved["memory"]:
cfg["memory"][key] = saved["memory"][key]
if isinstance(saved.get("process"), dict):
for key in cfg["process"]:
if key in saved["process"]:
cfg["process"][key] = saved["process"][key]
if isinstance(saved.get("restart"), dict):
for key in cfg["restart"]:
if key in saved["restart"]:
cfg["restart"][key] = saved["restart"][key]
if isinstance(saved.get("notifications"), bool):
cfg["notifications"] = saved["notifications"]
if isinstance(saved.get("tray_on_close"), bool):
cfg["tray_on_close"] = saved["tray_on_close"]
if isinstance(saved.get("theme"), str) and saved["theme"] in ("system", "light", "dark"):
cfg["theme"] = saved["theme"]
if isinstance(saved.get("services"), dict):
cfg["services"] = {str(k): str(v) for k, v in saved["services"].items()}
return cfg
def save_config(cfg: dict) -> bool:
try:
os.makedirs(LOG_DIR, exist_ok=True)
with open(CONFIG_FILE, "w", encoding="utf-8") as fh:
json.dump(cfg, fh, indent=2)
return True
except OSError:
return False
def _category_paths() -> dict:
"""Map each folder-based category to the existing directories it covers."""
env = os.environ
raw = {
"user_temp": [env.get("TEMP"), env.get("TMP"),
os.path.join(env.get("LOCALAPPDATA", ""), "Temp")],
"windows_temp": [os.path.join(env.get("WINDIR", r"C:\Windows"), "Temp")],
"wer": [os.path.join(env.get("PROGRAMDATA", ""),
"Microsoft", "Windows", "WER", "ReportQueue"),
os.path.join(env.get("PROGRAMDATA", ""),
"Microsoft", "Windows", "WER", "ReportArchive")],
}
out = {}
for key, paths in raw.items():
seen, dirs = set(), []
for p in paths:
if not p:
continue
ap = os.path.abspath(p)
if ap.lower() in seen or not os.path.isdir(ap):
continue
seen.add(ap.lower())
dirs.append(ap)
out[key] = dirs
return out
def estimate_category(key: str, min_age: float) -> int:
"""Bytes that cleaning this category would free right now (dry-run walk)."""
if key == "recycle_bin":
return recycle_bin_size()
total = 0
for base in _category_paths().get(key, []):
_, freed, _ = clean_location(base, True, min_age)
total += freed
return total
def _age_hours(path: str) -> float:
try:
return (time.time() - os.path.getmtime(path)) / 3600.0
except OSError:
return 0.0
def _tree_size(path: str) -> int:
total = 0
for root, _dirs, files in os.walk(path):
for f in files:
try:
total += os.path.getsize(os.path.join(root, f))
except OSError:
pass
return total
def clean_location(base: str, dry_run: bool, min_age: float) -> tuple:
"""Clean one folder. Returns (items_removed, bytes_freed, errors)."""
removed = errors = 0
freed = 0
base = os.path.abspath(base)
try:
entries = os.listdir(base)
except OSError:
return 0, 0, 1
for name in entries:
path = os.path.join(base, name)
# Boundary guard: never act outside the target folder.
if not os.path.abspath(path).startswith(base + os.sep):
continue
# Never touch our own PyInstaller runtime temp (_MEIxxxx / _MEIPASS),
# or we'd count (and fail to delete) the running EXE's own files.
meipass = getattr(sys, "_MEIPASS", "")
if "_MEI" in name or (meipass and os.path.abspath(path).startswith(meipass)):
continue
try:
if _age_hours(path) < min_age:
continue
if os.path.isdir(path) and not os.path.islink(path):
size = _tree_size(path)
if not dry_run:
shutil.rmtree(path, ignore_errors=True)
removed += 1
freed += size
else:
size = os.path.getsize(path) if os.path.isfile(path) else 0
if not dry_run:
os.remove(path)
removed += 1
freed += size
except (PermissionError, OSError):
errors += 1 # locked / in use -> skip
continue
return removed, freed, errors
def recycle_bin_size() -> int:
try:
import ctypes
from ctypes import wintypes
class SHQUERYRBINFO(ctypes.Structure):
_fields_ = [("cbSize", wintypes.DWORD),
("i64Size", ctypes.c_int64),
("i64NumItems", ctypes.c_int64)]
info = SHQUERYRBINFO()
info.cbSize = ctypes.sizeof(SHQUERYRBINFO)
if ctypes.windll.shell32.SHQueryRecycleBinW(None, ctypes.byref(info)) == 0:
return int(info.i64Size)
except Exception: # noqa: BLE001
pass
return 0
def empty_recycle_bin(dry_run: bool) -> int:
"""Empty the Recycle Bin. Returns bytes that were freed (best effort)."""
size = recycle_bin_size()
if dry_run or size == 0:
return size
try:
import ctypes
# NOCONFIRMATION | NOPROGRESSUI | NOSOUND
flags = 0x1 | 0x2 | 0x4
ctypes.windll.shell32.SHEmptyRecycleBinW(None, None, flags)
except Exception: # noqa: BLE001
return 0
return size
def run_cleanup(dry_run: bool, cfg: dict) -> int:
"""Clean only the categories enabled in cfg. Returns total bytes freed."""
enabled = cfg.get("cleanup", {})
min_age = cfg.get("min_age_hours", MIN_AGE_HOURS)
verb = "Would free" if dry_run else "Freed"
label_map = dict(CLEANUP_CATEGORIES)
total_bytes = total_items = total_errors = 0
active = [key for key, _ in CLEANUP_CATEGORIES if enabled.get(key)]
log(f" {'JUNK CLEANUP (preview)' if dry_run else 'JUNK CLEANUP'}"
f" (age > {min_age:g}h)", to_console=INTERACTIVE)
if not active:
log(" (no categories enabled - nothing to clean)", to_console=INTERACTIVE)
return 0
paths = _category_paths()
for key in active:
if key == "recycle_bin":
rb = empty_recycle_bin(dry_run)
total_bytes += rb
log(f" {label_map[key]}\n {verb} {_mb(rb):.1f} MB",
to_console=INTERACTIVE)
continue
cat_removed = cat_freed = cat_err = 0
for base in paths.get(key, []):
removed, freed, errors = clean_location(base, dry_run, min_age)
cat_removed += removed
cat_freed += freed
cat_err += errors
total_items += cat_removed
total_bytes += cat_freed
total_errors += cat_err
note = f" ({cat_err} skipped/locked)" if cat_err else ""
log(f" {label_map[key]}\n {verb} {_mb(cat_freed):.1f} MB "
f"in {cat_removed} item(s){note}", to_console=INTERACTIVE)
log(f" {'Would free' if dry_run else 'Freed'} a total of "
f"{_color(f'{_mb(total_bytes):.1f} MB', GREEN)} "
f"across {total_items} item(s), {total_errors} skipped.",
to_console=INTERACTIVE)
return total_bytes
# --------------------------------------------------------------------------- #
# Memory trim (purge the standby list — frees cached RAM). Needs admin.
# --------------------------------------------------------------------------- #
_SYSTEM_MEMORY_LIST_INFORMATION = 0x50
_MEMORY_EMPTY_WORKING_SETS = 2
_MEMORY_PURGE_STANDBY_LIST = 4
_STATUS_PRIVILEGE_NOT_HELD = 0xC0000061
def _enable_privilege(priv_name: str) -> bool:
"""Enable a named privilege on the current process token."""
try:
import ctypes
from ctypes import wintypes
advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
TOKEN_ADJUST_PRIVILEGES, TOKEN_QUERY = 0x0020, 0x0008
SE_PRIVILEGE_ENABLED = 0x00000002
class LUID(ctypes.Structure):
_fields_ = [("LowPart", wintypes.DWORD), ("HighPart", wintypes.LONG)]
class LUID_AND_ATTRIBUTES(ctypes.Structure):
_fields_ = [("Luid", LUID), ("Attributes", wintypes.DWORD)]
class TOKEN_PRIVILEGES(ctypes.Structure):
_fields_ = [("PrivilegeCount", wintypes.DWORD),
("Privileges", LUID_AND_ATTRIBUTES * 1)]
# Declare prototypes so 64-bit HANDLEs are not truncated to 32 bits.
kernel32.GetCurrentProcess.restype = wintypes.HANDLE
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
advapi32.OpenProcessToken.restype = wintypes.BOOL
advapi32.OpenProcessToken.argtypes = [
wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
advapi32.LookupPrivilegeValueW.restype = wintypes.BOOL
advapi32.LookupPrivilegeValueW.argtypes = [
wintypes.LPCWSTR, wintypes.LPCWSTR, ctypes.POINTER(LUID)]
advapi32.AdjustTokenPrivileges.restype = wintypes.BOOL
advapi32.AdjustTokenPrivileges.argtypes = [
wintypes.HANDLE, wintypes.BOOL, ctypes.POINTER(TOKEN_PRIVILEGES),
wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p]
h = wintypes.HANDLE()
if not advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
ctypes.byref(h)):
return False
luid = LUID()
if not advapi32.LookupPrivilegeValueW(None, priv_name, ctypes.byref(luid)):
kernel32.CloseHandle(h)
return False
tp = TOKEN_PRIVILEGES()
tp.PrivilegeCount = 1
tp.Privileges[0].Luid = luid
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED
ok = advapi32.AdjustTokenPrivileges(h, False, ctypes.byref(tp), 0, None, None)
err = ctypes.get_last_error()
kernel32.CloseHandle(h)
return bool(ok) and err == 0 # err 1300 = ERROR_NOT_ALL_ASSIGNED
except Exception: # noqa: BLE001
return False
def _set_memory_list(command: int) -> int:
"""Call NtSetSystemInformation(SystemMemoryListInformation). Returns NTSTATUS."""
import ctypes
ntdll = ctypes.windll.ntdll
ntdll.NtSetSystemInformation.restype = ctypes.c_ulong
ntdll.NtSetSystemInformation.argtypes = [ctypes.c_int, ctypes.c_void_p,
ctypes.c_ulong]
cmd = ctypes.c_int(command)
return ntdll.NtSetSystemInformation(_SYSTEM_MEMORY_LIST_INFORMATION,
ctypes.byref(cmd), ctypes.sizeof(cmd))
def memory_trim(purge_standby: bool = True, empty_working_sets: bool = False) -> dict:
"""
Free cached RAM. Returns dict with before/after available bytes, freed,
and flags ok / denied (needs admin).
"""
res = {"before": 0, "after": 0, "freed": 0, "ok": False, "denied": False,
"actions": []}
try:
import ctypes # noqa: F401
except Exception: # noqa: BLE001
return res
res["before"] = psutil.virtual_memory().available
_enable_privilege("SeProfileSingleProcessPrivilege")
_enable_privilege("SeIncreaseQuotaPrivilege")
def _do(cmd, label):
try:
status = _set_memory_list(cmd)
except Exception: # noqa: BLE001
return
if status == 0:
res["ok"] = True
res["actions"].append(label)
elif status == _STATUS_PRIVILEGE_NOT_HELD:
res["denied"] = True
if empty_working_sets:
_do(_MEMORY_EMPTY_WORKING_SETS, "working sets")
if purge_standby:
_do(_MEMORY_PURGE_STANDBY_LIST, "standby list")
res["after"] = psutil.virtual_memory().available
res["freed"] = max(0, res["after"] - res["before"])
return res
# --------------------------------------------------------------------------- #
# Startup programs (Run keys + Startup folders). Reversible enable/disable via
# the StartupApproved keys — exactly how Task Manager does it.
# --------------------------------------------------------------------------- #
_RUN_SUB = r"Software\Microsoft\Windows\CurrentVersion\Run"
_APPROVED_RUN = r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"
_APPROVED_RUN32 = r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run32"
_APPROVED_FOLDER = r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder"
def _is_admin() -> bool:
try:
import ctypes
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except Exception: # noqa: BLE001
return False
def _exe_from_command(command: str) -> str:
"""Extract the executable path from a Run command line."""
cmd = (command or "").strip()
if not cmd:
return ""
if cmd[0] == '"':
end = cmd.find('"', 1)
path = cmd[1:end] if end != -1 else cmd[1:]
else:
path = cmd.split(" ")[0]
return os.path.expandvars(path)
def _file_description(path: str) -> str:
"""Return an exe's FileDescription/ProductName from its version resource."""
try:
import ctypes
from ctypes import wintypes
if not path or not os.path.isfile(path):
return ""
ver = ctypes.windll.version
ver.GetFileVersionInfoSizeW.restype = wintypes.DWORD
ver.GetFileVersionInfoSizeW.argtypes = [wintypes.LPCWSTR,
ctypes.POINTER(wintypes.DWORD)]
ver.GetFileVersionInfoW.restype = wintypes.BOOL
ver.GetFileVersionInfoW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD,
wintypes.DWORD, ctypes.c_void_p]
ver.VerQueryValueW.restype = wintypes.BOOL
ver.VerQueryValueW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR,
ctypes.POINTER(ctypes.c_void_p),
ctypes.POINTER(wintypes.UINT)]
size = ver.GetFileVersionInfoSizeW(path, None)
if not size:
return ""
buf = ctypes.create_string_buffer(size)
if not ver.GetFileVersionInfoW(path, 0, size, buf):
return ""
ptr = ctypes.c_void_p()
ulen = wintypes.UINT()
if not ver.VerQueryValueW(buf, r"\VarFileInfo\Translation",
ctypes.byref(ptr), ctypes.byref(ulen)) or not ulen.value:
return ""
lang, codepage = ctypes.cast(
ptr, ctypes.POINTER(wintypes.WORD * 2)).contents[:]
for field in ("FileDescription", "ProductName"):
sub = "\\StringFileInfo\\%04x%04x\\%s" % (lang, codepage, field)
vptr = ctypes.c_void_p()
vlen = wintypes.UINT()
if ver.VerQueryValueW(buf, sub, ctypes.byref(vptr),
ctypes.byref(vlen)) and vlen.value:
s = ctypes.wstring_at(vptr, vlen.value).strip("\x00").strip()
if s:
return s
return ""
except Exception: # noqa: BLE001
return ""
def _friendly_name(command: str, fallback: str) -> str:
"""Human-readable app name for a Run command; fallback if unavailable."""
exe = _exe_from_command(command)
base = os.path.basename(exe).lower()
# These launchers say nothing useful about the real app -> keep raw name.
if base in ("rundll32.exe", "regsvr32.exe", "cmd.exe", "mshta.exe",
"powershell.exe", "conhost.exe", "wscript.exe", "cscript.exe"):
return fallback
desc = _file_description(exe)
return desc if desc else fallback
def _approved_enabled(hive, subkey: str, value_name: str, wow: int) -> bool:
"""Read StartupApproved state. Absent value => enabled. Byte0==3 => disabled."""
import winreg
try:
k = winreg.OpenKey(hive, subkey, 0, winreg.KEY_READ | wow)
try:
data, _ = winreg.QueryValueEx(k, value_name)
finally:
winreg.CloseKey(k)
if isinstance(data, (bytes, bytearray)) and len(data) >= 1 and data[0] == 3:
return False
except OSError:
pass
return True
def _read_run(hive, source: str, approved_subkey: str, wow: int) -> list:
import winreg
out = []
try:
k = winreg.OpenKey(hive, _RUN_SUB, 0, winreg.KEY_READ | wow)
except OSError:
return out
idx = 0
while True:
try:
name, val, _ = winreg.EnumValue(k, idx)
except OSError:
break
idx += 1
out.append({
"name": name, "display": _friendly_name(str(val), name),
"command": str(val), "source": source,
"hive": hive, "approved_subkey": approved_subkey, "approved_wow": 0,
"enabled": _approved_enabled(hive, approved_subkey, name, 0),
})
winreg.CloseKey(k)
return out
def _read_startup_folder(path: str, hive, source: str) -> list:
out = []
if not path or not os.path.isdir(path):
return out
for fn in os.listdir(path):
if fn.lower() in ("desktop.ini",) or fn.lower().endswith(".ini"):
continue
full = os.path.join(path, fn)
if not os.path.isfile(full):
continue
out.append({
"name": fn, "display": os.path.splitext(fn)[0], "command": full,
"source": source, "hive": hive, "approved_subkey": _APPROVED_FOLDER,
"approved_wow": 0,
"enabled": _approved_enabled(hive, _APPROVED_FOLDER, fn, 0),
})
return out
def _exe_path_from_command(cmd):
"""Extract the first .exe path referenced in a startup command."""
if not cmd:
return ""
import re
m = re.search(r'"([^"]+\.exe)"|\b([A-Za-z]:\\[^\s"*?<>|]+\.exe)', cmd, re.IGNORECASE)
if not m:
return ""
return m.group(1) or m.group(2)
def _file_publisher(cmd):
"""Best-effort publisher (CompanyName) from the executable's version info."""
import ctypes
path = _exe_path_from_command(cmd)
if not path or not os.path.exists(path):
return ""
try:
ver = ctypes.windll.version
size = ver.GetFileVersionInfoSizeW(path, None)
if not size:
return ""
buf = ctypes.create_string_buffer(size)
if not ver.GetFileVersionInfoW(path, 0, size, buf):
return ""
class LANGANDCODEPAGE(ctypes.Structure):
_fields_ = [("wLanguage", ctypes.wintypes.WORD),
("wCodePage", ctypes.wintypes.WORD)]
lpc = ctypes.POINTER(LANGANDCODEPAGE)()
lplen = ctypes.wintypes.UINT()
if not ver.VerQueryValueW(buf, "\\VarFileInfo\\Translation",
ctypes.byref(lpc), ctypes.byref(lplen)):
return ""
lang = f"{lpc[0].wLanguage:04x}{lpc[0].wCodePage:04x}"
cp = ctypes.create_unicode_buffer(256)
cplen = ctypes.wintypes.UINT()
if not ver.VerQueryValueW(buf, f"\\StringFileInfo\\{lang}\\CompanyName",
ctypes.byref(cp), ctypes.byref(cplen)):
return ""
return cp.value.strip()
except Exception:
return ""
def _startup_impact(cmd):
"""Rough startup-impact estimate from executable size (not a real measurement)."""
path = _exe_path_from_command(cmd)
if not path or not os.path.exists(path):
return "Not measured"
try:
sz = os.path.getsize(path)
except Exception:
return "Not measured"
if sz > 80 * 1024 * 1024:
return "High"
if sz > 10 * 1024 * 1024:
return "Medium"
return "Low"
def enumerate_startup() -> list:
"""List startup programs across Run keys and Startup folders."""
import winreg
env = os.environ
items = []
items += _read_run(winreg.HKEY_CURRENT_USER, "HKCU-Run", _APPROVED_RUN, 0)
items += _read_run(winreg.HKEY_LOCAL_MACHINE, "HKLM-Run", _APPROVED_RUN, 0)
items += _read_run(winreg.HKEY_LOCAL_MACHINE, "HKLM-Run32", _APPROVED_RUN32,
winreg.KEY_WOW64_32KEY)
user_startup = os.path.join(env.get("APPDATA", ""),
r"Microsoft\Windows\Start Menu\Programs\Startup")
common_startup = os.path.join(env.get("PROGRAMDATA", ""),
r"Microsoft\Windows\Start Menu\Programs\Startup")
items += _read_startup_folder(user_startup, winreg.HKEY_CURRENT_USER, "Startup-User")
items += _read_startup_folder(common_startup, winreg.HKEY_LOCAL_MACHINE, "Startup-Common")
for it in items:
cmd = it.get("command", "") or ""
it["publisher"] = _file_publisher(cmd)
it["impact"] = _startup_impact(cmd)
return items
def set_startup_enabled(item: dict, enabled: bool) -> bool:
"""Enable/disable a startup item via StartupApproved. Returns success."""
import winreg
try:
k = winreg.CreateKeyEx(item["hive"], item["approved_subkey"], 0,
winreg.KEY_SET_VALUE | item["approved_wow"])
data = bytes([2 if enabled else 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
try:
winreg.SetValueEx(k, item["name"], 0, winreg.REG_BINARY, data)
finally:
winreg.CloseKey(k)
return True
except (PermissionError, OSError):
return False
def run_startup_manager() -> None:
"""Interactive enable/disable of startup programs."""
admin = _is_admin()
items = enumerate_startup()
if not items:
print(" No startup programs found in Run keys or Startup folders.")
return
desired = [it["enabled"] for it in items]
while True:
print()
_title("STARTUP PROGRAMS")
print(" Programs that launch when Windows starts. Turning some off = faster boot.")
print(f" Type a number to toggle, {_color('S', GREEN)} to save, "
f"{_color('Q', YELLOW)} to go back.")
if not admin:
print(f" {_color('Note', YELLOW)}: not elevated - HKLM/system items "
f"can't be changed. Launch as administrator for those.")
_hr()
for idx, it in enumerate(items, start=1):
box = _color("[x]", GREEN) if desired[idx - 1] else _color("[ ]", YELLOW)
changed = "*" if desired[idx - 1] != it["enabled"] else " "
cmd = it["command"]
if len(cmd) > 26:
cmd = cmd[:23] + "..."
print(f" {box}{changed}{idx:>2}. {it['display'][:30]:<30} "