diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d601275..e46d6ef 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -144,64 +144,8 @@ jobs: $ErrorActionPreference = "Stop" $version = "${{ steps.version.outputs.tag }}" New-Item -ItemType Directory -Force -Path "artifacts/release/packages" | Out-Null - New-Item -ItemType Directory -Force -Path "artifacts/release/package-staging" | Out-Null - $sharedUninstall = "artifacts/release/package-staging/uninstall.bat" - $sharedLicense = "artifacts/release/package-staging/LICENSE.md" - - $uninstallContent = @' - @echo off - setlocal EnableExtensions - title ThreadPilot Uninstaller - - set "APP_DIR=%~dp0" - if "%APP_DIR:~-1%"=="\" set "APP_DIR=%APP_DIR:~0,-1%" - - echo ====================================================== - echo ThreadPilot Uninstaller - echo ====================================================== - echo. - - echo [1/4] Closing running ThreadPilot processes... - taskkill /IM "ThreadPilot.exe" /F >nul 2>&1 - - echo [2/4] Removing startup task and startup registry entry... - schtasks /Delete /TN "ThreadPilot_Launch" /F >nul 2>&1 - schtasks /Delete /TN "ThreadPilot_Startup" /F >nul 2>&1 - reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "ThreadPilot" /f >nul 2>&1 - - echo [3/4] Removing ThreadPilot user data for this Windows account... - rem Full uninstall removes only ThreadPilot-owned per-user AppData. Normal install/update paths never run this script. - if exist "%APPDATA%\ThreadPilot" ( - rd /s /q "%APPDATA%\ThreadPilot" - echo ThreadPilot user data removed. - ) else ( - echo No ThreadPilot user data folder found. - ) - - echo [4/4] Scheduling app folder removal... - start "" /min cmd /c "timeout /t 5 /nobreak >nul & rd /s /q \"%APP_DIR%\"" - - echo. - echo Uninstall completed. Remaining files will be removed in a few seconds. - endlocal - exit /b 0 - '@ - - Set-Content -LiteralPath $sharedUninstall -Value $uninstallContent -Encoding Ascii - Copy-Item "LICENSE" -Destination $sharedLicense -Force - - $portableStage = "artifacts/release/package-staging/portable" - New-Item -ItemType Directory -Force -Path $portableStage | Out-Null - - Copy-Item "artifacts/release/singlefile/*" -Destination $portableStage -Recurse -Force - - Copy-Item $sharedUninstall -Destination (Join-Path $portableStage "uninstall.bat") -Force - Copy-Item $sharedLicense -Destination (Join-Path $portableStage "LICENSE.md") -Force - - $portableZip = "artifacts/release/packages/ThreadPilot_$version`_Portable.zip" - - Compress-Archive -Path "$portableStage/*" -DestinationPath $portableZip -Force + ./build/package-release-zips.ps1 -Version $version -PublishDirectory artifacts/release/singlefile -OutputDirectory artifacts/release/packages - name: Generate checksums shell: pwsh diff --git a/App.xaml.cs b/App.xaml.cs index 6ee9fe2..9603d70 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -24,6 +24,9 @@ public partial class App : System.Windows.Application private const string LaunchedViaTaskArgument = "--launched-via-task"; private Mutex? singleInstanceMutex; + private EventWaitHandle? uninstallShutdownSignal; + private string[]? storeCleanupArguments; + private bool serviceProviderDisposed; private int uiExceptionDialogOpen; private DateTime lastUiExceptionDialogUtc = DateTime.MinValue; @@ -39,13 +42,43 @@ public App() this.ServiceProvider = services.BuildServiceProvider(); // Validate service configuration - ServiceConfiguration.ValidateServiceConfiguration(this.ServiceProvider); + if (!Environment.GetCommandLineArgs().Contains(UninstallCleanup.Argument)) + { + ServiceConfiguration.ValidateServiceConfiguration(this.ServiceProvider); + } } + internal void ScheduleStoreCleanup(bool purge, bool restore) + { + var args = new List { UninstallCleanup.Argument }; + if (!purge) + { + args.Add("--keep-data"); + } + + if (!restore) + { + args.Add("--keep-windows-changes"); + } + + this.storeCleanupArguments = args.ToArray(); + } + protected override void OnStartup(StartupEventArgs e) { + if (e.Args.Contains(UninstallCleanup.Argument)) + { + this.ShutdownMode = ShutdownMode.OnExplicitShutdown; + var result = UninstallCleanup.Run( + e.Args, + () => this.ServiceProvider.GetRequiredService().RecoverForUninstallAsync(), + this.DisposeServiceProvider); + this.Shutdown(result); + return; + } + // Parse command line arguments early so special startup modes can short-circuit normal flow. var startupMode = StartupMode.Parse(e.Args); bool effectiveStartMinimized = false; @@ -223,6 +256,19 @@ protected override void OnStartup(StartupEventArgs e) var mainWindow = this.ServiceProvider.GetRequiredService(); this.MainWindow = mainWindow; + try + { + this.uninstallShutdownSignal = UninstallCleanup.RegisterShutdown(() => + { + this.Dispatcher.BeginInvoke(new Action(() => + TaskSafety.FireAndForget(mainWindow.ShutdownForUninstallAsync(), _ => { }))); + }); + } + catch (Exception ex) when (ex is UnauthorizedAccessException or System.IO.IOException) + { + logger.LogWarning(ex, "Could not register graceful close for uninstall"); + } + // Handle startup behavior with comprehensive error handling try @@ -371,7 +417,12 @@ protected override void OnExit(ExitEventArgs e) this.DispatcherUnhandledException -= this.OnDispatcherUnhandledException; TaskScheduler.UnobservedTaskException -= this.OnUnobservedTaskException; + this.uninstallShutdownSignal?.Dispose(); this.DisposeServiceProvider(); + if (this.storeCleanupArguments != null) + { + UninstallCleanup.Run(this.storeCleanupArguments, fromStoreWindow: true); + } if (this.singleInstanceMutex != null) { @@ -392,12 +443,13 @@ protected override void OnExit(ExitEventArgs e) private void DisposeServiceProvider() { - if (this.ServiceProvider is not IDisposable disposableProvider) + if (this.serviceProviderDisposed || this.ServiceProvider is not IDisposable disposableProvider) { return; } var logger = this.ServiceProvider.GetService>(); + this.serviceProviderDisposed = true; try { disposableProvider.Dispose(); diff --git a/Helpers/DwmHelper.cs b/Helpers/DwmHelper.cs index acc7480..f297004 100644 --- a/Helpers/DwmHelper.cs +++ b/Helpers/DwmHelper.cs @@ -13,6 +13,13 @@ public static class DwmHelper [DllImport("dwmapi.dll")] private static extern int DwmSetWindowAttribute(IntPtr hwnd, int dwAttribute, ref int pvAttribute, int cbAttribute); + internal static void RoundPopupCorners(IntPtr handle) + { + const int windowCornerPreference = 33; + var roundSmall = 3; + _ = DwmSetWindowAttribute(handle, windowCornerPreference, ref roundSmall, sizeof(int)); + } + public static void ApplyWindowCaptionTheme(Window window, bool useDarkTheme) { ArgumentNullException.ThrowIfNull(window); diff --git a/Installer/setup.iss b/Installer/setup.iss index 6292397..e12f839 100644 --- a/Installer/setup.iss +++ b/Installer/setup.iss @@ -42,6 +42,8 @@ ArchitecturesInstallIn64BitMode=x64compatible ArchitecturesAllowed=x64compatible MinVersion=10.0.17763 UninstallDisplayIcon={app}\{#MyAppExeName} +; Replace the legacy uninstall log, which contained unconditional recursive AppData deletion. +UninstallLogMode=overwrite DisableReadyPage=yes ; Always Program Files: ThreadPilot runs elevated, and only there can a non-admin program not replace it. ; Installs in another folder move here on upgrade (see MovePreviousInstall below). @@ -69,17 +71,8 @@ Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: de [Run] Filename: "{app}\{#MyAppExeName}"; Flags: nowait; Check: IsThreadPilotUpdate -; ThreadPilot user data is preserved during install/update. Inno removes installed -; files and shortcuts automatically only when the generated uninstaller runs. -; Per-user AppData cleanup is limited to the account context used by uninstall. -[UninstallRun] -Filename: "taskkill.exe"; Parameters: "/IM ""{#MyAppExeName}"" /F"; Flags: runhidden waituntilterminated; RunOnceId: "UninstallKillThreadPilot" -Filename: "schtasks.exe"; Parameters: "/Delete /TN ""ThreadPilot_Launch"" /F"; Flags: runhidden waituntilterminated; RunOnceId: "UninstallRemoveThreadPilotLaunchTask" -Filename: "schtasks.exe"; Parameters: "/Delete /TN ""ThreadPilot_Startup"" /F"; Flags: runhidden waituntilterminated; RunOnceId: "UninstallRemoveThreadPilotStartupTask" -Filename: "reg.exe"; Parameters: "delete ""HKCU\Software\Microsoft\Windows\CurrentVersion\Run"" /v ""ThreadPilot"" /f"; Flags: runhidden waituntilterminated; RunOnceId: "UninstallRemoveThreadPilotRunEntry" - [UninstallDelete] -Type: filesandordirs; Name: "{userappdata}\ThreadPilot" +Type: dirifempty; Name: "{app}" [Code] const @@ -184,6 +177,33 @@ begin MovePreviousInstall(); end; +procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); +var + Parameters: string; + ExitCode: Integer; +begin + if CurUninstallStep <> usUninstall then + exit; + + Parameters := '--prepare-uninstall'; + if UninstallSilent then + begin + Parameters := Parameters + ' --silent'; + if ExpandConstant('{param:PURGEDATA|1}') = '0' then + Parameters := Parameters + ' --keep-data'; + if ExpandConstant('{param:RESTOREWINDOWS|1}') = '0' then + Parameters := Parameters + ' --keep-windows-changes'; + end; + + Log('ThreadPilot cleanup options: ' + Parameters); + if not Exec(ExpandConstant('{app}\{#MyAppExeName}'), Parameters, ExpandConstant('{app}'), + SW_SHOWNORMAL, ewWaitUntilTerminated, ExitCode) then + RaiseException('Could not start ThreadPilot cleanup.'); + Log(Format('ThreadPilot cleanup exit code: %d. Silent residual reports are in Windows Temp\ThreadPilot-uninstall-*.', [ExitCode])); + if (ExitCode <> 0) and (ExitCode <> 1) then + Abort; +end; + function IsThreadPilotUpdate(): Boolean; begin Result := CompareText(ExpandConstant('{param:THREADPILOTUPDATE|0}'), '1') = 0; diff --git a/Locales/de-DE.xaml b/Locales/de-DE.xaml index 95b1734..65da21f 100644 --- a/Locales/de-DE.xaml +++ b/Locales/de-DE.xaml @@ -302,6 +302,28 @@ manuell, von der App selbst oder von einem anderen Tool gesetzt Aktuelle ideale Prozessoren: CPU {0} keine CPU-Sets, Windows wählt die Kerne + CPU Sets sind aktiv. Das ist nicht die Maske All Cores. + CPU-Set-Diagnose + Liest den Prozessstandard und Thread-Overrides. Der Prozess wird nicht geändert. + Wähle einen Prozess, um seine CPU Sets zu lesen. Der Lesevorgang ändert den Prozess nicht. + CPU Sets konnten nicht gelesen werden. + {0} Threads erben den Prozessstandard; {1} haben ein explizites Override; {2} Lesevorgänge verweigert; {3} Threads während des Lesens beendet; {4} unvollständige Lesevorgänge. + Die Threadliste konnte nicht gelesen werden. Die Zusammenfassung oben enthält sie nicht. + Lesen unvollständig oder verweigert. Fehlende Threads sind nicht Threads, die den Prozessstandard erben. + Das sind von Windows gelesene Zuweisungen, nicht die CPU, auf der der Thread gerade läuft. + Und {0} weitere Threads wurden nicht aufgeführt. + Prozessstandard: keiner. Threads ohne Override platziert Windows. + Prozessstandard: Lesen verweigert. + Prozessstandard: nicht lesbar. + Prozessstandard: unvollständig gelesen, {0}. + Prozessstandard: {0}. + TID {0}: Lesen verweigert. + TID {0}: Thread während des Lesens beendet. + TID {0}: nicht gelesen. + TID {0}: explizites Override, unvollständig gelesen, {1}. + TID {0}: explizites Override, {1}. + Ideale CPU {0} (nicht die CPU, auf der er läuft). + Die harte Affinität enthält diese Zuweisung nicht. Kerne anwenden Wendet die CPU-Auswahl im gewählten Modus an und überprüft den Windows-Status CPU-Zuweisung anwenden und als Regel speichern @@ -453,7 +475,9 @@ Discord öffnen Melde Fehler oder unerwartetes Verhalten über GitHub Issues. Problem melden - Über + Vor der Deinstallation bereinigen + Externe Daten entfernen und Windows wiederherstellen, bevor das Store-Paket entfernt wird. + Updates und Über ThreadPilot Copyright © 2026 PrimeBuild Lizenz: AGPLv3 Suchen Sie nach Updates @@ -590,7 +614,11 @@ Modus Automatisch Isolation - Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps), versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS) und hält das Spiel auf CPUs mit zwei gleichen CCDs auf CCD0. + Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps) und versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS). Auf dieser CPU platziert Windows das Spiel. + Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps), versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS) und hält das Spiel auf den P-Cores. + Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps), versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS) und hält das Spiel auf CPUs mit zwei gleichen CCDs auf CCD0. + Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps), versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS) und hält das Spiel auf dem CCD mit 3D V-Cache. + Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps) und versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS). Auf dieser CPU platziert Windows das Spiel. Spielpriorität auf Höher als normal setzen Experimentell: in deinen Spielen messen. Niemals Hoch oder Echtzeit. Spiele und Apps @@ -640,8 +668,9 @@ Ausgewählt: {0} Ausstehende Einstellungen auf den ausgewählten Prozess anwenden Ausstehende Einstellungen auf {0} anwenden - 🔋 Energiepläne - 📋 Profile + Energiepläne + Profile + Update verfügbar — v{0} Einstellungen Beenden Keine Profile verfügbar @@ -770,6 +799,7 @@ ThreadPilot ein- oder ausblenden Überwachungsbenachrichtigung Benachrichtigung für Höchstleistung + Infobereichsmenü öffnen Systemoptimierungen öffnen Taste für das Kürzel {0} ist nicht verfügbar. Wählen Sie eine Taste mit Modifikator und eine verfügbare Kombination. diff --git a/Locales/en-US.xaml b/Locales/en-US.xaml index 0f4daea..71a7809 100644 --- a/Locales/en-US.xaml +++ b/Locales/en-US.xaml @@ -302,6 +302,28 @@ set by hand, by the app itself or by another tool Current ideal processors: CPU {0} no CPU Sets, Windows picks the cores + CPU Sets are active. This is not the All Cores mask. + CPU Sets diagnostic + Read the process default and any thread overrides. This does not change the process. + Select a process to read its CPU Sets. The read does not change the process. + Could not read CPU Sets. + {0} threads inherit the process default; {1} have an explicit override; {2} reads were denied; {3} threads ended during the read; {4} reads were partial. + The thread list could not be read. The summary above does not include those threads. + Read is partial or denied. Missing threads are not the same as threads that inherit the process default. + These are assignments read from Windows, not the CPU a thread is running on. + And {0} more threads were not listed. + Process default: none. Threads without an override are placed by Windows. + Process default: read denied. + Process default: could not be read. + Process default: partial read, {0}. + Process default: {0}. + TID {0}: read denied. + TID {0}: thread ended during the read. + TID {0}: could not be read. + TID {0}: explicit override, partial read, {1}. + TID {0}: explicit override, {1}. + Ideal CPU {0} (not the CPU it is running on). + Hard affinity does not include this assignment. Apply cores Apply the pending CPU selection with the selected mode and verify the Windows state Apply CPU Assignment and Save as Rule @@ -453,7 +475,9 @@ Open Discord Report bugs or unexpected behavior through GitHub Issues. Report an issue - About + Clean up before uninstalling + Remove external data and restore Windows before removing the Store package. + Updates and about Copyright © 2026 PrimeBuild License: AGPLv3 Check for updates @@ -590,7 +614,11 @@ Mode Automatic Isolation - Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and, on CPUs with two equal CCDs, keeps the game on CCD0. + Isolation also moves more secondary apps (launcher helpers, media players, office apps) and puts the selected background apps in efficiency mode (EcoQoS). On this CPU Windows still places the game. + Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and keeps the game on the P-cores. + Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and, on CPUs with two equal CCDs, keeps the game on CCD0. + Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and keeps the game on the CCD with 3D V-Cache. + Isolation also moves more secondary apps (launcher helpers, media players, office apps) and puts the selected background apps in efficiency mode (EcoQoS). On this CPU Windows still places the game. Raise game priority to Above Normal Experimental: measure it on your games. Never High or Realtime. Games and apps @@ -640,8 +668,9 @@ Selected: {0} Apply Pending Settings to Selected Process Apply Pending Settings to {0} - 🔋 Power Plans - 📋 Profiles + Power Plans + Profiles + Update available — v{0} Settings Exit No profiles available @@ -770,6 +799,7 @@ Show or hide ThreadPilot Monitoring notification High Performance notification + Open tray menu Open System Tweaks Shortcut key Can't use {0}. Choose a key with a modifier and a combination that's available. diff --git a/Locales/es-ES.xaml b/Locales/es-ES.xaml index ebcb4ba..aba0e77 100644 --- a/Locales/es-ES.xaml +++ b/Locales/es-ES.xaml @@ -302,6 +302,28 @@ establecidos a mano, por la propia app o por otra herramienta Procesadores ideales actuales: CPU {0} sin CPU Sets, Windows elige los núcleos + Hay CPU Sets activos. No es la máscara All Cores. + Diagnóstico de CPU Sets + Lee el valor predeterminado del proceso y las excepciones de los hilos. No modifica el proceso. + Selecciona un proceso para leer sus CPU Sets. La lectura no modifica el proceso. + No se pudieron leer los CPU Sets. + {0} hilos heredan el valor predeterminado del proceso; {1} tienen una excepción explícita; {2} lecturas denegadas; {3} hilos terminados durante la lectura; {4} lecturas parciales. + No se pudo leer la lista de hilos. El resumen de arriba no los incluye. + Lectura parcial o denegada. Los hilos que faltan no son hilos que heredan el valor predeterminado del proceso. + Son asignaciones leídas de Windows, no la CPU en la que se está ejecutando el hilo. + Y {0} hilos más no se muestran. + Valor predeterminado del proceso: ninguno. Windows coloca los hilos sin excepción. + Valor predeterminado del proceso: lectura denegada. + Valor predeterminado del proceso: no se pudo leer. + Valor predeterminado del proceso: lectura parcial, {0}. + Valor predeterminado del proceso: {0}. + TID {0}: lectura denegada. + TID {0}: el hilo terminó durante la lectura. + TID {0}: no se pudo leer. + TID {0}: excepción explícita, lectura parcial, {1}. + TID {0}: excepción explícita, {1}. + CPU ideal {0} (no la CPU en la que se está ejecutando). + La afinidad rígida no incluye esta asignación. Aplicar núcleos Aplica la selección de CPU con el modo elegido y verifica el estado de Windows Aplicar asignación de CPU y guardar como regla @@ -453,7 +475,9 @@ Abrir Discord Informa de errores o comportamientos inesperados mediante GitHub Issues. Informar de un problema - Acerca de + Limpiar antes de desinstalar + Elimina los datos externos y restaura Windows antes de quitar el paquete de Microsoft Store. + Actualizaciones e información Copyright © 2026 PrimeBuild Licencia: AGPLv3 Buscar actualizaciones @@ -590,7 +614,11 @@ Modo Automático Aislamiento - Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina), pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS) y, en CPU con dos CCD iguales, mantiene el juego en el CCD0. + Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina) y pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS). En esta CPU Windows coloca el juego. + Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina), pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS) y mantiene el juego en los P-cores. + Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina), pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS) y, en CPU con dos CCD iguales, mantiene el juego en el CCD0. + Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina), pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS) y mantiene el juego en el CCD con 3D V-Cache. + Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina) y pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS). En esta CPU Windows coloca el juego. Subir la prioridad del juego a Por encima de lo normal Experimental: mídelo en tus juegos. Nunca Alta ni Tiempo real. Juegos y aplicaciones @@ -640,8 +668,9 @@ Seleccionado: {0} Aplicar configuraciones pendientes al proceso seleccionado Aplicar configuraciones pendientes a {0} - 🔋 Planes de energía - 📋 Perfiles + Planes de energía + Perfiles + Actualización disponible — v{0} Configuración Salir No hay perfiles disponibles @@ -770,6 +799,7 @@ Mostrar u ocultar ThreadPilot Notificación de supervisión Notificación de alto rendimiento + Abrir el menú del área de notificación Abrir ajustes del sistema Tecla del atajo No se puede usar {0}. Elige una tecla con un modificador y una combinación disponible. diff --git a/Locales/fr-FR.xaml b/Locales/fr-FR.xaml index 26695cf..1802a69 100644 --- a/Locales/fr-FR.xaml +++ b/Locales/fr-FR.xaml @@ -302,6 +302,28 @@ définis à la main, par l'application elle-même ou par un autre outil Processeurs idéaux actuels : CPU {0} aucun CPU Set, Windows choisit les cœurs + Des CPU Sets sont actifs. Ce n'est pas le masque All Cores. + Diagnostic des CPU Sets + Lit la valeur par défaut du processus et les exceptions des threads. Ne modifie pas le processus. + Sélectionnez un processus pour lire ses CPU Sets. La lecture ne modifie pas le processus. + Impossible de lire les CPU Sets. + {0} threads héritent de la valeur par défaut du processus ; {1} ont une exception explicite ; {2} lectures refusées ; {3} threads terminés pendant la lecture ; {4} lectures partielles. + La liste des threads n'a pas pu être lue. Le résumé ci-dessus ne les inclut pas. + Lecture partielle ou refusée. Les threads manquants ne sont pas des threads qui héritent de la valeur par défaut du processus. + Ce sont des affectations lues dans Windows, pas le CPU sur lequel le thread s'exécute. + Et {0} autres threads ne sont pas listés. + Valeur par défaut du processus : aucune. Windows place les threads sans exception. + Valeur par défaut du processus : lecture refusée. + Valeur par défaut du processus : illisible. + Valeur par défaut du processus : lecture partielle, {0}. + Valeur par défaut du processus : {0}. + TID {0} : lecture refusée. + TID {0} : thread terminé pendant la lecture. + TID {0} : illisible. + TID {0} : exception explicite, lecture partielle, {1}. + TID {0} : exception explicite, {1}. + CPU idéal {0} (pas le CPU sur lequel il s'exécute). + L'affinité stricte n'inclut pas cette affectation. Appliquer les cœurs Applique la sélection CPU avec le mode choisi et vérifie l’état Windows Appliquer l’affectation CPU et enregistrer la règle @@ -453,7 +475,9 @@ Ouvrir Discord Signalez les bugs ou comportements inattendus via GitHub Issues. Signaler un problème - À propos + Nettoyer avant la désinstallation + Supprimez les données externes et restaurez Windows avant de retirer le paquet du Microsoft Store. + Mises à jour et informations Copyright © 2026 PrimeBuild Licence : AGPLv3 Vérifier les mises à jour @@ -590,7 +614,11 @@ Mode Automatique Isolation - L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques), met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS) et, sur les CPU à deux CCD identiques, garde le jeu sur le CCD0. + L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques) et met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS). Sur ce CPU, Windows place le jeu. + L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques), met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS) et garde le jeu sur les P-cores. + L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques), met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS) et, sur les CPU à deux CCD identiques, garde le jeu sur le CCD0. + L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques), met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS) et garde le jeu sur le CCD avec 3D V-Cache. + L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques) et met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS). Sur ce CPU, Windows place le jeu. Passer la priorité du jeu à Supérieure à la normale Expérimental : mesurez-le sur vos jeux. Jamais Haute ni Temps réel. Jeux et applications @@ -640,8 +668,9 @@ Sélectionné : {0} Appliquer les paramètres en attente au processus sélectionné Appliquer les paramètres en attente à {0} - 🔋 Plans d'alimentation - 📋 Profils + Plans d'alimentation + Profils + Mise à jour disponible — v{0} Paramètres Quitter Aucun profil disponible @@ -770,6 +799,7 @@ Afficher ou masquer ThreadPilot Notification de surveillance Notification Performances élevées + Ouvrir le menu de la zone de notification Ouvrir les réglages système Touche du raccourci Impossible d’utiliser {0}. Choisissez une touche avec un modificateur et une combinaison disponible. diff --git a/Locales/it-IT.xaml b/Locales/it-IT.xaml index f1aedef..d59d402 100644 --- a/Locales/it-IT.xaml +++ b/Locales/it-IT.xaml @@ -302,6 +302,28 @@ impostati a mano, dall'app stessa o da un altro programma Processori ideali attuali: CPU {0} nessun CPU Set, i core li sceglie Windows + CPU Set attivi. Non è la maschera Tutti i core. + Diagnostica CPU Set + Legge il default del processo e gli override dei thread. Non modifica il processo. + Seleziona un processo per leggere i CPU Set. La lettura non modifica il processo. + Impossibile leggere i CPU Set. + {0} thread ereditano il default del processo; {1} hanno un override esplicito; {2} letture negate; {3} thread terminati durante la lettura; {4} letture parziali. + L'elenco dei thread non è stato letto. Il riepilogo sopra non li include. + Lettura parziale o negata. I thread mancanti non sono thread che ereditano il default del processo. + Sono assegnazioni lette da Windows, non la CPU su cui il thread sta girando. + E altri {0} thread non elencati. + Default del processo: nessuno. I thread senza override li posiziona Windows. + Default del processo: lettura negata. + Default del processo: non letto. + Default del processo: lettura parziale, {0}. + Default del processo: {0}. + TID {0}: lettura negata. + TID {0}: thread terminato durante la lettura. + TID {0}: non letto. + TID {0}: override esplicito, lettura parziale, {1}. + TID {0}: override esplicito, {1}. + CPU ideale {0} (non la CPU su cui sta girando). + L'affinità rigida non include questa assegnazione. Applica core Applica la selezione CPU con la modalità scelta e verifica lo stato di Windows Applica assegnazione CPU e salva come regola @@ -453,7 +475,9 @@ Apri Discord Segnala bug o comportamenti anomali tramite GitHub Issues. Segnala un problema - Informazioni + Pulisci prima di disinstallare + Rimuovi i dati esterni e ripristina Windows prima di rimuovere il pacchetto Store. + Aggiornamenti e informazioni Copyright © 2026 PrimeBuild Licenza: AGPLv3 Controlla gli aggiornamenti @@ -590,7 +614,11 @@ Modalità Automatico Isolamento - Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio), mette le app in background selezionate in modalità efficienza (EcoQoS) e, sulle CPU con due CCD uguali, tiene il gioco sul CCD0. + Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio) e mette le app in background selezionate in modalità efficienza (EcoQoS). Su questa CPU il gioco lo posiziona Windows. + Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio), mette le app in background selezionate in modalità efficienza (EcoQoS) e tiene il gioco sui P-core. + Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio), mette le app in background selezionate in modalità efficienza (EcoQoS) e, sulle CPU con due CCD uguali, tiene il gioco sul CCD0. + Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio), mette le app in background selezionate in modalità efficienza (EcoQoS) e tiene il gioco sul CCD con 3D V-Cache. + Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio) e mette le app in background selezionate in modalità efficienza (EcoQoS). Su questa CPU il gioco lo posiziona Windows. Alza la priorità del gioco a Superiore al normale Sperimentale: misuralo sui tuoi giochi. Mai Alta o Tempo reale. Giochi e app @@ -640,8 +668,9 @@ Selezionato: {0} Applica le impostazioni in sospeso al processo selezionato Applica impostazioni in sospeso a {0} - 🔋 Piani di alimentazione - 📋 Profili + Piani di alimentazione + Profili + Aggiornamento disponibile — v{0} Impostazioni Esci Nessun profilo disponibile @@ -770,6 +799,7 @@ Mostra o nascondi ThreadPilot Notifica di monitoraggio Notifica Prestazioni elevate + Apri menu dell’area di notifica Apri Ottimizzazioni di sistema Tasto della scorciatoia Impossibile usare {0}. Scegli un tasto con un modificatore e una combinazione disponibile. diff --git a/Locales/ru-RU.xaml b/Locales/ru-RU.xaml index e4a33f5..cdfea0a 100644 --- a/Locales/ru-RU.xaml +++ b/Locales/ru-RU.xaml @@ -302,6 +302,28 @@ заданы вручную, самим приложением или другой программой Текущие идеальные процессоры: ЦП {0} нет CPU Sets, ядра выбирает Windows + CPU Sets активны. Это не маска All Cores. + Диагностика CPU Sets + Читает значение процесса по умолчанию и исключения потоков. Процесс не изменяется. + Выберите процесс, чтобы прочитать его CPU Sets. Чтение не изменяет процесс. + Не удалось прочитать CPU Sets. + {0} потоков наследуют значение процесса; {1} имеют явное исключение; {2} чтений отклонено; {3} потоков завершились во время чтения; {4} чтений частичные. + Список потоков прочитать не удалось. Сводка выше их не включает. + Чтение частичное или отклонено. Отсутствующие потоки — это не потоки, наследующие значение процесса. + Это назначения, прочитанные из Windows, а не ЦП, на котором поток выполняется. + И ещё {0} потоков не показаны. + Значение процесса: нет. Потоки без исключения размещает Windows. + Значение процесса: чтение отклонено. + Значение процесса: не прочитано. + Значение процесса: частичное чтение, {0}. + Значение процесса: {0}. + TID {0}: чтение отклонено. + TID {0}: поток завершился во время чтения. + TID {0}: не прочитан. + TID {0}: явное исключение, частичное чтение, {1}. + TID {0}: явное исключение, {1}. + Идеальный ЦП {0} (не тот, на котором поток выполняется). + Жёсткая affinity не включает это назначение. Применить ядра Применяет выбор ЦП в выбранном режиме и проверяет состояние Windows. Применить назначение ЦП и сохранить правило @@ -453,7 +475,9 @@ Открыть Discord Сообщайте об ошибках и неожиданном поведении через GitHub Issues. Сообщить о проблеме - О + Очистить перед удалением + Удалите внешние данные и восстановите настройки Windows перед удалением пакета Microsoft Store. + Обновления и сведения © 2026 PrimeBuild. Лицензия: AGPLv3 Проверьте наличие обновлений @@ -590,7 +614,11 @@ Режим Автоматически Изоляция - Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения), включает для выбранных фоновых приложений режим эффективности (EcoQoS), а на ЦП с двумя одинаковыми CCD оставляет игру на CCD0. + Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения) и включает для выбранных фоновых приложений режим эффективности (EcoQoS). На этом ЦП игру размещает Windows. + Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения), включает для выбранных фоновых приложений режим эффективности (EcoQoS) и оставляет игру на P-ядрах. + Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения), включает для выбранных фоновых приложений режим эффективности (EcoQoS), а на ЦП с двумя одинаковыми CCD оставляет игру на CCD0. + Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения), включает для выбранных фоновых приложений режим эффективности (EcoQoS) и оставляет игру на CCD с 3D V-Cache. + Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения) и включает для выбранных фоновых приложений режим эффективности (EcoQoS). На этом ЦП игру размещает Windows. Повысить приоритет игры до «Выше среднего» Экспериментально: проверьте на своих играх. Никогда «Высокий» или «Реального времени». Игры и приложения @@ -640,8 +668,9 @@ Выбрано: {0} Применить ожидающие настройки к выбранному процессу Применить ожидающие настройки к {0} - 🔋 Планы электропитания - 📋 Профили + Планы электропитания + Профили + Доступно обновление — v{0} Настройки Выход Нет доступных профилей @@ -770,6 +799,7 @@ Показать или скрыть ThreadPilot Уведомление о мониторинге Уведомление о высокой производительности + Открыть меню области уведомлений Открыть системные настройки Клавиша сочетания Не удаётся использовать {0}. Выберите клавишу с модификатором и доступное сочетание. diff --git a/Locales/zh-CN.xaml b/Locales/zh-CN.xaml index cbbbd46..29eae8d 100644 --- a/Locales/zh-CN.xaml +++ b/Locales/zh-CN.xaml @@ -302,6 +302,28 @@ 由手动、应用自身或其他工具设置 当前理想处理器:CPU {0} 无 CPU 集,由 Windows 选择核心 + CPU Sets 已生效。这不是 All Cores 掩码。 + CPU Sets 诊断 + 读取进程默认值和线程覆盖。不会修改进程。 + 选择一个进程以读取其 CPU Sets。读取不会修改进程。 + 无法读取 CPU Sets。 + {0} 个线程继承进程默认值;{1} 个有显式覆盖;{2} 次读取被拒绝;{3} 个线程在读取期间结束;{4} 次读取不完整。 + 无法读取线程列表。上面的摘要不包含这些线程。 + 读取不完整或被拒绝。缺失的线程并不是继承进程默认值的线程。 + 这些是从 Windows 读取的分配,不是线程正在运行的 CPU。 + 还有 {0} 个线程未列出。 + 进程默认值:无。没有覆盖的线程由 Windows 放置。 + 进程默认值:读取被拒绝。 + 进程默认值:未能读取。 + 进程默认值:部分读取,{0}。 + 进程默认值:{0}。 + TID {0}:读取被拒绝。 + TID {0}:线程在读取期间结束。 + TID {0}:未能读取。 + TID {0}:显式覆盖,部分读取,{1}。 + TID {0}:显式覆盖,{1}。 + 理想 CPU {0}(不是它正在运行的 CPU)。 + 硬亲和性不包含此分配。 应用核心 使用所选模式应用待处理 CPU 选择,并验证 Windows 状态 应用 CPU 分配并保存为规则 @@ -453,7 +475,9 @@ 打开 Discord 通过 GitHub Issues 报告错误或异常行为。 报告问题 - 关于应用 + 卸载前清理 + 移除 Microsoft Store 软件包之前,清除外部数据并还原 Windows 设置。 + 更新和关于 版权所有 © 2026 PrimeBuild 软件授权: AGPLv3 检查新版本 @@ -590,7 +614,11 @@ 模式 自动 隔离 - 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),让选定的后台应用进入效率模式(EcoQoS),并在两个 CCD 相同的 CPU 上让游戏保持在 CCD0。 + 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),并让选定的后台应用进入效率模式(EcoQoS)。在这颗 CPU 上,游戏由 Windows 放置。 + 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),让选定的后台应用进入效率模式(EcoQoS),并让游戏保持在 P 核上。 + 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),让选定的后台应用进入效率模式(EcoQoS),并在两个 CCD 相同的 CPU 上让游戏保持在 CCD0。 + 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),让选定的后台应用进入效率模式(EcoQoS),并让游戏保持在带 3D V-Cache 的 CCD 上。 + 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),并让选定的后台应用进入效率模式(EcoQoS)。在这颗 CPU 上,游戏由 Windows 放置。 将游戏优先级提高到“高于正常” 实验性功能:请在你的游戏中实测。绝不使用“高”或“实时”。 游戏和应用 @@ -640,8 +668,9 @@ 已选择: {0} 应用待处理设置到所选进程 应用待处理设置到 {0} - 🔋 电源计划 - 📋 配置文件 + 电源计划 + 配置文件 + 有可用更新 — v{0} 应用设置 退出程序 无可用配置文件 @@ -770,6 +799,7 @@ 显示或隐藏 ThreadPilot 进程监控通知 高性能通知 + 打开系统托盘菜单 打开系统调整 快捷键按键 无法使用 {0}。请选择包含修饰键且可用的组合。 diff --git a/MainWindow.Behaviors.partial.cs b/MainWindow.Behaviors.partial.cs index 691b24f..dacbeef 100644 --- a/MainWindow.Behaviors.partial.cs +++ b/MainWindow.Behaviors.partial.cs @@ -626,6 +626,8 @@ private async Task InitializeSystemTrayAsync() this.systemTrayService.ExitRequested += this.OnExitRequested; this.systemTrayService.MonitoringToggleRequested += this.OnMonitoringToggleRequested; this.systemTrayService.SettingsRequested += this.OnSettingsRequested; + this.systemTrayService.UpdatesRequested += this.OnUpdatesRequested; + this.serviceProvider.GetRequiredService().AvailableReleaseChanged += this.OnAvailableReleaseChanged; this.systemTrayService.PowerPlanChangeRequested += this.OnPowerPlanChangeRequested; this.systemTrayService.ProfileApplicationRequested += this.OnProfileApplicationRequested; this.systemTrayService.PerformanceDashboardRequested += this.OnPerformanceDashboardRequested; @@ -708,7 +710,9 @@ private void OnDashboardRequested(object? sender, EventArgs e) // An update must not stop at the unsaved-settings prompt: the installer is already running. internal Task ShutdownForUpdateAsync() => this.PerformGracefulShutdownAsync(validateUnsavedChanges: false); - private async Task PerformGracefulShutdownAsync(bool validateUnsavedChanges = true) + internal Task ShutdownForUninstallAsync() => this.PerformGracefulShutdownAsync(validateUnsavedChanges: false, restoreDefaultPowerPlan: false); + + private async Task PerformGracefulShutdownAsync(bool validateUnsavedChanges = true, bool restoreDefaultPowerPlan = true) { if (this.isPerformingShutdown) { @@ -778,7 +782,7 @@ private async Task PerformGracefulShutdownAsync(bool validateUnsavedChanges = tr } // 3. Restore default power plan if configured - if (this.settingsService.Settings.RestoreDefaultPowerPlanOnExit) + if (restoreDefaultPowerPlan && this.settingsService.Settings.RestoreDefaultPowerPlanOnExit) { try { @@ -936,6 +940,22 @@ await this.notificationService.ShowErrorNotificationAsync( } } + private void OnAvailableReleaseChanged(object? sender, EventArgs e) + { + this.Dispatcher.BeginInvoke(new Action(() => + { + var release = this.serviceProvider.GetRequiredService().AvailableRelease; + this.systemTrayService.SetAvailableUpdate(release?.Version.ToString()); + this.settingsViewModel.SetAvailableUpdate(release); + })); + } + + private void OnUpdatesRequested(object? sender, EventArgs e) + { + this.ShowWindowFromTray("Settings"); + this.SettingsView.ShowUpdates(); + } + private void OnSettingsRequested(object? sender, EventArgs e) { try @@ -1124,6 +1144,10 @@ private async Task HandleShortcutActionAsync(string actionName) this.ShowWindowFromTray("Tweaks"); break; + case ShortcutActions.OpenTrayMenu: + this.systemTrayService.OpenMenu(); + break; + case ShortcutActions.OpenSettings: this.ShowWindowFromTray("Settings"); break; @@ -2332,6 +2356,8 @@ private void UnsubscribeSystemTrayEvents() this.systemTrayService.ExitRequested -= this.OnExitRequested; this.systemTrayService.MonitoringToggleRequested -= this.OnMonitoringToggleRequested; this.systemTrayService.SettingsRequested -= this.OnSettingsRequested; + this.systemTrayService.UpdatesRequested -= this.OnUpdatesRequested; + this.serviceProvider.GetRequiredService().AvailableReleaseChanged -= this.OnAvailableReleaseChanged; this.systemTrayService.PowerPlanChangeRequested -= this.OnPowerPlanChangeRequested; this.systemTrayService.ProfileApplicationRequested -= this.OnProfileApplicationRequested; this.systemTrayService.PerformanceDashboardRequested -= this.OnPerformanceDashboardRequested; diff --git a/Platforms/Windows/CpuSetMapping.cs b/Platforms/Windows/CpuSetMapping.cs index 3d92ce3..f227929 100644 --- a/Platforms/Windows/CpuSetMapping.cs +++ b/Platforms/Windows/CpuSetMapping.cs @@ -24,6 +24,8 @@ private CpuSetMapping( public bool IsEmpty => this.cpuSetIdsByProcessor.Count == 0; + public IReadOnlyList CpuSetIds => this.processorsByCpuSetId.Keys.OrderBy(id => id).ToArray(); + public static CpuSetMapping Create(IReadOnlyDictionary cpuSetIdsByProcessor) { ArgumentNullException.ThrowIfNull(cpuSetIdsByProcessor); diff --git a/Platforms/Windows/ProcessCpuSetHandler.cs b/Platforms/Windows/ProcessCpuSetHandler.cs index 6cf562b..3f0bf31 100644 --- a/Platforms/Windows/ProcessCpuSetHandler.cs +++ b/Platforms/Windows/ProcessCpuSetHandler.cs @@ -27,6 +27,7 @@ public class ProcessCpuSetHandler : IProcessCpuSetHandler private SafeProcessHandle? queryLimitedInfoHandle; private SafeProcessHandle? setLimitedInfoHandle; + private readonly int queryOpenError; private bool disposed = false; public ProcessCpuSetHandler(uint processId, string executableName, ILogger? logger = null) @@ -52,11 +53,12 @@ internal ProcessCpuSetHandler( ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION, false, processId); + this.queryOpenError = 0; if (this.queryLimitedInfoHandle == null || this.queryLimitedInfoHandle.IsInvalid) { - var error = this.nativeApi.GetLastWin32Error(); - this.logger?.LogWarning("Failed to open process {ProcessId} for querying: {Error}", processId, new Win32Exception(error).Message); + this.queryOpenError = this.nativeApi.GetLastWin32Error(); + this.logger?.LogWarning("Failed to open process {ProcessId} for querying: {Error}", processId, new Win32Exception(this.queryOpenError).Message); } } @@ -66,6 +68,27 @@ internal ProcessCpuSetHandler( public bool IsValid => this.queryLimitedInfoHandle != null && !this.queryLimitedInfoHandle.IsInvalid; + internal CpuSetMapping Mapping => this.cpuSetMapping; + + internal CpuSetIdRead ReadDefaultCpuSets() + { + if (!this.IsValid) + { + return new CpuSetIdRead( + this.queryOpenError == 5 ? CpuSetReadKind.AccessDenied : CpuSetReadKind.Unavailable, + [], + this.queryOpenError); + } + + var ids = this.TryGetDefaultCpuSetIds(); + if (ids == null) + { + return new CpuSetIdRead(CpuSetReadKind.Unavailable, [], this.nativeApi.GetLastWin32Error()); + } + + return new CpuSetIdRead(ids.Count == 0 ? CpuSetReadKind.Empty : CpuSetReadKind.Read, ids, 0); + } + public IReadOnlyList? GetDefaultCpuSetLogicalProcessorIndexes() { var cpuSetIds = this.TryGetDefaultCpuSetIds(); diff --git a/Platforms/Windows/ProcessThreadCpuAssignmentHandler.cs b/Platforms/Windows/ProcessThreadCpuAssignmentHandler.cs index b727bff..1967190 100644 --- a/Platforms/Windows/ProcessThreadCpuAssignmentHandler.cs +++ b/Platforms/Windows/ProcessThreadCpuAssignmentHandler.cs @@ -68,6 +68,59 @@ public ThreadCpuAssignmentResult ApplyGroupAffinity(IReadOnlyList }); } + internal static ThreadCpuSetProbeResult ProbeSelectedCpuSets(int processId) + { + try + { + using var process = Process.GetProcessById(processId); + var probes = new List(); + foreach (ProcessThread thread in process.Threads) + { + probes.Add(ProbeThread(thread.Id)); + } + + return new ThreadCpuSetProbeResult(true, null, probes); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or Win32Exception) + { + var error = ex is Win32Exception win32 ? win32.NativeErrorCode : 0; + return new ThreadCpuSetProbeResult(false, error == 0 ? null : error, []); + } + } + + internal static ThreadCpuSetProbe ProbeThread(int threadId) + { + using var handle = NativeMethods.OpenThread(ThreadQueryLimitedInformation, false, (uint)threadId); + if (handle.IsInvalid) + { + return ThreadCpuSetProbe.OpenFailed(threadId, Marshal.GetLastWin32Error()); + } + + var affinity = ReadAffinity(handle); + var ideal = ReadIdeal(handle); + if (!NativeMethods.GetThreadSelectedCpuSets(handle, null, 0, out var required)) + { + var error = Marshal.GetLastWin32Error(); + if (error != 122 || required == 0) + { + return ThreadCpuSetProbe.QueryFailed(threadId, error, ideal, affinity); + } + } + + if (required == 0) + { + return ThreadCpuSetProbe.NoOverride(threadId, ideal, affinity); + } + + var ids = new uint[required]; + if (!NativeMethods.GetThreadSelectedCpuSets(handle, ids, required, out var filled)) + { + return ThreadCpuSetProbe.QueryFailed(threadId, Marshal.GetLastWin32Error(), ideal, affinity); + } + + return ThreadCpuSetProbe.Override(threadId, ids.Take((int)filled).ToArray(), ideal, affinity); + } + public IReadOnlyList? GetIdealProcessorIndexes() { try @@ -201,6 +254,26 @@ private ThreadCpuAssignmentResult ApplyToThreads(Func : ThreadCpuAssignmentResult.Succeeded(applied); } + private static ProcessorRef? ReadIdeal(SafeWaitHandle handle) + { + if (!NativeMethods.GetThreadIdealProcessorEx(handle, out var processor)) + { + return null; + } + + return new ProcessorRef(processor.Group, processor.Number, (processor.Group * 64) + processor.Number); + } + + private static (bool Read, ushort Group, ulong Mask) ReadAffinity(SafeWaitHandle handle) + { + if (!NativeMethods.GetThreadGroupAffinity(handle, out var affinity)) + { + return (false, 0, 0); + } + + return (true, affinity.Group, (ulong)affinity.Mask); + } + private static ProcessorNumber ToProcessorNumber(ProcessorRef processor) => new() { @@ -246,6 +319,14 @@ private static partial class NativeMethods [LibraryImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool GetThreadGroupAffinity(SafeWaitHandle thread, out GroupAffinity groupAffinity); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool GetThreadSelectedCpuSets( + SafeWaitHandle thread, + uint[]? cpuSetIds, + uint cpuSetIdCount, + out uint requiredIdCount); } } diff --git a/Platforms/Windows/ThreadCpuSetDiagnostic.cs b/Platforms/Windows/ThreadCpuSetDiagnostic.cs new file mode 100644 index 0000000..40a68ab --- /dev/null +++ b/Platforms/Windows/ThreadCpuSetDiagnostic.cs @@ -0,0 +1,232 @@ +namespace ThreadPilot.Platforms.Windows +{ + using ThreadPilot.Models; + + internal enum CpuSetReadKind + { + Read, + Empty, + AccessDenied, + Terminated, + Unavailable, + Partial, + } + + internal sealed record CpuSetIdRead(CpuSetReadKind Kind, IReadOnlyList Ids, int Win32Error); + + internal readonly record struct ThreadCpuSetProbe( + int ThreadId, + bool Opened, + int OpenError, + bool Queried, + int QueryError, + uint RequiredCount, + IReadOnlyList Ids, + ProcessorRef? IdealProcessor, + bool AffinityRead, + ushort AffinityGroup, + ulong AffinityMask) + { + public static ThreadCpuSetProbe OpenFailed(int threadId, int error) => + new(threadId, false, error, false, 0, 0, [], null, false, 0, 0); + + public static ThreadCpuSetProbe QueryFailed(int threadId, int error, ProcessorRef? ideal, (bool Read, ushort Group, ulong Mask) affinity) => + new(threadId, true, 0, false, error, 0, [], ideal, affinity.Read, affinity.Group, affinity.Mask); + + public static ThreadCpuSetProbe NoOverride(int threadId, ProcessorRef? ideal, (bool Read, ushort Group, ulong Mask) affinity) => + new(threadId, true, 0, true, 0, 0, [], ideal, affinity.Read, affinity.Group, affinity.Mask); + + public static ThreadCpuSetProbe Override(int threadId, IReadOnlyList ids, ProcessorRef? ideal, (bool Read, ushort Group, ulong Mask) affinity) => + new(threadId, true, 0, true, 0, (uint)ids.Count, ids, ideal, affinity.Read, affinity.Group, affinity.Mask); + } + + internal sealed record ThreadCpuSetProbeResult(bool ProcessEnumerated, int? ProcessError, IReadOnlyList Threads); + + internal sealed record ThreadCpuSetObservation( + int ThreadId, + CpuSetReadKind Kind, + bool HasExplicitOverride, + IReadOnlyList CpuSetIds, + IReadOnlyList Processors, + bool MappingIncomplete, + int? Win32Error, + ProcessorRef? IdealProcessor, + bool AffinityConflictsWithAssignment); + + internal sealed record ProcessCpuSetDiagnostic( + CpuSetReadKind DefaultKind, + IReadOnlyList DefaultCpuSetIds, + IReadOnlyList DefaultProcessors, + bool DefaultMappingIncomplete, + bool ThreadsEnumerated, + int? ThreadEnumerationError, + IReadOnlyList Threads) + { + public int InheritedCount => this.Threads.Count(thread => thread.Kind == CpuSetReadKind.Empty && !thread.HasExplicitOverride); + + public int OverrideCount => this.Threads.Count(thread => thread.HasExplicitOverride); + + public int DeniedCount => this.Threads.Count(thread => thread.Kind == CpuSetReadKind.AccessDenied); + + public int TerminatedCount => this.Threads.Count(thread => thread.Kind == CpuSetReadKind.Terminated); + + public int PartialCount => this.Threads.Count(thread => thread.Kind == CpuSetReadKind.Partial || thread.MappingIncomplete); + + public bool IsPartial => + this.DefaultKind is CpuSetReadKind.Partial or CpuSetReadKind.AccessDenied or CpuSetReadKind.Unavailable + || this.DefaultMappingIncomplete + || !this.ThreadsEnumerated + || this.Threads.Any(thread => thread.Kind is not CpuSetReadKind.Read and not CpuSetReadKind.Empty || thread.MappingIncomplete); + } + + internal static class ThreadCpuSetDiagnosticClassifier + { + public static ProcessCpuSetDiagnostic Combine( + CpuSetIdRead defaults, + ThreadCpuSetProbeResult probes, + CpuSetMapping mapping) + { + ArgumentNullException.ThrowIfNull(defaults); + ArgumentNullException.ThrowIfNull(probes); + ArgumentNullException.ThrowIfNull(mapping); + + var mappedDefault = Map(defaults.Ids, mapping); + var defaultKind = defaults.Kind; + if (defaultKind == CpuSetReadKind.Read && mappedDefault.Incomplete) + { + defaultKind = CpuSetReadKind.Partial; + } + + var threads = probes.Threads + .Select(probe => Classify(probe, mapping)) + .OrderBy(thread => thread.Kind == CpuSetReadKind.Empty ? 1 : 0) + .ThenBy(thread => thread.ThreadId) + .ToList(); + + return new ProcessCpuSetDiagnostic( + defaultKind, + defaults.Ids, + mappedDefault.Processors, + mappedDefault.Incomplete, + probes.ProcessEnumerated, + probes.ProcessError, + threads); + } + + public static ThreadCpuSetObservation Classify(ThreadCpuSetProbe probe, CpuSetMapping mapping) + { + ArgumentNullException.ThrowIfNull(mapping); + + if (!probe.Opened) + { + return Failed(probe.ThreadId, KindForOpenError(probe.OpenError), probe.OpenError, probe); + } + + if (!probe.Queried) + { + return Failed(probe.ThreadId, KindForQueryError(probe.QueryError), probe.QueryError, probe); + } + + if (probe.RequiredCount == 0 || probe.Ids.Count == 0) + { + return new ThreadCpuSetObservation( + probe.ThreadId, + CpuSetReadKind.Empty, + false, + [], + [], + false, + null, + probe.IdealProcessor, + false); + } + + var mapped = Map(probe.Ids, mapping); + var kind = mapped.Incomplete ? CpuSetReadKind.Partial : CpuSetReadKind.Read; + return new ThreadCpuSetObservation( + probe.ThreadId, + kind, + true, + probe.Ids, + mapped.Processors, + mapped.Incomplete, + null, + probe.IdealProcessor, + AffinityConflicts(probe, mapped.Processors)); + } + + public static (IReadOnlyList Processors, bool Incomplete) Map(IReadOnlyList ids, CpuSetMapping mapping) + { + var processors = new List(); + var incomplete = false; + foreach (var id in ids.Distinct().OrderBy(id => id)) + { + if (mapping.TryGetProcessorRef(id, out var processor)) + { + processors.Add(processor); + } + else + { + incomplete = true; + } + } + + if (ids.Count > 0 && mapping.IsEmpty) + { + incomplete = true; + } + + return (processors, incomplete); + } + + private static ThreadCpuSetObservation Failed(int threadId, CpuSetReadKind kind, int error, ThreadCpuSetProbe probe) => + new(threadId, kind, false, [], [], kind == CpuSetReadKind.Partial, error, probe.IdealProcessor, false); + + private static CpuSetReadKind KindForOpenError(int error) => error switch + { + 5 => CpuSetReadKind.AccessDenied, + 87 => CpuSetReadKind.Terminated, + _ => CpuSetReadKind.Unavailable, + }; + + private static CpuSetReadKind KindForQueryError(int error) => error switch + { + 5 => CpuSetReadKind.AccessDenied, + 87 => CpuSetReadKind.Terminated, + 122 => CpuSetReadKind.Partial, + _ => CpuSetReadKind.Unavailable, + }; + + private static bool AffinityConflicts(ThreadCpuSetProbe probe, IReadOnlyList processors) + { + if (!probe.AffinityRead || processors.Count == 0) + { + return false; + } + + // Windows reports only the primary group's mask. Outside that group the affinity is unknown. + return processors.Any(processor => + processor.Group == probe.AffinityGroup + && (processor.LogicalProcessorNumber >= 64 + || (probe.AffinityMask & (1UL << processor.LogicalProcessorNumber)) == 0)); + } + } + + internal interface ICpuSetDiagnosticSource + { + ProcessCpuSetDiagnostic Read(int processId, string name); + } + + internal sealed class ProcessCpuSetDiagnosticReader : ICpuSetDiagnosticSource + { + public static ProcessCpuSetDiagnosticReader Instance { get; } = new(); + + public ProcessCpuSetDiagnostic Read(int processId, string name) + { + using var handler = new ProcessCpuSetHandler((uint)processId, name); + var defaults = handler.ReadDefaultCpuSets(); + var probes = ProcessThreadCpuAssignmentHandler.ProbeSelectedCpuSets(processId); + return ThreadCpuSetDiagnosticClassifier.Combine(defaults, probes, handler.Mapping); + } + } +} diff --git a/README.md b/README.md index d9af69f..4075ff1 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,20 @@ Get-FileHash .\ThreadPilot_v_Setup.exe -Algorithm SHA256 Get-FileHash .\ThreadPilot_v_Portable.zip -Algorithm SHA256 ``` +**Tray keyboard shortcut**. Edit **Open tray menu** under **Settings → Global shortcuts**. New installations use **Ctrl+Shift+F11**. In an existing shortcut configuration, enable the new action and choose a combination. + +#### Uninstall + +- **Setup EXE**. Use **Settings → Apps → Installed apps → ThreadPilot → Uninstall**. The confirmation offers data removal and restoration of tracked Windows settings. Both options start selected. In-place setup keeps your data. +- **Portable ZIP**. Run `uninstall.bat` in the extracted folder. The script checks the packaged file hashes and leaves exports and changed files in place. The containing folder is kept. +- **Microsoft Store**. In ThreadPilot, open **Settings → Clean up before uninstalling**. Then uninstall ThreadPilot in Windows Settings. The Store removal handles the package. The ThreadPilot cleanup handles external data, the startup task and eligible Windows changes. + +For unattended EXE removal use the registered uninstaller with `/VERYSILENT /SUPPRESSMSGBOXES /NORESTART`. It attempts Windows recovery and removes app data by default. Set `/PURGEDATA=0` to keep app data or `/RESTOREWINDOWS=0` to keep Windows changes. Silent cleanup warnings are written to `%WINDIR%\Temp\ThreadPilot-uninstall-*\cleanup.log`. + +For unattended portable removal run `uninstall.bat -Silent` from an elevated shell. Use `-KeepData` to preserve app data and `-KeepWindowsChanges` to skip Windows recovery. Exit code 1 indicates residual files or changes. Exit code 2 means the app could not prepare for removal. + +Cleanup retains shared data when it detects another distribution. It also retains user data when the elevated Windows account differs from the interactive account. Windows changes without reliable provenance and failed restore entries appear in the last cleanup report. Existing exports in user-chosen locations remain in place. + Compare the result with `SHA256SUMS.txt` from the same release. ## 🖼️ Screenshots diff --git a/Services/GameModeService.cs b/Services/GameModeService.cs index 79a9e47..fe1c33a 100644 --- a/Services/GameModeService.cs +++ b/Services/GameModeService.cs @@ -55,14 +55,17 @@ public async Task SetGameModeAsync(bool enabled) try { - using var key = Registry.CurrentUser.CreateSubKey(this.gameBarKeyPath, writable: true); - if (key == null) + if (this.gameBarKeyPath == DefaultGameBarKeyPath) { - this.logger.LogWarning("GameBar registry key not found, cannot modify Game Mode"); - return false; + RegistryTweakHistory.Write(Registry.CurrentUser, this.gameBarKeyPath, GameModeValueName, + enabled ? 1 : 0, RegistryValueKind.DWord); + } + else + { + using var key = Registry.CurrentUser.CreateSubKey(this.gameBarKeyPath, writable: true); + key.SetValue(GameModeValueName, enabled ? 1 : 0, RegistryValueKind.DWord); } - key.SetValue(GameModeValueName, enabled ? 1 : 0, RegistryValueKind.DWord); this.logger.LogInformation("Set Windows Game Mode to {State}", enabled ? "enabled" : "disabled"); return true; } diff --git a/Services/GameSessionService.cs b/Services/GameSessionService.cs index b281e3a..3bc1ca5 100644 --- a/Services/GameSessionService.cs +++ b/Services/GameSessionService.cs @@ -198,6 +198,8 @@ public interface IGameSessionService : IDisposable /// Stops watching and restores everything Game Boost changed. Task StopAsync(); + + Task RecoverForUninstallAsync(); } /// @@ -358,6 +360,20 @@ public async Task StartAsync() } } + public async Task RecoverForUninstallAsync() + { + await this.stateLock.WaitAsync().ConfigureAwait(false); + try + { + this.startupRecovery = JournalRecoveryState.ReadPending; + await this.RecoverStartupJournalAsync(logReadFailure: true).ConfigureAwait(false); + } + finally + { + this.stateLock.Release(); + } + } + public async Task StopAsync() { lock (this.timerGate) diff --git a/Services/IKeyboardShortcutService.cs b/Services/IKeyboardShortcutService.cs index 0286ac5..87e1f6e 100644 --- a/Services/IKeyboardShortcutService.cs +++ b/Services/IKeyboardShortcutService.cs @@ -105,6 +105,7 @@ public static class ShortcutActions public const string PowerPlanPowerSaver = "PowerPlanPowerSaver"; public const string RefreshProcessList = "RefreshProcessList"; public const string OpenSettings = "OpenSettings"; + public const string OpenTrayMenu = "OpenTrayMenu"; public const string OpenTweaks = "OpenTweaks"; public const string ExitApplication = "ExitApplication"; } diff --git a/Services/ISystemTrayService.cs b/Services/ISystemTrayService.cs index 590e618..9ac6a02 100644 --- a/Services/ISystemTrayService.cs +++ b/Services/ISystemTrayService.cs @@ -16,6 +16,10 @@ public interface ISystemTrayService : IDisposable event EventHandler? SettingsRequested; + event EventHandler? UpdatesRequested; + + void SetAvailableUpdate(string? version); + event EventHandler? PowerPlanChangeRequested; event EventHandler? ProfileApplicationRequested; @@ -28,6 +32,8 @@ public interface ISystemTrayService : IDisposable void Show(); + void OpenMenu(); + void Hide(); void UpdateTooltip(string tooltip); diff --git a/Services/KeyboardShortcutService.cs b/Services/KeyboardShortcutService.cs index dc4e42c..1e3db7f 100644 --- a/Services/KeyboardShortcutService.cs +++ b/Services/KeyboardShortcutService.cs @@ -346,6 +346,13 @@ public Dictionary GetDefaultShortcuts() IsEnabled = true, IsGlobal = true, }, + [ShortcutActions.OpenTrayMenu] = new KeyboardShortcut + { + ActionName = ShortcutActions.OpenTrayMenu, + Key = Key.F11, + Modifiers = ModifierKeys.Control | ModifierKeys.Shift, + Description = "Open tray menu", + }, [ShortcutActions.OpenTweaks] = new KeyboardShortcut { ActionName = ShortcutActions.OpenTweaks, @@ -440,6 +447,7 @@ private string GetActionDescription(string actionName) ShortcutActions.PowerPlanPowerSaver => "Switch to Power Saver power plan", ShortcutActions.RefreshProcessList => "Refresh process list", ShortcutActions.OpenSettings => "Open Settings tab", + ShortcutActions.OpenTrayMenu => "Open tray menu", ShortcutActions.OpenTweaks => "Open System Tweaks tab", ShortcutActions.ExitApplication => "Exit application", _ => actionName, diff --git a/Services/PowerPlanService.cs b/Services/PowerPlanService.cs index 826ea17..26154b5 100644 --- a/Services/PowerPlanService.cs +++ b/Services/PowerPlanService.cs @@ -284,16 +284,9 @@ public async Task ImportCustomPowerPlan(string filePath) try { - var result = await this.RunPowerCfgAsync("/import", normalizedPath).ConfigureAwait(false); - - if (result.ExitCode != 0) + if (!await WindowsTweakHistory.ImportPlanAsync(normalizedPath, this.processRunner).ConfigureAwait(false)) { - this.logger.LogWarning( - "Power plan import failed for '{Path}' with exit code {ExitCode}. stderr: {StdErr}", - normalizedPath, - result.ExitCode, - result.StandardError); - + this.logger.LogWarning("Windows could not import the power plan from {Path}", normalizedPath); return false; } diff --git a/Services/ProcessService.cs b/Services/ProcessService.cs index a3fe2aa..11e96f3 100644 --- a/Services/ProcessService.cs +++ b/Services/ProcessService.cs @@ -1133,30 +1133,20 @@ public async Task SetRegistryPriorityAsync(ProcessModel process, bool enab try { var imageKeyPath = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\" + imageName; - using (var legacyKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(imageKeyPath, writable: true)) + var priorityValue = priority switch { - // Earlier versions wrote this value, which Windows never reads. - legacyKey?.DeleteValue("PriorityClass", false); - } - - using var key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(imageKeyPath + @"\PerfOptions"); - if (enable) - { - int priorityValue = priority switch - { - ProcessPriorityClass.Idle => 1, - ProcessPriorityClass.BelowNormal => 5, - ProcessPriorityClass.AboveNormal => 6, - ProcessPriorityClass.High => 3, - _ => 2, // Normal - }; - - key.SetValue("CpuPriorityClass", priorityValue, Microsoft.Win32.RegistryValueKind.DWord); - } - else - { - key.DeleteValue("CpuPriorityClass", false); - } + ProcessPriorityClass.Idle => 1, + ProcessPriorityClass.BelowNormal => 5, + ProcessPriorityClass.AboveNormal => 6, + ProcessPriorityClass.High => 3, + _ => 2, + }; + RegistryTweakHistory.Write( + Microsoft.Win32.Registry.LocalMachine, + imageKeyPath + @"\PerfOptions", + "CpuPriorityClass", + enable ? priorityValue : null, + Microsoft.Win32.RegistryValueKind.DWord); this.AuditProcessOperation("SetProcessPriority", process.Name, success: true); diff --git a/Services/RegistryTweakHistory.cs b/Services/RegistryTweakHistory.cs new file mode 100644 index 0000000..63c29b1 --- /dev/null +++ b/Services/RegistryTweakHistory.cs @@ -0,0 +1,171 @@ +namespace ThreadPilot.Services; + +using System.Globalization; +using System.Text.Json; +using Microsoft.Win32; + +internal static class RegistryTweakHistory +{ + private const string HistoryPath = @"SOFTWARE\ThreadPilot\TweakHistory"; + private static readonly object Gate = new(); + + internal static void Write(RegistryKey root, string path, string name, object? value, RegistryValueKind kind) + { + lock (Gate) + { + var written = RegistryValue.From(value, kind); + var current = Read(root, path, name); + if (current == written) + { + return; + } + + using var history = Registry.LocalMachine.CreateSubKey(HistoryPath + "\\" + CurrentUserSid); + var id = $"{root.Name}|{path}|{name}"; + var previous = ReadChange(history, id); + // A later external change becomes the baseline if the user explicitly sets the tweak again. + var ownsCurrent = previous != null && (previous.Written == current || previous.PreviousWritten == current); + var original = ownsCurrent ? previous!.Original : current; + history.SetValue(id, JsonSerializer.Serialize(new RegistryChange(root.Name, path, name, original, written, + ownsCurrent ? current : null))); + history.Flush(); + + Apply(root, path, name, written); + if (Read(root, path, name) != written) + { + throw new InvalidOperationException($"Could not verify {path}\\{name}."); + } + if (ownsCurrent) + { + history.SetValue(id, JsonSerializer.Serialize(new RegistryChange(root.Name, path, name, original, written, null))); + } + } + } + + internal static RegistryValue? GetTrackedOriginal(RegistryKey root, string path, string name) + { + lock (Gate) + { + using var history = Registry.LocalMachine.OpenSubKey(HistoryPath + "\\" + CurrentUserSid); + var change = history == null ? null : ReadChange(history, $"{root.Name}|{path}|{name}"); + return change != null && Read(root, path, name) == change.Written ? change.Original : null; + } + } + + internal static void Restore(List residuals, List failures) + { + lock (Gate) + { + var userPath = HistoryPath + "\\" + CurrentUserSid; + using (var history = Registry.LocalMachine.OpenSubKey(userPath, writable: true)) + { + if (history == null) + { + return; + } + + foreach (var id in history.GetValueNames()) + { + try + { + var change = ReadChange(history, id) ?? throw new InvalidOperationException(); + var root = change.Root switch + { + "HKEY_LOCAL_MACHINE" => Registry.LocalMachine, + "HKEY_CURRENT_USER" => Registry.CurrentUser, + _ => throw new InvalidOperationException(), + }; + var current = Read(root, change.Path, change.Name); + if (ShouldRestore(current, change.Original, change.Written) + || (current != change.Original && change.PreviousWritten == current)) + { + Apply(root, change.Path, change.Name, change.Original); + if (Read(root, change.Path, change.Name) != change.Original) + { + throw new InvalidOperationException(); + } + } + else if (current != change.Original) + { + residuals.Add($"{id}: a later change was preserved."); + } + + history.DeleteValue(id); + } + catch (Exception ex) + { + failures.Add($"{id}: restore failed ({ex.Message}). Recovery entry retained."); + } + } + + if (history.ValueCount != 0) + { + return; + } + } + + Registry.LocalMachine.DeleteSubKey(userPath, throwOnMissingSubKey: false); + using var parent = Registry.LocalMachine.OpenSubKey(HistoryPath); + if (parent is { SubKeyCount: 0, ValueCount: 0 }) + { + Registry.LocalMachine.DeleteSubKey(HistoryPath, throwOnMissingSubKey: false); + } + } + } + + internal static bool ShouldRestore(RegistryValue current, RegistryValue original, RegistryValue written) => + current != original && current == written; + + internal static string CurrentUserSid + { + get + { + using var identity = System.Security.Principal.WindowsIdentity.GetCurrent(); + return identity.User?.Value ?? throw new InvalidOperationException("Windows account SID is unavailable."); + } + } + + private static RegistryChange? ReadChange(RegistryKey history, string name) => + history.GetValue(name) is string json ? JsonSerializer.Deserialize(json) : null; + + private static RegistryValue Read(RegistryKey root, string path, string name) + { + using var key = root.OpenSubKey(path); + var value = key?.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames); + return value == null ? default : RegistryValue.From(value, key!.GetValueKind(name)); + } + + private static void Apply(RegistryKey root, string path, string name, RegistryValue value) + { + if (value.Text == null) + { + using var existing = root.OpenSubKey(path, writable: true); + existing?.DeleteValue(name, throwOnMissingValue: false); + return; + } + + using var key = root.CreateSubKey(path); + object data = value.Kind switch + { + RegistryValueKind.DWord => int.Parse(value.Text, CultureInfo.InvariantCulture), + RegistryValueKind.QWord => long.Parse(value.Text, CultureInfo.InvariantCulture), + RegistryValueKind.String or RegistryValueKind.ExpandString => value.Text, + _ => throw new InvalidOperationException("Unsupported registry value type."), + }; + key.SetValue(name, data, value.Kind); + } + + internal readonly record struct RegistryValue(string? Text, RegistryValueKind Kind) + { + internal static RegistryValue From(object? value, RegistryValueKind kind) => value switch + { + null => default, + int dword when kind == RegistryValueKind.DWord => new(dword.ToString(CultureInfo.InvariantCulture), kind), + long qword when kind == RegistryValueKind.QWord => new(qword.ToString(CultureInfo.InvariantCulture), kind), + string text when kind is RegistryValueKind.String or RegistryValueKind.ExpandString => new(text, kind), + _ => throw new InvalidOperationException("Unsupported registry value type."), + }; + } + + private sealed record RegistryChange(string Root, string Path, string Name, RegistryValue Original, RegistryValue Written, RegistryValue? PreviousWritten); +} diff --git a/Services/SystemTrayService.cs b/Services/SystemTrayService.cs index d127005..d817b0c 100644 --- a/Services/SystemTrayService.cs +++ b/Services/SystemTrayService.cs @@ -2,9 +2,12 @@ namespace ThreadPilot.Services { using System; using System.Drawing; + using System.Drawing.Drawing2D; using System.IO; + using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.Extensions.Logging; + using ThreadPilot.Helpers; using ThreadPilot.Models; using MediaSolidColorBrush = System.Windows.Media.SolidColorBrush; @@ -17,6 +20,8 @@ public class SystemTrayService : ISystemTrayService private ToolStripMenuItem? selectedProcessMenuItem; private ToolStripMenuItem? monitoringToggleMenuItem; private ToolStripMenuItem? settingsMenuItem; + private ToolStripMenuItem? updateMenuItem; + private string? updateVersion; private ToolStripMenuItem? powerPlansMenuItem; private ToolStripMenuItem? profilesMenuItem; private ToolStripMenuItem? performanceMenuItem; @@ -30,7 +35,6 @@ public class SystemTrayService : ISystemTrayService private TrayIconState currentIconState = TrayIconState.Normal; private bool isDarkTheme = true; private Font? menuFont; - private Point lastContextMenuOpenPoint = Point.Empty; private bool disposed = false; public event EventHandler? QuickApplyRequested; @@ -43,6 +47,8 @@ public class SystemTrayService : ISystemTrayService public event EventHandler? SettingsRequested; + public event EventHandler? UpdatesRequested; + public event EventHandler? PowerPlanChangeRequested; public event EventHandler? ProfileApplicationRequested; @@ -90,7 +96,7 @@ public void Initialize() // Set up event handlers this.notifyIcon.DoubleClick += this.OnTrayIconDoubleClick; - this.notifyIcon.MouseUp += this.OnTrayIconMouseUp; + this.notifyIcon.ContextMenuStrip = this.contextMenu; // Set initial icon state this.UpdateTrayIcon(TrayIconState.Normal); @@ -107,6 +113,12 @@ public void Initialize() private void CreateContextMenu() { this.contextMenu = new ContextMenuStrip(); + this.contextMenu.Opening += (_, _) => this.ApplyContextMenuTheme(); + this.contextMenu.Opened += (_, _) => DwmHelper.RoundPopupCorners(this.contextMenu.Handle); + this.updateMenuItem = new ToolStripMenuItem(); + this.updateMenuItem.Click += (_, _) => this.UpdatesRequested?.Invoke(this, EventArgs.Empty); + this.contextMenu.Items.Add(this.updateMenuItem); + this.SetAvailableUpdate(this.updateVersion); this.menuFont = CreatePreferredMenuFont(this.contextMenu.Font.Size); this.contextMenu.Font = this.menuFont; @@ -160,11 +172,13 @@ private void CreateContextMenu() this.contextMenu.Items.Add(new ToolStripSeparator()); // Power Plans submenu - this.powerPlansMenuItem = new ToolStripMenuItem(this.Localize("SystemTray_PowerPlans", "🔋 Power Plans")); + this.powerPlansMenuItem = new ToolStripMenuItem(this.Localize("SystemTray_PowerPlans", "Power Plans")); + this.powerPlansMenuItem.DropDownOpened += (_, _) => DwmHelper.RoundPopupCorners(this.powerPlansMenuItem.DropDown.Handle); this.contextMenu.Items.Add(this.powerPlansMenuItem); // Profiles submenu - this.profilesMenuItem = new ToolStripMenuItem(this.Localize("SystemTray_Profiles", "📋 Profiles")); + this.profilesMenuItem = new ToolStripMenuItem(this.Localize("SystemTray_Profiles", "Profiles")); + this.profilesMenuItem.DropDownOpened += (_, _) => DwmHelper.RoundPopupCorners(this.profilesMenuItem.DropDown.Handle); this.contextMenu.Items.Add(this.profilesMenuItem); this.contextMenu.Items.Add(new ToolStripSeparator()); @@ -185,6 +199,26 @@ private void CreateContextMenu() this.ApplyContextMenuTheme(); } + public void OpenMenu() + { + if (this.contextMenu == null) + { + return; + } + + if (this.contextMenu.Visible) + { + this.contextMenu.Close(ToolStripDropDownCloseReason.Keyboard); + return; + } + + this.contextMenu.Show(Cursor.Position); + _ = SetForegroundWindow(this.contextMenu.Handle); + this.contextMenu.Focus(); + this.contextMenu.Items.Cast() + .FirstOrDefault(item => item.Available && item.Enabled && item.CanSelect)?.Select(); + } + public void Show() { if (this.notifyIcon != null) @@ -249,28 +283,15 @@ private void OnTrayIconDoubleClick(object? sender, EventArgs e) this.ShowMainWindowRequested?.Invoke(this, EventArgs.Empty); } - private void OnTrayIconMouseUp(object? sender, MouseEventArgs e) + public void SetAvailableUpdate(string? version) { - if (e.Button != MouseButtons.Right || this.contextMenu == null) + this.updateVersion = version; + if (this.updateMenuItem != null) { - return; + this.updateMenuItem.Text = string.Format( + this.Localize("SystemTray_UpdateAvailable", "Update available — v{0}"), version); + this.updateMenuItem.Visible = version != null; } - - var cursorPosition = Cursor.Position; - var workingArea = Screen.FromPoint(cursorPosition.IsEmpty ? this.lastContextMenuOpenPoint : cursorPosition).WorkingArea; - var openPoint = SystemTrayMenuPlacement.ResolveMenuOpenPoint( - cursorPosition, - this.lastContextMenuOpenPoint, - Rectangle.Empty, - workingArea); - this.lastContextMenuOpenPoint = openPoint; - - if (this.contextMenu.Visible) - { - this.contextMenu.Close(ToolStripDropDownCloseReason.CloseCalled); - } - - this.contextMenu.Show(openPoint, ToolStripDropDownDirection.Default); } private void OnQuickApplyClick(object? sender, EventArgs e) @@ -542,7 +563,7 @@ public void Dispose() if (this.notifyIcon != null) { - this.notifyIcon.MouseUp -= this.OnTrayIconMouseUp; + this.notifyIcon.ContextMenuStrip = null; this.notifyIcon.Visible = false; this.notifyIcon.Dispose(); this.notifyIcon = null; @@ -601,6 +622,7 @@ private void OnLanguageChanged(object? sender, string language) private void UpdateLocalizedMenuText() { + this.SetAvailableUpdate(this.updateVersion); if (this.notifyIcon != null) { this.notifyIcon.Text = this.Localize("MainWindow_Title", "ThreadPilot - Process & Power Plan Manager"); @@ -623,12 +645,12 @@ private void UpdateLocalizedMenuText() if (this.powerPlansMenuItem != null) { - this.powerPlansMenuItem.Text = this.Localize("SystemTray_PowerPlans", "🔋 Power Plans"); + this.powerPlansMenuItem.Text = this.Localize("SystemTray_PowerPlans", "Power Plans"); } if (this.profilesMenuItem != null) { - this.profilesMenuItem.Text = this.Localize("SystemTray_Profiles", "📋 Profiles"); + this.profilesMenuItem.Text = this.Localize("SystemTray_Profiles", "Profiles"); } if (this.settingsMenuItem != null) @@ -734,7 +756,15 @@ private void ApplyContextMenuTheme() Color borderColor; Color disabledColor; - if (this.isDarkTheme) + if (SystemInformation.HighContrast) + { + backgroundColor = SystemColors.Menu; + foregroundColor = SystemColors.MenuText; + selectionColor = SystemColors.Highlight; + borderColor = SystemColors.MenuText; + disabledColor = SystemColors.GrayText; + } + else if (this.isDarkTheme) { // Force stable dark palette for WinForms tray menu even if XAML resources are unavailable. backgroundColor = Color.FromArgb(28, 28, 30); @@ -747,20 +777,26 @@ private void ApplyContextMenuTheme() { backgroundColor = ResolveColorFromResource("SurfaceAltBrush", SystemColors.Menu); foregroundColor = ResolveColorFromResource("TextPrimaryBrush", SystemColors.MenuText); - selectionColor = ResolveColorFromResource("SoftSelectionBackgroundBrush", SystemColors.Highlight); + selectionColor = ResolveColorFromResource("SoftSelectionBackgroundBrush", Color.FromArgb(224, 233, 243)); borderColor = ResolveColorFromResource("BorderBrush", SystemColors.ControlDark); disabledColor = ResolveColorFromResource("TextDisabledBrush", SystemColors.GrayText); } - this.contextMenu.RenderMode = ToolStripRenderMode.Professional; - this.contextMenu.Renderer = new ToolStripProfessionalRenderer(new TrayMenuColorTable(backgroundColor, selectionColor, borderColor)); + ToolStripRenderer renderer = SystemInformation.HighContrast + ? new HighContrastTrayMenuRenderer() + : new TrayMenuRenderer(new TrayMenuColorTable(backgroundColor, selectionColor, borderColor)); + this.contextMenu.Renderer = renderer; this.contextMenu.BackColor = backgroundColor; this.contextMenu.ForeColor = foregroundColor; - ApplyMenuItemTheme(this.contextMenu.Items, backgroundColor, foregroundColor, disabledColor); + ApplyMenuItemTheme(this.contextMenu.Items, renderer, backgroundColor, foregroundColor, disabledColor); + if (!SystemInformation.HighContrast && this.updateMenuItem != null) + { + this.updateMenuItem.ForeColor = this.isDarkTheme ? Color.FromArgb(167, 206, 255) : Color.FromArgb(0, 75, 141); + } } - private static void ApplyMenuItemTheme(ToolStripItemCollection items, Color backColor, Color foreColor, Color disabledColor) + private static void ApplyMenuItemTheme(ToolStripItemCollection items, ToolStripRenderer renderer, Color backColor, Color foreColor, Color disabledColor) { foreach (ToolStripItem item in items) { @@ -769,22 +805,84 @@ private static void ApplyMenuItemTheme(ToolStripItemCollection items, Color back continue; } + var dpi = item.Owner?.DeviceDpi ?? 96; + item.Padding = new Padding(10 * dpi / 96, 5 * dpi / 96, 10 * dpi / 96, 5 * dpi / 96); item.BackColor = backColor; item.ForeColor = item.Enabled ? foreColor : disabledColor; if (item is ToolStripMenuItem menuItem) { + menuItem.DropDown.Renderer = renderer; menuItem.DropDown.BackColor = backColor; menuItem.DropDown.ForeColor = foreColor; if (menuItem.DropDownItems.Count > 0) { - ApplyMenuItemTheme(menuItem.DropDownItems, backColor, foreColor, disabledColor); + ApplyMenuItemTheme(menuItem.DropDownItems, renderer, backColor, foreColor, disabledColor); } } } } + private sealed class HighContrastTrayMenuRenderer : ToolStripSystemRenderer + { + protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) + { + if (e.Item.Selected && e.Item.Enabled) + { + e.TextColor = SystemColors.HighlightText; + } + + base.OnRenderItemText(e); + } + } + + private sealed class TrayMenuRenderer(TrayMenuColorTable colors) : ToolStripProfessionalRenderer(colors) + { + protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e) + { + e.ArrowColor = e.Item?.ForeColor ?? SystemColors.MenuText; + base.OnRenderArrow(e); + } + + protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) + { + using var pen = new Pen(colors.MenuBorder); + var inset = 10 * (e.ToolStrip?.DeviceDpi ?? 96) / 96; + var y = e.Item.Height / 2; + e.Graphics.DrawLine(pen, inset, y, e.Item.Width - inset, y); + } + + protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) + { + if (!e.Item.Selected && !e.Item.Pressed) + { + return; + } + + var dpi = e.Item.Owner?.DeviceDpi ?? 96; + var bounds = new Rectangle(Point.Empty, e.Item.Size); + bounds.Inflate(-4 * dpi / 96, -2 * dpi / 96); + var radius = 8 * dpi / 96; + if (bounds.Width <= radius || bounds.Height <= radius) + { + return; + } + + using var path = new GraphicsPath(); + path.AddArc(bounds.Left, bounds.Top, radius, radius, 180, 90); + path.AddArc(bounds.Right - radius, bounds.Top, radius, radius, 270, 90); + path.AddArc(bounds.Right - radius, bounds.Bottom - radius, radius, radius, 0, 90); + path.AddArc(bounds.Left, bounds.Bottom - radius, radius, radius, 90, 90); + path.CloseFigure(); + using var brush = new SolidBrush(colors.MenuItemSelected); + var smoothing = e.Graphics.SmoothingMode; + e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; + e.Graphics.FillPath(brush, path); + e.Graphics.SmoothingMode = smoothing; + } + } + private sealed class TrayMenuColorTable : ProfessionalColorTable { private readonly Color backgroundColor; @@ -817,6 +915,10 @@ public TrayMenuColorTable(Color backgroundColor, Color selectionColor, Color bor public override Color MenuItemBorder => this.borderColor; } + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetForegroundWindow(IntPtr window); + private static Font CreatePreferredMenuFont(float baseSize) { var size = Math.Max(8.5f, baseSize); diff --git a/Services/SystemTweaksService.cs b/Services/SystemTweaksService.cs index 45bbdc0..79c3d98 100644 --- a/Services/SystemTweaksService.cs +++ b/Services/SystemTweaksService.cs @@ -20,7 +20,6 @@ namespace ThreadPilot.Services public class SystemTweaksService : ISystemTweaksService { private static readonly string ScExecutablePath = Path.Combine(Environment.SystemDirectory, "sc.exe"); - private static readonly Regex ServiceNameRegex = new("^[A-Za-z0-9_.-]+$", RegexOptions.Compiled); private static readonly TimeSpan ExternalCommandTimeout = TimeSpan.FromSeconds(20); private static readonly Guid ProcessorSettingsSubgroupGuid = new("54533251-82be-4824-96c1-47b60b740d00"); private static readonly Guid CoreParkingSettingGuid = new("0cc5b647-c1df-4637-891a-dec35c318583"); @@ -137,24 +136,12 @@ public async Task SetPointerPrecisionAsync(bool enabled) } values = GetPointerPrecisionValues(enabled, values); - var notified = NativeMethods.SystemParametersInfo( - NativeMethods.SpiSetMouse, - 0, - values, - NativeMethods.SpifUpdateIniFile | NativeMethods.SpifSendChange); - if (!notified) - { - this.logger.LogWarning( - "Windows did not apply pointer precision immediately: {Error}", - new Win32Exception(Marshal.GetLastWin32Error()).Message); - } - try { - using var key = Registry.CurrentUser.CreateSubKey(@"Control Panel\Mouse", writable: true); - key.SetValue("MouseThreshold1", values[0].ToString(CultureInfo.InvariantCulture), RegistryValueKind.String); - key.SetValue("MouseThreshold2", values[1].ToString(CultureInfo.InvariantCulture), RegistryValueKind.String); - key.SetValue("MouseSpeed", values[2].ToString(CultureInfo.InvariantCulture), RegistryValueKind.String); + const string path = @"Control Panel\Mouse"; + RegistryTweakHistory.Write(Registry.CurrentUser, path, "MouseThreshold1", values[0].ToString(CultureInfo.InvariantCulture), RegistryValueKind.String); + RegistryTweakHistory.Write(Registry.CurrentUser, path, "MouseThreshold2", values[1].ToString(CultureInfo.InvariantCulture), RegistryValueKind.String); + RegistryTweakHistory.Write(Registry.CurrentUser, path, "MouseSpeed", values[2].ToString(CultureInfo.InvariantCulture), RegistryValueKind.String); } catch (Exception ex) { @@ -162,6 +149,12 @@ public async Task SetPointerPrecisionAsync(bool enabled) return false; } + if (!NativeMethods.SystemParametersInfo(NativeMethods.SpiSetMouse, 0, values, NativeMethods.SpifSendChange)) + { + this.logger.LogWarning("Windows did not apply pointer precision immediately: {Error}", new Win32Exception(Marshal.GetLastWin32Error()).Message); + return false; + } + var status = await this.GetPointerPrecisionStatusAsync(); this.RaiseStatusChanged(nameof(SystemTweak.PointerPrecision), status); return status.IsAvailable && status.IsEnabled == enabled; @@ -420,26 +413,7 @@ public async Task SetSysMainAsync(bool enabled) return false; } - using var serviceController = new ServiceController("SysMain"); - if (!await this.SetServiceStartModeAsync("SysMain", enabled ? ServiceStartMode.Automatic : ServiceStartMode.Disabled)) - { - this.logger.LogError("Failed to set SysMain startup mode"); - return false; - } - - serviceController.Refresh(); - - if (enabled && serviceController.Status == ServiceControllerStatus.Stopped) - { - serviceController.Start(); - serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30)); - } - else if (!enabled && (serviceController.Status == ServiceControllerStatus.Running || serviceController.Status == ServiceControllerStatus.Paused)) - { - serviceController.Stop(); - serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30)); - } - + await WindowsTweakHistory.SetSysMainAsync(enabled); var status = await this.GetSysMainStatusAsync(); this.TweakStatusChanged?.Invoke(this, new TweakStatusChangedEventArgs("SysMain", status)); @@ -501,7 +475,7 @@ public async Task SetPrefetchAsync(bool enabled) } // Set EnablePrefetcher: 0 = disabled, 3 = enabled for both applications and boot - key.SetValue("EnablePrefetcher", enabled ? 3 : 0, RegistryValueKind.DWord); + RegistryTweakHistory.Write(Registry.LocalMachine, @"SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PrefetchParameters", "EnablePrefetcher", enabled ? 3 : 0, RegistryValueKind.DWord); var status = await this.GetPrefetchStatusAsync(); this.TweakStatusChanged?.Invoke(this, new TweakStatusChangedEventArgs("Prefetch", status)); @@ -569,7 +543,7 @@ public async Task SetPowerThrottlingAsync(bool enabled) } // Set PowerThrottlingOff: 1 = throttling disabled, 0 = throttling enabled - key.SetValue("PowerThrottlingOff", enabled ? 1 : 0, RegistryValueKind.DWord); + RegistryTweakHistory.Write(Registry.LocalMachine, @"SYSTEM\CurrentControlSet\Control\Power\PowerThrottling", "PowerThrottlingOff", enabled ? 1 : 0, RegistryValueKind.DWord); var status = await this.GetPowerThrottlingStatusAsync(); this.TweakStatusChanged?.Invoke(this, new TweakStatusChangedEventArgs("PowerThrottling", status)); @@ -631,7 +605,7 @@ public async Task SetHighSchedulingCategoryAsync(bool enabled) return false; } - key.SetValue(SchedulingCategoryValueName, GetHighSchedulingCategoryRegistryValue(enabled), RegistryValueKind.String); + RegistryTweakHistory.Write(Registry.LocalMachine, GamesSchedulingKeyPath, SchedulingCategoryValueName, GetHighSchedulingCategoryRegistryValue(enabled), RegistryValueKind.String); var status = await this.GetHighSchedulingCategoryStatusAsync(); this.TweakStatusChanged?.Invoke(this, new TweakStatusChangedEventArgs("HighSchedulingCategory", status)); @@ -647,34 +621,6 @@ public async Task SetHighSchedulingCategoryAsync(bool enabled) } } - private async Task SetServiceStartModeAsync(string serviceName, ServiceStartMode mode) - { - if (!ServiceNameRegex.IsMatch(serviceName)) - { - this.logger.LogWarning("Rejected invalid service name format: {ServiceName}", serviceName); - return false; - } - - var startModeValue = mode switch - { - ServiceStartMode.Automatic => "auto", - ServiceStartMode.Manual => "demand", - ServiceStartMode.Disabled => "disabled", - _ => "demand", - }; - - var result = await RunProcessAsync(ScExecutablePath, $"config \"{serviceName}\" start= {startModeValue}"); - if (result.ExitCode != 0) - { - this.logger.LogWarning( - "Failed to update service start mode for {ServiceName}. ExitCode={ExitCode}, Error={Error}", - serviceName, result.ExitCode, result.StandardError); - return false; - } - - return true; - } - internal static string GetHighSchedulingCategoryRegistryValue(bool enabled) => enabled ? HighSchedulingCategoryEnabledValue : HighSchedulingCategoryDisabledValue; @@ -814,24 +760,8 @@ private async Task SetRegistryTargetsAsync( } var backups = this.LoadRegistryBackups(); - var changedBackups = false; try { - foreach (var target in targets) - { - var backupKey = target.BackupKey; - if (!backups.ContainsKey(backupKey)) - { - backups[backupKey] = new RegistryValueBackup(target.Value, target.Kind); - changedBackups = true; - } - } - - if (changedBackups) - { - await SaveRegistryBackupsAsync(backups); - } - await WriteDriverRegistryTargetsAsync( targets, target => @@ -841,11 +771,19 @@ await WriteDriverRegistryTargetsAsync( return enabledValue; } - // A user-writable backup may restore only values this tweak itself writes. - return restoreOriginalWhenDisabled && backups.TryGetValue(target.BackupKey, out var backup) - && (backup.Value == enabledValue || backup.Value == disabledValue) - ? backup.Value - : disabledValue; + if (restoreOriginalWhenDisabled) + { + var original = RegistryTweakHistory.GetTrackedOriginal(Registry.LocalMachine, target.Path, target.ValueName); + var originalValue = int.TryParse(original?.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var initialValue) + ? initialValue + : backups.GetValueOrDefault(target.BackupKey)?.Value; + if (originalValue == enabledValue || originalValue == disabledValue) + { + return originalValue.Value; + } + } + + return disabledValue; }, WriteDriverRegistryValue, async () => @@ -918,9 +856,13 @@ private static void WriteDriverRegistryValue(RegistryTarget target, int value) { using var key = Registry.LocalMachine.OpenSubKey(target.Path, writable: true) ?? throw new IOException($"Device registry key '{target.Path}' is no longer available."); - key.SetValue(target.ValueName, target.Kind == RegistryValueKind.String - ? value.ToString(CultureInfo.InvariantCulture) - : value, target.Kind); + object written = target.Kind switch + { + RegistryValueKind.String => value.ToString(CultureInfo.InvariantCulture), + RegistryValueKind.QWord => (long)value, + _ => value, + }; + RegistryTweakHistory.Write(Registry.LocalMachine, target.Path, target.ValueName, written, target.Kind); } private Dictionary LoadRegistryBackups() @@ -945,14 +887,6 @@ private Dictionary LoadRegistryBackups() } } - private static async Task SaveRegistryBackupsAsync(Dictionary backups) - { - StoragePaths.EnsureAppDataDirectories(); - await AtomicFileWriter.WriteAllTextAsync( - StoragePaths.DeviceTweakBackupsFilePath, - JsonSerializer.Serialize(backups, new JsonSerializerOptions { WriteIndented = true })); - } - private static bool TryReadAcPowerSetting(Guid settingGuid, out uint value, out string? error) => TryReadAcPowerSetting(ProcessorSettingsSubgroupGuid, settingGuid, out value, out error); @@ -968,6 +902,11 @@ private static bool TryReadAcPowerSetting( return false; } + return TryReadAcPowerSetting(schemeGuid, subgroupGuid, settingGuid, out value, out error); + } + + private static bool TryReadAcPowerSetting(Guid schemeGuid, Guid subgroupGuid, Guid settingGuid, out uint value, out string? error) + { var result = NativeMethods.PowerReadAcValueIndex( IntPtr.Zero, ref schemeGuid, @@ -998,6 +937,29 @@ private static bool TryWriteAcPowerSetting( return false; } + if (!TryReadAcPowerSetting(schemeGuid, subgroupGuid, settingGuid, out var current, out error)) + { + return false; + } + + if (current == value) + { + return true; + } + + WindowsTweakHistory.RecordPowerSetting(schemeGuid, subgroupGuid, settingGuid, current, value); + if (!TryWriteAcPowerSetting(schemeGuid, subgroupGuid, settingGuid, value, activate: true, out error) + || !TryReadAcPowerSetting(schemeGuid, subgroupGuid, settingGuid, out current, out error) || current != value) + { + return false; + } + + WindowsTweakHistory.ConfirmPowerSetting(schemeGuid, subgroupGuid, settingGuid, value); + return true; + } + + private static bool TryWriteAcPowerSetting(Guid schemeGuid, Guid subgroupGuid, Guid settingGuid, uint value, bool activate, out string? error) + { var writeResult = NativeMethods.PowerWriteAcValueIndex( IntPtr.Zero, ref schemeGuid, @@ -1010,7 +972,7 @@ private static bool TryWriteAcPowerSetting( return false; } - var activateResult = NativeMethods.PowerSetActiveScheme(IntPtr.Zero, ref schemeGuid); + var activateResult = activate ? NativeMethods.PowerSetActiveScheme(IntPtr.Zero, ref schemeGuid) : 0; if (activateResult != 0) { error = new Win32Exception((int)activateResult).Message; @@ -1021,7 +983,34 @@ private static bool TryWriteAcPowerSetting( return true; } - private static bool TryGetActivePowerScheme(out Guid schemeGuid, out string? error) + internal static bool RestorePowerSetting(Guid scheme, Guid subgroup, Guid setting, uint original, uint written, uint? previousWritten) + { + if (!TryReadAcPowerSetting(scheme, subgroup, setting, out var current, out var error)) + { + throw new InvalidOperationException(error); + } + + if (current == original) + { + return true; + } + + if (current != written && current != previousWritten) + { + return false; + } + + if (!TryGetActivePowerScheme(out var active, out error) + || !TryWriteAcPowerSetting(scheme, subgroup, setting, original, activate: active == scheme, out error) + || !TryReadAcPowerSetting(scheme, subgroup, setting, out current, out error) || current != original) + { + throw new InvalidOperationException(error ?? "The previous power setting could not be verified."); + } + + return true; + } + + internal static bool TryGetActivePowerScheme(out Guid schemeGuid, out string? error) { schemeGuid = Guid.Empty; var result = NativeMethods.PowerGetActiveScheme(IntPtr.Zero, out var schemePointer); @@ -1183,7 +1172,7 @@ public async Task SetMenuShowDelayAsync(bool enabled) } // Set MenuShowDelay: 0 = no delay, 400 = default delay - key.SetValue("MenuShowDelay", enabled ? "400" : "0", RegistryValueKind.String); + RegistryTweakHistory.Write(Registry.CurrentUser, @"Control Panel\Desktop", "MenuShowDelay", enabled ? "400" : "0", RegistryValueKind.String); var status = await this.GetMenuShowDelayStatusAsync(); this.TweakStatusChanged?.Invoke(this, new TweakStatusChangedEventArgs("MenuShowDelay", status)); diff --git a/Services/UninstallCleanup.cs b/Services/UninstallCleanup.cs new file mode 100644 index 0000000..c6c9ca9 --- /dev/null +++ b/Services/UninstallCleanup.cs @@ -0,0 +1,684 @@ +namespace ThreadPilot.Services; + +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Security.AccessControl; +using System.Security.Principal; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Windows; +using Microsoft.Win32; +using Microsoft.Win32.SafeHandles; + +internal static partial class UninstallCleanup +{ + internal const string Argument = "--prepare-uninstall"; + private const string InstanceMutex = @"Global\ThreadPilot_SingleInstance"; + private const string PackageFamily = "LorenzoMassafra.ThreadPilot_2j208vxf88tt6"; + private const string InstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{E8F7A3B2-5C4D-4E6F-8A9B-1C2D3E4F5A6B}_is1"; + private const string RunKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; + + internal static EventWaitHandle RegisterShutdown(Action request) + { + var security = new EventWaitHandleSecurity(); + using var identity = WindowsIdentity.GetCurrent(); + var administrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); + var elevated = new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator); + var allowed = elevated ? administrators : identity.User!; + security.SetOwner(allowed); + security.AddAccessRule(new EventWaitHandleAccessRule(allowed, EventWaitHandleRights.FullControl, AccessControlType.Allow)); + security.AddAccessRule(new EventWaitHandleAccessRule( + new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow)); + var signal = EventWaitHandleAcl.Create(false, EventResetMode.AutoReset, ShutdownEventName(Environment.ProcessId), out _, security); + ThreadPool.RegisterWaitForSingleObject(signal, (_, _) => request(), null, Timeout.Infinite, executeOnlyOnce: true); + return signal; + } + + internal static bool TryChooseOptions(string title, out bool purge, out bool restore) + { + var data = new System.Windows.Controls.CheckBox + { + Content = "Remove ThreadPilot settings, profiles, rules, logs and temporary files", + IsChecked = true, + Margin = new Thickness(0, 0, 0, 12), + }; + var windows = new System.Windows.Controls.CheckBox + { + Content = "Restore Windows changes tracked by ThreadPilot", + IsChecked = true, + Margin = new Thickness(0, 0, 0, 18), + }; + var buttons = new System.Windows.Controls.StackPanel + { + Orientation = System.Windows.Controls.Orientation.Horizontal, + HorizontalAlignment = System.Windows.HorizontalAlignment.Right, + }; + var proceed = new System.Windows.Controls.Button + { + Content = "Continue", + IsDefault = true, + MinWidth = 94, + Padding = new Thickness(12, 5, 12, 5), + Margin = new Thickness(0, 0, 8, 0), + }; + buttons.Children.Add(proceed); + buttons.Children.Add(new System.Windows.Controls.Button + { + Content = "Cancel", + IsCancel = true, + MinWidth = 94, + Padding = new Thickness(12, 5, 12, 5), + }); + var panel = new System.Windows.Controls.StackPanel { Margin = new Thickness(20) }; + panel.Children.Add(data); + panel.Children.Add(windows); + panel.Children.Add(buttons); + var window = new Window + { + Title = title, + Content = panel, + SizeToContent = SizeToContent.WidthAndHeight, + ResizeMode = ResizeMode.NoResize, + WindowStartupLocation = WindowStartupLocation.CenterScreen, + }; + proceed.Click += (_, _) => window.DialogResult = true; + if (System.Windows.Application.Current.MainWindow is { IsVisible: true } owner) + { + window.Owner = owner; + window.WindowStartupLocation = WindowStartupLocation.CenterOwner; + } + + var confirmed = window.ShowDialog() == true; + purge = data.IsChecked == true; + restore = windows.IsChecked == true; + return confirmed; + } + + internal static int Run(string[] args, Func? recoverGameBoost = null, Action? closeServices = null, bool fromStoreWindow = false) + { + var silent = args.Contains("--silent"); + var purge = !args.Contains("--keep-data"); + var restore = !args.Contains("--keep-windows-changes"); + if (!silent && !fromStoreWindow && !TryChooseOptions("Uninstall ThreadPilot", out purge, out restore)) + { + return 2; + } + + var residuals = new List(); + string? legacyNote = null; + try + { + if (!fromStoreWindow) + { + StopMatchingInstance(); + } + } + catch (Exception ex) + { + Report([ex.Message], silent, fromStoreWindow); + return 2; + } + + try + { + var executable = Environment.ProcessPath ?? throw new InvalidOperationException("ThreadPilot executable path is unavailable."); + using var install = Registry.LocalMachine.OpenSubKey(InstallKey); + var installedPath = install?.GetValue("InstallLocation") is string installDir + ? Path.Combine(installDir, "ThreadPilot.exe") + : null; + var sameUser = IsSessionUser(); + var shared = StoreDistribution.IsStoreBuild + ? installedPath != null + : IsStoreInstalled() || (installedPath != null && !SamePath(installedPath, executable)); + + RemoveStartup(executable, sameUser, residuals); + if (!sameUser) + { + residuals.Add("User data and Windows recovery were retained because the elevated account differs from the signed-in account, or no interactive account is available."); + } + else if (shared) + { + residuals.Add("Shared data and Windows settings were retained because another ThreadPilot distribution is installed."); + } + else + { + var journal = Path.Combine(StoragePaths.AppDataRoot, "game_boost_journal.json"); + if (restore) + { + var failures = new List(); + if (recoverGameBoost != null && File.Exists(journal)) + { + Attempt("Game Boost recovery", failures, () => + { + if (HasReparsePoint(journal)) + { + throw new InvalidOperationException("Linked recovery journal was retained."); + } + + Task.Run(recoverGameBoost).GetAwaiter().GetResult(); + closeServices?.Invoke(); + if (File.Exists(journal)) + { + throw new InvalidOperationException("Recovery journal was retained."); + } + }); + } + + Attempt("Windows registry recovery", failures, () => RegistryTweakHistory.Restore(residuals, failures)); + Attempt("Power plan and SysMain recovery", failures, () => WindowsTweakHistory.Restore(residuals, failures)); + if (failures.Count != 0) + { + residuals.AddRange(failures); + Report(residuals, silent, fromStoreWindow); + return 2; + } + + Attempt("ThreadPilot registry cleanup", residuals, () => + { + const string appKey = @"SOFTWARE\ThreadPilot"; + using var key = Registry.LocalMachine.OpenSubKey(appKey); + if (key is { ValueCount: 0, SubKeyCount: 0 }) + { + Registry.LocalMachine.DeleteSubKey(appKey, throwOnMissingSubKey: false); + } + }); + } + + if (File.Exists(journal)) + { + residuals.Add("Game Boost recovery journal retained."); + } + + var legacyBackup = StoragePaths.DeviceTweakBackupsFilePath; + if (File.Exists(legacyBackup)) + { + residuals.Add("device_tweak_backups.json retained for older driver changes without a recorded last-written value."); + } + + Attempt("Windows recovery for other accounts", residuals, () => + { + using var history = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\ThreadPilot"); + foreach (var section in new[] { "TweakHistory", "PowerSettings", "ServiceSettings", "ImportedPlans" }) + { + using var entries = history?.OpenSubKey(section); + if (entries?.GetSubKeyNames().Any(sid => sid != RegistryTweakHistory.CurrentUserSid) == true) + { + residuals.Add($"{section}: recovery data belonging to another Windows account was retained."); + } + } + }); + + var hadSettings = File.Exists(StoragePaths.SettingsFilePath); + if (purge) + { + RemoveData(residuals); + } + + if (hadSettings) + { + legacyNote = "If you applied tweaks with an older ThreadPilot version, verify Game Mode, pointer precision, SysMain, scheduler, prefetch, power throttling, power plans and IFEO priorities. Older versions could change these without recording a verifiable baseline."; + } + } + } + catch (Exception ex) + { + residuals.Add("Cleanup could not finish: " + ex.Message); + } + + Report(residuals, silent, fromStoreWindow, legacyNote); + return residuals.Count == 0 ? 0 : 1; + } + + private static void StopMatchingInstance() + { + foreach (var process in Process.GetProcessesByName("ThreadPilot")) + { + using (process) + { + if (process.Id == Environment.ProcessId || process.HasExited) + { + continue; + } + + try + { + if (process.MainModule?.FileName is not string path || !SamePath(path, Environment.ProcessPath!)) + { + continue; + } + + if (!EventWaitHandle.TryOpenExisting(ShutdownEventName(process.Id), out var signal)) + { + throw new InvalidOperationException("Close the running copy of ThreadPilot from its tray menu and retry uninstall."); + } + + using (signal) + { + if (!signal.Set()) + { + throw new InvalidOperationException("Could not request a graceful ThreadPilot shutdown."); + } + } + + if (!process.WaitForExit(30000)) + { + throw new InvalidOperationException("ThreadPilot did not finish shutting down. Retry when cleanup has completed."); + } + } + catch (InvalidOperationException) when (process.HasExited) + { + } + } + } + + if (Mutex.TryOpenExisting(InstanceMutex, out var running)) + { + running.Dispose(); + throw new InvalidOperationException("Another ThreadPilot distribution is running. Close it from its tray menu before uninstalling."); + } + } + + private static void RemoveStartup(string executable, bool sameUser, List residuals) + { + Attempt("Scheduled tasks", residuals, () => + { + var schedulerType = Type.GetTypeFromProgID("Schedule.Service", throwOnError: true)!; + dynamic scheduler = Activator.CreateInstance(schedulerType)!; + scheduler.Connect(); + dynamic folder = scheduler.GetFolder("\\"); + var names = StoreDistribution.IsStoreBuild + ? new[] { "ThreadPilot_Store_Startup", "ThreadPilot_Store_Launch" } + : new[] { "ThreadPilot_Startup", "ThreadPilot_Launch" }; + + foreach (var name in names) + { + Attempt(name, residuals, () => + { + dynamic task; + try + { + task = folder.GetTask(name); + } + catch (Exception ex) when (ex.HResult == unchecked((int)0x80070002)) + { + return; + } + + var definition = System.Xml.Linq.XDocument.Parse((string)task.Xml); + var actions = definition.Descendants().Where(e => e.Name.LocalName == "Exec").ToArray(); + if (actions.Length != 1) + { + residuals.Add($"{name}: unrecognized action retained."); + return; + } + + var action = actions[0]; + var command = action.Elements().FirstOrDefault(e => e.Name.LocalName == "Command")?.Value; + var arguments = action.Elements().FirstOrDefault(e => e.Name.LocalName == "Arguments")?.Value; + var packageLaunch = StoreDistribution.IsStoreBuild + && SamePath(Environment.ExpandEnvironmentVariables(command ?? string.Empty), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe")) + && string.Equals(arguments, $"shell:AppsFolder\\{PackageFamily}!App", StringComparison.OrdinalIgnoreCase); + var windowsApps = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsApps") + Path.DirectorySeparatorChar; + var legacyStorePath = command != null && command.StartsWith(windowsApps, StringComparison.OrdinalIgnoreCase) + ? command[windowsApps.Length..].Split(Path.DirectorySeparatorChar) + : []; + var legacyStoreLaunch = StoreDistribution.IsStoreBuild && legacyStorePath.Length == 3 + && StoreTaskPackage().IsMatch(legacyStorePath[0]) + && string.Equals(legacyStorePath[1], "App", StringComparison.OrdinalIgnoreCase) + && string.Equals(legacyStorePath[2], "ThreadPilot.exe", StringComparison.OrdinalIgnoreCase); + if (packageLaunch || legacyStoreLaunch || SamePath(command, executable)) + { + folder.DeleteTask(name, 0); + } + else + { + residuals.Add($"{name}: task points to another copy or an unrecognized command."); + } + }); + } + }); + + if (sameUser && !StoreDistribution.IsStoreBuild) + { + Attempt("Legacy startup entry", residuals, () => + { + using var run = Registry.CurrentUser.OpenSubKey(RunKey, writable: true); + if (run?.GetValue("ThreadPilot") is string command + && (SamePath(command, executable) + || command.StartsWith($"\"{executable}\" ", StringComparison.OrdinalIgnoreCase) + || command.StartsWith(executable + " ", StringComparison.OrdinalIgnoreCase))) + { + run.DeleteValue("ThreadPilot", throwOnMissingValue: false); + } + }); + } + } + + private static void RemoveData(List residuals) + { + var roaming = StoragePaths.AppDataRoot; + var local = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ThreadPilot"); + var temp = Path.GetTempPath(); + Attempt("User data", residuals, () => + { + using var identity = WindowsIdentity.GetCurrent(); + // Use the interactive user's shell token. A linked UAC token can be limited to identification. + _ = GetWindowThreadProcessId(GetShellWindow(), out var shellPid); + if (shellPid == 0) + { + throw new InvalidOperationException("No interactive shell token is available."); + } + + using var shell = Process.GetProcessById((int)shellPid); + const uint tokenDuplicateAndQuery = 0x0002 | 0x0008; + if (!OpenProcessToken(shell.SafeHandle, tokenDuplicateAndQuery, out var token)) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + using (token) + using (var shellIdentity = new WindowsIdentity(token.DangerousGetHandle())) + { + if (shellIdentity.User != identity.User + || new WindowsPrincipal(shellIdentity).IsInRole(WindowsBuiltInRole.Administrator)) + { + throw new InvalidOperationException("The shell does not have a limited token for this user."); + } + + WindowsIdentity.RunImpersonated(token, () => RemoveUserData(roaming, local, temp, residuals)); + } + }); + Attempt("Update and task temporary folders", residuals, () => + { + var administrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); + foreach (var directory in new DirectoryInfo(AdminOnlyDirectory.DefaultRoot).EnumerateDirectories("ThreadPilot-*")) + { + if (!TempFolderName().IsMatch(directory.Name)) + { + continue; + } + + Attempt(directory.FullName, residuals, () => + { + if (HasReparsePoint(directory.FullName) + || !administrators.Equals(directory.GetAccessControl().GetOwner(typeof(SecurityIdentifier))) + || directory.EnumerateFileSystemInfos().Any(item => + (item.Attributes & (FileAttributes.ReparsePoint | FileAttributes.Directory)) != 0)) + { + residuals.Add($"{directory.FullName}: ownership or contents could not be verified."); + return; + } + + directory.Delete(recursive: true); + }); + } + }); + + } + + private static void RemoveUserData(string root, string local, string temp, List residuals) + { + string[] rootFiles = ["settings.json", "core_masks.json", "persistent_rules.json", "ui-state.json", "ui-state.json.tmp"]; + RemoveFrom(root, name => MatchesDataArtifact(name, candidate => rootFiles.Contains(candidate, StringComparer.OrdinalIgnoreCase))); + RemoveFrom(Path.Combine(root, "Configuration"), name => MatchesDataArtifact(name, candidate => candidate.Equals("ProcessPowerPlanAssociations.json", StringComparison.OrdinalIgnoreCase))); + RemoveFrom(Path.Combine(root, "Profiles"), name => MatchesDataArtifact(name, candidate => candidate.EndsWith(".json", StringComparison.OrdinalIgnoreCase)), + verifyFile: path => + { + using var stream = File.OpenRead(path); + return IsProcessProfile(stream); + }); + // Existing .pow files have no ownership record that distinguishes app copies from user exports. + RemoveFrom(Path.Combine(root, "Powerplans"), _ => false); + RemoveFrom(Path.Combine(local, "Logs"), name => AppLogName().IsMatch(name)); + RemoveFrom(temp, name => name.Equals("ThreadPilot_Debug.log", StringComparison.OrdinalIgnoreCase), removeDirectory: false); + + foreach (var path in new[] { root, local }) + { + Attempt(path, residuals, () => + { + if (!DirectoryExistsForCleanup(path)) + { + return; + } + + if (HasReparsePoint(path) || Directory.EnumerateFileSystemEntries(path).Any()) + { + residuals.Add($"{path}: remaining files were retained."); + return; + } + + Directory.Delete(path); + }); + } + + void RemoveFrom(string path, Func isOwnedFile, bool removeDirectory = true, Func? verifyFile = null) + { + Attempt(path, residuals, () => + { + if (!DirectoryExistsForCleanup(path)) + { + return; + } + + if (HasReparsePoint(path)) + { + residuals.Add($"{path}: linked folder retained."); + return; + } + + foreach (var file in new DirectoryInfo(path).EnumerateFiles().Where(file => isOwnedFile(file.Name))) + { + if (file.Attributes.HasFlag(FileAttributes.ReparsePoint)) + { + residuals.Add($"{file.FullName}: linked file retained."); + continue; + } + + Attempt(file.FullName, residuals, () => + { + if (verifyFile == null || verifyFile(file.FullName)) + { + file.Delete(); + } + else + { + residuals.Add($"{file.FullName}: ownership could not be verified."); + } + }); + } + + if (removeDirectory && !Directory.EnumerateFileSystemEntries(path).Any()) + { + Directory.Delete(path); + } + }); + } + } + + internal static bool IsProcessProfile(Stream stream) + { + try + { + using var reader = new StreamReader(stream, leaveOpen: true); + using var profile = JsonDocument.Parse(reader.ReadToEnd()); + var root = profile.RootElement; + return root.ValueKind == JsonValueKind.Object + && root.TryGetProperty("ProcessName", out var name) && name.ValueKind == JsonValueKind.String + && root.TryGetProperty("Priority", out var priority) && priority.ValueKind == JsonValueKind.Number + && root.TryGetProperty("ProcessorAffinity", out var affinity) && affinity.ValueKind == JsonValueKind.Number; + } + catch (JsonException) + { + return false; + } + } + + internal static bool MatchesDataArtifact(string name, Func matchesDataFile) + { + if (matchesDataFile(name)) + { + return true; + } + + if (name.EndsWith(".bak", StringComparison.OrdinalIgnoreCase)) + { + return matchesDataFile(name[..^4]); + } + + var temp = AtomicDataName().Match(name); + return temp.Success && matchesDataFile(temp.Groups[1].Value); + } + + private static bool DirectoryExistsForCleanup(string path) + { + try + { + return (File.GetAttributes(path) & FileAttributes.Directory) != 0; + } + catch (Exception ex) when (ex is DirectoryNotFoundException or FileNotFoundException) + { + return false; + } + } + + private static bool IsStoreInstalled() + { + uint count = 0; + uint size = 0; + var status = GetPackagesByPackageFamily(PackageFamily, ref count, IntPtr.Zero, ref size, IntPtr.Zero); + return status switch + { + 0 => count > 0, + 122 => true, + _ => throw new Win32Exception(status, "Could not determine whether ThreadPilot from Microsoft Store is installed."), + }; + } + + private static bool IsSessionUser() + { + using var process = Process.GetCurrentProcess(); + using var identity = WindowsIdentity.GetCurrent(); + var user = ReadSessionInfo(process.SessionId, 5); + var domain = ReadSessionInfo(process.SessionId, 7); + return !string.IsNullOrEmpty(user) + && new NTAccount(domain ?? string.Empty, user).Translate(typeof(SecurityIdentifier)).Equals(identity.User); + } + + private static string? ReadSessionInfo(int sessionId, int field) + { + if (!WTSQuerySessionInformation(IntPtr.Zero, sessionId, field, out var value, out _)) + { + return null; + } + + try + { + return Marshal.PtrToStringUni(value); + } + finally + { + WTSFreeMemory(value); + } + } + + internal static bool HasReparsePoint(string path) + { + for (string? current = Path.GetFullPath(path); current != null; current = Path.GetDirectoryName(current)) + { + if ((File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) + { + return true; + } + } + + return false; + } + + private static bool SamePath(string? left, string right) => + string.Equals(left?.Trim().Trim('"'), right, StringComparison.OrdinalIgnoreCase); + + private static string ShutdownEventName(int pid) => $@"Global\ThreadPilot_Uninstall_{pid}"; + + private static void Attempt(string operation, List residuals, Action action) + { + try + { + action(); + } + catch (Exception ex) + { + residuals.Add($"{operation}: {ex.Message}"); + } + } + + private static void Report(IReadOnlyList residuals, bool silent, bool fromStoreWindow, string? legacyNote = null) + { + var summary = residuals.Count == 0 + ? "ThreadPilot cleanup completed." + : "Items requiring attention:" + Environment.NewLine + string.Join(Environment.NewLine, residuals); + if (legacyNote != null) + { + summary += Environment.NewLine + Environment.NewLine + legacyNote; + } + + if (fromStoreWindow) + { + summary += Environment.NewLine + Environment.NewLine + "To remove the package, open Windows Settings → Apps → Installed apps → ThreadPilot."; + } + + if (!silent) + { + System.Windows.MessageBox.Show(summary, "ThreadPilot cleanup", MessageBoxButton.OK, + residuals.Count == 0 ? MessageBoxImage.Information : MessageBoxImage.Warning); + } + + if (silent && residuals.Count != 0) + { + // Create a new admin-owned directory before writing from the elevated cleanup process. + try + { + var directory = AdminOnlyDirectory.Create(Path.Combine(AdminOnlyDirectory.DefaultRoot, $"ThreadPilot-uninstall-{Guid.NewGuid():N}")); + File.WriteAllText(Path.Combine(directory, "cleanup.log"), summary); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Trace.TraceWarning("Could not write ThreadPilot uninstall report: {0}", ex.Message); + } + } + } + + [GeneratedRegex(@"^[.](.+)[.][0-9a-f]{32}[.]tmp$", RegexOptions.IgnoreCase)] + private static partial Regex AtomicDataName(); + + [GeneratedRegex(@"^LorenzoMassafra[.]ThreadPilot_[0-9.]+_x64__2j208vxf88tt6$", RegexOptions.IgnoreCase)] + private static partial Regex StoreTaskPackage(); + + [GeneratedRegex(@"^ThreadPilot(?:_\d{8}_\d{6})?\.log$", RegexOptions.IgnoreCase)] + private static partial Regex AppLogName(); + + [GeneratedRegex(@"^ThreadPilot-(?:task-|uninstall-|update-[0-9A-Za-z.+-]+-)[0-9a-f]{32}$", RegexOptions.IgnoreCase)] + private static partial Regex TempFolderName(); + + [DllImport("user32.dll")] + private static extern IntPtr GetShellWindow(); + + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId); + + [DllImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool OpenProcessToken(SafeProcessHandle process, uint access, out SafeAccessTokenHandle token); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + private static extern int GetPackagesByPackageFamily(string family, ref uint count, IntPtr fullNames, ref uint bufferLength, IntPtr buffer); + + [DllImport("wtsapi32.dll", CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool WTSQuerySessionInformation(IntPtr server, int session, int infoClass, out IntPtr buffer, out int bytes); + + [DllImport("wtsapi32.dll")] + private static extern void WTSFreeMemory(IntPtr memory); +} diff --git a/Services/UpdateModels.cs b/Services/UpdateModels.cs index 7a588ee..f7b3fa0 100644 --- a/Services/UpdateModels.cs +++ b/Services/UpdateModels.cs @@ -72,6 +72,10 @@ public interface IApplicationVersionProvider public interface IUpdateService { + UpdateReleaseInfo? AvailableRelease { get; } + + event EventHandler? AvailableReleaseChanged; + Task CheckForUpdatesAsync(UpdateCheckRequest request, CancellationToken cancellationToken = default); Task DownloadAndInstallAsync(UpdateReleaseInfo release, CancellationToken cancellationToken = default); diff --git a/Services/UpdateService.cs b/Services/UpdateService.cs index c4955b8..ffcf8b5 100644 --- a/Services/UpdateService.cs +++ b/Services/UpdateService.cs @@ -25,6 +25,10 @@ public sealed class UpdateService : IUpdateService private readonly SemaphoreSlim checkGate = new(1, 1); private readonly SemaphoreSlim installGate = new(1, 1); + public UpdateReleaseInfo? AvailableRelease { get; private set; } + + public event EventHandler? AvailableReleaseChanged; + public UpdateService( GitHubUpdateChecker updateChecker, IApplicationSettingsService settingsService, @@ -82,7 +86,10 @@ public async Task CheckForUpdatesAsync(UpdateCheckRequest req return new UpdateCheckResult(UpdateCheckStatus.Failed, currentVersion, null, "Unable to determine the latest ThreadPilot release."); } - if (release.Version > currentVersion) + this.AvailableRelease = release.Version > currentVersion ? release : null; + this.AvailableReleaseChanged?.Invoke(this, EventArgs.Empty); + + if (this.AvailableRelease != null) { this.logger.LogInformation( "ThreadPilot update available: current {CurrentVersion}, latest {LatestVersion}", diff --git a/Services/WindowsTweakHistory.cs b/Services/WindowsTweakHistory.cs new file mode 100644 index 0000000..861c254 --- /dev/null +++ b/Services/WindowsTweakHistory.cs @@ -0,0 +1,318 @@ +namespace ThreadPilot.Services; + +using System.IO; +using System.Security.Cryptography; +using System.ServiceProcess; +using System.Text.Json; +using Microsoft.Win32; +using ThreadPilot.Services.Abstractions; + +internal static class WindowsTweakHistory +{ + private static readonly SystemProcessRunner Runner = new(); + private static readonly TimeSpan CommandTimeout = TimeSpan.FromSeconds(25); + private static readonly Guid Balanced = new("381b4222-f694-41f0-9685-ff5bb260df2e"); + private const string PowerSchemes = @"SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes"; + private const string SysMainPath = @"SYSTEM\CurrentControlSet\Services\SysMain"; + + internal static RegistryKey Open(string section) => + Registry.LocalMachine.CreateSubKey($@"SOFTWARE\ThreadPilot\{section}\{RegistryTweakHistory.CurrentUserSid}"); + + internal static void RecordPowerSetting(Guid scheme, Guid subgroup, Guid setting, uint current, uint desired) + { + if (current == desired) + { + return; + } + + using var history = Open("PowerSettings"); + var id = $"{scheme:D}/{subgroup:D}/{setting:D}"; + var previous = Read(history, id); + var original = previous?.Written == current || previous?.PreviousWritten == current ? previous.Original : current; + var entry = new PowerSettingChange(original, desired, original == current ? null : current); + Store(history, id, entry); + } + + internal static void ConfirmPowerSetting(Guid scheme, Guid subgroup, Guid setting, uint written) + { + using var history = Open("PowerSettings"); + var id = $"{scheme:D}/{subgroup:D}/{setting:D}"; + var change = Read(history, id); + if (change?.Written == written && change.PreviousWritten.HasValue) + { + Store(history, id, change with { PreviousWritten = null }); + } + } + + internal static async Task ImportPlanAsync(string file, IProcessRunner runner) + { + var id = Guid.NewGuid().ToString("D"); + using var history = Open("ImportedPlans"); + Store(history, id, new ImportedPlan(null)); + var import = await PowerCfg(runner, "/import", file, id).ConfigureAwait(false); + if (import.ExitCode != 0) + { + if (!PowerPlanExists(id)) + { + history.DeleteValue(id); + } + + return false; + } + + var fingerprint = await FingerprintAsync(id, runner).ConfigureAwait(false); + Store(history, id, new ImportedPlan(fingerprint)); + return true; + } + + internal static async Task SetSysMainAsync(bool enabled) + { + var current = ReadSysMain(); + var desired = new SysMainState(enabled ? ServiceStartMode.Automatic : ServiceStartMode.Disabled, false, enabled); + if (current == desired) + { + return; + } + + using var history = Open("ServiceSettings"); + var previous = Read(history, "SysMain"); + var original = previous?.Written == current || previous?.PreviousWritten == current ? previous.Original : current; + Store(history, "SysMain", new SysMainChange(original, desired, current)); + await WriteSysMainAsync(desired).ConfigureAwait(false); + Store(history, "SysMain", new SysMainChange(original, desired, null)); + } + + internal static void Restore(List residuals, List failures) + { + RestoreSection("PowerSettings", (history, id) => + { + var parts = id.Split('/'); + if (parts.Length != 3 || !Guid.TryParse(parts[0], out var scheme) + || !Guid.TryParse(parts[1], out var subgroup) || !Guid.TryParse(parts[2], out var setting)) + { + throw new InvalidDataException("Invalid recorded power setting."); + } + + if (!PowerPlanExists(parts[0])) + { + return true; + } + + var entry = Read(history, id) ?? throw new InvalidDataException(id); + return SystemTweaksService.RestorePowerSetting(scheme, subgroup, setting, entry.Original, entry.Written, entry.PreviousWritten); + }); + RestoreSection("ServiceSettings", (history, id) => + { + if (id != "SysMain") + { + throw new InvalidDataException("Unrecognized service in recovery history."); + } + + var entry = Read(history, id) ?? throw new InvalidDataException(id); + var current = ReadSysMain(); + if (current == entry.Original) + { + return true; + } + + if (current != entry.Written && current != entry.PreviousWritten) + { + if (entry.PreviousWritten.HasValue) + { + throw new InvalidOperationException("SysMain has an unverified startup or running state after an incomplete write."); + } + + return false; + } + + WriteSysMainAsync(entry.Original).GetAwaiter().GetResult(); + return true; + }); + RestoreSection("ImportedPlans", (history, id) => + { + if (!Guid.TryParseExact(id, "D", out var scheme)) + { + throw new InvalidDataException("Invalid recorded power plan identifier."); + } + + if (!PowerPlanExists(id)) + { + return true; + } + + var entry = Read(history, id) ?? throw new InvalidDataException(id); + if (entry.Fingerprint == null) + { + throw new InvalidDataException("The imported plan fingerprint is missing."); + } + + if (FingerprintAsync(id, Runner).GetAwaiter().GetResult() != entry.Fingerprint) + { + return false; + } + + if (!SystemTweaksService.TryGetActivePowerScheme(out var active, out var error)) + { + throw new InvalidOperationException(error); + } + + if (active == scheme) + { + var fallback = Balanced.ToString("D"); + if (!PowerPlanExists(fallback) + || PowerCfg(Runner, "/setactive", fallback).GetAwaiter().GetResult().ExitCode != 0 + || !SystemTweaksService.TryGetActivePowerScheme(out active, out _) || active != Balanced) + { + throw new InvalidOperationException("Could not activate the Balanced plan before removal."); + } + } + + if (PowerCfg(Runner, "/delete", id).GetAwaiter().GetResult().ExitCode != 0 || PowerPlanExists(id)) + { + throw new InvalidOperationException("Windows did not remove the imported power plan."); + } + + return true; + }); + + void RestoreSection(string section, Func restore) + { + var path = $@"SOFTWARE\ThreadPilot\{section}\{RegistryTweakHistory.CurrentUserSid}"; + using (var history = Registry.LocalMachine.OpenSubKey(path, writable: true)) + { + if (history == null) + { + return; + } + + foreach (var id in history.GetValueNames()) + { + try + { + if (!restore(history, id)) + { + residuals.Add($"{id}: a later change was preserved."); + } + + history.DeleteValue(id); + } + catch (Exception ex) + { + failures.Add($"{id}: restore failed ({ex.Message}). Recovery entry retained."); + } + } + + if (history.ValueCount != 0) + { + return; + } + } + + Registry.LocalMachine.DeleteSubKey(path, throwOnMissingSubKey: false); + var sectionPath = $@"SOFTWARE\ThreadPilot\{section}"; + using var parent = Registry.LocalMachine.OpenSubKey(sectionPath); + if (parent is { SubKeyCount: 0, ValueCount: 0 }) + { + Registry.LocalMachine.DeleteSubKey(sectionPath, throwOnMissingSubKey: false); + } + } + } + + private static SysMainState ReadSysMain() + { + using var controller = new ServiceController("SysMain"); + if (controller.Status is not (ServiceControllerStatus.Stopped or ServiceControllerStatus.Running) + || controller.StartType is not (ServiceStartMode.Automatic or ServiceStartMode.Manual or ServiceStartMode.Disabled)) + { + throw new InvalidOperationException("SysMain is in a state that cannot be safely restored."); + } + + using var key = Registry.LocalMachine.OpenSubKey(SysMainPath); + return new(controller.StartType, controller.StartType == ServiceStartMode.Automatic && Equals(key?.GetValue("DelayedAutoStart"), 1), + controller.Status == ServiceControllerStatus.Running); + } + + private static async Task WriteSysMainAsync(SysMainState state) + { + var start = state.Start switch + { + ServiceStartMode.Automatic => state.Delayed ? "delayed-auto" : "auto", + ServiceStartMode.Manual => "demand", + ServiceStartMode.Disabled => "disabled", + _ => throw new InvalidOperationException(), + }; + using var controller = new ServiceController("SysMain"); + // A disabled service can be running if its startup type was changed after it started. + if (state.Start == ServiceStartMode.Disabled && state.Running && controller.Status != ServiceControllerStatus.Running) + { + await Configure("demand").ConfigureAwait(false); + controller.Start(); + controller.WaitForStatus(ServiceControllerStatus.Running, CommandTimeout); + } + + await Configure(start).ConfigureAwait(false); + controller.Refresh(); + if (state.Running && controller.Status == ServiceControllerStatus.Stopped) + { + controller.Start(); + controller.WaitForStatus(ServiceControllerStatus.Running, CommandTimeout); + } + else if (!state.Running && controller.Status == ServiceControllerStatus.Running) + { + controller.Stop(); + controller.WaitForStatus(ServiceControllerStatus.Stopped, CommandTimeout); + } + + if (ReadSysMain() != state) + { + throw new InvalidOperationException("SysMain startup configuration or running status could not be verified."); + } + + static async Task Configure(string start) + { + var result = await Runner.RunAsync(Path.Combine(Environment.SystemDirectory, "sc.exe"), + ["config", "SysMain", "start=", start], CommandTimeout).ConfigureAwait(false); + if (result.ExitCode != 0) + { + throw new InvalidOperationException("Windows did not change the SysMain startup configuration."); + } + } + } + + private static bool PowerPlanExists(string id) + { + using var key = Registry.LocalMachine.OpenSubKey(PowerSchemes + "\\" + id); + return key != null; + } + + private static async Task FingerprintAsync(string id, IProcessRunner runner) + { + var result = await PowerCfg(runner, "/qh", id).ConfigureAwait(false); + if (result.ExitCode != 0 || string.IsNullOrWhiteSpace(result.StandardOutput)) + { + throw new InvalidOperationException("Windows could not read back the imported power plan."); + } + + return Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(result.StandardOutput))); + } + + private static Task PowerCfg(IProcessRunner runner, params string[] arguments) => + runner.RunAsync(Path.Combine(Environment.SystemDirectory, "powercfg.exe"), arguments, CommandTimeout); + + private static T? Read(RegistryKey key, string name) where T : class => + key.GetValue(name) is string json ? JsonSerializer.Deserialize(json) : null; + + private static void Store(RegistryKey key, string name, T entry) + { + key.SetValue(name, JsonSerializer.Serialize(entry)); + key.Flush(); + } + + private sealed record PowerSettingChange(uint Original, uint Written, uint? PreviousWritten); + + private sealed record ImportedPlan(string? Fingerprint); + + private sealed record SysMainChange(SysMainState Original, SysMainState Written, SysMainState? PreviousWritten); + + private readonly record struct SysMainState(ServiceStartMode Start, bool Delayed, bool Running); +} diff --git a/Tests/ThreadPilot.Core.Tests/KeyboardShortcutEditingTests.cs b/Tests/ThreadPilot.Core.Tests/KeyboardShortcutEditingTests.cs index 58179f3..5106ce9 100644 --- a/Tests/ThreadPilot.Core.Tests/KeyboardShortcutEditingTests.cs +++ b/Tests/ThreadPilot.Core.Tests/KeyboardShortcutEditingTests.cs @@ -90,6 +90,22 @@ public async Task LoadShortcutsFromSettingsAsync_ExplicitlyDisabledDefaultsStayD Assert.Empty(await service.GetRegisteredShortcutsAsync()); } + [Fact] + public async Task OpenTrayMenuShortcut_CanBeReassignedAndApplied() + { + using var service = CreateService(); + await service.LoadShortcutsFromSettingsAsync(); + var shortcuts = service.GetConfiguredShortcuts().ToList(); + var tray = shortcuts.Single(binding => binding.ActionName == ShortcutActions.OpenTrayMenu); + tray.Key = Key.F10; + tray.Modifiers = ModifierKeys.Control | ModifierKeys.Alt; + + Assert.Null(await service.ApplyAndSaveAsync(shortcuts, () => Task.CompletedTask)); + var applied = (await service.GetRegisteredShortcutsAsync())[ShortcutActions.OpenTrayMenu]; + Assert.Equal(Key.F10, applied.Key); + Assert.Equal(ModifierKeys.Control | ModifierKeys.Alt, applied.Modifiers); + } + private static KeyboardShortcutService CreateService(ApplicationSettingsModel? settings = null, Key blockedKey = Key.None) { var profile = new Mock(); diff --git a/Tests/ThreadPilot.Core.Tests/PackagingMetadataTests.cs b/Tests/ThreadPilot.Core.Tests/PackagingMetadataTests.cs index 5c02fc9..87ad732 100644 --- a/Tests/ThreadPilot.Core.Tests/PackagingMetadataTests.cs +++ b/Tests/ThreadPilot.Core.Tests/PackagingMetadataTests.cs @@ -53,24 +53,24 @@ public void PrimaryInstaller_RemovesThreadPilotOwnedDataOnlyDuringUninstall() var root = FindRepositoryRoot(); var script = File.ReadAllText(Path.Combine(root, "Installer", "setup.iss")); - Assert.Contains("[UninstallDelete]", script, StringComparison.Ordinal); - Assert.Contains("Name: \"{userappdata}\\ThreadPilot\"", script, StringComparison.Ordinal); - Assert.Contains("ThreadPilot user data is preserved during install/update", script, StringComparison.Ordinal); - Assert.Contains("ThreadPilot_Launch", script, StringComparison.Ordinal); - Assert.Contains("ThreadPilot_Startup", script, StringComparison.Ordinal); + Assert.Contains("UninstallLogMode=overwrite", script, StringComparison.Ordinal); + Assert.Contains("--prepare-uninstall", script, StringComparison.Ordinal); + Assert.Contains("{param:PURGEDATA|1}", script, StringComparison.Ordinal); + Assert.Contains("Type: dirifempty; Name: \"{app}\"", script, StringComparison.Ordinal); + Assert.DoesNotContain("filesandordirs", script, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("{userappdata}", script, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("[InstallDelete]", script, StringComparison.Ordinal); - Assert.DoesNotContain("Name: \"{userappdata}\"", script, StringComparison.Ordinal); + Assert.DoesNotContain("taskkill.exe", script, StringComparison.OrdinalIgnoreCase); } [Fact] - public void LocalPortablePackages_UseOneUninstallerForCurrentAndLegacyStartupTasks() + public void LocalAndPublishedPortablePackages_UseTheSameManifestAndUninstaller() { var root = FindRepositoryRoot(); - var uninstaller = Path.Combine(root, "build", "portable-uninstall.bat"); - AssertFileContains(uninstaller, "ThreadPilot_Launch"); - AssertFileContains(uninstaller, "ThreadPilot_Startup"); + AssertFileContains(Path.Combine(root, "build", "portable-uninstall.ps1"), "uninstall-files.json"); AssertFileContains(Path.Combine(root, "build", "package-release-zips.ps1"), "portable-uninstall.bat"); AssertFileContains(Path.Combine(root, "build", "build-release.ps1"), "package-release-zips.ps1"); + AssertFileContains(Path.Combine(root, ".github", "workflows", "release.yml"), "package-release-zips.ps1"); } [Fact] diff --git a/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs index 781e85f..1701543 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs @@ -3,6 +3,7 @@ namespace ThreadPilot.Core.Tests using Microsoft.Extensions.Logging.Abstractions; using Moq; using ThreadPilot.Models; + using ThreadPilot.Platforms.Windows; using ThreadPilot.Services; using ThreadPilot.ViewModels; @@ -169,6 +170,67 @@ public void SelectingProcessBoostedByGameBoost_SaysGameBoostSetTheCpuSets() Assert.True(SpinWait.SpinUntil(() => viewModel.CurrentAffinityText == expected, TimeSpan.FromSeconds(2)), viewModel.CurrentAffinityText); } + [Fact] + public void SelectingProcessWithCpuSets_DoesNotLeaveTheAllCoresMaskSelected() + { + var processService = CreateRunningProcessService(cpuSets: [0]); + var allCores = CoreMask.CreateAllCoresMask(2); + var masks = new System.Collections.ObjectModel.ObservableCollection { allCores }; + var coreMaskService = new Mock(MockBehavior.Loose); + coreMaskService.SetupGet(service => service.AvailableMasks).Returns(masks); + coreMaskService.SetupGet(service => service.DefaultMask).Returns(allCores); + using var viewModel = CreateViewModel( + processService.Object, + new Mock(MockBehavior.Loose).Object, + cpuTopologyProvider: null, + coreMaskService: coreMaskService.Object); + viewModel.CpuTopology = CreateTwoCoreTopology(); + viewModel.CpuCores = new System.Collections.ObjectModel.ObservableCollection(viewModel.CpuTopology.LogicalCores); + viewModel.AvailableCoreMasks = masks; + viewModel.SelectedCoreMask = allCores; + + viewModel.SelectedProcess = new ProcessModel { ProcessId = 1234, Name = "Game", ProcessorAffinity = 3 }; + + Assert.True(SpinWait.SpinUntil( + () => viewModel.SelectedCoreMask == null && viewModel.CoreMaskPickerHint.Contains("All Cores", StringComparison.Ordinal), + TimeSpan.FromSeconds(2)), + viewModel.CoreMaskPickerHint); + Assert.False(viewModel.HasPendingAffinityEdits); + Assert.True(viewModel.CpuCores[0].IsSelected); + Assert.False(viewModel.CpuCores[1].IsSelected); + } + + [Fact] + public void ReadCpuSetDiagnostic_ShowsOverrideSeparatelyFromDeniedReads() + { + var processService = CreateRunningProcessService(cpuSets: []); + using var viewModel = CreateViewModel(processService.Object, new Mock(MockBehavior.Loose).Object, cpuTopologyProvider: null); + viewModel.SelectedProcess = new ProcessModel { ProcessId = 1234, Name = "Game", ProcessorAffinity = 3 }; + var mapping = CpuSetMapping.Create(new Dictionary { [new ProcessorRef(0, 1, 1)] = 10 }); + viewModel.CpuSetDiagnosticSource = new FakeCpuSetDiagnosticSource( + ThreadCpuSetDiagnosticClassifier.Combine( + new CpuSetIdRead(CpuSetReadKind.Read, [10], 0), + new ThreadCpuSetProbeResult( + true, + null, + [ + ThreadCpuSetProbe.NoOverride(1, null, (false, 0, 0)), + ThreadCpuSetProbe.Override(2, [10], null, (false, 0, 0)), + ThreadCpuSetProbe.OpenFailed(3, 5), + ]), + mapping)); + + viewModel.ReadCpuSetDiagnosticCommand.Execute(null); + + Assert.True(SpinWait.SpinUntil(() => viewModel.CpuSetDiagnosticText.Contains("TID 2", StringComparison.Ordinal), TimeSpan.FromSeconds(2)), viewModel.CpuSetDiagnosticText); + Assert.Contains("explicit override", viewModel.CpuSetDiagnosticText, StringComparison.Ordinal); + Assert.Contains("TID 3: read denied.", viewModel.CpuSetDiagnosticText, StringComparison.Ordinal); + Assert.Contains("not the CPU a thread is running on", viewModel.CpuSetDiagnosticText, StringComparison.Ordinal); + + viewModel.SelectedProcess = new ProcessModel { ProcessId = 1235, Name = "Other Game", ProcessorAffinity = 3 }; + Assert.Empty(viewModel.CpuSetDiagnosticText); + } + [Fact] public void SelectingProcessWithoutCpuSets_SaysWindowsPicksTheCores() { @@ -202,7 +264,8 @@ private static ProcessViewModel CreateViewModel( IGameModeService gameModeService, ICpuTopologyProvider? cpuTopologyProvider, IApplicationSettingsService? settingsService = null, - IGameSessionService? gameSessionService = null) + IGameSessionService? gameSessionService = null, + ICoreMaskService? coreMaskService = null) { var virtualizedProcessService = new Mock(MockBehavior.Loose); virtualizedProcessService.SetupProperty( @@ -213,7 +276,7 @@ private static ProcessViewModel CreateViewModel( var powerPlanService = new Mock(MockBehavior.Loose); var notificationService = new Mock(MockBehavior.Loose); var systemTrayService = new Mock(MockBehavior.Loose); - var coreMaskService = new Mock(MockBehavior.Loose); + coreMaskService ??= new Mock(MockBehavior.Loose).Object; var associationService = new Mock(MockBehavior.Loose); return new ProcessViewModel( @@ -225,7 +288,7 @@ private static ProcessViewModel CreateViewModel( powerPlanService.Object, notificationService.Object, systemTrayService.Object, - coreMaskService.Object, + coreMaskService, associationService.Object, gameModeService, cpuTopologyProvider: cpuTopologyProvider, @@ -233,6 +296,18 @@ private static ProcessViewModel CreateViewModel( gameSessionService: gameSessionService); } + private sealed class FakeCpuSetDiagnosticSource : ICpuSetDiagnosticSource + { + private readonly ProcessCpuSetDiagnostic diagnostic; + + public FakeCpuSetDiagnosticSource(ProcessCpuSetDiagnostic diagnostic) + { + this.diagnostic = diagnostic; + } + + public ProcessCpuSetDiagnostic Read(int processId, string name) => this.diagnostic; + } + private static CpuTopologyModel CreateTwoCoreTopology() { return new CpuTopologyModel diff --git a/Tests/ThreadPilot.Core.Tests/ProcessViewXamlBindingTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessViewXamlBindingTests.cs index a6fba0e..d99aebf 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessViewXamlBindingTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessViewXamlBindingTests.cs @@ -14,6 +14,16 @@ public sealed class ProcessViewXamlBindingTests "Views", "ProcessView.xaml"); + [Fact] + public void CpuSetDiagnostic_IsAReadOnlyDisplayNextToTheMaskPicker() + { + var serialized = File.ReadAllText(ProcessViewPath); + Assert.Contains("ReadCpuSetDiagnosticCommand", serialized, StringComparison.Ordinal); + Assert.Contains("CpuSetDiagnosticText", serialized, StringComparison.Ordinal); + Assert.Contains("CoreMaskPickerHint", serialized, StringComparison.Ordinal); + Assert.Contains("SelectedItem=\"{Binding SelectedCoreMask, Mode=TwoWay}\"", serialized, StringComparison.Ordinal); + } + [Fact] public void LastOperationMessageBinding_IsDisplayOnly() { diff --git a/Tests/ThreadPilot.Core.Tests/RegistryTweakHistoryTests.cs b/Tests/ThreadPilot.Core.Tests/RegistryTweakHistoryTests.cs new file mode 100644 index 0000000..4e9a700 --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/RegistryTweakHistoryTests.cs @@ -0,0 +1,19 @@ +namespace ThreadPilot.Core.Tests; + +using Microsoft.Win32; +using ThreadPilot.Services; + +public sealed class RegistryTweakHistoryTests +{ + [Fact] + public void RestoreRequiresTheSameValueAndRegistryTypeThreadPilotWrote() + { + var original = new RegistryTweakHistory.RegistryValue("1", RegistryValueKind.DWord); + var written = new RegistryTweakHistory.RegistryValue("2", RegistryValueKind.DWord); + Assert.True(RegistryTweakHistory.ShouldRestore(written, original, written)); + Assert.False(RegistryTweakHistory.ShouldRestore(original, original, written)); + Assert.False(RegistryTweakHistory.ShouldRestore(new("2", RegistryValueKind.String), original, written)); + Assert.False(RegistryTweakHistory.ShouldRestore(default, original, written)); + Assert.True(RegistryTweakHistory.ShouldRestore(written, default, written)); + } +} diff --git a/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs b/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs index 8626f20..37756fe 100644 --- a/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs +++ b/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs @@ -52,6 +52,31 @@ public async Task Load_ShowsSettingsAndDecision_ToggleSavesAtOnce() Assert.Equal(["Wow"], saved.GameBoostManualGames); } + [Fact] + public async Task IsolationDescription_OnIntelDoesNotCiteCcd0() + { + var settings = new ApplicationSettingsModel(); + var settingsService = new Mock(); + settingsService.SetupGet(service => service.Settings).Returns(settings); + var session = new Mock(); + session.Setup(service => service.GetDecisionAsync()) + .ReturnsAsync(new GameBoostDecision(GameBoostTopologyKind.IntelHybrid, null, null)); + var localization = new Mock(); + localization.Setup(service => service.GetString(It.IsAny())).Returns((string key) => key); + var viewModel = new SystemTweaksViewModel( + new Mock().Object, + new Mock().Object, + localization.Object, + NullLogger.Instance, + settingsService: settingsService.Object, + gameSessionService: session.Object); + + await viewModel.LoadGameBoostAsync(); + + Assert.Contains("P-cores", viewModel.GameBoostIsolationDescription, StringComparison.Ordinal); + Assert.DoesNotContain("CCD0", viewModel.GameBoostIsolationDescription, StringComparison.Ordinal); + } + [Fact] public void TweaksView_HasGameBoostCard() { @@ -61,13 +86,15 @@ public void TweaksView_HasGameBoostCard() Assert.Contains("{Binding GameBoostIsolation, Mode=TwoWay}", serialized, StringComparison.Ordinal); Assert.Contains("{Binding SaveGameBoostListsCommand}", serialized, StringComparison.Ordinal); Assert.Contains("{Binding GameBoostDecisionText}", serialized, StringComparison.Ordinal); + Assert.Contains("{Binding GameBoostIsolationDescription}", serialized, StringComparison.Ordinal); + Assert.DoesNotContain("GameBoost_Mode_Description", serialized, StringComparison.Ordinal); } [Fact] public void EveryLocale_HasTheGameBoostKeys() { var english = GameBoostKeys("en-US"); - Assert.Equal(19, english.Count); + Assert.Equal(23, english.Count); foreach (var language in new[] { "it-IT", "de-DE", "es-ES", "fr-FR", "ru-RU", "zh-CN" }) { Assert.Equal(english, GameBoostKeys(language)); diff --git a/Tests/ThreadPilot.Core.Tests/ThreadCpuSetDiagnosticTests.cs b/Tests/ThreadPilot.Core.Tests/ThreadCpuSetDiagnosticTests.cs new file mode 100644 index 0000000..cbee449 --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/ThreadCpuSetDiagnosticTests.cs @@ -0,0 +1,201 @@ +namespace ThreadPilot.Core.Tests +{ + using System.Runtime.InteropServices; + using Microsoft.Win32.SafeHandles; + using ThreadPilot.Models; + using ThreadPilot.Platforms.Windows; + using ThreadPilot.ViewModels; + + public sealed partial class ThreadCpuSetDiagnosticTests + { + [Fact] + public void NoOverride_IsNotAnExplicitSelection() + { + var observation = ThreadCpuSetDiagnosticClassifier.Classify( + ThreadCpuSetProbe.NoOverride(11, new ProcessorRef(0, 1, 1), (false, 0, 0)), + CpuSetMapping.Empty); + + Assert.Equal(CpuSetReadKind.Empty, observation.Kind); + Assert.False(observation.HasExplicitOverride); + Assert.Empty(observation.CpuSetIds); + } + + [Fact] + public void Override_IsSeparateFromTheProcessDefault() + { + var mapping = Mapping((0, 1, 1, 10u), (0, 2, 2, 20u)); + var diagnostic = ThreadCpuSetDiagnosticClassifier.Combine( + new CpuSetIdRead(CpuSetReadKind.Read, [10], 0), + new ThreadCpuSetProbeResult(true, null, [ThreadCpuSetProbe.Override(42, [20], new ProcessorRef(0, 2, 2), (false, 0, 0))]), + mapping); + + Assert.Equal([10u], diagnostic.DefaultCpuSetIds); + var thread = Assert.Single(diagnostic.Threads); + Assert.True(thread.HasExplicitOverride); + Assert.Equal([20u], thread.CpuSetIds); + Assert.Equal(0, diagnostic.InheritedCount); + Assert.Equal(1, diagnostic.OverrideCount); + var text = CpuSetDiagnosticFormatter.Format(diagnostic, (_, fallback) => fallback); + Assert.Contains("Process default: CPU 1.", text, StringComparison.Ordinal); + Assert.Contains("TID 42: explicit override, CPU 2.", text, StringComparison.Ordinal); + Assert.Contains("not the CPU a thread is running on", text, StringComparison.Ordinal); + } + + [Fact] + public void TerminatedThread_IsReportedAndDoesNotCountAsInherited() + { + var diagnostic = Combine(ThreadCpuSetProbe.OpenFailed(8, 87)); + + Assert.Equal(CpuSetReadKind.Terminated, Assert.Single(diagnostic.Threads).Kind); + Assert.Equal(1, diagnostic.TerminatedCount); + Assert.Equal(0, diagnostic.InheritedCount); + Assert.True(diagnostic.IsPartial); + Assert.Contains("thread ended during the read", CpuSetDiagnosticFormatter.Format(diagnostic, (_, fallback) => fallback), StringComparison.Ordinal); + } + + [Fact] + public void AccessDenied_IsShownAsDeniedNotAsNoOverride() + { + var diagnostic = Combine(ThreadCpuSetProbe.OpenFailed(9, 5), ThreadCpuSetProbe.NoOverride(10, null, (false, 0, 0))); + + Assert.Equal(1, diagnostic.DeniedCount); + Assert.Equal(1, diagnostic.InheritedCount); + Assert.True(diagnostic.IsPartial); + var text = CpuSetDiagnosticFormatter.Format(diagnostic, (_, fallback) => fallback); + Assert.Contains("TID 9: read denied.", text, StringComparison.Ordinal); + Assert.Contains("Read is partial or denied.", text, StringComparison.Ordinal); + Assert.DoesNotContain("TID 9: explicit override", text, StringComparison.Ordinal); + } + + [Fact] + public void UnmappedCpuSetId_IsAPartialRead() + { + var mapping = Mapping((0, 0, 0, 10u)); + var observation = ThreadCpuSetDiagnosticClassifier.Classify( + ThreadCpuSetProbe.Override(4, [10, 999], null, (false, 0, 0)), + mapping); + + Assert.Equal(CpuSetReadKind.Partial, observation.Kind); + Assert.True(observation.HasExplicitOverride); + Assert.True(observation.MappingIncomplete); + Assert.Equal(new ProcessorRef(0, 0, 0), Assert.Single(observation.Processors)); + } + + [Fact] + public void MultipleGroups_AreNotFlattenedIntoOneMask() + { + var mapping = CpuSetMapping.Create(new Dictionary + { + [new ProcessorRef(0, 1, 1)] = 10, + [new ProcessorRef(1, 0, 64)] = 20, + }); + var observation = ThreadCpuSetDiagnosticClassifier.Classify( + ThreadCpuSetProbe.Override(7, [20, 10], null, (true, 0, 0x2)), + mapping); + + Assert.Equal([(ushort)0, (ushort)1], observation.Processors.Select(processor => processor.Group)); + Assert.False(observation.AffinityConflictsWithAssignment); + var text = CpuSetDiagnosticFormatter.FormatProcessors(observation.Processors); + Assert.Equal("G0:CPU 1, G1:CPU 0", text); + } + + [Fact] + public void RigidAffinity_IsDistinctFromTheCpuSetAssignment() + { + var mapping = Mapping((0, 2, 2, 20u)); + var observation = ThreadCpuSetDiagnosticClassifier.Classify( + ThreadCpuSetProbe.Override(5, [20], null, (true, 0, 0x1)), + mapping); + + Assert.True(observation.AffinityConflictsWithAssignment); + Assert.Contains( + "Hard affinity does not include this assignment.", + CpuSetDiagnosticFormatter.Format( + ThreadCpuSetDiagnosticClassifier.Combine( + new CpuSetIdRead(CpuSetReadKind.Empty, [], 0), + new ThreadCpuSetProbeResult(true, null, [ThreadCpuSetProbe.Override(5, [20], null, (true, 0, 0x1))]), + mapping), + (_, fallback) => fallback), + StringComparison.Ordinal); + } + + [Fact] + public void LiveProcess_NoOverrideThenOverrideThenTerminatedThread() + { + using var handler = new ProcessCpuSetHandler((uint)Environment.ProcessId, "ThreadPilot.Tests"); + var cpuSetIds = handler.Mapping.CpuSetIds; + Assert.NotEmpty(cpuSetIds); + var cpuSetId = cpuSetIds[0]; + + using var started = new ManualResetEventSlim(false); + using var release = new ManualResetEventSlim(false); + var threadId = 0; + var thread = new Thread(() => + { + threadId = (int)Native.GetCurrentThreadId(); + started.Set(); + release.Wait(); + }); + thread.Start(); + Assert.True(started.Wait(TimeSpan.FromSeconds(5))); + + try + { + var before = ProcessThreadCpuAssignmentHandler.ProbeThread(threadId); + Assert.False(before.RequiredCount > 0 && before.Ids.Count > 0, "The worker started with an unexpected CPU Set override."); + + using (var handle = Native.OpenThread(0x0400 | 0x0800, false, (uint)threadId)) + { + Assert.False(handle.IsInvalid); + Assert.True(Native.SetThreadSelectedCpuSets(handle, [cpuSetId], 1)); + var overridden = ProcessThreadCpuAssignmentHandler.ProbeThread(threadId); + Assert.Equal([cpuSetId], overridden.Ids); + Assert.True(Native.SetThreadSelectedCpuSets(handle, null, 0)); + } + + var cleared = ProcessThreadCpuAssignmentHandler.ProbeThread(threadId); + Assert.Equal(0u, cleared.RequiredCount); + Assert.Empty(cleared.Ids); + } + finally + { + release.Set(); + Assert.True(thread.Join(TimeSpan.FromSeconds(5))); + } + + // A just-exited thread object can still be opened until Windows drops it, and the id can be reused. + // ERROR_INVALID_PARAMETER from OpenThread is the terminated signal the reader records; a tid that + // was never a thread produces that error without the race. + var ended = ProcessThreadCpuAssignmentHandler.ProbeThread(int.MaxValue); + Assert.False(ended.Opened); + Assert.Equal(87, ended.OpenError); + Assert.Equal( + CpuSetReadKind.Terminated, + ThreadCpuSetDiagnosticClassifier.Classify(ended, handler.Mapping).Kind); + } + + private static ProcessCpuSetDiagnostic Combine(params ThreadCpuSetProbe[] probes) => + ThreadCpuSetDiagnosticClassifier.Combine( + new CpuSetIdRead(CpuSetReadKind.Empty, [], 0), + new ThreadCpuSetProbeResult(true, null, probes), + CpuSetMapping.Empty); + + private static CpuSetMapping Mapping(params (ushort Group, byte Number, int Global, uint Id)[] items) => + CpuSetMapping.Create(items.ToDictionary( + item => new ProcessorRef(item.Group, item.Number, item.Global), + item => item.Id)); + + private static partial class Native + { + [LibraryImport("kernel32.dll")] + internal static partial uint GetCurrentThreadId(); + + [LibraryImport("kernel32.dll", SetLastError = true)] + internal static partial SafeWaitHandle OpenThread(uint desiredAccess, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, uint threadId); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool SetThreadSelectedCpuSets(SafeWaitHandle thread, uint[]? cpuSetIds, uint cpuSetIdCount); + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj b/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj index c24baec..4747442 100644 --- a/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj +++ b/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj @@ -4,6 +4,7 @@ net8.0-windows10.0.22000.0 enable enable + true false cobertura diff --git a/Tests/ThreadPilot.Core.Tests/UninstallCleanupTests.cs b/Tests/ThreadPilot.Core.Tests/UninstallCleanupTests.cs new file mode 100644 index 0000000..6d3b70e --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/UninstallCleanupTests.cs @@ -0,0 +1,31 @@ +namespace ThreadPilot.Core.Tests; + +using System.IO; +using System.Text; +using ThreadPilot.Services; + +public sealed class UninstallCleanupTests +{ + [Theory] + [InlineData("""{"ProcessName":"test","Priority":32,"ProcessorAffinity":7}""", true)] + [InlineData("""{"Settings":{},"Rules":[],"CoreMasks":[]}""", false)] + [InlineData("{broken", false)] + public void CleanupDistinguishesProcessProfilesFromExports(string json, bool expected) + { + using var stream = new MemoryStream(Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(json)).ToArray()); + Assert.Equal(expected, UninstallCleanup.IsProcessProfile(stream)); + } + + [Theory] + [InlineData("SETTINGS.JSON", true)] + [InlineData("settings.json.bak", true)] + [InlineData(".settings.json.002b3091041f4e929d7d4b35f4b97320.tmp", true)] + [InlineData(".settings.json.random.tmp", false)] + [InlineData(".export.json.002b3091041f4e929d7d4b35f4b97320.tmp", false)] + [InlineData("device_tweak_backups.json.bak", false)] + public void CleanupRecognizesOnlyTheDataFileAndItsAtomicArtifacts(string name, bool expected) + { + Assert.Equal(expected, UninstallCleanup.MatchesDataArtifact(name, + candidate => candidate.Equals("settings.json", StringComparison.OrdinalIgnoreCase))); + } +} diff --git a/Tests/ThreadPilot.Core.Tests/UpdateServiceTests.cs b/Tests/ThreadPilot.Core.Tests/UpdateServiceTests.cs index 9b7dffe..e4c5ca5 100644 --- a/Tests/ThreadPilot.Core.Tests/UpdateServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/UpdateServiceTests.cs @@ -78,6 +78,7 @@ public async Task CheckForUpdatesAsync_StartupChecksOnEveryLaunch() var result = await harness.Service.CheckForUpdatesAsync(new UpdateCheckRequest(UpdateCheckTrigger.Startup)); Assert.Equal(UpdateCheckStatus.UpdateAvailable, result.Status); + Assert.Same(result.Release, harness.Service.AvailableRelease); Assert.True(harness.ReleaseClient.RequestedReleases); } diff --git a/ViewModels/CpuSetDiagnosticText.cs b/ViewModels/CpuSetDiagnosticText.cs new file mode 100644 index 0000000..aa14d09 --- /dev/null +++ b/ViewModels/CpuSetDiagnosticText.cs @@ -0,0 +1,156 @@ +namespace ThreadPilot.ViewModels +{ + using System.Globalization; + using ThreadPilot.Models; + using ThreadPilot.Platforms.Windows; + + internal static class CpuSetDiagnosticFormatter + { + public static string Format(ProcessCpuSetDiagnostic diagnostic, Func text) + { + ArgumentNullException.ThrowIfNull(diagnostic); + ArgumentNullException.ThrowIfNull(text); + + var lines = new List + { + FormatDefault(diagnostic, text), + string.Format( + CultureInfo.CurrentCulture, + text( + "ProcessView_CpuSetDiag_Summary", + "{0} threads inherit the process default; {1} have an explicit override; {2} reads were denied; {3} threads ended during the read; {4} reads were partial."), + diagnostic.InheritedCount, + diagnostic.OverrideCount, + diagnostic.DeniedCount, + diagnostic.TerminatedCount, + diagnostic.PartialCount), + }; + + if (!diagnostic.ThreadsEnumerated) + { + lines.Add(text( + "ProcessView_CpuSetDiag_ThreadsUnlisted", + "The thread list could not be read. The summary above does not include those threads.")); + } + + if (diagnostic.IsPartial) + { + lines.Add(text( + "ProcessView_CpuSetDiag_PartialBanner", + "Read is partial or denied. Missing threads are not the same as threads that inherit the process default.")); + } + + lines.Add(text( + "ProcessView_CpuSetDiag_NotRunningCpu", + "These are assignments read from Windows, not the CPU a thread is running on.")); + + foreach (var thread in diagnostic.Threads.Where(item => item.HasExplicitOverride || item.Kind is CpuSetReadKind.AccessDenied or CpuSetReadKind.Terminated or CpuSetReadKind.Unavailable or CpuSetReadKind.Partial).Take(12)) + { + lines.Add(FormatThread(thread, text)); + } + + var listed = diagnostic.Threads.Count(item => item.HasExplicitOverride || item.Kind is CpuSetReadKind.AccessDenied or CpuSetReadKind.Terminated or CpuSetReadKind.Unavailable or CpuSetReadKind.Partial); + if (listed > 12) + { + lines.Add(string.Format( + CultureInfo.CurrentCulture, + text("ProcessView_CpuSetDiag_More", "And {0} more threads were not listed."), + listed - 12)); + } + + return string.Join(Environment.NewLine, lines); + } + + public static string FormatProcessors(IReadOnlyList processors) + { + if (processors.Count == 0) + { + return string.Empty; + } + + var showGroup = processors.Any(processor => processor.Group != 0); + return string.Join(", ", processors.Select(processor => showGroup + ? FormattableString.Invariant($"G{processor.Group}:CPU {processor.LogicalProcessorNumber}") + : FormattableString.Invariant($"CPU {processor.LogicalProcessorNumber}"))); + } + + private static string FormatDefault(ProcessCpuSetDiagnostic diagnostic, Func text) + { + return diagnostic.DefaultKind switch + { + CpuSetReadKind.Empty => text( + "ProcessView_CpuSetDiag_DefaultNone", + "Process default: none. Threads without an override are placed by Windows."), + CpuSetReadKind.AccessDenied => text( + "ProcessView_CpuSetDiag_DefaultDenied", + "Process default: read denied."), + CpuSetReadKind.Unavailable => text( + "ProcessView_CpuSetDiag_DefaultUnavailable", + "Process default: could not be read."), + _ => string.Format( + CultureInfo.CurrentCulture, + diagnostic.DefaultMappingIncomplete + ? text("ProcessView_CpuSetDiag_DefaultPartial", "Process default: partial read, {0}.") + : text("ProcessView_CpuSetDiag_DefaultRead", "Process default: {0}."), + DescribeIds(diagnostic.DefaultCpuSetIds, diagnostic.DefaultProcessors)), + }; + } + + private static string FormatThread(ThreadCpuSetObservation thread, Func text) + { + if (thread.Kind == CpuSetReadKind.AccessDenied) + { + return string.Format(CultureInfo.CurrentCulture, text("ProcessView_CpuSetDiag_ThreadDenied", "TID {0}: read denied."), thread.ThreadId); + } + + if (thread.Kind == CpuSetReadKind.Terminated) + { + return string.Format(CultureInfo.CurrentCulture, text("ProcessView_CpuSetDiag_ThreadEnded", "TID {0}: thread ended during the read."), thread.ThreadId); + } + + if (!thread.HasExplicitOverride) + { + return string.Format(CultureInfo.CurrentCulture, text("ProcessView_CpuSetDiag_ThreadUnread", "TID {0}: could not be read."), thread.ThreadId); + } + + var assignment = DescribeIds(thread.CpuSetIds, thread.Processors); + var line = string.Format( + CultureInfo.CurrentCulture, + thread.MappingIncomplete + ? text("ProcessView_CpuSetDiag_OverridePartial", "TID {0}: explicit override, partial read, {1}.") + : text("ProcessView_CpuSetDiag_Override", "TID {0}: explicit override, {1}."), + thread.ThreadId, + assignment); + if (thread.IdealProcessor is ProcessorRef ideal) + { + line += " " + string.Format( + CultureInfo.CurrentCulture, + text("ProcessView_CpuSetDiag_Ideal", "Ideal CPU {0} (not the CPU it is running on)."), + FormatProcessors([ideal])); + } + + if (thread.AffinityConflictsWithAssignment) + { + line += " " + text( + "ProcessView_CpuSetDiag_RigidAffinity", + "Hard affinity does not include this assignment."); + } + + return line; + } + + private static string DescribeIds(IReadOnlyList ids, IReadOnlyList processors) + { + var formatted = FormatProcessors(processors); + var unmapped = ids.Distinct().Count() - processors.Count; + if (formatted.Length == 0) + { + return ids.Count == 0 ? "none" : "CPU set ids " + string.Join(", ", ids.Distinct().OrderBy(id => id)); + } + + return unmapped > 0 + ? formatted + ", " + unmapped.ToString(CultureInfo.CurrentCulture) + " unmapped" + : formatted; + } + } +} diff --git a/ViewModels/ProcessViewModel.Behaviors.partial.cs b/ViewModels/ProcessViewModel.Behaviors.partial.cs index 21b5571..65904b3 100644 --- a/ViewModels/ProcessViewModel.Behaviors.partial.cs +++ b/ViewModels/ProcessViewModel.Behaviors.partial.cs @@ -132,6 +132,7 @@ await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => partial void OnSelectedProcessChanged(ProcessModel? value) { + this.CpuSetDiagnosticText = string.Empty; this.SetCpuAssignmentMode( this.settingsService?.Settings.DefaultCpuAssignmentMode ?? CpuAssignmentMode.Automatic, overriddenByRule: false); @@ -537,6 +538,7 @@ private void UpdateCoreSelections( } this.UpdateAffinityDisplayState(); + this.SyncCoreMaskPickerToDisplayedCores(); } private long CalculateAffinityMask() @@ -1193,10 +1195,81 @@ private void CreateCustomMask() partial void OnSelectedCoreMaskChanged(CoreMask? oldValue, CoreMask? newValue) { - if (newValue == null) + if (this.suppressCoreMaskPickerSync || newValue == null) + { return; + } + + this.UpdateCoreSelectionsFromMask(newValue); + } + + private void SyncCoreMaskPickerToDisplayedCores() + { + if (this.HasPendingAffinityEdits || this.CpuCores.Count == 0) + { + return; + } + + var match = this.FindMaskMatchingDisplayedCores(); + this.SetDisplayedCoreMask(match); + var cpuSetsAreActive = this.currentSoftCpuAssignmentText != null + && this.SelectedCpuAssignmentMode == CpuAssignmentMode.CpuSets; + this.CoreMaskPickerHint = match == null && cpuSetsAreActive && this.SelectedProcess != null + ? this.UiText( + "ProcessView_CpuSetsNotAMask", + "CPU Sets are active. This is not the All Cores mask.") + : string.Empty; + } - UpdateCoreSelectionsFromMask(newValue); + private CoreMask? FindMaskMatchingDisplayedCores() + { + if (this.SelectedCoreMask != null && this.MaskMatchesDisplayedCores(this.SelectedCoreMask)) + { + return this.SelectedCoreMask; + } + + return this.AvailableCoreMasks.FirstOrDefault(this.MaskMatchesDisplayedCores); + } + + private bool MaskMatchesDisplayedCores(CoreMask mask) + { + if (mask.BoolMask.Count == 0) + { + return false; + } + + foreach (var core in this.CpuCores) + { + if (core.LogicalCoreId < 0 || core.LogicalCoreId >= mask.BoolMask.Count) + { + return false; + } + + if (core.IsSelected != mask.BoolMask[core.LogicalCoreId]) + { + return false; + } + } + + return true; + } + + private void SetDisplayedCoreMask(CoreMask? mask) + { + if (ReferenceEquals(this.SelectedCoreMask, mask)) + { + return; + } + + this.suppressCoreMaskPickerSync = true; + try + { + this.SelectedCoreMask = mask; + } + finally + { + this.suppressCoreMaskPickerSync = false; + } } private void UpdateCoreSelectionsFromMask(CoreMask mask) @@ -2269,6 +2342,7 @@ private void ClearProcessSelection() this.HasPendingAffinityEdits = false; this.currentSoftCpuAssignmentText = null; + this.CoreMaskPickerHint = string.Empty; this.UpdateAffinityDisplayState(); // Reset power plan to current system default diff --git a/ViewModels/ProcessViewModel.CpuSetDiagnostic.cs b/ViewModels/ProcessViewModel.CpuSetDiagnostic.cs new file mode 100644 index 0000000..a5416f4 --- /dev/null +++ b/ViewModels/ProcessViewModel.CpuSetDiagnostic.cs @@ -0,0 +1,46 @@ +namespace ThreadPilot.ViewModels +{ + using CommunityToolkit.Mvvm.Input; + using Microsoft.Extensions.Logging; + using ThreadPilot.Platforms.Windows; + + public partial class ProcessViewModel + { + internal ICpuSetDiagnosticSource CpuSetDiagnosticSource { get; set; } = ProcessCpuSetDiagnosticReader.Instance; + + [RelayCommand] + private async Task ReadCpuSetDiagnosticAsync() + { + var process = this.SelectedProcess; + if (process == null) + { + this.CpuSetDiagnosticText = this.UiText( + "ProcessView_CpuSetDiag_NoProcess", + "Select a process to read its CPU Sets. The read does not change the process."); + return; + } + + var source = this.CpuSetDiagnosticSource; + try + { + var diagnostic = await Task.Run(() => source.Read(process.ProcessId, process.Name)).ConfigureAwait(true); + if (!ReferenceEquals(this.SelectedProcess, process)) + { + return; + } + + this.CpuSetDiagnosticText = CpuSetDiagnosticFormatter.Format(diagnostic, this.UiText); + } + catch (Exception ex) + { + this.Logger.LogWarning(ex, "CPU Set diagnostic failed for {ProcessName}", process.Name); + if (ReferenceEquals(this.SelectedProcess, process)) + { + this.CpuSetDiagnosticText = this.UiText( + "ProcessView_CpuSetDiag_Failed", + "Could not read CPU Sets."); + } + } + } + } +} diff --git a/ViewModels/ProcessViewModel.cs b/ViewModels/ProcessViewModel.cs index 65be7fa..bb5e051 100644 --- a/ViewModels/ProcessViewModel.cs +++ b/ViewModels/ProcessViewModel.cs @@ -53,6 +53,7 @@ public partial class ProcessViewModel : BaseViewModel private bool isApplyingFilter; private bool filterRefreshPending; private bool suppressCoreSelectionEvents; + private bool suppressCoreMaskPickerSync; private bool suppressCpuAssignmentModeChanges; private bool cpuAssignmentModeOverriddenByRule; private string? currentSoftCpuAssignmentText; @@ -105,6 +106,12 @@ public partial class ProcessViewModel : BaseViewModel [ObservableProperty] private string affinityEditStateText = "Select a process to view its current Windows affinity."; + [ObservableProperty] + private string coreMaskPickerHint = string.Empty; + + [ObservableProperty] + private string cpuSetDiagnosticText = string.Empty; + [ObservableProperty] private bool isTopologyDetectionSuccessful = false; diff --git a/ViewModels/SettingsViewModel.cs b/ViewModels/SettingsViewModel.cs index 3d3fd0a..2b0e50a 100644 --- a/ViewModels/SettingsViewModel.cs +++ b/ViewModels/SettingsViewModel.cs @@ -832,6 +832,18 @@ private async Task RefreshPowerPlansAsync() return result.Status == UpdateInstallStatus.Started ? null : result.Message; } + internal void SetAvailableUpdate(UpdateReleaseInfo? release) + { + this.availableUpdate = release; + this.IsUpdateAvailable = release != null; + if (release != null) + { + this.LatestUpdateVersion = $"v{release.Version}"; + } + + this.UpdateLastCheckedText(); + } + private async Task CheckUpdatesAsync() { try @@ -853,9 +865,7 @@ await this.notificationService.ShowErrorNotificationAsync( if (result.IsUpdateAvailable && result.Release != null) { - this.availableUpdate = result.Release; - this.LatestUpdateVersion = $"v{result.Release.Version}"; - this.IsUpdateAvailable = true; + this.SetAvailableUpdate(result.Release); this.StatusMessage = this.GetLocalizedString("Settings_StatusNewVersionFormat", "New version available: {0}", result.Release.Version); await this.notificationService.ShowNotificationAsync( "Update available", diff --git a/ViewModels/SystemTweaksViewModel.GameBoost.cs b/ViewModels/SystemTweaksViewModel.GameBoost.cs index 54853e9..30c29ea 100644 --- a/ViewModels/SystemTweaksViewModel.GameBoost.cs +++ b/ViewModels/SystemTweaksViewModel.GameBoost.cs @@ -37,6 +37,10 @@ public partial class SystemTweaksViewModel [ObservableProperty] private string gameBoostDecisionText = string.Empty; + [ObservableProperty] + private string gameBoostIsolationDescription = + "Isolation also moves more secondary apps (launcher helpers, media players, office apps) and puts the selected background apps in efficiency mode (EcoQoS). On this CPU Windows still places the game."; + [ObservableProperty] private string gameBoostManualGamesText = string.Empty; @@ -152,6 +156,21 @@ private async Task RefreshGameBoostDecisionTextAsync() var decision = await this.gameSessionService.GetDecisionAsync(); var game = decision.GameSelection?.GlobalLogicalProcessorIndexes.Count ?? 0; var background = decision.BackgroundSelection?.GlobalLogicalProcessorIndexes.Count ?? 0; + var isolation = decision.Kind switch + { + GameBoostTopologyKind.IntelHybrid => this.Localize( + "GameBoost_Isolation_Intel", + "Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and keeps the game on the P-cores."), + GameBoostTopologyKind.AmdSymmetricMultiL3 => this.Localize( + "GameBoost_Isolation_AmdEqual", + "Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and, on CPUs with two equal CCDs, keeps the game on CCD0."), + GameBoostTopologyKind.AmdAsymmetricCache => this.Localize( + "GameBoost_Isolation_AmdVCache", + "Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and keeps the game on the CCD with 3D V-Cache."), + _ => this.Localize( + "GameBoost_Isolation_Generic", + "Isolation also moves more secondary apps (launcher helpers, media players, office apps) and puts the selected background apps in efficiency mode (EcoQoS). On this CPU Windows still places the game."), + }; var text = decision.Kind switch { GameBoostTopologyKind.AmdAsymmetricCache => this.Localize( @@ -178,7 +197,11 @@ private async Task RefreshGameBoostDecisionTextAsync() "On this CPU Windows decides the cores; Game Boost only applies the optional priority."), }; - await InvokeOnUiAsync(() => this.GameBoostDecisionText = text); + await InvokeOnUiAsync(() => + { + this.GameBoostDecisionText = text; + this.GameBoostIsolationDescription = isolation; + }); } private static List SplitLines(string text) => diff --git a/Views/ProcessView.xaml b/Views/ProcessView.xaml index 93e068b..6081971 100644 --- a/Views/ProcessView.xaml +++ b/Views/ProcessView.xaml @@ -611,6 +611,15 @@ DisplayMemberPath="Name" ToolTip="{DynamicResource ProcessView_RowMaskTooltip}" AutomationProperties.Name="{DynamicResource ProcessView_PendingCoreMask}"/> +