-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimizer.py
More file actions
2558 lines (2282 loc) · 130 KB
/
optimizer.py
File metadata and controls
2558 lines (2282 loc) · 130 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
"""
minoreOptimizer — Windows System Optimization Tool
License: MIT License
Copyright (c) 2024 bpm500 — https://github.com/bpm500
"""
import sys
import os
import subprocess
import ctypes
import platform
import webbrowser
import threading
import time
import json
import winreg
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QTabWidget, QVBoxLayout,
QHBoxLayout, QPushButton, QLabel, QCheckBox, QScrollArea,
QGroupBox, QFrame, QTextEdit, QMessageBox, QSpacerItem, QSizePolicy,
QLineEdit, QColorDialog, QSlider, QSpinBox, QGridLayout
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QSize, QTimer, QPropertyAnimation, QEasingCurve
from PyQt6.QtGui import QFont, QIcon, QColor, QPalette, QPixmap, QCursor, QPainter, QBrush
# ══════════════════════════════════════════════════════════════════
# HELPERS
# ══════════════════════════════════════════════════════════════════
if getattr(sys, "frozen", False):
BASE_DIR = os.path.dirname(sys.executable)
_BUNDLE_DIR = sys._MEIPASS # type: ignore[attr-defined]
else:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
_BUNDLE_DIR = BASE_DIR
def asset(name):
p = os.path.join(BASE_DIR, name)
if os.path.exists(p):
return p
return os.path.join(_BUNDLE_DIR, name)
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def run_as_admin():
ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, " ".join(sys.argv), None, 1
)
def run_cmd(cmd, timeout=30):
"""Run command with timeout. Returns (output, success)."""
try:
r = subprocess.run(
cmd, shell=True, capture_output=True,
text=True, encoding="utf-8", errors="ignore",
timeout=timeout
)
out = (r.stdout + r.stderr).strip()
ok = r.returncode == 0
return out, ok
except subprocess.TimeoutExpired:
return f"[TIMEOUT] Command exceeded {timeout}s limit", False
except Exception as e:
return str(e), False
def run_cmd_s(cmd, timeout=30):
"""run_cmd but returns only the string (legacy compat)."""
out, _ = run_cmd(cmd, timeout)
return out
def run_ps(script, timeout=30):
return run_cmd_s(
f'powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "{script}"',
timeout
)
def safe_run_batch(cmds, log_fn, label="", max_errors=5, timeout=20):
"""
Smart batch runner with adaptive logic:
- TIMEOUT is treated as WARNING only, NOT as an error.
A slow HDD can delay reg/netsh commands — we wait and move on.
- ERROR counter only increments on real failures (returncode != 0
AND output contains known error keywords).
- Aborts only after max_errors REAL errors in a row.
- Returns True if completed, False if aborted.
"""
# Keywords that indicate a genuine failure vs. "command not found on this OS"
REAL_ERROR_KEYWORDS = [
"access is denied", "not recognized", "invalid parameter",
"failed", "error:", "cannot", "refused", "0x8"
]
errors = 0
for cmd in cmds:
out, ok = run_cmd(cmd, timeout)
if ok or not out:
errors = 0 # success — reset error streak
continue
out_low = out.lower()
# Timeout: warn but do NOT count as error — slow HDD/system
if "[TIMEOUT]" in out:
log_fn(f" ⚠ [SLOW] {label} — команда медленная, продолжаем: {cmd[:55]}...")
continue
# "Not applicable" style results — command ran but feature not present
# e.g. schtasks on non-existent task, sc on non-existent service
if any(k in out_low for k in ["не существует", "not exist", "не найден",
"no tasks", "specified service", "1060",
"element not found", "no instances"]):
continue # silently skip — feature just not present on this system
# Real error
is_real_err = any(k in out_low for k in REAL_ERROR_KEYWORDS)
if is_real_err:
errors += 1
log_fn(f" ✗ [ERR {errors}/{max_errors}] {cmd[:60]}")
if errors >= max_errors:
log_fn(f" ⚠ {label}: {max_errors} реальных ошибок подряд — пропускаем блок")
return False
# Non-zero but not a recognized error = warning only
return True
def run_process_streaming(cmd, log_fn, parse_progress=None, timeout=600):
"""
Run a long command and stream its output line-by-line.
parse_progress: optional callable(line) -> str|None — returns display text or None
Filters out garbled non-ASCII (Russian console artifacts etc.).
Returns True on success.
"""
import re
try:
proc = subprocess.Popen(
cmd, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding="utf-8", errors="replace"
)
deadline = time.time() + timeout
for raw_line in proc.stdout:
if time.time() > deadline:
proc.kill()
log_fn(" ⚠ [TIMEOUT] Процесс прерван по таймауту")
return False
line = raw_line.strip()
if not line:
continue
# Strip obvious encoding garbage (sequences of replacement chars)
line_clean = re.sub(r'[^\x00-\x7F\u0400-\u04FF\s%.,\[\]():/\\=_\-+#!?]', '', line).strip()
if not line_clean:
continue
if parse_progress:
display = parse_progress(line_clean)
if display:
log_fn(display)
else:
log_fn(f" {line_clean}")
proc.wait()
return proc.returncode == 0
except Exception as e:
log_fn(f" ✗ Ошибка запуска: {e}")
return False
# ══════════════════════════════════════════════════════════════════
# STYLESHEET
# ══════════════════════════════════════════════════════════════════
STYLE = """
* { font-family: 'Segoe UI', Arial, sans-serif; }
QMainWindow, QWidget#root { background: #181818; }
QTabWidget::pane { border: none; background: #1e1e1e; }
QTabBar { background: #141414; }
QTabBar::tab {
background: #141414; color: #888;
padding: 11px 24px; font-size: 13px;
border-bottom: 2px solid transparent; margin-right: 1px;
}
QTabBar::tab:selected {
color: #e8e8e8; border-bottom: 2px solid #4f9ef8; background: #1e1e1e;
}
QTabBar::tab:hover:!selected { color: #bbb; background: #1a1a1a; }
QScrollArea { border: none; background: transparent; }
QScrollBar:vertical { background: #1e1e1e; width: 6px; border-radius: 3px; }
QScrollBar::handle:vertical { background: #444; border-radius: 3px; min-height: 24px; }
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }
QGroupBox {
color: #7ab4f5; border: 1px solid #2a2a2a; border-radius: 8px;
margin-top: 12px; padding: 14px 12px 10px 12px;
font-size: 12px; font-weight: 600; letter-spacing: 0.5px;
}
QGroupBox::title { subcontrol-origin: margin; left: 12px; padding: 0 6px; }
QCheckBox { color: #c8c8c8; font-size: 13px; spacing: 10px; padding: 4px 2px; }
QCheckBox::indicator {
width: 17px; height: 17px; border: 1px solid #444;
border-radius: 4px; background: #252525;
}
QCheckBox::indicator:checked { background: #4f9ef8; border-color: #4f9ef8; }
QCheckBox::indicator:hover { border-color: #666; }
QCheckBox:hover { color: #e8e8e8; }
QPushButton {
background: #2a2a2a; color: #c8c8c8; border: 1px solid #383838;
border-radius: 6px; padding: 8px 16px; font-size: 13px;
}
QPushButton:hover { background: #333; border-color: #555; color: #e8e8e8; }
QPushButton:pressed { background: #222; }
QPushButton:disabled { color: #555; border-color: #2a2a2a; }
QPushButton#btnOptimize {
background: qlineargradient(x1:0,y1:0,x2:1,y2:1, stop:0 #1a5fc4, stop:1 #1248a0);
color: #fff; font-size: 15px; font-weight: 700;
border: none; border-radius: 8px; padding: 13px 36px; letter-spacing: 0.3px;
}
QPushButton#btnOptimize:hover {
background: qlineargradient(x1:0,y1:0,x2:1,y2:1, stop:0 #2068d4, stop:1 #1a55b5);
}
QPushButton#btnRestore {
background: qlineargradient(x1:0,y1:0,x2:1,y2:1, stop:0 #1a7a3a, stop:1 #145e2c);
color: #fff; font-size: 13px; border: none; border-radius: 7px; padding: 11px 22px;
}
QPushButton#btnRestore:hover {
background: qlineargradient(x1:0,y1:0,x2:1,y2:1, stop:0 #218a44, stop:1 #1a7a3a);
}
QPushButton#btnCopy {
background: #252530; color: #8ab4f8; border: 1px solid #363660;
border-radius: 6px; padding: 8px 16px; font-size: 12px;
}
QPushButton#btnCopy:hover { background: #2d2d42; }
QPushButton#btnDeepSeek {
background: #1a2540; color: #7ab4f5; border: 1px solid #2a3a60;
border-radius: 6px; padding: 8px 16px; font-size: 12px;
}
QPushButton#btnDeepSeek:hover { background: #202e54; }
QPushButton#btnMSI {
background: #2a1515; color: #f47878; border: 1px solid #4a2020;
border-radius: 6px; padding: 8px 16px; font-size: 12px;
}
QPushButton#btnMSI:hover { background: #341a1a; }
QPushButton#btnGithub {
background: transparent; color: #888; border: 1px solid #333;
border-radius: 6px; padding: 7px 14px; font-size: 12px;
}
QPushButton#btnGithub:hover { background: #252525; color: #bbb; border-color: #555; }
QLabel#titleBig { font-size: 24px; font-weight: 700; color: #f0f0f0; }
QLabel#titleSub { font-size: 13px; color: #666; }
QLabel#infoCard {
background: #232323; border: 1px solid #2d2d2d; border-radius: 10px;
color: #c8c8c8; font-size: 14px; padding: 18px 20px;
}
QLabel#sysCard {
background: #1c1c1c; border: 1px solid #2a2a2a; border-radius: 10px;
color: #c8c8c8; font-size: 14px; padding: 20px 22px;
}
QLabel#warnLabel {
color: #e07a5f; font-size: 12px; font-style: italic;
padding: 8px 4px 4px 4px; border-top: 1px solid #2d2d2d; margin-top: 6px;
}
QFrame#sep { background: #282828; max-height: 1px; }
QPushButton#profileFull, QPushButton#profileMedium,
QPushButton#profileLight, QPushButton#profileLaptop {
background: #242424; color: #777; border: 1px solid #333;
border-radius: 8px; font-size: 12px; font-weight: 500; padding: 6px 4px;
}
QPushButton#profileFull:hover, QPushButton#profileMedium:hover,
QPushButton#profileLight:hover, QPushButton#profileLaptop:hover {
background: #2c2c2c; border-color: #555; color: #bbb;
}
QPushButton#profileFull[active='true'] { background:#1a2a3a; border:2px solid #4f9ef8; color:#7ab4f5; font-weight:700; }
QPushButton#profileMedium[active='true'] { background:#1e2a1e; border:2px solid #4edd4e; color:#7de87d; font-weight:700; }
QPushButton#profileLight[active='true'] { background:#2a2a1a; border:2px solid #f0c040; color:#f0d070; font-weight:700; }
QPushButton#profileLaptop[active='true'] { background:#2a1a2a; border:2px solid #c07af0; color:#d4a0f8; font-weight:700; }
QLabel#profileDesc {
background: #1e1e2a; border: 1px solid #2a2a3a; border-radius: 8px;
color: #9ab4d8; font-size: 12px; padding: 10px 14px; font-style: italic;
}
QWidget#consoleRoot { background: #0d0d0d; }
QTextEdit#console {
background: #0d0d0d; color: #b8ffb8; border: none;
font-family: 'Cascadia Code', 'Consolas', monospace; font-size: 12px;
selection-background-color: #1a3a1a;
}
QPushButton#btnReboot {
background: #143a14; color: #4edd4e; border: 1px solid #247a24;
border-radius: 6px; padding: 9px 22px; font-size: 13px;
}
QPushButton#btnReboot:hover { background: #1a4e1a; }
QPushButton#btnReboot:disabled { background: #1e1e1e; color: #444; border-color: #333; }
QPushButton#btnCloseConsole {
background: #2a1414; color: #e07a5f; border: 1px solid #4a2020;
border-radius: 6px; padding: 9px 22px; font-size: 13px;
}
QPushButton#btnCloseConsole:hover { background: #361c1c; }
/* ── Fast Utility Tab ── */
QWidget#fuCard {
background: #1e1e1e;
border: 1px solid #2a2a2a;
border-radius: 10px;
}
QPushButton#fuRunBtn {
background: qlineargradient(x1:0,y1:0,x2:1,y2:1, stop:0 #1a5fc4, stop:1 #1248a0);
color: #fff; font-size: 14px; font-weight: 700;
border: none; border-radius: 8px; padding: 12px 32px;
}
QPushButton#fuRunBtn:hover {
background: qlineargradient(x1:0,y1:0,x2:1,y2:1, stop:0 #2068d4, stop:1 #1a55b5);
}
QPushButton#fuRunBtn:disabled { background: #252525; color: #555; }
QLineEdit#rgbInput {
background: #1a1a1a; color: #c8c8c8; border: 1px solid #3a3a3a;
border-radius: 5px; padding: 5px 10px; font-size: 12px;
font-family: 'Consolas', monospace;
}
QLineEdit#rgbInput:focus { border-color: #4f9ef8; }
QPushButton#colorPreview {
border: 2px solid #444; border-radius: 6px; min-width: 36px; max-width: 36px;
min-height: 36px; max-height: 36px;
}
QPushButton#colorPreview:hover { border-color: #888; }
QSlider::groove:horizontal {
height: 4px; background: #333; border-radius: 2px;
}
QSlider::handle:horizontal {
background: #4f9ef8; width: 14px; height: 14px; margin: -5px 0;
border-radius: 7px;
}
QSlider::sub-page:horizontal { background: #4f9ef8; border-radius: 2px; }
QLabel#colorSwatch {
border: 2px solid #444; border-radius: 6px;
min-width: 24px; min-height: 24px;
}
"""
# ══════════════════════════════════════════════════════════════════
# SYSTEM INFO
# ══════════════════════════════════════════════════════════════════
def _get_gpu_full_info():
results = []
# Strategy 1: NVIDIA NVML
try:
nvml = ctypes.windll.LoadLibrary("nvml.dll")
nvml.nvmlInit()
count = ctypes.c_uint(0)
nvml.nvmlDeviceGetCount(ctypes.byref(count))
class nvmlMemory_t(ctypes.Structure):
_fields_ = [("total", ctypes.c_ulonglong),
("free", ctypes.c_ulonglong),
("used", ctypes.c_ulonglong)]
for i in range(count.value):
handle = ctypes.c_void_p()
nvml.nvmlDeviceGetHandleByIndex(i, ctypes.byref(handle))
mem = nvmlMemory_t()
nvml.nvmlDeviceGetMemoryInfo(handle, ctypes.byref(mem))
name_buf = ctypes.create_string_buffer(96)
nvml.nvmlDeviceGetName(handle, name_buf, 96)
name = name_buf.value.decode("utf-8", errors="replace").strip()
if name:
results.append((name, mem.total / (1024 ** 3)))
nvml.nvmlShutdown()
if results:
return results
except Exception:
pass
# Strategy 2: Intel via registry
try:
path = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) as key:
for i in range(winreg.QueryInfoKey(key)[0]):
try:
with winreg.OpenKey(key, winreg.EnumKey(key, i)) as sub:
try:
desc, _ = winreg.QueryValueEx(sub, "DriverDesc")
if "Intel" in desc and any(x in desc for x in ("Arc", "UHD", "Iris")):
try:
m, _ = winreg.QueryValueEx(sub, "HardwareInformation.AdapterMemorySize")
results.append((desc, abs(int(m)) / (1024 ** 3)))
except Exception:
results.append((desc, 0.0))
except Exception:
pass
except Exception:
pass
except Exception:
pass
if results:
return results
# Strategy 3: PowerShell CIM uint64
try:
cmd = (
"$gpus = Get-CimInstance Win32_VideoController | "
"Where-Object { $_.Name -notmatch 'Parsec|Virtual|Remote|Indirect|Microsoft Basic|RDP|SpaceDesk|Moonlight|Sunshine|AnyDesk|TeamViewer|VNC|Citrix' }; "
"$list = $gpus | ForEach-Object { @{ Name = $_.Name; VRAM = [uint64]$_.AdapterRAM } }; "
"$list | ConvertTo-Json -Compress"
)
raw = subprocess.check_output(
["powershell", "-NoProfile", "-NonInteractive", "-Command", cmd],
text=True, creationflags=0x08000000, timeout=15
)
data = json.loads(raw.strip())
if isinstance(data, dict):
data = [data]
for item in data:
name = str(item.get("Name", "")).strip()
vram_bytes = int(item.get("VRAM", 0))
if name:
results.append((name, vram_bytes / (1024 ** 3)))
except Exception:
pass
return results if results else [("Не определено", 0.0)]
def get_system_info():
info = {}
try:
out = run_cmd_s("wmic cpu get Name,MaxClockSpeed /format:list", 10)
name = freq = ""
for line in out.splitlines():
if line.startswith("Name="):
name = line.split("=", 1)[1].strip()
elif line.startswith("MaxClockSpeed="):
mhz = line.split("=", 1)[1].strip()
try:
freq = f"{int(mhz)/1000:.2f} GHz"
except:
freq = mhz
info["cpu"] = f"{name} — {freq}" if name else "Не определено"
except:
info["cpu"] = "Ошибка"
try:
gpu_list = _get_gpu_full_info()
lines = [f"{n} — {v:.1f} GB" if v > 0.1 else n for n, v in gpu_list]
info["gpu"] = "\n".join(lines) if lines else "Не определено"
info["gpu_list"] = gpu_list
except:
info["gpu"] = "Ошибка"
info["gpu_list"] = []
try:
out = run_cmd_s("wmic memorychip get Capacity,Speed /format:list", 10)
total, speeds = 0, []
for line in out.splitlines():
if line.startswith("Capacity="):
try:
total += int(line.split("=", 1)[1].strip())
except:
pass
elif line.startswith("Speed="):
spd = line.split("=", 1)[1].strip()
if spd and spd not in speeds:
speeds.append(spd)
info["ram"] = f"{total//(1024**3)} GB — {speeds[0]+' MHz' if speeds else '?'}"
except:
info["ram"] = "Ошибка"
return info
# ══════════════════════════════════════════════════════════════════
# TOAST NOTIFICATION
# ══════════════════════════════════════════════════════════════════
class ToastNotification(QWidget):
def __init__(self, parent, message):
super().__init__(parent,
Qt.WindowType.FramelessWindowHint |
Qt.WindowType.Tool |
Qt.WindowType.WindowStaysOnTopHint)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
lay = QHBoxLayout(self)
lay.setContentsMargins(18, 12, 18, 12)
icon = QLabel("✅")
icon.setStyleSheet("font-size:18px; background:transparent;")
lbl = QLabel(message)
lbl.setStyleSheet(
"color:#e8e8e8; font-size:14px; font-weight:600; "
"background:transparent; font-family:'Segoe UI';"
)
lay.addWidget(icon)
lay.addSpacing(6)
lay.addWidget(lbl)
self.setStyleSheet(
"ToastNotification { background:#1e2a3a; border:1px solid #2e4a6a; border-radius:10px; }"
)
self.adjustSize()
if parent:
pr = parent.rect()
px = parent.mapToGlobal(pr.topLeft())
self.move(px.x() + (pr.width()-self.width())//2,
px.y() + (pr.height()-self.height())//2)
self.setWindowOpacity(0.0)
self.show()
self._a_in = QPropertyAnimation(self, b"windowOpacity")
self._a_in.setDuration(250)
self._a_in.setStartValue(0.0)
self._a_in.setEndValue(0.96)
self._a_in.setEasingCurve(QEasingCurve.Type.OutCubic)
self._a_in.start()
QTimer.singleShot(3200, self._fade_out)
def _fade_out(self):
self._a_out = QPropertyAnimation(self, b"windowOpacity")
self._a_out.setDuration(350)
self._a_out.setStartValue(0.96)
self._a_out.setEndValue(0.0)
self._a_out.setEasingCurve(QEasingCurve.Type.InCubic)
self._a_out.finished.connect(self.close)
self._a_out.start()
# ══════════════════════════════════════════════════════════════════
# OPTIMIZATION WORKER
# ══════════════════════════════════════════════════════════════════
class OptimizeWorker(QThread):
log = pyqtSignal(str)
finished = pyqtSignal()
def __init__(self, settings):
super().__init__()
self.s = settings
def L(self, text):
self.log.emit(text)
def _batch(self, cmds, label="", timeout=20):
"""Safe batch runner — aborts block after 5 errors, respects timeouts."""
return safe_run_batch(cmds, self.L, label, max_errors=5, timeout=timeout)
def _ps(self, script, timeout=25):
out = run_ps(script, timeout)
if "[TIMEOUT]" in out:
self.L(f" ✗ [TIMEOUT] PowerShell script exceeded {timeout}s")
return out
def run(self):
s = self.s
self.L("=" * 64)
self.L(" minoreOptimizer — Запуск оптимизации системы")
self.L("=" * 64)
# ── 1. Power plan ────────────────────────────────────────
if s.get("perf_preset"):
self.L("\n[►] Установка плана электропитания...")
run_cmd_s("powercfg -duplicatescheme e9a42b02-d5df-448d-aa00-03f14749eb61 2>NUL", 10)
run_cmd_s("powercfg /setactive e9a42b02-d5df-448d-aa00-03f14749eb61 2>NUL", 10)
run_cmd_s("powercfg /change monitor-timeout-ac 0", 5)
run_cmd_s("powercfg /change standby-timeout-ac 0", 5)
run_cmd_s("powercfg /change hibernate-timeout-ac 0", 5)
self.L(" ✓ Готово")
# ── 2. Telemetry ─────────────────────────────────────────
if s.get("disable_telemetry"):
self.L("\n[►] Отключение телеметрии и кейлоггера...")
self._batch([
'reg add "HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\DataCollection" /v AllowTelemetry /t REG_DWORD /d 0 /f',
'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\DataCollection" /v AllowTelemetry /t REG_DWORD /d 0 /f',
'sc stop DiagTrack & sc config DiagTrack start= disabled',
'sc stop dmwappushservice & sc config dmwappushservice start= disabled',
'reg add "HKCU\\SOFTWARE\\Microsoft\\Input\\TIPC" /v Enabled /t REG_DWORD /d 0 /f',
'reg add "HKLM\\SOFTWARE\\Policies\\Microsoft\\InputPersonalization" /v AllowInputPersonalization /t REG_DWORD /d 0 /f',
'reg add "HKCU\\SOFTWARE\\Microsoft\\InputPersonalization" /v RestrictImplicitTextCollection /t REG_DWORD /d 1 /f',
'reg add "HKCU\\SOFTWARE\\Microsoft\\InputPersonalization" /v RestrictImplicitInkCollection /t REG_DWORD /d 1 /f',
], "Телеметрия")
self.L(" ✓ Готово")
# ── 3. Privacy ───────────────────────────────────────────
if s.get("disable_privacy"):
self.L("\n[►] Отключение приватных настроек...")
self._batch([
'reg add "HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\AdvertisingInfo" /v Enabled /t REG_DWORD /d 0 /f',
'reg add "HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\AdvertisingInfo" /v DisabledByGroupPolicy /t REG_DWORD /d 1 /f',
'reg add "HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Privacy" /v TailoredExperiencesWithDiagnosticDataEnabled /t REG_DWORD /d 0 /f',
'reg add "HKCU\\SOFTWARE\\Microsoft\\Personalization\\Settings" /v AcceptedPrivacyPolicy /t REG_DWORD /d 0 /f',
], "Приватность")
self.L(" ✓ Готово")
# ── 4. Telemetry tasks ───────────────────────────────────
if s.get("disable_telemetry_tasks"):
self.L("\n[►] Отключение задач телеметрии, Copilot, AI, Recall...")
tasks = [
"\\Microsoft\\Windows\\Application Experience\\Microsoft Compatibility Appraiser",
"\\Microsoft\\Windows\\Application Experience\\ProgramDataUpdater",
"\\Microsoft\\Windows\\Customer Experience Improvement Program\\Consolidator",
"\\Microsoft\\Windows\\Customer Experience Improvement Program\\UsbCeip",
"\\Microsoft\\Windows\\DiskDiagnostic\\Microsoft-Windows-DiskDiagnosticDataCollector",
"\\Microsoft\\Windows\\Feedback\\Siuf\\DmClient",
"\\Microsoft\\Windows\\Feedback\\Siuf\\DmClientOnScenarioDownload",
"\\Microsoft\\Windows\\Windows Error Reporting\\QueueReporting",
"\\Microsoft\\Windows\\CloudExperienceHost\\CreateObjectTask",
"\\Microsoft\\Windows\\Autochk\\Proxy",
"\\Microsoft\\Windows\\NetTrace\\GatherNetworkInfo",
"\\Microsoft\\Windows\\Diagnosis\\Scheduled",
"\\Microsoft\\Windows\\WindowsAI\\CreateSuggestionIndex",
"\\Microsoft\\Windows\\Recall\\AutoIndexRecall",
]
self._batch(
[f'schtasks /Change /Disable /TN "{t}" 2>NUL' for t in tasks],
"Задачи телеметрии", timeout=8
)
run_cmd_s('reg add "HKCU\\Software\\Policies\\Microsoft\\Windows\\WindowsCopilot" /v TurnOffWindowsCopilot /t REG_DWORD /d 1 /f', 5)
self.L(" ✓ Готово")
# ── 5. Spy tasks ─────────────────────────────────────────
if s.get("disable_spy_tasks"):
self.L("\n[►] Отключение шпионских задач планировщика...")
self._batch(
[f'schtasks /Change /Disable /TN "{t}" 2>NUL' for t in [
"\\Microsoft\\Windows\\Maps\\MapsToastTask",
"\\Microsoft\\Windows\\Maps\\MapsUpdateTask",
"\\Microsoft\\Windows\\Shell\\FamilySafetyMonitor",
"\\Microsoft\\Windows\\Shell\\FamilySafetyRefreshTask",
"\\Microsoft\\Windows\\Location\\Notifications",
"\\Microsoft\\Windows\\Location\\WindowsActionDialog",
"\\Microsoft\\Windows\\BrokerInfrastructure\\BrokerTask",
"\\Microsoft\\Windows\\Management\\Provisioning\\Cellular",
]], "Шпионские задачи", timeout=8
)
self.L(" ✓ Готово")
# ── 6. Defender ──────────────────────────────────────────
if s.get("disable_defender"):
self.L("\n[►] Отключение Windows Defender...")
self._batch([
'reg add "HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender" /v DisableAntiSpyware /t REG_DWORD /d 1 /f',
'reg add "HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender\\Real-Time Protection" /v DisableRealtimeMonitoring /t REG_DWORD /d 1 /f',
], "Defender")
run_ps("Set-MpPreference -DisableRealtimeMonitoring $true", 15)
self.L(" ✓ Готово (требуется перезагрузка)")
# ── 7. OneDrive ──────────────────────────────────────────
if s.get("remove_onedrive"):
self.L("\n[►] Удаление OneDrive...")
run_cmd_s("taskkill /f /im OneDrive.exe 2>NUL", 5)
time.sleep(1)
# Method 1: winget (Win10 21H1+ / Win11)
out, ok = run_cmd("winget uninstall --id Microsoft.OneDrive --silent --accept-source-agreements 2>NUL", 45)
if ok:
self.L(" ✓ Удалено через winget")
else:
# Method 2: classic installer (legacy builds)
self.L(" > winget недоступен, используем классический деинсталлятор...")
run_cmd_s('%SystemRoot%\\SysWOW64\\OneDriveSetup.exe /uninstall 2>NUL', 30)
run_cmd_s('%SystemRoot%\\System32\\OneDriveSetup.exe /uninstall 2>NUL', 30)
# Method 3: PowerShell package removal
run_ps(
"Get-AppxPackage *OneDrive* | Remove-AppxPackage -ErrorAction SilentlyContinue; "
"Get-AppxProvisionedPackage -Online | Where-Object DisplayName -like *OneDrive* | "
"Remove-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue",
timeout=40
)
# Always: disable via policy + remove autostart
run_cmd_s('reg add "HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\OneDrive" /v DisableFileSyncNGSC /t REG_DWORD /d 1 /f', 5)
run_cmd_s('reg add "HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\OneDrive" /v DisableLibrariesDefaultSaveToOneDrive /t REG_DWORD /d 1 /f', 5)
run_cmd_s('reg delete "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" /v OneDrive /f 2>NUL', 5)
# Remove OneDrive from Explorer sidebar
run_cmd_s('reg add "HKCU\\Software\\Classes\\CLSID\\{018D5C66-4533-4307-9B53-224DE2ED1FE6}" /v System.IsPinnedToNameSpaceTree /t REG_DWORD /d 0 /f', 5)
self.L(" ✓ Готово")
# ── 8. Photo viewer ──────────────────────────────────────
if s.get("set_photo_viewer"):
self.L("\n[►] Установка классического просмотрщика фото...")
self._batch(
[f'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows Photo Viewer\\Capabilities\\FileAssociations" /v "{ext}" /t REG_SZ /d "PhotoViewer.FileAssoc.Tiff" /f'
for ext in [".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tif", ".tiff"]],
"PhotoViewer", timeout=5
)
self.L(" ✓ Готово")
# ── 9. Xbox Game Bar ─────────────────────────────────────
if s.get("disable_xbox_gamebar"):
self.L("\n[►] Отключение Xbox Game Bar и DVR...")
self._batch([
'reg add "HKCU\\System\\GameConfigStore" /v GameDVR_Enabled /t REG_DWORD /d 0 /f',
'reg add "HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\GameDVR" /v AllowGameDVR /t REG_DWORD /d 0 /f',
'reg add "HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\GameDVR" /v AppCaptureEnabled /t REG_DWORD /d 0 /f',
'reg add "HKCU\\SOFTWARE\\Microsoft\\GameBar" /v UseNexusForGameBarEnabled /t REG_DWORD /d 0 /f',
'sc stop XblGameSave & sc config XblGameSave start= disabled',
'sc stop XboxNetApiSvc & sc config XboxNetApiSvc start= disabled',
], "Xbox GameBar")
self.L(" ✓ Готово")
# ── 10. GPU HW Scheduling ────────────────────────────────
if s.get("gpu_hw_scheduling"):
self.L("\n[►] Включение GPU Hardware Accelerated Scheduling...")
run_cmd_s('reg add "HKLM\\SYSTEM\\CurrentControlSet\\Control\\GraphicsDrivers" /v HwSchMode /t REG_DWORD /d 2 /f', 5)
self.L(" ✓ Готово (требуется перезагрузка)")
# ── 11. Network ──────────────────────────────────────────
if s.get("optimize_network"):
self.L("\n[►] Оптимизация сети (TCP/IP, DNS, Nagle)...")
self._batch([
'reg add "HKLM\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters" /v TCPNoDelay /t REG_DWORD /d 1 /f',
'reg add "HKLM\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters" /v TcpAckFrequency /t REG_DWORD /d 1 /f',
'reg add "HKLM\\SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters" /v CacheHashTableBucketSize /t REG_DWORD /d 1 /f',
'reg add "HKLM\\SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters" /v CacheHashTableSize /t REG_DWORD /d 384 /f',
'netsh int tcp set global autotuninglevel=normal',
'netsh int tcp set global dca=enabled',
'netsh int tcp set global netdma=enabled',
'netsh int tcp set global ecncapability=disabled',
'netsh int tcp set global rss=enabled',
'netsh winsock reset',
'ipconfig /flushdns',
], "Сеть", timeout=15)
self.L(" ✓ Готово")
# ── 12. Registry cleanup ─────────────────────────────────
if s.get("clean_registry"):
self.L("\n[►] Очистка устаревших ключей реестра...")
self._batch([
'reg delete "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RecentDocs" /f 2>NUL',
'reg delete "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU" /f 2>NUL',
'reg delete "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\TypedPaths" /f 2>NUL',
'reg delete "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\UserAssist" /f 2>NUL',
'reg delete "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedPidlMRU" /f 2>NUL',
'reg delete "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSavePidlMRU" /f 2>NUL',
], "Реестр", timeout=5)
self.L(" ✓ Готово")
# ── 13. Timer / HPET ─────────────────────────────────────
if s.get("timer_resolution"):
self.L("\n[►] Настройка таймера прерываний (HPET/DynamicTick)...")
self._batch([
"bcdedit /set useplatformtick yes",
"bcdedit /deletevalue useplatformclock 2>NUL",
"bcdedit /set disabledynamictick yes",
], "Timer", timeout=8)
self.L(" ✓ Готово (требуется перезагрузка)")
# ── 14. Pagefile ─────────────────────────────────────────
if s.get("optimize_pagefile"):
self.L("\n[►] Оптимизация виртуальной памяти (pagefile)...")
self._ps(
"$cs = Get-WmiObject Win32_ComputerSystem; "
"$cs.AutomaticManagedPagefile = $false; $cs.Put() | Out-Null; "
"$pf = Get-WmiObject Win32_PageFileSetting; "
"if ($pf) { $pf.InitialSize = 4096; $pf.MaximumSize = 8192; $pf.Put() | Out-Null }",
timeout=20
)
run_cmd_s('reg add "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Memory Management" /v ClearPageFileAtShutdown /t REG_DWORD /d 1 /f', 5)
self.L(" ✓ Готово (требуется перезагрузка)")
# ── 15. DNS / Winsock ────────────────────────────────────
if s.get("dns_winsock"):
self.L("\n[►] Сброс DNS-кэша и Winsock...")
self._batch([
"ipconfig /flushdns",
"ipconfig /registerdns",
"netsh winsock reset catalog",
"netsh int ip reset",
], "DNS/Winsock", timeout=15)
self.L(" ✓ Готово")
# ── 16. Search indexing ──────────────────────────────────
if s.get("disable_search_index"):
self.L("\n[►] Отключение индексирования поиска...")
run_cmd_s("sc stop WSearch & sc config WSearch start= disabled", 10)
self.L(" ✓ Готово")
# ── 17. Services ─────────────────────────────────────────
if s.get("disable_services"):
self.L("\n[►] Отключение лишних служб...")
self._optimize_services()
self.L(" ✓ Готово")
# ── 18. Memory cleaner — safe, Windows-aware ─────────────
if s.get("memory_clean"):
self.L("\n[►] Очистка оперативной памяти...")
# 1. Flush working sets of non-critical processes only
# We use NtSetSystemInformation with SystemMemoryListCommand
# via PowerShell — this is what RAMMap does internally.
# It flushes Modified/Standby lists without touching
# running processes or our own app.
clean_script = (
"Add-Type -TypeDefinition @'\n"
"using System;\n"
"using System.Runtime.InteropServices;\n"
"public class MemClean {\n"
" [DllImport(\"ntdll.dll\")] public static extern uint\n"
" NtSetSystemInformation(int cls, ref int info, int len);\n"
" public static void FlushStandby() {\n"
" int cmd = 4; // MemoryPurgeStandbyList\n"
" NtSetSystemInformation(0x50, ref cmd, 4);\n"
" cmd = 3; // MemoryFlushModifiedList\n"
" NtSetSystemInformation(0x50, ref cmd, 4);\n"
" }\n"
"}\n"
"'@ -Language CSharp\n"
"[MemClean]::FlushStandby()"
)
# Write to temp file to avoid inline escaping issues
tmp = os.path.join(os.environ.get("TEMP", "C:\\Temp"), "mc_flush.ps1")
try:
with open(tmp, "w", encoding="utf-8") as f:
f.write(clean_script)
out, ok = run_cmd(
f'powershell -NoProfile -ExecutionPolicy Bypass -File "{tmp}"',
timeout=12
)
if ok:
self.L(" ✓ Standby/Modified списки RAM очищены")
else:
self.L(" ⚠ NtSetSystemInformation не поддержан — используем fallback")
# Fallback: ProcessIdleTasks (safe, only flushes idle queues)
run_cmd("rundll32.exe advapi32.dll,ProcessIdleTasks", timeout=6)
except Exception as e:
self.L(f" ⚠ Fallback: {e}")
run_cmd("rundll32.exe advapi32.dll,ProcessIdleTasks", timeout=6)
finally:
try:
os.remove(tmp)
except Exception:
pass
# 2. Force GC on our own process memory (safe, only affects this app)
import gc; gc.collect()
self.L(" ✓ Готово")
# ── 19. CHKDSK ───────────────────────────────────────────
if s.get("fix_errors"):
self.L("\n[►] Планирование CHKDSK при перезагрузке...")
run_cmd_s("echo Y | chkdsk C: /f", 10)
self.L(" ✓ Запланировано при следующей загрузке")
# ── 20. Invalid data ─────────────────────────────────────
if s.get("clean_invalid"):
self.L("\n[►] Очистка недопустимых данных устройств...")
self._batch([
'reg delete "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\UserAssist" /f 2>NUL',
"pnputil /scan-devices 2>NUL",
], "Данные устройств", timeout=15)
self.L(" ✓ Готово")
# ── 21. Drivers ──────────────────────────────────────────
if s.get("fix_drivers"):
self.L("\n[►] Проверка несовместимых драйверов...")
out = run_ps(
"Get-PnpDevice | Where-Object {$_.Status -ne 'OK'} | "
"Select-Object Name,Status | Format-Table -AutoSize | Out-String",
timeout=20
)
if out.strip() and "[TIMEOUT]" not in out:
self.L(out)
else:
self.L(" Все устройства работают корректно")
self.L(" ✓ Готово")
# ── 22. Junk cleaner ─────────────────────────────────────
if s.get("clean_junk"):
self.L("\n[►] Удаление мусора...")
# Phase 1: quick file deletes (5s each)
self._batch([
'del /s /f /q "%TEMP%\\*.*" 2>NUL',
'del /s /f /q "C:\\Windows\\Temp\\*.*" 2>NUL',
'del /s /f /q "C:\\Windows\\Prefetch\\*.*" 2>NUL',
'reg delete "HKCU\\Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\Bags" /f 2>NUL',
'reg delete "HKCU\\Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\BagMRU" /f 2>NUL',
'ie4uinit.exe -ClearIconCache',
], "Мусор (быстрое)", timeout=5)
# Phase 2: slower ops with generous timeouts
self.L(" > Очистка кэша обновлений Windows...")
run_cmd_s("net stop wuauserv 2>NUL", 10)
run_cmd_s("net stop bits 2>NUL", 10)
run_cmd_s('rmdir /s /q "%SystemRoot%\\SoftwareDistribution\\Download" 2>NUL', 15)
run_cmd_s("net start wuauserv 2>NUL", 10)
run_cmd_s("net start bits 2>NUL", 10)
self.L(" > Очистка кэша Edge...")
run_cmd_s('rmdir /s /q "%LOCALAPPDATA%\\Microsoft\\Edge\\User Data\\Default\\Cache" 2>NUL', 10)
self.L(" > WinSxS cleanup (может занять 1-2 мин)...")
run_cmd_s("dism /online /cleanup-image /startcomponentcleanup", timeout=120)
self.L(" ✓ Готово")
# ── 23. Metro apps ───────────────────────────────────────
metro = {
"remove_3dbuilder": ["Microsoft.3DBuilder"],
"remove_camera": ["Microsoft.WindowsCamera"],
"remove_mail": ["Microsoft.windowscommunicationsapps", "Microsoft.WindowsMaps"],
"remove_money": ["Microsoft.BingFinance", "Microsoft.BingSports",
"Microsoft.BingNews", "Microsoft.BingWeather"],
"remove_groove": ["Microsoft.ZuneMusic", "Microsoft.ZuneVideo"],
"remove_people": ["Microsoft.People", "Microsoft.Office.OneNote"],
"remove_phone": ["Microsoft.WindowsPhone", "Microsoft.Windows.Photos"],
"remove_solitaire": ["Microsoft.MicrosoftSolitaireCollection"],
"remove_voice": ["Microsoft.WindowsSoundRecorder"],
"remove_xbox": ["Microsoft.XboxApp", "Microsoft.XboxGameOverlay",
"Microsoft.XboxGamingOverlay", "Microsoft.XboxIdentityProvider",
"Microsoft.Xbox.TCUI", "Microsoft.XboxSpeechToTextOverlay"],
}
for key, pkgs in metro.items():
if s.get(key):
for pkg in pkgs:
self.L(f"\n[►] Удаление {pkg}...")
out = run_ps(f"Get-AppxPackage *{pkg}* | Remove-AppxPackage", timeout=30)
if "[TIMEOUT]" in out:
self.L(f" ✗ Timeout при удалении {pkg} — пропущено")
else:
self.L(" ✓ Готово")
# ── 24–32. Advanced tweaks ───────────────────────────────
if s.get("disable_dynamic_tick"):
self.L("\n[►] Отключение Dynamic Tick...")
run_cmd_s("bcdedit /set disabledynamictick yes", 8)
self.L(" ✓ Готово (требуется перезагрузка)")
if s.get("force_hpet"):
self.L("\n[►] Принудительный HPET + TSC Sync Enhanced...")
run_cmd_s("bcdedit /set useplatformclock true", 8)
run_cmd_s("bcdedit /set tscsyncpolicy Enhanced", 8)
self.L(" ✓ Готово (требуется перезагрузка)")
if s.get("disable_nagle"):
self.L("\n[►] Отключение алгоритма Nagle на всех интерфейсах...")
self._ps(
"$path = 'HKLM:\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces'; "
"Get-ChildItem $path | ForEach-Object { "
" Set-ItemProperty -Path $_.PSPath -Name 'TcpAckFrequency' -Value 1 -Type DWord -Force -EA SilentlyContinue; "
" Set-ItemProperty -Path $_.PSPath -Name 'TCPNoDelay' -Value 1 -Type DWord -Force -EA SilentlyContinue }",
timeout=15
)
self.L(" ✓ Готово")
if s.get("disable_mouse_accel"):
self.L("\n[►] Отключение ускорения мыши...")
self._batch([
'reg add "HKCU\\Control Panel\\Mouse" /v MouseSpeed /t REG_SZ /d 0 /f',
'reg add "HKCU\\Control Panel\\Mouse" /v MouseThreshold1 /t REG_SZ /d 0 /f',
'reg add "HKCU\\Control Panel\\Mouse" /v MouseThreshold2 /t REG_SZ /d 0 /f',
'reg add "HKCU\\Control Panel\\Mouse" /v MouseSensitivity /t REG_SZ /d 10 /f',
], "Mouse", timeout=5)
self.L(" ✓ Готово")
if s.get("processor_idle_disable"):
self.L("\n[►] Processor Idle Disable — агрессивный режим CPU...")
run_cmd_s("powercfg -attributes SUB_PROCESSOR IDLEDISABLE -ATTRIB_HIDE", 8)
run_cmd_s("powercfg -setacvalueindex scheme_current SUB_PROCESSOR IDLEDISABLE 1", 8)
run_cmd_s("powercfg -setactive scheme_current", 8)
self.L(" ✓ Готово")
if s.get("system_responsiveness"):
self.L("\n[►] System Responsiveness = 0 (приоритет игровых задач)...")
self._batch([
'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Multimedia\\SystemProfile" /v SystemResponsiveness /t REG_DWORD /d 0 /f',
'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Multimedia\\SystemProfile\\Tasks\\Games" /v "GPU Priority" /t REG_DWORD /d 8 /f',
'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Multimedia\\SystemProfile\\Tasks\\Games" /v "Priority" /t REG_DWORD /d 6 /f',
'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Multimedia\\SystemProfile\\Tasks\\Games" /v "Scheduling Category" /t REG_SZ /d "High" /f',
], "Responsiveness", timeout=5)
self.L(" ✓ Готово")
if s.get("network_throttling"):
self.L("\n[►] Убрать Network Throttling Index...")
run_cmd_s(
'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Multimedia\\SystemProfile" '
'/v NetworkThrottlingIndex /t REG_DWORD /d 4294967295 /f', 5
)
self.L(" ✓ Готово")
if s.get("disable_core_parking"):
self.L("\n[►] Отключение Core Parking (все ядра активны)...")
run_cmd_s("powercfg -attributes SUB_PROCESSOR CPMINCORES -ATTRIB_HIDE", 8)
run_cmd_s("powercfg -setacvalueindex scheme_current SUB_PROCESSOR CPMINCORES 100", 8)
run_cmd_s("powercfg -setactive scheme_current", 8)
self.L(" ✓ Готово")
if s.get("network_stack_boost"):
self.L("\n[►] Network Stack Boost...")
self._batch([
"netsh int tcp set global autotuninglevel=normal",
"netsh int tcp set global rss=enabled",
"netsh int tcp set global chimney=enabled",
"netsh int tcp set global dca=enabled",
"netsh int tcp set global netdma=enabled",
"netsh int tcp set global ecncapability=disabled",
"netsh int tcp set heuristics disabled",
], "NetStack", timeout=10)
self.L(" ✓ Готово")
# ── 33. CPU Scheduling Optimization (Win11) ──────────────
if s.get("cpu_scheduling"):
self.L("\n[►] CPU Scheduling Optimization (Windows 11)...")