diff --git a/.github/workflows/build-windows-installer.yml b/.github/workflows/build-windows-installer.yml new file mode 100644 index 0000000..517aa97 --- /dev/null +++ b/.github/workflows/build-windows-installer.yml @@ -0,0 +1,47 @@ +name: build-windows-installer + +# Run this from the Actions tab ("Run workflow") if you have no Windows PC to build on. +# It runs the tests, builds FrameTweak.exe with PyInstaller, builds the Inno Setup installer, +# and attaches both as downloadable artifacts. +on: + workflow_dispatch: + +jobs: + build: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: requirements-dev.txt + - name: Install dependencies + run: python -m pip install --disable-pip-version-check -r requirements-dev.txt + - name: Run tests + run: python -m pytest -q + env: + QT_QPA_PLATFORM: offscreen + - name: Build the app with PyInstaller + run: python -m PyInstaller --noconfirm --clean FrameTweak.spec + - name: Check the exe was built + shell: pwsh + run: | + if (-not (Test-Path dist\FrameTweak\FrameTweak.exe)) { throw "dist\FrameTweak\FrameTweak.exe was not built" } + - name: Install Inno Setup + run: choco install innosetup --no-progress -y + - name: Build the installer + shell: pwsh + run: | + & "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" installer\FrameTweak.iss + if (-not (Test-Path dist-installer\FrameTweak-Setup.exe)) { throw "dist-installer\FrameTweak-Setup.exe was not built" } + - uses: actions/upload-artifact@v4 + with: + name: FrameTweak-Setup + path: dist-installer/FrameTweak-Setup.exe + if-no-files-found: error + - uses: actions/upload-artifact@v4 + with: + name: FrameTweak-portable + path: dist/FrameTweak + if-no-files-found: error diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..ee79dc2 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,25 @@ +name: tests + +# Runs the test suite on a real Windows machine, which is where FrameTweak is meant to run. +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +jobs: + test: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: requirements-dev.txt + - name: Install dependencies + run: python -m pip install --disable-pip-version-check -r requirements-dev.txt + - name: Run tests + run: python -m pytest -q + env: + QT_QPA_PLATFORM: offscreen diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a20c55e --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# Python +__pycache__/ +*.py[cod] +.pytest_cache/ + +# Created by Install-FrameTweak.bat / Build-FrameTweak.bat +.venv/ +build/ +dist/ +dist-installer/ diff --git a/README.md b/README.md index 8bc7027..d084972 100644 --- a/README.md +++ b/README.md @@ -20,13 +20,13 @@ | Area | What you get | |---|---| -| **Dashboard** | Live CPU/RAM/disk gauges; Windows version, CPU, GPU, RAM, disk, power plan, Game Mode, startup count; recent actions. Unreadable values show "Unavailable". | +| **Dashboard** | Live CPU/RAM/disk gauges; Windows version, CPU, GPU, RAM, disk, power plan, Game Mode, startup count; recent actions. Unreadable values show "Unavailable". **Export report** saves a plain-text summary (system, tweak status, recent actions) you can attach to a bug report or keep as a before/after record. | | **Monitoring** | Live CPU, RAM and disk charts and top memory users. Samples only while the page is visible. | -| **Gaming** | 10-second measured diagnostic (CPU/RAM/disk, top processes, display resolution and refresh rate, NVIDIA GPU via `nvidia-smi`, sensors when exposed). Findings cite their evidence and avoid definitive "bottleneck" claims. Profiles (3 presets + custom, validated JSON import/export). History with before/after comparison. **No FPS is measured.** | +| **Gaming** | 10-second measured diagnostic (CPU/RAM/disk, top processes, display resolution and refresh rate, NVIDIA GPU via `nvidia-smi`, sensors when exposed). Findings cite their evidence and avoid definitive "bottleneck" claims. Profiles (4 presets + custom, validated JSON import/export). History with before/after comparison. **No FPS is measured.** | | **Startup** | Lists Run-key and Startup-folder entries with status. Enable/disable through `StartupApproved` (what Task Manager uses): backed up, verified, undoable. Nothing is deleted. | | **Debloat** | Detects installed Store apps and offers removal of a **curated allow-list only** (23 optional Microsoft apps such as Weather, News, Solitaire, Clipchamp, Copilot). Security, Store, Xbox/gaming and system components are blocked. One confirmation lists exactly what will be removed; each removal is verified. Removal is not auto-reversible (reinstall from the Microsoft Store). | -| **Tweaks** | Game Mode and the High performance power plan, each with what/why/drawbacks/admin/reversible/current value. | -| **Cleanup** | User temp files and crash dumps only. Analyze first, then confirm. Skips files modified in the last 24 h and locked files, never follows symlinks, refuses protected folders. Reports measured bytes removed. | +| **Tweaks** | 9 individually applied, reversible tweaks in four groups, each shown with what/why/drawbacks/admin/reversible/current value and an Applied / Not applied status, plus **Undo all** (one confirmation listing exactly what is restored). **Gaming:** Game Mode, High performance power plan, Game DVR background capture off, Game Bar controller-button/tips off. **Input:** mouse pointer acceleration off, Sticky Keys / Filter Keys pop-ups off (only the shortcut flag is cleared, your other accessibility flags are kept). **Visuals:** transparency effects off. **Privacy:** advertising ID off, Windows suggestions and tips off. All are current-user (HKCU) settings and need no administrator rights. | +| **Cleanup** | A fixed list of temp and cache folders: user temp files, crash dumps, this user's Windows error reports, and the DirectX / NVIDIA / AMD shader caches (shader caches start **unselected**: they rebuild automatically, but games can stutter on their next launch). Analyze first, then confirm. Scanning and cleaning run in the background so the window stays responsive. Skips files modified in the last 24 h and locked files, never follows symlinks, refuses protected folders. Reports measured bytes removed. | | **Logs / Settings** | Local log viewer; persisted monitoring interval and window size. | ### Safety principles @@ -61,8 +61,8 @@ No Windows PC? Push to GitHub and run the **build-windows-installer** workflow; ## Architecture ``` main.py entry point (start-up errors -> native message box + log) -src/core/ sysinfo, winproc (the only subprocess launcher), applog, paths -src/tweaks/ engine.py (backup/apply/verify/rollback/undo) + catalog.py +src/core/ sysinfo, winproc (the only subprocess launcher), applog, paths, report +src/tweaks/ engine.py (backup/apply/verify/rollback/undo/undo-all), regtweaks.py (validated HKCU tweaks), catalog.py src/startup/ inspect_startup.py, manage.py src/debloat/ appx.py (curated allow-list, deny patterns, verified removal) src/cleanup/ cleaner.py (allow-listed roots, age gate, symlink-safe) @@ -79,12 +79,14 @@ tests/ tools/ assets/ installer/ .github/workflows/ pip install -r requirements-dev.txt python -m pytest -q ``` -46 tests cover system-info fallbacks, backup/restore, the change engine (including failed writes, failed verification, corrupt backups), startup toggling against a fake registry, debloat classification and refusals, cleanup safety, profile validation/import/export, diagnostics analysis, subprocess hygiene, icon assets, the background worker, window smoke tests, and static checks of the `.bat` scripts. Destructive operations are always mocked; tests never touch real system settings. +The tests cover system-info fallbacks, backup/restore, the change engine (including failed writes, failed verification, corrupt backups, multi-value rollback, undo-all), every registry tweak against a fake registry (including tampered backups and wrong value types), startup toggling against a fake registry, debloat classification and refusals, cleanup safety and the cleanup categories, the exported report, profile validation/import/export, diagnostics analysis, subprocess hygiene, icon assets, the background worker, window smoke tests, and static checks of the `.bat` scripts. Destructive operations are always mocked; tests never touch real system settings. + +The **tests** GitHub Actions workflow runs the suite on a real Windows runner for every push and pull request; the **build-windows-installer** workflow (run it manually from the Actions tab) runs the tests, builds the exe and installer and attaches them as downloads. ### Verification status | | Status | |---|---| -| Unit and headless UI tests | Run: 46 passed (Linux) | +| Unit tests (logic, engine, tweaks, cleanup, report) | Run: 86 passed (Linux). Two headless Qt smoke tests need PySide6 and were skipped where the latest changes were written, so run `python -m pytest -q` (or the CI workflow) to confirm the UI pages. | | Registry, `powercfg`, `Get/Remove-AppxPackage`, display API, `nvidia-smi` | Written, mocked in tests, **not run on Windows** | | `.bat` installer/launcher/uninstaller/build scripts | Statically checked only, **not run on Windows** | | PyInstaller exe, Inno Setup installer, desktop shortcut, "no console window" behavior | **Not built or run** | @@ -93,15 +95,15 @@ Safe manual check on Windows: apply Game Mode from Tweaks and undo it, confirmin ## Known limitations - Windows 10/11 only (other versions are flagged unsupported). -- Only two tweaks so far (Game Mode, High performance plan). Presets are therefore similar. +- Tweak gains vary and are often small; FrameTweak never measures FPS, so use the before/after diagnostics to check what changed on your PC. +- The mouse and keyboard tweaks write the current-user settings Windows reads at sign-in, so they usually take effect after you sign out and back in. - GPU stats need NVIDIA + `nvidia-smi`; AMD/Intel show Unavailable. CPU temperature is usually not exposed by Windows. - No FPS measurement; that needs an external tool and is out of scope. - Changing all-users (HKLM) startup entries requires running FrameTweak as administrator. -- Cleanup scan runs on the UI thread; large temp folders may briefly pause the window. - Unsigned installer: SmartScreen may warn. ## Roadmap -Privacy and visual-effects tweaks; Edge startup/background behavior tweaks; AMD/Intel GPU sensors; light theme; code signing; optional external FPS-tool integration (opt-in). +More privacy and visual-effects tweaks; Edge startup/background behavior tweaks; a one-click restore point before debloating (needs administrator); AMD/Intel GPU sensors; light theme; code signing; optional external FPS-tool integration (opt-in). ## Disclaimer FrameTweak changes Windows settings and can uninstall apps. It is provided as-is, without warranty. Create a restore point and read each confirmation. It does not guarantee any FPS improvement. diff --git a/installer/FrameTweak.iss b/installer/FrameTweak.iss index c13c235..c969855 100644 --- a/installer/FrameTweak.iss +++ b/installer/FrameTweak.iss @@ -1,7 +1,7 @@ ; Inno Setup 6 script. Installs per-user by default (no admin needed); user may choose all-users at the prompt. [Setup] AppName=FrameTweak -AppVersion=0.3.0 +AppVersion=0.4.0 AppPublisher=FrameTweak DefaultDirName={autopf}\FrameTweak DefaultGroupName=FrameTweak diff --git a/src/cleanup/cleaner.py b/src/cleanup/cleaner.py index 23cf97f..f67a269 100644 --- a/src/cleanup/cleaner.py +++ b/src/cleanup/cleaner.py @@ -1,23 +1,35 @@ """Safe temp cleanup: allow-listed roots only, never follows symlinks, skips recent/locked files.""" import os, tempfile, time from dataclasses import dataclass, field -from typing import Iterable, List +from typing import Iterable, List, Optional PROTECTED_NAMES = {"downloads", "documents", "desktop", "pictures", "videos", "music", "onedrive"} @dataclass class Category: id: str; name: str; path: str + default_selected: bool = True # False for caches whose removal has a visible cost (they rebuild on next use) + note: str = "" @dataclass class CleanResult: bytes_removed: int = 0; files_removed: int = 0; skipped: int = 0 errors: List[str] = field(default_factory=list) -def categories() -> List[Category]: - cats = [Category("user_temp", "User temporary files", tempfile.gettempdir())] - local = os.environ.get("LOCALAPPDATA") - if local: cats.append(Category("crash_dumps", "Application crash dumps", os.path.join(local, "CrashDumps"))) +REBUILD = "Rebuilt automatically; the first launch of each game may stutter or load slowly while shaders recompile." + +def categories(local_appdata: Optional[str] = None, temp_dir: Optional[str] = None) -> List[Category]: + """Fixed, allow-listed cleanup locations that exist on this PC. Paths can be injected for tests.""" + local = local_appdata if local_appdata is not None else os.environ.get("LOCALAPPDATA") + cats = [Category("user_temp", "User temporary files", temp_dir or tempfile.gettempdir())] + if local: + j = lambda *p: os.path.join(local, *p) + cats += [Category("crash_dumps", "Application crash dumps", j("CrashDumps")), + Category("wer_reports", "Windows error reports (this user)", j("Microsoft", "Windows", "WER")), + Category("dx_shader_cache", "DirectX shader cache (rebuilds on next game launch)", j("D3DSCache"), False, REBUILD), + Category("nv_dx_cache", "NVIDIA DirectX shader cache (rebuilds on next game launch)", j("NVIDIA", "DXCache"), False, REBUILD), + Category("nv_gl_cache", "NVIDIA OpenGL shader cache (rebuilds on next game launch)", j("NVIDIA", "GLCache"), False, REBUILD), + Category("amd_dx_cache", "AMD shader cache (rebuilds on next game launch)", j("AMD", "DxCache"), False, REBUILD)] return [c for c in cats if os.path.isdir(c.path)] def validate_root(path: str, allowed: Iterable[str]) -> str: diff --git a/src/core/report.py b/src/core/report.py new file mode 100644 index 0000000..6bb8948 --- /dev/null +++ b/src/core/report.py @@ -0,0 +1,48 @@ +"""Plain-text system report the user can save and share. Built only from values FrameTweak actually read: +anything unreadable says 'Unavailable', and no FPS or performance numbers are ever invented.""" +import os, time +from typing import Iterable, List, Optional, Tuple +from src.core import sysinfo +from src.tweaks import engine + +APPLIED = {True: "Applied", False: "Not applied", None: "Unavailable"} +ON_OFF = {True: "On", False: "Off", None: "Unavailable"} + +def tweak_status(tweaks: Iterable[engine.Tweak]) -> List[Tuple[str, str]]: + """(tweak name, 'Applied' | 'Not applied' | 'Unavailable') by reading each setting right now.""" + return [(t.name, APPLIED[engine.is_applied(t)]) for t in tweaks] + +def _memory(total: Optional[int], free: Optional[int]) -> str: + return "Unavailable" if total is None or free is None else f"{sysinfo.fmt_bytes(free)} free of {sysinfo.fmt_bytes(total)}" + +def build_report(s: sysinfo.SystemSnapshot, tweaks: List[Tuple[str, str]], actions: List[str], now: Optional[float] = None) -> str: + u = lambda x: x if x not in (None, "") else "Unavailable" + when = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now if now is not None else time.time())) + cores = f" ({s.cpu_cores} threads)" if s.cpu_cores else "" + lines = ["FrameTweak system report", f"Generated: {when}", "Values FrameTweak could not read are shown as Unavailable. No FPS is measured.", "", + "System", + f" Windows: {u(s.windows)}" + ("" if s.supported or not s.windows else " (unsupported version)"), + f" CPU: {u(s.cpu)}{cores}", + f" GPU: {u(s.gpu)}", + f" RAM: {_memory(s.ram_total, s.ram_available)}", + f" Disk: {_memory(s.disk_total, s.disk_free)}", + f" Power plan: {u(s.power_plan)}", + f" Game Mode: {ON_OFF[s.game_mode]}", "", "Tweaks"] + lines += [f" {name}: {state}" for name, state in tweaks] or [" None available"] + lines += ["", "Recent actions (from the local log)"] + lines += [f" {a}" for a in actions] or [" None recorded yet"] + if s.notes: lines += ["", "Notes"] + [f" {n}" for n in s.notes] + lines += ["", "Review this file before sharing it: it can include app names from your startup and debloat actions."] + return "\n".join(lines) + "\n" + +def save_report(text: str, directory: str) -> str: + """Write the report as a new file in `directory` (never overwrites) and return its path.""" + os.makedirs(directory, exist_ok=True) + stamp = time.strftime("%Y%m%d-%H%M%S") + for n in range(100): + path = os.path.join(directory, f"FrameTweak-report-{stamp}{'' if n == 0 else f'-{n}'}.txt") + try: + with open(path, "x", encoding="utf-8") as f: f.write(text) + return path + except FileExistsError: continue + raise OSError("Could not choose a free report file name") diff --git a/src/profiles/store.py b/src/profiles/store.py index 8f152c5..2c2ecd5 100644 --- a/src/profiles/store.py +++ b/src/profiles/store.py @@ -2,11 +2,16 @@ import json, os, re, tempfile from typing import List -KNOWN = {"game_mode": "Enable Windows Game Mode", "power_high": "Use the High performance power plan"} +# Tweaks a profile may contain (id -> name; names must match the Tweaks catalog, a test checks that). +KNOWN = {"game_mode": "Enable Windows Game Mode", "power_high": "Use the High performance power plan", + "game_dvr_off": "Turn off Game DVR background capture", "gamebar_quiet": "Stop the controller button and tips from opening Game Bar", + "mouse_accel_off": "Turn off mouse pointer acceleration", "sticky_keys_prompts_off": "Stop the Sticky Keys and Filter Keys pop-ups"} PRESETS = { "Balanced": {"tweaks": ["game_mode"], "notes": "Game Mode only; leaves your power plan alone."}, "Gaming": {"tweaks": ["game_mode", "power_high"], "notes": "Game Mode and the High performance power plan. Uses more power."}, "Low Background Activity": {"tweaks": ["game_mode"], "notes": "Game Mode, then use the Startup page and close background apps yourself. FrameTweak never auto-closes processes."}, + "Competitive": {"tweaks": ["game_mode", "power_high", "game_dvr_off", "gamebar_quiet", "mouse_accel_off", "sticky_keys_prompts_off"], + "notes": "For fast-paced games: less Game Bar activity, no pointer acceleration and no Sticky Keys pop-ups, on top of Game Mode and High performance. Uses more power; the mouse and keyboard changes need a sign-out to take effect."}, } EXE = re.compile(r"^[A-Za-z0-9._ -]{1,64}\.exe$") diff --git a/src/tweaks/catalog.py b/src/tweaks/catalog.py index 04b12da..1d94505 100644 --- a/src/tweaks/catalog.py +++ b/src/tweaks/catalog.py @@ -2,11 +2,21 @@ import re, sys from src.core import winproc from src.tweaks.engine import Tweak +from src.tweaks.regtweaks import DWORD, SZ, RegValue, flags_without_bit, registry_tweak WIN = lambda: sys.platform == "win32" GAMEBAR = r"Software\Microsoft\GameBar" +GAMEDVR = r"Software\Microsoft\Windows\CurrentVersion\GameDVR" +CONFIGSTORE = r"System\GameConfigStore" +MOUSE = r"Control Panel\Mouse" +ACCESS = r"Control Panel\Accessibility" +PERSONALIZE = r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" +ADINFO = r"Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo" +CDM = r"Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" GUID = re.compile(r"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}") HIGH_PERF = "8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c" +CATEGORIES = ("Gaming", "Input", "Visuals", "Privacy") # display order on the Tweaks page +SIGN_OUT = "Sign out and back in for it to take effect." def _reg_read(path, name): import winreg @@ -29,7 +39,7 @@ def _powercfg(*args): return r.stdout def power_read(): - m = GUID.search(_powercfg("/getactivescheme")); + m = GUID.search(_powercfg("/getactivescheme")); if not m: raise RuntimeError("Active power plan not found") return m.group(0).lower() @@ -41,6 +51,12 @@ def high_perf_available(): try: return HIGH_PERF in _powercfg("/list").lower() except Exception: return False +# Accessibility "keyboard shortcut is active" flag (SKF_/FKF_/TKF_HOTKEYACTIVE) and each value's Windows default. +HOTKEY_BIT = 0x4 +_STICKY = (RegValue(ACCESS + r"\StickyKeys", "Flags", SZ), RegValue(ACCESS + r"\Keyboard Response", "Flags", SZ), + RegValue(ACCESS + r"\ToggleKeys", "Flags", SZ)) +_STICKY_DEFAULTS = {_STICKY[0].key: 510, _STICKY[1].key: 126, _STICKY[2].key: 62} + def catalog(): return [ Tweak("game_mode", "Enable Windows Game Mode", @@ -48,10 +64,48 @@ def catalog(): "Game Mode asks Windows to prioritise the foreground game and limit some background activity.", "Gains vary and are often small. Undo restores the exact previous state (including 'not set').", False, True, lambda: _reg_read(GAMEBAR, "AutoGameModeEnabled"), - lambda v: _reg_write(GAMEBAR, "AutoGameModeEnabled", v), 1, WIN), + lambda v: _reg_write(GAMEBAR, "AutoGameModeEnabled", v), 1, WIN, category="Gaming"), Tweak("power_high", "Use the High performance power plan", "Runs powercfg /setactive for the built-in High performance plan.", "Avoids aggressive CPU down-clocking, which can reduce stutter on some desktops.", "Higher power use and heat; on laptops it shortens battery life. Plan may not exist on some PCs (then unavailable).", - False, True, power_read, power_write, HIGH_PERF, lambda: WIN() and high_perf_available()), + False, True, power_read, power_write, HIGH_PERF, lambda: WIN() and high_perf_available(), category="Gaming"), + registry_tweak("game_dvr_off", "Turn off Game DVR background capture", + "Sets HKCU\\System\\GameConfigStore\\GameDVR_Enabled and HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\GameDVR\\AppCaptureEnabled to 0.", + "Stops the Xbox Game Bar's background capture feature, which can add some load while a game runs.", + "Game Bar clips, screenshots and 'record that' stop working. Gains vary and are often small. Undo restores the exact previous values (including 'not set').", + [RegValue(CONFIGSTORE, "GameDVR_Enabled", DWORD, 0), RegValue(GAMEDVR, "AppCaptureEnabled", DWORD, 0)], category="Gaming"), + registry_tweak("gamebar_quiet", "Stop the controller button and tips from opening Game Bar", + "Sets HKCU\\Software\\Microsoft\\GameBar\\UseNexusForGameBarEnabled and ShowStartupPanel to 0.", + "Stops the Xbox controller's Guide button from opening Game Bar on top of your game, and hides Game Bar's first-run tips panel.", + "You can no longer open Game Bar with the controller button (it can still be opened from the keyboard). This does not change performance by itself.", + [RegValue(GAMEBAR, "UseNexusForGameBarEnabled", DWORD, 0), RegValue(GAMEBAR, "ShowStartupPanel", DWORD, 0)], category="Gaming"), + registry_tweak("mouse_accel_off", "Turn off mouse pointer acceleration", + "Sets HKCU\\Control Panel\\Mouse\\MouseSpeed, MouseThreshold1 and MouseThreshold2 to \"0\" (the 'Enhance pointer precision' option).", + "Pointer movement then follows your hand movement directly instead of depending on how fast you move, which many shooter players prefer for consistent aim. Many games read raw mouse input and ignore this setting.", + "The desktop pointer feels different, and quick flicks travel less far until you adjust the pointer speed. Undo restores the exact previous values.", + [RegValue(MOUSE, "MouseSpeed", SZ, "0"), RegValue(MOUSE, "MouseThreshold1", SZ, "0"), RegValue(MOUSE, "MouseThreshold2", SZ, "0")], + category="Input", note=SIGN_OUT), + registry_tweak("sticky_keys_prompts_off", "Stop the Sticky Keys and Filter Keys pop-ups", + "Clears the 'keyboard shortcut is active' flag in HKCU\\Control Panel\\Accessibility (StickyKeys, Keyboard Response and ToggleKeys \\Flags). Every other flag you have set is kept.", + "Stops the pop-up that appears when Shift is pressed five times, right Shift is held for 8 seconds, or Num Lock is held for 5 seconds, which can pull you out of a full-screen game.", + "Those keyboard shortcuts no longer start the accessibility features; you can still switch them on in Settings > Accessibility. Undo restores the exact previous values.", + _STICKY, category="Input", note=SIGN_OUT, target_fn=flags_without_bit(_STICKY, _STICKY_DEFAULTS, HOTKEY_BIT)), + registry_tweak("transparency_off", "Turn off transparency effects", + "Sets HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\\EnableTransparency to 0.", + "Turns off the see-through blur on the taskbar, Start and windows, so the desktop has slightly less to draw.", + "Windows looks flatter. The difference is usually small and mostly noticeable on weak integrated graphics.", + [RegValue(PERSONALIZE, "EnableTransparency", DWORD, 0)], category="Visuals"), + registry_tweak("ad_id_off", "Turn off the advertising ID", + "Sets HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\AdvertisingInfo\\Enabled to 0.", + "Stops Windows giving apps an advertising ID that is used to personalise ads across apps.", + "Ads shown inside apps stay but become less personalised. No performance effect.", + [RegValue(ADINFO, "Enabled", DWORD, 0)], category="Privacy"), + registry_tweak("tips_ads_off", "Turn off Windows suggestions and tips", + "Sets these HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\ContentDeliveryManager values to 0: SubscribedContent-338388Enabled, SubscribedContent-338389Enabled, SubscribedContent-353694Enabled, SubscribedContent-353696Enabled, SystemPaneSuggestionsEnabled, SoftLandingEnabled.", + "Stops Windows promoting apps and tips in Start, Settings and notifications.", + "You no longer see Microsoft's suggestions and tips. Windows updates may turn some of these back on. No meaningful performance effect.", + [RegValue(CDM, n, DWORD, 0) for n in ("SubscribedContent-338388Enabled", "SubscribedContent-338389Enabled", "SubscribedContent-353694Enabled", + "SubscribedContent-353696Enabled", "SystemPaneSuggestionsEnabled", "SoftLandingEnabled")], + category="Privacy"), ] diff --git a/src/tweaks/engine.py b/src/tweaks/engine.py index 86fc581..334cece 100644 --- a/src/tweaks/engine.py +++ b/src/tweaks/engine.py @@ -1,30 +1,58 @@ """Central change engine: read -> backup -> write -> re-read to validate -> rollback on failure.""" from dataclasses import dataclass -from typing import Any, Callable +from typing import Any, Callable, List, Optional, Tuple from src.backup.store import BackupStore, BackupError @dataclass class Tweak: id: str; name: str; what: str; why: str; drawbacks: str needs_admin: bool; reversible: bool - read: Callable[[], Any]; write: Callable[[Any], None]; target: Any + read: Callable[[], Any]; write: Callable[[Any], None] + target: Any # the wanted value, or a function orig -> wanted value (used to change one flag and keep the rest) supported: Callable[[], bool] = lambda: True + category: str = "General" + note: str = "" # extra caveat shown after a change, e.g. "Sign out and back in for it to take effect." @dataclass class Result: ok: bool; message: str +def resolve_target(t: Tweak, orig: Any) -> Any: + """The value the tweak wants, given the value read just now.""" + return t.target(orig) if callable(t.target) else t.target + +def is_applied(t: Tweak) -> Optional[bool]: + """True/False when the setting can be read here, None when it cannot be determined.""" + try: + if not t.supported(): return None + cur = t.read() + return cur == resolve_target(t, cur) + except Exception: + return None + +def _short_key(key: str) -> str: + """'Control Panel\\Mouse|MouseSpeed' -> 'Mouse\\MouseSpeed' (last key segment and value name).""" + return key.rsplit("\\", 1)[-1].replace("|", "\\") + +def format_value(v: Any) -> str: + """Human-readable form of a stored value (multi-value tweaks keep a dict keyed 'path|name').""" + if v is None: return "not set" + if isinstance(v, dict): return ", ".join(f"{_short_key(str(k))}={format_value(x)}" for k, x in v.items()) + return repr(v) + def apply(t: Tweak, store: BackupStore) -> Result: if not t.supported(): return Result(False, "Unavailable here (unsupported system, or administrator rights needed). Nothing changed.") try: orig = t.read() except Exception as e: return Result(False, f"Could not read the current setting. Nothing changed. ({e})") - if orig == t.target: return Result(True, "Already set. Nothing to change.") + try: target = resolve_target(t, orig) + except Exception as e: return Result(False, f"Could not work out the new value from the current setting. Nothing changed. ({e})") + if orig == target: return Result(True, "Already set. Nothing to change.") try: store.record(t.id, {"value": orig}) except BackupError as e: return Result(False, f"Backup failed, so nothing was changed. ({e})") try: - t.write(t.target); now = t.read() - if now == t.target: return Result(True, "Applied and verified.") + t.write(target); now = t.read() + if now == target: return Result(True, "Applied and verified." + (f" {t.note}" if t.note else "")) err = f"setting reads {now!r} after the change" except Exception as e: err = str(e) @@ -48,3 +76,20 @@ def undo(t: Tweak, store: BackupStore) -> Result: except Exception as e: return Result(False, f"Restore failed: {e}") return Result(True, "Original value restored and verified.") + +def undo_all(tweaks: List[Tweak], store: BackupStore) -> List[Tuple[str, Result]]: + """Restore every tweak that still has a saved original. One entry per tweak, newest change first. + + If a tweak was applied more than once, every saved record is undone so the oldest original wins.""" + try: ids = [b["id"] for b in store.pending()] + except BackupError as e: return [("Backups", Result(False, f"Backups unreadable: {e}"))] + out = [] + for t in tweaks: + n = ids.count(t.id) + if not n: continue + r = Result(False, "No saved original value to restore.") + for _ in range(n): + r = undo(t, store) + if not r.ok: break + out.append((t.name, r)) + return out diff --git a/src/tweaks/regtweaks.py b/src/tweaks/regtweaks.py new file mode 100644 index 0000000..e9844fb --- /dev/null +++ b/src/tweaks/regtweaks.py @@ -0,0 +1,86 @@ +"""Registry tweaks (current user only) built from plain data. + +A tweak can change several values at once; its saved state is a dict keyed 'path|name'. Real winreg I/O is +injected so the logic is testable off Windows. Backups are untrusted input: restoring only ever writes the +values this tweak declares, with the declared type, and rejects anything else.""" +import sys +from dataclasses import dataclass +from typing import Any, Callable, Dict, Iterable, Optional, Tuple +from src.tweaks.engine import Tweak + +DWORD, SZ = "dword", "sz" +WIN = lambda: sys.platform == "win32" + +@dataclass(frozen=True) +class RegValue: + path: str # under HKEY_CURRENT_USER + name: str + kind: str # DWORD or SZ + target: Any = None # wanted value (unused when the tweak supplies target_fn) + + def __post_init__(self): + if self.kind not in (DWORD, SZ): raise ValueError(f"unknown registry kind {self.kind!r}") + if not self.path or not self.name or "\x00" in self.path + self.name or "|" in self.path + self.name: + raise ValueError("invalid registry path or value name") + + @property + def key(self) -> str: return f"{self.path}|{self.name}" + +def check_value(rv: RegValue, v: Any) -> Any: + """None means 'not set'. Anything of the wrong type is refused rather than coerced.""" + if v is None: return None + if rv.kind == DWORD and isinstance(v, int) and not isinstance(v, bool) and 0 <= v <= 0xFFFFFFFF: return v + if rv.kind == SZ and isinstance(v, str): return v + raise ValueError(f"unexpected value {v!r} for {rv.name}") + +def _win_read(path: str, name: str): + import winreg + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as k: return winreg.QueryValueEx(k, name)[0] + except FileNotFoundError: return None + +def _win_write(path: str, name: str, kind: str, val) -> None: + import winreg + if val is None: # restore "not set" + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_SET_VALUE) as k: winreg.DeleteValue(k, name) + except FileNotFoundError: pass + return + with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_SET_VALUE) as k: + if kind == DWORD: winreg.SetValueEx(k, name, 0, winreg.REG_DWORD, int(val)) + else: winreg.SetValueEx(k, name, 0, winreg.REG_SZ, str(val)) + +def clear_flag_bit(cur: Optional[str], bit: int, default: int) -> str: + """Clear one bit of a flags value stored as a decimal string, keeping every other bit. + A missing value means Windows uses `default`. Unparseable text raises, so the tweak refuses to touch it.""" + value = default if cur is None else int(cur) + return str(value & ~bit) + +def flags_without_bit(values: Iterable[RegValue], defaults: Dict[str, int], bit: int) -> Callable[[dict], dict]: + """target_fn for tweaks that switch off one bit in several flag values.""" + vals = tuple(values) + return lambda orig: {v.key: clear_flag_bit(orig[v.key], bit, defaults[v.key]) for v in vals} + +def registry_tweak(id: str, name: str, what: str, why: str, drawbacks: str, values: Iterable[RegValue], category: str = "General", + note: str = "", target_fn: Optional[Callable[[dict], dict]] = None, + io: Optional[Tuple[Callable, Callable]] = None) -> Tweak: + rd, wr = io or (_win_read, _win_write) + vals = tuple(values) + if not vals: raise ValueError("a registry tweak needs at least one value") + if target_fn is None: + if any(v.target is None for v in vals): raise ValueError("every value needs a target (or give target_fn)") + target: Any = {v.key: check_value(v, v.target) for v in vals} + else: + target = target_fn + + def read() -> dict: + return {v.key: check_value(v, rd(v.path, v.name)) for v in vals} + + def write(state) -> None: + if not isinstance(state, dict): raise ValueError("saved value is not valid") + if any(v.key not in state for v in vals): raise ValueError("saved value is incomplete") + checked = [(v, check_value(v, state[v.key])) for v in vals] # validate everything before writing anything + for v, x in checked: wr(v.path, v.name, v.kind, x) + + return Tweak(id, name, what, why, drawbacks, False, True, read, write, target, + (lambda: True) if io else WIN, category, note) diff --git a/src/ui/app.py b/src/ui/app.py index 292a252..2eaadd9 100644 --- a/src/ui/app.py +++ b/src/ui/app.py @@ -3,8 +3,9 @@ from PySide6.QtGui import QPainter, QColor, QPen, QPolygonF, QIcon, QPixmap, QLinearGradient, QBrush, QPainterPath, QFont from PySide6.QtWidgets import (QSizePolicy, QApplication, QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QListWidget, QListWidgetItem, QStackedWidget, QLabel, QPushButton, QFrame, QGridLayout, QPlainTextEdit, QComboBox, QGraphicsOpacityEffect, QGraphicsDropShadowEffect) -from src.core import sysinfo +from src.core import sysinfo, report from src.core.applog import get_logger, data_dir, log_path +from src.tweaks.catalog import catalog from src.core.paths import resource_path from src.monitoring.live import LiveMonitor from src.startup.inspect_startup import read_startup_entries @@ -116,7 +117,7 @@ class Window(QMainWindow): NAV = ["Dashboard", "Monitoring", "Startup", "Gaming", "Debloat", "Tweaks", "Cleanup", "Logs", "Settings"] def __init__(self): super().__init__(); self.setWindowTitle("FrameTweak"); self.setWindowIcon(QIcon(resource_path("assets/frametweak.ico"))) - self.log = get_logger(); self.mon = LiveMonitor(); self.cfg = QSettings("FrameTweak", "FrameTweak"); self.resize(1120, 700) + self.log = get_logger(); self.mon = LiveMonitor(); self.cfg = QSettings("FrameTweak", "FrameTweak"); self.resize(1120, 700); self._snap = None # last analysis, used by Export report g = self.cfg.value("geometry") if g: self.restoreGeometry(g) root = QWidget(); self.setCentralWidget(root); v = QVBoxLayout(root); v.setContentsMargins(0, 0, 0, 0); v.setSpacing(0); v.addWidget(self._header()); gl = QFrame(); gl.setObjectName("glow"); gl.setFixedHeight(2); v.addWidget(gl) @@ -151,15 +152,24 @@ def _dashboard(self): f, v = card(k, "…"); self.cards[k] = v; grid.addWidget(f, i // 2, i % 2) self.warn = QLabel(""); self.warn.setObjectName("dim"); self.warn.setWordWrap(True); l.addWidget(self.warn) self.recent = QLabel(""); self.recent.setObjectName("dim"); self.recent.setWordWrap(True); l.addWidget(self.recent) - self.abtn = QPushButton("Analyze PC"); self.abtn.setProperty("primary", True); self.abtn.clicked.connect(self.analyze); self.abtn.setFixedWidth(140); l.addWidget(self.abtn); l.addStretch() + self.abtn = QPushButton("Analyze PC"); self.abtn.setProperty("primary", True); self.abtn.clicked.connect(self.analyze); self.abtn.setFixedWidth(140) + self.rbtn = QPushButton("Export report"); self.rbtn.setToolTip("Save a plain-text summary of this PC, your tweak status and recent actions"); self.rbtn.clicked.connect(self.export_report) + br = QHBoxLayout(); br.addWidget(self.abtn); br.addWidget(self.rbtn); br.addStretch(); l.addLayout(br); l.addStretch() self.analyze(); return w + def export_report(self): + if self._snap is None: self.statusBar().showMessage("Run Analyze PC first, then export the report.", 6000); return + acts = [x for x in self._log_lines() if re.search(r"tweak|startup|debloat|cleanup", x)][-20:] + try: path = report.save_report(report.build_report(self._snap, report.tweak_status(catalog()), acts), data_dir()) + except OSError as e: self.statusBar().showMessage(f"Could not save the report: {e}", 8000); self.log.error("report failed: %s", e); return + self.statusBar().showMessage(f"Report saved to {path}", 12000); self.log.info("Report exported") + def analyze(self): self.abtn.setEnabled(False); self.statusBar().showMessage("Analyzing…") run_bg(lambda: (sysinfo.collect(), len(read_startup_entries())), self._show, lambda m: (self.abtn.setEnabled(True), self.statusBar().showMessage(f"Analysis failed: {m}"), self.log.error("analysis failed: %s", m))) def _show(self, res): - s, n = res; u = lambda x: x if x not in (None, "") else "Unavailable"; c = self.cards + s, n = res; self._snap = s; u = lambda x: x if x not in (None, "") else "Unavailable"; c = self.cards c["Windows"].setText(u(s.windows) + ("" if s.supported or not s.windows else " (unsupported version)")) c["CPU"].setText(f"{u(s.cpu)} ({s.cpu_cores} threads)" if s.cpu_cores else u(s.cpu)); c["GPU"].setText(u(s.gpu)) c["RAM"].setText(f"{sysinfo.fmt_bytes(s.ram_available)} free of {sysinfo.fmt_bytes(s.ram_total)}") diff --git a/src/ui/pages.py b/src/ui/pages.py index 28179eb..7022589 100644 --- a/src/ui/pages.py +++ b/src/ui/pages.py @@ -1,3 +1,4 @@ +import html from PySide6.QtCore import Qt from PySide6.QtWidgets import (QWidget, QVBoxLayout, QLabel, QFrame, QPushButton, QHBoxLayout, QMessageBox, QTableWidget, QTableWidgetItem, QHeaderView, QScrollArea, QApplication) @@ -5,40 +6,62 @@ from src.core.applog import data_dir, get_logger from src.core import sysinfo from src.tweaks import engine -from src.tweaks.catalog import catalog +from src.tweaks.catalog import catalog, CATEGORIES from src.cleanup import cleaner +from src.ui.worker import run_bg def _head(l, title, sub): h = QLabel(title); h.setObjectName("h1"); l.addWidget(h) s = QLabel(sub); s.setObjectName("dim"); s.setWordWrap(True); l.addWidget(s) +STATE_COLOR = {True: "#34d399", False: "#7d8896", None: "#f59e0b"} +STATE_TEXT = {True: "Applied", False: "Not applied", None: "Unavailable"} + def tweaks_page(): log, store = get_logger(), BackupStore(data_dir()) w = QWidget(); l = QVBoxLayout(w) _head(l, "Tweaks", "Each change is individually approved, backed up first, verified after applying, and undoable. Nothing needs administrator rights.") + top = QHBoxLayout(); ua = QPushButton("Undo all applied changes…"); top.addWidget(ua); top.addStretch(); l.addLayout(top) status = QLabel(""); status.setWordWrap(True); status.setObjectName("dim") - body = QVBoxLayout(); l.addLayout(body); l.addWidget(status); l.addStretch() + holder = QWidget(); body = QVBoxLayout(holder); body.setContentsMargins(0, 0, 0, 0) + sc = QScrollArea(); sc.setWidgetResizable(True); sc.setFrameShape(QFrame.NoFrame); sc.setWidget(holder) + l.addWidget(sc, 1); l.addWidget(status) + def card(t, pending): + f = QFrame(); f.setObjectName("card"); fl = QVBoxLayout(f) + try: cur = html.escape(engine.format_value(t.read())) if t.supported() else "Unavailable" + except Exception: cur = "Unavailable" + applied = engine.is_applied(t); e = html.escape + txt = (f"{e(t.name)}   {STATE_TEXT[applied]}
Changes: {e(t.what)}
Why: {e(t.why)}
Drawbacks: {e(t.drawbacks)}
" + f"Administrator: {'required' if t.needs_admin else 'not required'} | Reversible: {'yes' if t.reversible else 'no'} | " + f"Current value: {cur}" + (f"
After applying: {e(t.note)}" if t.note else "") + ("" if t.supported() else "
Not supported on this system.")) + lab = QLabel(txt); lab.setWordWrap(True); lab.setTextFormat(Qt.RichText); fl.addWidget(lab) + row = QHBoxLayout(); a = QPushButton("Apply"); u = QPushButton("Undo"); a.setEnabled(t.supported() and applied is not True); u.setEnabled(pending) + a.clicked.connect(lambda _=0, t=t: run(t, True)); u.clicked.connect(lambda _=0, t=t: run(t, False)) + row.addWidget(a); row.addWidget(u); row.addStretch(); fl.addLayout(row); return f def render(): while body.count(): - it = body.takeAt(0); it.widget().deleteLater() if it.widget() else None - for t in catalog(): - f = QFrame(); f.setObjectName("card"); fl = QVBoxLayout(f) - try: cur = repr(t.read()) if t.supported() else "Unavailable" - except Exception: cur = "Unavailable" - pending = any(b["id"] == t.id for b in _safe_pending(store)) - txt = (f"{t.name}
Changes: {t.what}
Why: {t.why}
Drawbacks: {t.drawbacks}
" - f"Administrator: {'required' if t.needs_admin else 'not required'} | Reversible: {'yes' if t.reversible else 'no'} | " - f"Current value: {cur}" + ("" if t.supported() else "
Not supported on this system.")) - lab = QLabel(txt); lab.setWordWrap(True); lab.setTextFormat(Qt.RichText); fl.addWidget(lab) - row = QHBoxLayout(); a = QPushButton("Apply"); u = QPushButton("Undo"); a.setEnabled(t.supported()); u.setEnabled(pending) - a.clicked.connect(lambda _=0, t=t: run(t, True)); u.clicked.connect(lambda _=0, t=t: run(t, False)) - row.addWidget(a); row.addWidget(u); row.addStretch(); fl.addLayout(row); body.addWidget(f) + it = body.takeAt(0) + if it.widget(): it.widget().deleteLater() + tweaks = catalog(); pending = {b["id"] for b in _safe_pending(store)}; ua.setEnabled(any(t.id in pending for t in tweaks)) + for cat in sorted({t.category for t in tweaks}, key=lambda c: CATEGORIES.index(c) if c in CATEGORIES else len(CATEGORIES)): + head = QLabel(cat.upper()); head.setObjectName("dim"); body.addWidget(head) + for t in tweaks: + if t.category == cat: body.addWidget(card(t, t.id in pending)) + body.addStretch() def run(t, do_apply): q = QMessageBox.question(w, "Confirm", f"{'Apply' if do_apply else 'Undo'}: {t.name}?\n\n{t.what}") if q != QMessageBox.Yes: return r = engine.apply(t, store) if do_apply else engine.undo(t, store) log.info("tweak %s %s -> %s: %s", "apply" if do_apply else "undo", t.id, r.ok, r.message) status.setText(f"{t.name}: {r.message}"); render() + def undo_everything(): + pend = {b["id"] for b in _safe_pending(store)}; todo = [t for t in catalog() if t.id in pend] + if not todo: status.setText("Nothing to undo."); return + if QMessageBox.question(w, "Confirm", "Restore the original values saved before these changes:\n\n" + "\n".join("• " + t.name for t in todo)) != QMessageBox.Yes: return + results = engine.undo_all(todo, store) + for name, r in results: log.info("tweak undo-all %s -> %s: %s", name, r.ok, r.message) + status.setText("\n".join(f"{name}: {r.message}" for name, r in results)); render() + ua.clicked.connect(undo_everything) render(); return w def _safe_pending(store): @@ -47,28 +70,42 @@ def _safe_pending(store): def cleanup_page(): log = get_logger(); w = QWidget(); l = QVBoxLayout(w) - _head(l, "Cleanup", "Only temporary locations. Files modified in the last 24 hours and locked files are left alone. Downloads, documents, browsers and game saves are never touched.") + _head(l, "Cleanup", "Only temporary locations and rebuildable caches. Files modified in the last 24 hours and locked files are left alone. Downloads, documents, browsers and game saves are never touched. Shader caches start unselected: they are rebuilt automatically, but games may stutter on their next launch.") t = QTableWidget(0, 3); t.verticalHeader().setVisible(False); t.setHorizontalHeaderLabels(["Category", "Reclaimable", "Files"]); t.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch); l.addWidget(t) status = QLabel("Click Analyze to measure reclaimable space."); status.setObjectName("dim"); status.setWordWrap(True) ab, cb = QPushButton("Analyze"), QPushButton("Clean selected"); cb.setEnabled(False) row = QHBoxLayout(); row.addWidget(ab); row.addWidget(cb); row.addStretch(); l.addLayout(row); l.addWidget(status) - cats = cleaner.categories(); allowed = [c.path for c in cats] + cats = cleaner.categories(); allowed = [c.path for c in cats]; last = [""] # result of the last clean, shown above the rescan status if not cats: status.setText("No cleanup locations found on this system.") + def scan(): # runs off the UI thread + out = [] + for c in cats: + try: out.append(cleaner.analyze(c.path, allowed)) + except Exception as e: out.append((0, 0)); log.warning("analyze %s failed: %s", c.id, e) + return out + def show(res): + t.setRowCount(len(cats)); total = 0 + for r, (c, (size, n)) in enumerate(zip(cats, res)): + total += size + it = QTableWidgetItem(c.name); it.setFlags(it.flags() | Qt.ItemIsUserCheckable); it.setCheckState(Qt.Checked if n and c.default_selected else Qt.Unchecked) + if c.note: it.setToolTip(c.note) + t.setItem(r, 0, it); t.setItem(r, 1, QTableWidgetItem(sysinfo.fmt_bytes(size))); t.setItem(r, 2, QTableWidgetItem(str(n))) + status.setText((last[0] + "\n" if last[0] else "") + f"Estimated reclaimable: {sysinfo.fmt_bytes(total)} (an estimate; locked files may remain)."); last[0] = ""; ab.setEnabled(True); cb.setEnabled(bool(cats)) + def failed(m): ab.setEnabled(True); cb.setEnabled(bool(cats)); status.setText(f"Cleanup failed: {m}"); log.error("cleanup failed: %s", m) def analyze(): - status.setText("Analyzing…"); QApplication.processEvents(); t.setRowCount(len(cats)); total = 0 - for r, c in enumerate(cats): - try: size, n = cleaner.analyze(c.path, allowed); total += size - except Exception as e: size, n = 0, 0; log.warning("analyze %s failed: %s", c.id, e) - it = QTableWidgetItem(c.name); it.setFlags(it.flags() | Qt.ItemIsUserCheckable); it.setCheckState(Qt.Checked if n else Qt.Unchecked); t.setItem(r, 0, it) - t.setItem(r, 1, QTableWidgetItem(sysinfo.fmt_bytes(size))); t.setItem(r, 2, QTableWidgetItem(str(n))) - status.setText(f"Estimated reclaimable: {sysinfo.fmt_bytes(total)} (an estimate; locked files may remain)."); cb.setEnabled(bool(cats)) + if not cats: return + status.setText((last[0] + "\n" if last[0] else "") + "Analyzing…"); ab.setEnabled(False); cb.setEnabled(False); run_bg(scan, show, failed) def do_clean(): sel = [c for r, c in enumerate(cats) if t.item(r, 0) and t.item(r, 0).checkState() == Qt.Checked] if not sel: status.setText("Nothing selected."); return - if QMessageBox.question(w, "Confirm cleanup", "Permanently delete old temporary files in:\n" + "\n".join(c.path for c in sel)) != QMessageBox.Yes: return - tot = skipped = 0 - for c in sel: - try: r = cleaner.clean(c.path, allowed); tot += r.bytes_removed; skipped += r.skipped; log.info("cleanup %s removed=%d skipped=%d", c.id, r.bytes_removed, r.skipped) - except Exception as e: log.error("cleanup %s failed: %s", c.id, e) - status.setText(f"Removed {sysinfo.fmt_bytes(tot)} (measured). {skipped} file(s) in use were skipped."); analyze() + if QMessageBox.question(w, "Confirm cleanup", "Permanently delete old files in:\n" + "\n".join(c.path for c in sel)) != QMessageBox.Yes: return + def work(): # runs off the UI thread + tot = skipped = 0 + for c in sel: + try: r = cleaner.clean(c.path, allowed); tot += r.bytes_removed; skipped += r.skipped; log.info("cleanup %s removed=%d skipped=%d", c.id, r.bytes_removed, r.skipped) + except Exception as e: log.error("cleanup %s failed: %s", c.id, e) + return tot, skipped + def done(res): + last[0] = f"Removed {sysinfo.fmt_bytes(res[0])} (measured). {res[1]} file(s) in use were skipped."; analyze() + status.setText("Cleaning…"); ab.setEnabled(False); cb.setEnabled(False); run_bg(work, done, failed) ab.clicked.connect(analyze); cb.clicked.connect(do_clean); return w diff --git a/tests/test_cleanup_report.py b/tests/test_cleanup_report.py new file mode 100644 index 0000000..15ead78 --- /dev/null +++ b/tests/test_cleanup_report.py @@ -0,0 +1,74 @@ +import os, time +from src.cleanup import cleaner +from src.core import report, sysinfo +from src.tweaks.engine import Tweak + +def _old(p, hours=48): t = time.time() - hours * 3600; os.utime(p, (t, t)) + +# ---- cleanup categories +def _tree(tmp_path, *rel): + local, temp = tmp_path / "Local", tmp_path / "Temp"; temp.mkdir() + for r in rel: (local / r).mkdir(parents=True) + return local, temp + +def test_only_existing_fixed_locations_are_offered(tmp_path): + local, temp = _tree(tmp_path, "CrashDumps", "D3DSCache", os.path.join("NVIDIA", "DXCache"), os.path.join("Microsoft", "Windows", "WER")) + cats = {c.id: c for c in cleaner.categories(str(local), str(temp))} + assert set(cats) == {"user_temp", "crash_dumps", "wer_reports", "dx_shader_cache", "nv_dx_cache"} # GLCache and AMD folders don't exist here + for cid, c in cats.items(): + if cid != "user_temp": assert os.path.realpath(c.path).startswith(os.path.realpath(str(local)) + os.sep) + +def test_shader_caches_start_unselected_with_an_explanation(tmp_path): + local, temp = _tree(tmp_path, "CrashDumps", "D3DSCache", os.path.join("AMD", "DxCache")) + cats = {c.id: c for c in cleaner.categories(str(local), str(temp))} + assert cats["user_temp"].default_selected and cats["crash_dumps"].default_selected + for cid in ("dx_shader_cache", "amd_dx_cache"): + assert not cats[cid].default_selected and "recompile" in cats[cid].note and "rebuilds" in cats[cid].name + +def test_no_localappdata_means_only_user_temp(tmp_path): + temp = tmp_path / "Temp"; temp.mkdir() + assert [c.id for c in cleaner.categories("", str(temp))] == ["user_temp"] + +def test_shader_cache_cleaning_keeps_the_same_safety_rules(tmp_path): + local, temp = _tree(tmp_path, "D3DSCache"); root = local / "D3DSCache" + old, new = root / "old.bin", root / "new.bin"; old.write_bytes(b"x" * 10); new.write_bytes(b"y" * 10); _old(old) + allowed = [c.path for c in cleaner.categories(str(local), str(temp))] + r = cleaner.clean(str(root), allowed); assert r.bytes_removed == 10 and not old.exists() and new.exists() and root.exists() + +# ---- report +def _snap(**kw): + s = sysinfo.SystemSnapshot() + for k, v in kw.items(): setattr(s, k, v) + return s + +def test_report_never_invents_values(): + text = report.build_report(sysinfo.SystemSnapshot(), [], [], now=0) + assert "Game Mode: Unavailable" in text and "RAM: Unavailable" in text and "None available" in text and "None recorded yet" in text + assert "No FPS is measured" in text and text.endswith("\n") + +def test_report_shows_what_was_read(): + s = _snap(windows="Windows 11 (build 22631, AMD64)", supported=True, cpu="Test CPU", cpu_cores=16, gpu="Test GPU", ram_total=16 << 30, + ram_available=8 << 30, disk_total=500 << 30, disk_free=100 << 30, power_plan="High performance", game_mode=True, notes=["a note"]) + text = report.build_report(s, [("Tweak A", "Applied"), ("Tweak B", "Not applied")], ["tweak apply a -> True: ok"], now=0) + for part in ("Windows 11 (build 22631, AMD64)", "Test CPU (16 threads)", "Test GPU", "8.0 GB free of 16.0 GB", "100.0 GB free of 500.0 GB", "High performance", + "Game Mode: On", "Tweak A: Applied", "Tweak B: Not applied", "tweak apply a -> True: ok", "a note"): + assert part in text, part + assert "unsupported" not in text + +def test_report_flags_unsupported_windows(): + assert "(unsupported version)" in report.build_report(_snap(windows="Windows 7", supported=False), [], [], now=0) + +def test_tweak_status_reads_each_setting(): + st = {"on": 1, "off": 0} + mk = lambda i: Tweak(i, i.title(), "", "", "", False, True, lambda: st[i], lambda v: None, 1) + off = mk("off"); off.supported = lambda: False + broken = Tweak("x", "X", "", "", "", False, True, lambda: 1 / 0, lambda v: None, 1) + assert report.tweak_status([mk("on"), mk("off"), off, broken]) == [("On", "Applied"), ("Off", "Not applied"), ("Off", "Unavailable"), ("X", "Unavailable")] + +def test_save_report_never_overwrites_an_existing_file(tmp_path): + p1 = report.save_report("first", str(tmp_path)); p2 = report.save_report("second", str(tmp_path)) + assert p1 != p2 and open(p1, encoding="utf-8").read() == "first" and open(p2, encoding="utf-8").read() == "second" + assert os.path.basename(p1).startswith("FrameTweak-report-") and p1.endswith(".txt") + +def test_save_report_creates_the_folder(tmp_path): + p = report.save_report("x", str(tmp_path / "new" / "dir")); assert os.path.exists(p) diff --git a/tests/test_gaming_profiles.py b/tests/test_gaming_profiles.py index fa31f15..f9d79a0 100644 --- a/tests/test_gaming_profiles.py +++ b/tests/test_gaming_profiles.py @@ -1,10 +1,11 @@ -import json, pytest +import json, sys, pytest from src.gaming import diagnostics as dg from src.profiles.store import ProfileStore, validate_profile, compare_snapshots def test_collect_real_but_fast(monkeypatch): s = dg.collect(seconds=2, interval=1.0, sleep=lambda x: None) - assert s["seconds"] == 2 and s["ram_avg"] is not None and 0 <= s["cpu_avg"] <= 100 and s["display"] is None + assert s["seconds"] == 2 and s["ram_avg"] is not None and 0 <= s["cpu_avg"] <= 100 + assert sys.platform == "win32" or s["display"] is None # the display is only read on Windows def test_analyze_cites_evidence_and_hedges(): f = dg.analyze({"seconds": 10, "ram_avg": 92.0, "ram_max": 95.0, "cpu_avg": 30.0, "cpu_max": 50.0, "disk_avg": 1.0, "disk_max": 2.0, diff --git a/tests/test_regtweaks.py b/tests/test_regtweaks.py new file mode 100644 index 0000000..0400087 --- /dev/null +++ b/tests/test_regtweaks.py @@ -0,0 +1,165 @@ +import json, os, sys, pytest +from src.backup.store import BackupStore +from src.tweaks import engine +from src.tweaks.engine import Tweak, apply, undo, undo_all, is_applied, format_value +from src.tweaks.regtweaks import DWORD, SZ, RegValue, check_value, clear_flag_bit, flags_without_bit, registry_tweak + +class FakeReg: + """In-memory stand-in for HKCU. Records every write so tests can assert exactly what was touched.""" + def __init__(self, data=None): self.data, self.writes = dict(data or {}), [] + def read(self, path, name): return self.data.get((path, name)) + def write(self, path, name, kind, val): + self.writes.append((path, name, kind, val)) + if val is None: self.data.pop((path, name), None) + else: self.data[(path, name)] = val + @property + def io(self): return (self.read, self.write) + +A, B = RegValue("K\\One", "A", DWORD, 0), RegValue("K\\Two", "B", SZ, "0") + +def tweak(reg, **kw): return registry_tweak("t", "T", "what", "why", "drawbacks", [A, B], io=reg.io, **kw) + +# ---- registry_tweak +def test_multi_value_apply_then_undo_restores_exact_originals(tmp_path): + reg = FakeReg({("K\\One", "A"): 1}); st = BackupStore(str(tmp_path)); t = tweak(reg) # B starts 'not set' + r = apply(t, st); assert r.ok and r.message.startswith("Applied and verified"), r + assert reg.data == {("K\\One", "A"): 0, ("K\\Two", "B"): "0"} + assert undo(t, st).ok and reg.data == {("K\\One", "A"): 1} # A back to 1, B deleted again (was not set) + +def test_note_is_shown_after_apply(tmp_path): + t = tweak(FakeReg(), note="Sign out."); assert apply(t, BackupStore(str(tmp_path))).message.endswith("Sign out.") + +def test_already_set_changes_nothing(tmp_path): + reg = FakeReg({("K\\One", "A"): 0, ("K\\Two", "B"): "0"}); r = apply(tweak(reg), BackupStore(str(tmp_path))) + assert r.ok and r.message.startswith("Already") and reg.writes == [] + +def test_wrong_registry_type_is_refused_not_coerced(tmp_path): + reg = FakeReg({("K\\Two", "B"): 5}); r = apply(tweak(reg), BackupStore(str(tmp_path))) # B should be text, is a number + assert not r.ok and "Nothing changed" in r.message and reg.writes == [] + +def test_failed_second_write_rolls_back_the_first(tmp_path): + reg = FakeReg({("K\\One", "A"): 7}); orig_write = reg.write + def flaky(path, name, kind, val): + if path == "K\\Two" and val is not None: raise OSError("denied") + orig_write(path, name, kind, val) + t = registry_tweak("t", "T", "w", "y", "d", [A, B], io=(reg.read, flaky)) + r = apply(t, BackupStore(str(tmp_path))); assert not r.ok and "restored" in r.message.lower() and reg.data == {("K\\One", "A"): 7} + +def test_restore_only_writes_declared_values_and_types(): + reg = FakeReg(); t = tweak(reg) + t.write({"K\\One|A": 3, "K\\Two|B": "9", "HKEY\\Evil|x": 1, "K\\One|Extra": 1}) # extras from a tampered backup are ignored + assert sorted((p, n) for p, n, *_ in reg.writes) == [("K\\One", "A"), ("K\\Two", "B")] + +@pytest.mark.parametrize("bad", ["text", None, [], {"K\\One|A": 1}, {"K\\One|A": "1", "K\\Two|B": "0"}, {"K\\One|A": True, "K\\Two|B": "0"}, + {"K\\One|A": -1, "K\\Two|B": "0"}, {"K\\One|A": 2 ** 32, "K\\Two|B": "0"}, {"K\\One|A": 1, "K\\Two|B": 5}]) +def test_restore_validates_everything_before_writing_anything(bad): + reg = FakeReg(); t = tweak(reg) + with pytest.raises(ValueError): t.write(bad) + assert reg.writes == [] + +def test_registry_tweak_definition_errors(): + with pytest.raises(ValueError): registry_tweak("t", "T", "w", "y", "d", [], io=FakeReg().io) + with pytest.raises(ValueError): registry_tweak("t", "T", "w", "y", "d", [RegValue("K", "A", DWORD)], io=FakeReg().io) # no target + with pytest.raises(ValueError): RegValue("K", "A", "binary", 1) + with pytest.raises(ValueError): RegValue("K\\x", "a|b", DWORD, 1) + with pytest.raises(ValueError): RegValue("", "a", DWORD, 1) + with pytest.raises(ValueError): registry_tweak("t", "T", "w", "y", "d", [RegValue("K", "A", DWORD, True)], io=FakeReg().io) + +def test_check_value_types(): + assert check_value(A, None) is None and check_value(A, 5) == 5 and check_value(B, "x") == "x" + for rv, bad in ((A, "5"), (A, True), (A, 1.5), (B, 5), (B, b"x")): + with pytest.raises(ValueError): check_value(rv, bad) + +# ---- flag-bit tweaks +def test_clear_flag_bit_keeps_other_bits(): + assert clear_flag_bit("510", 4, 510) == "506" and clear_flag_bit("511", 4, 510) == "507" and clear_flag_bit("506", 4, 510) == "506" + assert clear_flag_bit(None, 4, 126) == "122" # not set -> Windows default, minus the hotkey bit + with pytest.raises(ValueError): clear_flag_bit("not a number", 4, 510) + +def sticky_tweak(reg): + vals = [RegValue("Acc\\Sticky", "Flags", SZ), RegValue("Acc\\Filter", "Flags", SZ)] + defaults = {vals[0].key: 510, vals[1].key: 126} + return registry_tweak("s", "Sticky", "w", "y", "d", vals, target_fn=flags_without_bit(vals, defaults, 4), io=reg.io) + +def test_sticky_flags_keep_user_settings_and_undo_exactly(tmp_path): + reg = FakeReg({("Acc\\Sticky", "Flags"): "511"}); t = sticky_tweak(reg); st = BackupStore(str(tmp_path)) + assert is_applied(t) is False + assert apply(t, st).ok and reg.data == {("Acc\\Sticky", "Flags"): "507", ("Acc\\Filter", "Flags"): "122"} + assert is_applied(t) is True and apply(t, st).message.startswith("Already") + assert undo(t, st).ok and reg.data == {("Acc\\Sticky", "Flags"): "511"} + +def test_unparseable_flags_are_left_alone(tmp_path): + reg = FakeReg({("Acc\\Sticky", "Flags"): "weird"}); r = apply(sticky_tweak(reg), BackupStore(str(tmp_path))) + assert not r.ok and "Nothing changed" in r.message and reg.writes == [] + +# ---- engine helpers +def simple(state, tid="t", target=1): + return Tweak(tid, tid.upper(), "", "", "", False, True, lambda: state.get(tid), lambda v: state.__setitem__(tid, v), target) + +def test_callable_target_is_resolved_from_current_value(tmp_path): + s = {"t": 10}; t = simple(s, target=lambda cur: cur + 5) + assert apply(t, BackupStore(str(tmp_path))).ok and s["t"] == 15 + +def test_is_applied_states(): + s = {}; t = simple(s); assert is_applied(t) is False + s["t"] = 1; assert is_applied(t) is True + t.supported = lambda: False; assert is_applied(t) is None + t2 = simple(s); t2.read = lambda: (_ for _ in ()).throw(OSError("x")); assert is_applied(t2) is None + +def test_undo_all_restores_every_pending_tweak(tmp_path): + s = {"a": 0, "b": None}; ta, tb, tc = simple(s, "a"), simple(s, "b"), simple(s, "c"); st = BackupStore(str(tmp_path)) + apply(ta, st); apply(tb, st) + res = undo_all([ta, tb, tc], st) # tc was never applied, so it is not listed + assert [(n, r.ok) for n, r in res] == [("A", True), ("B", True)] and s == {"a": 0, "b": None} and st.pending() == [] + +def test_undo_all_goes_back_to_the_oldest_original_after_repeat_applies(tmp_path): + s = {"a": 0}; t = simple(s, "a"); st = BackupStore(str(tmp_path)) + apply(t, st); s["a"] = 5 # something else changed it, then it is applied again + apply(t, st); assert s["a"] == 1 and len(st.pending()) == 2 + res = undo_all([t], st); assert res[0][1].ok and s["a"] == 0 and st.pending() == [] + +def test_undo_all_with_unreadable_backups(tmp_path): + (tmp_path / "backups.json").write_text("garbage"); res = undo_all([simple({})], BackupStore(str(tmp_path))) + assert len(res) == 1 and not res[0][1].ok and "unreadable" in res[0][1].message + +def test_format_value(): + assert format_value(None) == "not set" and format_value(1) == "1" and format_value("x") == "'x'" + assert format_value({"Control Panel\\Mouse|MouseSpeed": "1", "K\\Game|Dvr": None}) == "Mouse\\MouseSpeed='1', Game\\Dvr=not set" + +# ---- the real catalog +from src.tweaks.catalog import catalog, CATEGORIES, HOTKEY_BIT +from src.profiles.store import KNOWN, PRESETS, validate_profile + +def test_catalog_entries_are_complete_and_safe(): + ts = catalog(); ids = [t.id for t in ts] + assert len(ids) == len(set(ids)) and len(ts) >= 9 + for t in ts: + assert all(isinstance(x, str) and x.strip() for x in (t.name, t.what, t.why, t.drawbacks)), t.id + assert t.category in CATEGORIES and t.reversible and not t.needs_admin, t.id + assert "fps" not in t.why.lower() and "guarantee" not in (t.why + t.drawbacks).lower(), t.id # no promised gains + +def test_building_the_catalog_never_touches_the_system(): + ts = catalog(); assert all(callable(t.read) and callable(t.write) for t in ts) # only closures are built + if sys.platform != "win32": assert not any(t.supported() for t in ts) + +def test_catalog_only_touches_the_current_user_hive(): + root = os.path.dirname(os.path.dirname(__file__)) + for f in ("src/tweaks/catalog.py", "src/tweaks/regtweaks.py"): + t = open(os.path.join(root, f), encoding="utf-8").read(); assert "HKEY_LOCAL_MACHINE" not in t and "HKLM" not in t, f + +def test_profile_tweaks_exist_and_names_match_the_catalog(): + by_id = {t.id: t for t in catalog()} + assert set(KNOWN) <= set(by_id) and all(KNOWN[i] == by_id[i].name for i in KNOWN) + for name, p in PRESETS.items(): + d = validate_profile({"name": name, "tweaks": p["tweaks"], "notes": p["notes"]}); assert d["tweaks"] == p["tweaks"], name + +def test_original_presets_unchanged_and_competitive_added(): + assert list(PRESETS)[:3] == ["Balanced", "Gaming", "Low Background Activity"] and "Competitive" in PRESETS + assert PRESETS["Gaming"]["tweaks"] == ["game_mode", "power_high"] + +def test_sticky_catalog_tweak_uses_windows_defaults_when_values_are_missing(): + import src.tweaks.catalog as c + t = next(x for x in catalog() if x.id == "sticky_keys_prompts_off"); keys = [v.key for v in c._STICKY] + assert HOTKEY_BIT == 4 + assert t.target({k: None for k in keys}) == dict(zip(keys, ["506", "122", "58"])) # defaults 510 / 126 / 62 minus the hotkey bit + assert t.target(dict(zip(keys, ["511", "126", "62"]))) == dict(zip(keys, ["507", "122", "58"])) # other flags kept