diff --git a/App.xaml.cs b/App.xaml.cs
index 9603d70..434bc32 100644
--- a/App.xaml.cs
+++ b/App.xaml.cs
@@ -169,7 +169,7 @@ protected override void OnStartup(StartupEventArgs e)
if (!createdNew)
{
- System.Windows.MessageBox.Show(
+ ThreadPilot.Helpers.AppMessageBox.Show(
"ThreadPilot is already running.",
"Instance already open",
MessageBoxButton.OK,
@@ -315,7 +315,7 @@ protected override void OnStartup(StartupEventArgs e)
// Show error message and exit gracefully
var errorMessage = $"ThreadPilot failed to start:\n\n{ex.Message}\n\nStack Trace:\n{ex.StackTrace}";
- System.Windows.MessageBox.Show(errorMessage, "ThreadPilot Startup Error",
+ ThreadPilot.Helpers.AppMessageBox.Show(errorMessage, "ThreadPilot Startup Error",
MessageBoxButton.OK, MessageBoxImage.Error);
// Exit the application
@@ -475,7 +475,7 @@ private void ShowElevationRequiredMessage()
return;
}
- System.Windows.MessageBox.Show(
+ ThreadPilot.Helpers.AppMessageBox.Show(
"ThreadPilot requires administrator privileges to start.\n\n" +
"Please relaunch the application and approve the UAC prompt.\n\n" +
"This instance will now close.",
@@ -490,7 +490,7 @@ private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
this.ReportUnhandledException(exception, "AppDomain.CurrentDomain.UnhandledException", LogLevel.Critical);
var errorMessage = $"A critical error occurred:\n\n{exception?.Message}\n\nThe application will now exit.";
- System.Windows.MessageBox.Show(errorMessage, "Critical Error",
+ ThreadPilot.Helpers.AppMessageBox.Show(errorMessage, "Critical Error",
MessageBoxButton.OK, MessageBoxImage.Error);
}
@@ -514,7 +514,7 @@ private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledEx
this.lastUiExceptionDialogUtc = DateTime.UtcNow;
var errorMessage = $"An error occurred in the user interface:\n\n{e.Exception.Message}\n\nDo you want to continue?";
- var result = System.Windows.MessageBox.Show(errorMessage, "UI Error",
+ var result = ThreadPilot.Helpers.AppMessageBox.Show(errorMessage, "UI Error",
MessageBoxButton.YesNo, MessageBoxImage.Error);
if (result == MessageBoxResult.Yes)
diff --git a/Helpers/AppMessageBox.cs b/Helpers/AppMessageBox.cs
new file mode 100644
index 0000000..74a4a53
--- /dev/null
+++ b/Helpers/AppMessageBox.cs
@@ -0,0 +1,114 @@
+namespace ThreadPilot.Helpers
+{
+ using System.Windows;
+ using System.Windows.Controls;
+ using System.Windows.Media;
+
+ ///
+ /// Drop-in replacement for System.Windows.MessageBox that uses the app theme and localized buttons.
+ /// Falls back to the native box when the app resources are not loaded (startup failures, cleanup mode).
+ ///
+ public static class AppMessageBox
+ {
+ public static MessageBoxResult Show(string text, string? caption = null, MessageBoxButton button = MessageBoxButton.OK,
+ MessageBoxImage icon = MessageBoxImage.None, MessageBoxResult defaultResult = MessageBoxResult.None) =>
+ Show(null, text, caption, button, icon, defaultResult);
+
+ public static MessageBoxResult Show(Window? owner, string text, string? caption = null, MessageBoxButton button = MessageBoxButton.OK,
+ MessageBoxImage icon = MessageBoxImage.None, MessageBoxResult defaultResult = MessageBoxResult.None)
+ {
+ var app = Application.Current;
+ if (app == null || app.TryFindResource("AppBackgroundBrush") is not SolidColorBrush background)
+ {
+ return owner == null
+ ? MessageBox.Show(text, caption ?? string.Empty, button, icon, defaultResult)
+ : MessageBox.Show(owner, text, caption ?? string.Empty, button, icon, defaultResult);
+ }
+
+ if (!app.Dispatcher.CheckAccess())
+ {
+ return app.Dispatcher.Invoke(() => Show(owner, text, caption, button, icon, defaultResult));
+ }
+
+ owner ??= app.MainWindow is { IsVisible: true } main ? main : null;
+ var cancelResult = button switch
+ {
+ MessageBoxButton.OK => MessageBoxResult.OK,
+ MessageBoxButton.YesNo => MessageBoxResult.No,
+ _ => MessageBoxResult.Cancel,
+ };
+ var result = cancelResult;
+ var dialog = new Window
+ {
+ Title = caption ?? "ThreadPilot",
+ Owner = owner,
+ Width = 460,
+ SizeToContent = SizeToContent.Height,
+ ResizeMode = ResizeMode.NoResize,
+ ShowInTaskbar = owner == null,
+ WindowStartupLocation = owner == null ? WindowStartupLocation.CenterScreen : WindowStartupLocation.CenterOwner,
+ };
+
+ var buttons = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 20, 0, 0) };
+ var results = button switch
+ {
+ MessageBoxButton.OKCancel => new[] { MessageBoxResult.OK, MessageBoxResult.Cancel },
+ MessageBoxButton.YesNo => new[] { MessageBoxResult.Yes, MessageBoxResult.No },
+ MessageBoxButton.YesNoCancel => new[] { MessageBoxResult.Yes, MessageBoxResult.No, MessageBoxResult.Cancel },
+ _ => new[] { MessageBoxResult.OK },
+ };
+ var focus = defaultResult != MessageBoxResult.None && Array.IndexOf(results, defaultResult) >= 0 ? defaultResult : results[0];
+ foreach (var value in results)
+ {
+ var choice = new Button
+ {
+ Content = app.TryFindResource($"Dialog_{value}") as string ?? value.ToString(),
+ MinWidth = 88,
+ Padding = new Thickness(16, 8, 16, 8),
+ Margin = new Thickness(10, 0, 0, 0),
+ IsDefault = value == focus,
+ IsCancel = value == cancelResult,
+ };
+ choice.Click += (_, _) =>
+ {
+ result = value;
+ dialog.Close();
+ };
+ buttons.Children.Add(choice);
+ }
+
+ var body = new DockPanel { Margin = new Thickness(24) };
+ DockPanel.SetDock(buttons, Dock.Bottom);
+ body.Children.Add(buttons);
+ var (glyph, brushKey) = icon switch
+ {
+ MessageBoxImage.Error => ("", "ErrorTextBrush"),
+ MessageBoxImage.Warning => ("", "WarningTextBrush"),
+ MessageBoxImage.Question => ("", "TextSecondaryBrush"),
+ MessageBoxImage.Information => ("", "TextSecondaryBrush"),
+ _ => (string.Empty, string.Empty),
+ };
+ if (glyph.Length > 0)
+ {
+ var image = new TextBlock
+ {
+ Text = glyph,
+ FontFamily = new FontFamily("Segoe Fluent Icons, Segoe MDL2 Assets"),
+ FontSize = 28,
+ Margin = new Thickness(0, 0, 16, 0),
+ VerticalAlignment = VerticalAlignment.Top,
+ };
+ image.SetResourceReference(TextBlock.ForegroundProperty, brushKey);
+ DockPanel.SetDock(image, Dock.Left);
+ body.Children.Add(image);
+ }
+
+ body.Children.Add(new TextBlock { Text = text, TextWrapping = TextWrapping.Wrap });
+ dialog.Content = body;
+ var color = background.Color;
+ dialog.SourceInitialized += (_, _) => DwmHelper.ApplyWindowCaptionTheme(dialog, color.R + color.G + color.B < 384);
+ dialog.ShowDialog();
+ return result;
+ }
+ }
+}
diff --git a/Helpers/NavigationBehavior.cs b/Helpers/NavigationBehavior.cs
index 42337c1..a13853d 100644
--- a/Helpers/NavigationBehavior.cs
+++ b/Helpers/NavigationBehavior.cs
@@ -44,7 +44,7 @@ public static async Task EnsureCanNavigateAsync(
var result = showUnsavedSettingsPromptAsync != null
? await showUnsavedSettingsPromptAsync()
- : MessageBox.Show(
+ : ThreadPilot.Helpers.AppMessageBox.Show(
"You have unsaved changes in Settings.\n\nChoose an action:\n- Yes: Save changes\n- No: Discard changes\n- Cancel: Stay on current tab",
"Unsaved Settings",
MessageBoxButton.YesNoCancel,
diff --git a/Locales/de-DE.xaml b/Locales/de-DE.xaml
index 65da21f..4d2039f 100644
--- a/Locales/de-DE.xaml
+++ b/Locales/de-DE.xaml
@@ -561,6 +561,10 @@
Die Automatisierungsüberwachung bleibt auch nach einem Neustart deaktiviert.
Automatisierung für Energiepläne, CPU-Masken, Prioritäten und gespeicherte Regeln läuft erst nach erneutem Aktivieren wieder.
Abbrechen
+ OK
+ Abbrechen
+ Ja
+ Nein
Überwachung deaktivieren
Verwerfen
Speichern
@@ -594,6 +598,8 @@
Öffnet Windows-Sicherheit. Das Deaktivieren verringert die Systemsicherheit und kann einen Neustart erfordern.
Hardwarebeschleunigte GPU-Planung
Öffnet die Windows-Grafikeinstellungen zur Prüfung von HAGS.
+ Hintergrundaufnahme
+ Öffnet die Windows-Aufnahmeeinstellungen, um die Hintergrundaufnahme für diesen Benutzer zu ändern.
Optimierungen für Fensterspiele
Öffnet die Windows-Grafikeinstellungen für Flip-Model-Optimierungen.
Selektives USB-Energiesparen
@@ -807,4 +813,7 @@
Alt
Umschalt
Win
+ Spieleinstellungen prüfen
+ Zwei Aufzeichnungen vergleichen
+ Bearbeiteten Bericht speichern…
diff --git a/Locales/en-US.xaml b/Locales/en-US.xaml
index 71a7809..00b51ef 100644
--- a/Locales/en-US.xaml
+++ b/Locales/en-US.xaml
@@ -561,6 +561,10 @@
Automation monitoring will remain disabled after restart.
Process power-plan, CPU mask, priority, and saved-rule automation will not run until you enable it again.
Cancel
+ OK
+ Cancel
+ Yes
+ No
Disable monitoring
Discard
Save
@@ -594,6 +598,8 @@
Opens Windows Security. Disabling this protection reduces system security and may require a restart.
Hardware-accelerated GPU scheduling
Opens Windows graphics settings to let you review HAGS.
+ Background recording
+ Open Windows Captures to change background recording for this user.
Optimizations for windowed games
Opens Windows graphics settings to manage Flip Model optimizations.
USB Selective Suspend
@@ -807,4 +813,7 @@
Alt
Shift
Win
+ Inspect game settings
+ Compare two captures
+ Save edited report…
diff --git a/Locales/es-ES.xaml b/Locales/es-ES.xaml
index aba0e77..62818a2 100644
--- a/Locales/es-ES.xaml
+++ b/Locales/es-ES.xaml
@@ -561,6 +561,10 @@
La supervisión de automatización seguirá deshabilitada después de reiniciar.
La automatización de planes de energía, máscaras de CPU, prioridades y reglas guardadas no se ejecutará hasta volver a habilitarla.
Cancelar
+ Aceptar
+ Cancelar
+ Sí
+ No
Deshabilitar supervisión
Descartar
Guardar
@@ -594,6 +598,8 @@
Abre Seguridad de Windows. Desactivarla reduce la seguridad y puede requerir reiniciar.
Programación de GPU acelerada por hardware
Abre la configuración gráfica de Windows para revisar HAGS.
+ Grabación en segundo plano
+ Abre Capturas de Windows para cambiar la grabación en segundo plano de este usuario.
Optimizaciones para juegos en ventana
Abre la configuración gráfica de Windows para administrar Flip Model.
Suspensión selectiva USB
@@ -807,4 +813,7 @@
Alt
Mayús
Win
+ Revisar ajustes del juego
+ Comparar dos capturas
+ Guardar informe editado…
diff --git a/Locales/fr-FR.xaml b/Locales/fr-FR.xaml
index 1802a69..2074d66 100644
--- a/Locales/fr-FR.xaml
+++ b/Locales/fr-FR.xaml
@@ -561,6 +561,10 @@
La surveillance de l'automatisation restera désactivée après le redémarrage.
L'automatisation des plans d'alimentation, masques CPU, priorités et règles enregistrées ne fonctionnera pas jusqu'à sa réactivation.
Annuler
+ OK
+ Annuler
+ Oui
+ Non
Désactiver la surveillance
Jeter
Enregistrer
@@ -594,6 +598,8 @@
Ouvre Sécurité Windows. La désactivation réduit la sécurité et peut nécessiter un redémarrage.
Planification GPU à accélération matérielle
Ouvre les paramètres graphiques Windows pour vérifier HAGS.
+ Enregistrement en arrière-plan
+ Ouvre Captures de Windows pour modifier l'enregistrement en arrière-plan de cet utilisateur.
Optimisations des jeux fenêtrés
Ouvre les paramètres graphiques Windows pour gérer les optimisations Flip Model.
Suspension sélective USB
@@ -807,4 +813,7 @@
Alt
Maj
Win
+ Examiner les réglages du jeu
+ Comparer deux captures
+ Enregistrer le rapport modifié…
diff --git a/Locales/it-IT.xaml b/Locales/it-IT.xaml
index d59d402..c4c872e 100644
--- a/Locales/it-IT.xaml
+++ b/Locales/it-IT.xaml
@@ -561,6 +561,10 @@
Il monitoraggio dell'automazione rimarrà disabilitato anche dopo il riavvio.
L'automazione di piano energetico, maschera CPU, priorità e regole salvate non verrà eseguita finché non la riabiliti.
Annulla
+ OK
+ Annulla
+ Sì
+ No
Disabilita monitoraggio
Scartare
Salva
@@ -594,6 +598,8 @@
Apre Sicurezza di Windows. Disattivare questa protezione riduce la sicurezza e può richiedere il riavvio.
Pianificazione GPU con accelerazione hardware
Apre le impostazioni grafiche di Windows per controllare HAGS.
+ Registrazione in background
+ Apre Acquisizioni di Windows per modificare la registrazione in background di questo utente.
Ottimizzazioni per giochi in finestra
Apre le impostazioni grafiche di Windows per gestire le ottimizzazioni Flip Model.
Sospensione selettiva USB
@@ -807,4 +813,7 @@
Alt
Maiusc
Win
+ Diagnostica gioco
+ Confronta due catture
+ Salva il rapporto modificato…
diff --git a/Locales/ru-RU.xaml b/Locales/ru-RU.xaml
index cdfea0a..e7fdd58 100644
--- a/Locales/ru-RU.xaml
+++ b/Locales/ru-RU.xaml
@@ -561,6 +561,10 @@
Мониторинг автоматизации останется отключенным после перезапуска.
Автоматизация планов питания, масок ЦП, приоритетов и сохраненных правил не будет выполняться, пока вы не включите ее снова.
Отмена
+ ОК
+ Отмена
+ Да
+ Нет
Отключить мониторинг
Отбросить
Сохранить
@@ -594,6 +598,8 @@
Открывает Безопасность Windows. Отключение снижает безопасность и может потребовать перезагрузки.
Аппаратное планирование GPU
Открывает параметры графики Windows для проверки HAGS.
+ Фоновая запись
+ Открывает раздел «Клипы» Windows, чтобы изменить фоновую запись для этого пользователя.
Оптимизация оконных игр
Открывает параметры графики Windows для управления Flip Model.
Выборочная приостановка USB
@@ -807,4 +813,7 @@
Alt
Shift
Win
+ Проверить настройки игры
+ Сравнить две записи
+ Сохранить изменённый отчёт…
diff --git a/Locales/zh-CN.xaml b/Locales/zh-CN.xaml
index 29eae8d..fcc9acf 100644
--- a/Locales/zh-CN.xaml
+++ b/Locales/zh-CN.xaml
@@ -561,6 +561,10 @@
自动化监控在重启后仍将保持禁用。
在再次启用前,进程电源计划、CPU 掩码、优先级和已保存规则的自动化不会运行。
取消
+ 确定
+ 取消
+ 是
+ 否
禁用监控
放弃更改
保存
@@ -594,6 +598,8 @@
打开 Windows 安全中心。关闭此保护会降低系统安全性,并且可能需要重启。
硬件加速 GPU 计划
打开 Windows 图形设置以查看 HAGS。
+ 后台录制
+ 打开 Windows 捕获设置以更改此用户的后台录制。
窗口化游戏优化
打开 Windows 图形设置以管理 Flip Model 优化。
USB 选择性暂停
@@ -807,4 +813,7 @@
Alt
Shift
Win
+ 检查游戏设置
+ 比较两次捕获
+ 保存编辑后的报告…
diff --git a/MainWindow.Behaviors.partial.cs b/MainWindow.Behaviors.partial.cs
index dacbeef..924afb3 100644
--- a/MainWindow.Behaviors.partial.cs
+++ b/MainWindow.Behaviors.partial.cs
@@ -144,7 +144,7 @@ private async Task CheckForUpdatesAtStartupAsync()
?? "Install ThreadPilot update";
var messageFormat = Application.Current.TryFindResource("Settings_UpdateConfirmMessageFormat") as string
?? "ThreadPilot will download, verify and install version {0}, then restart automatically. Continue?";
- var confirmation = MessageBox.Show(
+ var confirmation = ThreadPilot.Helpers.AppMessageBox.Show(
this,
string.Format(messageFormat, result.Release.Version),
title,
@@ -166,7 +166,7 @@ private async Task CheckForUpdatesAtStartupAsync()
{
var failureFormat = Application.Current.TryFindResource("Settings_StatusUpdateInstallFailedFormat") as string
?? "Update install failed: {0}";
- MessageBox.Show(
+ ThreadPilot.Helpers.AppMessageBox.Show(
this,
string.Format(failureFormat, installResult.Message),
title,
@@ -342,7 +342,7 @@ private void ShowInitializationError(Exception ex)
{
this.UpdateLoadingStatus("Initialization failed", ex.Message);
- var result = System.Windows.MessageBox.Show(
+ var result = ThreadPilot.Helpers.AppMessageBox.Show(
$"ThreadPilot failed to initialize properly:\n\n{ex.Message}\n\nDebug log: {this.debugLogPath}\n\nWould you like to retry initialization or close the application?",
"Initialization Error",
MessageBoxButton.YesNo,
@@ -2285,7 +2285,7 @@ protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
if (this.isPerformanceIntroVisible)
{
e.Cancel = true;
- System.Windows.MessageBox.Show(
+ ThreadPilot.Helpers.AppMessageBox.Show(
"Please complete the Performance introduction before closing the application.\n\nClick 'Continue to Performance' to proceed.",
"Performance Introduction Required",
MessageBoxButton.OK,
diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs
index 556c7e0..0261c58 100644
--- a/MainWindow.xaml.cs
+++ b/MainWindow.xaml.cs
@@ -101,7 +101,6 @@ public MainWindow(
this.InitializeComponent();
System.Diagnostics.Debug.WriteLine("InitializeComponent completed");
this.RestoreUiState();
- this.ConfigureDiagnosticsNavigation();
// Initialize loading overlay
this.InitializeLoadingOverlay();
@@ -148,7 +147,7 @@ public MainWindow(
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error in MainWindow constructor: {ex}");
- System.Windows.MessageBox.Show(
+ ThreadPilot.Helpers.AppMessageBox.Show(
$"Error initializing MainWindow:\n\n{ex.Message}\n\nStack Trace:\n{ex.StackTrace}",
"MainWindow Initialization Error", MessageBoxButton.OK, MessageBoxImage.Error);
throw;
@@ -176,11 +175,10 @@ public void ConfigureStartupMode(bool isSilentStartupMode, bool showStartupMinim
this.powerPlanViewModel.PauseAutoRefresh();
}
- private void ConfigureDiagnosticsNavigation()
+ internal async Task ReviewGameRulesAsync(string executable)
{
- this.NavPerf.Visibility = AppNavigationOptions.ShowAdvancedDiagnostics
- ? Visibility.Visible
- : Visibility.Collapsed;
+ await this.NavMenuItem_ClickAsync(this.NavProcess, new RoutedEventArgs());
+ this.processViewModel.SearchText = System.IO.Path.GetFileNameWithoutExtension(executable);
}
private PerformanceViewModel GetPerformanceViewModel()
diff --git a/Services/AtomicFileWriter.cs b/Services/AtomicFileWriter.cs
index 21e4876..88cf5ed 100644
--- a/Services/AtomicFileWriter.cs
+++ b/Services/AtomicFileWriter.cs
@@ -7,6 +7,19 @@ namespace ThreadPilot.Services
internal static class AtomicFileWriter
{
+ // User-selected exports may already have a neighbouring .bak file owned by the user.
+ internal static async Task SaveExportAsync(string path, Stream content)
+ {
+ var staging = Path.Combine(Path.GetDirectoryName(path)!, $".{Guid.NewGuid():N}.tmp");
+ var file = new FileStream(staging, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, FileOptions.Asynchronous);
+ try
+ {
+ using (file) await content.CopyToAsync(file);
+ File.Move(staging, path, overwrite: true);
+ }
+ finally { File.Delete(staging); }
+ }
+
public static async Task WriteAllTextAsync(string filePath, string content, Encoding? encoding = null)
{
if (string.IsNullOrWhiteSpace(filePath))
diff --git a/Services/ElevationService.cs b/Services/ElevationService.cs
index 398682e..78e157a 100644
--- a/Services/ElevationService.cs
+++ b/Services/ElevationService.cs
@@ -51,7 +51,7 @@ public async Task RequestElevationIfNeeded()
LogRequestingElevation(this.logger);
// Show elevation prompt to user
- var result = System.Windows.MessageBox.Show(
+ var result = ThreadPilot.Helpers.AppMessageBox.Show(
"ThreadPilot requires administrator privileges to manage process affinity and power plans.\n\n" +
"Would you like to restart the application with administrator privileges?",
"Administrator Privileges Required",
@@ -127,7 +127,7 @@ public async Task RestartWithElevation(string[]? arguments = null)
await this.securityService.AuditElevatedAction("ApplicationRestart", "Self", false);
// Show user-friendly error message
- System.Windows.MessageBox.Show(
+ ThreadPilot.Helpers.AppMessageBox.Show(
"Failed to restart with administrator privileges. Please manually run ThreadPilot as administrator.",
"Elevation Failed",
MessageBoxButton.OK,
diff --git a/Services/GameDiagnosticReport.cs b/Services/GameDiagnosticReport.cs
new file mode 100644
index 0000000..be0b1c5
--- /dev/null
+++ b/Services/GameDiagnosticReport.cs
@@ -0,0 +1,129 @@
+namespace ThreadPilot.Services;
+
+using System.Management;
+using System.Runtime.InteropServices;
+using Microsoft.Win32;
+using ThreadPilot.Models;
+
+internal static class GameDiagnosticReport
+{
+ public static string Read(GameBoostDecision? decision = null)
+ {
+ var parking = new Dictionary();
+ var topology = new WindowsCpuTopologyProvider().CreateSnapshot(default, parking);
+ using var cpu = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0");
+ var lines = new List { $"{cpu?.GetValue("ProcessorNameString") ?? "Unknown CPU"}" };
+ foreach (var group in topology.LogicalProcessors.GroupBy(p => topology.TryGetLastLevelCacheIndex(p, out var i) ? i : -1))
+ {
+ var size = topology.TryGetLastLevelCacheSize(group.Key, out var bytes) ? $"{bytes / 1048576} MiB" : "unknown size";
+ var parked = group.All(parking.ContainsKey) ? $"{group.Count(p => parking[p])}/{group.Count()}" : "unknown";
+ var game = decision?.GameSelection?.GlobalLogicalProcessorIndexes;
+ var background = decision?.BackgroundSelection?.GlobalLogicalProcessorIndexes;
+ var selected = decision == null ? "" : $", requested game/background CPUs: {group.Count(p => game?.Contains(p.GlobalIndex) == true)}/{group.Count(p => background?.Contains(p.GlobalIndex) == true)}";
+ lines.Add($"L3 {(group.Key < 0 ? "unknown" : group.Key)} ({size}), parked logical processors: {parked}{selected}");
+ }
+
+ if (topology.Signature.LastLevelCacheGroupCount > 1 && $"{cpu?.GetValue("ProcessorNameString")}".Contains("AMD"))
+ {
+ lines.Add("AMD V-Cache optimizer: " + Query("Win32_PnPSignedDriver", "DeviceName, DriverVersion", " WHERE DeviceName LIKE '%3D V-Cache%'"));
+ }
+
+ if ($"{cpu?.GetValue("ProcessorNameString")}".Contains("Intel") && cpu?.GetValue("Update Revision") is byte[] revision && revision.Length == 8)
+ lines.Add($"Intel microcode (registry): 0x{BitConverter.ToUInt32(revision, 4):X}. Check the OEM BIOS guidance for this model.");
+
+ using var graphics = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\GraphicsDrivers");
+ lines.Add("HAGS preference: " + (graphics?.GetValue("HwSchMode") switch
+ {
+ 1 => "off", 2 => "on", _ => "Windows default or unknown",
+ }) + ".");
+ using var gameBar = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\GameBar");
+ lines.Add("Game Mode preference: " + (gameBar?.GetValue("AutoGameModeEnabled") switch
+ {
+ null => "Windows default (on)", 0 => "off", 1 => "on", _ => "unknown",
+ }));
+
+ lines.Add("Display adapters (driver): " + Query("Win32_VideoController", "Name, DriverVersion", ""));
+ foreach (var screen in System.Windows.Forms.Screen.AllScreens)
+ {
+ var mode = new DisplayMode { Size = (ushort)Marshal.SizeOf() };
+ var hz = EnumDisplaySettings(screen.DeviceName, -1, ref mode) && mode.Frequency > 1 ? $"{mode.Frequency} Hz" : "unknown refresh";
+ lines.Add($"{screen.DeviceName} · {screen.Bounds.Width} × {screen.Bounds.Height} · {hz} · {ReadDisplayAdapter(screen.DeviceName)}");
+ }
+ lines.Add("RAM (bytes): " + Query("Win32_ComputerSystem", "TotalPhysicalMemory", ""));
+ lines.Add("VRR, game adapter and driver profile overrides: unknown. Record display, frame cap and frame generation with the capture.");
+ return string.Join(Environment.NewLine, lines);
+ }
+
+ // DEVMODEW offsets for dmSize and dmDisplayFrequency (wingdi.h).
+ [StructLayout(LayoutKind.Explicit, Size = 220)]
+ private struct DisplayMode
+ {
+ [FieldOffset(68)] public ushort Size;
+ [FieldOffset(184)] public uint Frequency;
+ }
+
+ [DllImport("user32.dll", EntryPoint = "EnumDisplaySettingsW", CharSet = CharSet.Unicode)]
+ private static extern bool EnumDisplaySettings(string device, int index, ref DisplayMode mode);
+
+ private static unsafe string ReadDisplayAdapter(string device)
+ {
+ var adapter = new OpenDisplayAdapter { DeviceName = device };
+ if (D3DKMTOpenAdapterFromGdiDisplayName(ref adapter) != 0) return "HAGS and VRAM unknown";
+ try
+ {
+ // d3dkmthk.h: WDDM_2_7_CAPS bits 0/1 are supported/enabled for this adapter.
+ uint caps = 0;
+ var query = new AdapterQuery { Adapter = adapter.Handle, Type = 70, Data = (nint)(&caps), Size = sizeof(uint) };
+ string hags = D3DKMTQueryAdapterInfo(ref query) != 0 ? "unknown" : (caps & 1) == 0 ? "unsupported"
+ : (caps & 2) != 0 ? "enabled" : "disabled";
+ // GETSEGMENTSIZE returns dedicated video, dedicated system and shared system memory in bytes.
+ ulong* segments = stackalloc ulong[3];
+ query = new AdapterQuery { Adapter = adapter.Handle, Type = 3, Data = (nint)segments, Size = 3 * sizeof(ulong) };
+ var vram = D3DKMTQueryAdapterInfo(ref query) == 0 ? $"{segments[0] / 1048576} MiB" : "unknown";
+ return $"HAGS {hags} · dedicated video memory {vram}";
+ }
+ finally { _ = D3DKMTCloseAdapter(ref adapter.Handle); }
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct OpenDisplayAdapter
+ {
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DeviceName;
+ public uint Handle;
+ public uint LuidLow;
+ public int LuidHigh;
+ public uint Source;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct AdapterQuery
+ {
+ public uint Adapter, Type;
+ public nint Data;
+ public uint Size;
+ }
+
+ [DllImport("gdi32.dll")] private static extern int D3DKMTOpenAdapterFromGdiDisplayName(ref OpenDisplayAdapter adapter);
+ [DllImport("gdi32.dll")] private static extern int D3DKMTQueryAdapterInfo(ref AdapterQuery query);
+ [DllImport("gdi32.dll")] private static extern int D3DKMTCloseAdapter(ref uint adapter);
+
+ private static string Query(string table, string fields, string filter)
+ {
+ try
+ {
+ using var search = new ManagementObjectSearcher($"SELECT {fields} FROM {table}{filter}");
+ using var rows = search.Get();
+ var values = new List();
+ foreach (ManagementObject row in rows)
+ {
+ using (row) values.Add(string.Join(", ", fields.Split(", ").Select(f => row[f]?.ToString() ?? "unknown")));
+ }
+
+ return values.Count > 0 ? string.Join(" / ", values) : "unknown";
+ }
+ catch (Exception ex) when (ex is ManagementException or UnauthorizedAccessException or System.Runtime.InteropServices.COMException)
+ {
+ return "unknown";
+ }
+ }
+}
diff --git a/Services/GuidedFrameCapture.cs b/Services/GuidedFrameCapture.cs
new file mode 100644
index 0000000..c626b28
--- /dev/null
+++ b/Services/GuidedFrameCapture.cs
@@ -0,0 +1,170 @@
+namespace ThreadPilot.Services;
+
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Security.Cryptography;
+using Microsoft.VisualBasic.FileIO;
+
+internal static class GuidedFrameCapture
+{
+ // The containing app is elevated. Execute only the tested upstream console from Program Files.
+ internal static readonly string RecorderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
+ @"Intel\PresentMon\PresentMonConsoleApplication\PresentMon-2.6.0-x64.exe");
+ private const string RecorderHash = "B2A706BC6AD475749E3B7E3409263AA1E6906D45BDCF993F6DBC0F660188F1AF";
+
+ internal static async Task RunAsync(string executable, TextWriter output, Task startSegment,
+ IProgress status, CancellationToken cancel)
+ {
+ using var image = File.OpenRead(RecorderPath);
+ if (Convert.ToHexString(await SHA256.HashDataAsync(image, cancel)) != RecorderHash)
+ throw new InvalidDataException("This capture requires the tested Intel PresentMon 2.6.0 x64 console.");
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancel);
+ deadline.CancelAfter(TimeSpan.FromMinutes(2));
+ var probe = new GameBoostProcessProbe();
+ status.Report("Armed · waiting for the selected game executable (2 minutes).");
+ using var target = await FindGameAsync(executable, deadline.Token);
+ var pid = target.Id;
+ var identity = target.StartTime.ToUniversalTime().Ticks;
+ using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancel);
+ linked.CancelAfter(TimeSpan.FromMinutes(2));
+ using var handle = probe.TryOpen(pid, identity, () =>
+ {
+ try { linked.Cancel(); } catch (ObjectDisposedException) { }
+ return Task.CompletedTask;
+ }) ?? throw new InvalidOperationException("Game exited or its identity could not be verified.");
+
+ string session = $"ThreadPilot-{Guid.NewGuid():N}";
+ status.Report($"PID {pid} · waiting for frames. Frames before attachment are outside this capture.");
+ using var recorder = StartRecorder(session, "--process_id", pid.ToString(CultureInfo.InvariantCulture),
+ "--output_stdout", "--no_console_stats", "--v1_metrics", "--terminate_on_proc_exit", "--timed", "125", "--terminate_after_timed");
+ var errors = recorder.StandardError.ReadToEndAsync();
+ try
+ {
+ var token = linked.Token;
+ string? header = await recorder.StandardOutput.ReadLineAsync(token);
+ if (header == null) throw new InvalidDataException("Zero frames. " + await errors);
+ var names = Split(header);
+ var columns = new FrameColumns(names);
+ int timeIndex = Array.IndexOf(names, "TimeInSeconds");
+ if (timeIndex < 0) throw new InvalidDataException("PresentMon capture timestamp is missing.");
+ double? first = null;
+ bool ready = false;
+ int frames = 0;
+ string? line;
+ while ((line = await recorder.StandardOutput.ReadLineAsync(token)) != null)
+ {
+ var fields = Split(line);
+ var frame = columns.Read(fields);
+ if (frame.Stream.Pid != pid || frame.Ms == 0) continue;
+ if (!double.TryParse(fields[timeIndex], NumberStyles.Float, CultureInfo.InvariantCulture, out var time) || !double.IsFinite(time))
+ throw new InvalidDataException("Invalid frame timestamp.");
+ if (!ready)
+ {
+ ready = true;
+ status.Report("Frames detected · start the 30 s segment when the scene is ready.");
+ }
+
+ if (!startSegment.IsCompletedSuccessfully) continue;
+ if (!first.HasValue)
+ {
+ first = time;
+ await output.WriteLineAsync(header);
+ status.Report("Measuring 30 seconds from the first selected frame.");
+ }
+ if (time - first >= 30) return frames;
+ await output.WriteLineAsync(line);
+ frames++;
+ }
+
+ throw new InvalidDataException($"{frames} measured intervals; recording ended before the segment completed. {await errors}");
+ }
+ catch (OperationCanceledException) when (!cancel.IsCancellationRequested)
+ {
+ throw new InvalidOperationException(target.HasExited ? "Game exited before the segment completed." : "Timed out waiting for frames or segment completion.");
+ }
+ finally
+ {
+ if (!recorder.HasExited)
+ {
+ // Ask upstream to close only our unique ETW session before releasing the consumer.
+ var remainingOutput = recorder.StandardOutput.BaseStream.CopyToAsync(Stream.Null);
+ using var stop = StartRecorder(session, "--terminate_existing_session");
+ var stopOutput = stop.StandardOutput.ReadToEndAsync();
+ var stopErrors = stop.StandardError.ReadToEndAsync();
+ await WaitOrKillAsync(stop);
+ await Task.WhenAll(stopOutput, stopErrors);
+ await WaitOrKillAsync(recorder);
+ await remainingOutput;
+ }
+ await errors;
+ }
+ }
+
+ private static Process StartRecorder(string session, params string[] args)
+ {
+ var info = new ProcessStartInfo(RecorderPath)
+ {
+ CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true,
+ WorkingDirectory = Path.GetDirectoryName(RecorderPath)!,
+ };
+ info.ArgumentList.Add("--session_name");
+ info.ArgumentList.Add(session);
+ foreach (var arg in args) info.ArgumentList.Add(arg);
+ return Process.Start(info) ?? throw new IOException("PresentMon did not start.");
+ }
+
+ private static async Task WaitOrKillAsync(Process process)
+ {
+ try { await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(4)); }
+ catch (TimeoutException)
+ {
+ if (!process.HasExited) process.Kill();
+ await process.WaitForExitAsync();
+ }
+ }
+
+ private static string[] Split(string row)
+ {
+ if (!row.Contains('"')) return row.Split(',');
+ using var parser = new TextFieldParser(new StringReader(row));
+ parser.SetDelimiters(",");
+ return parser.ReadFields() ?? [];
+ }
+
+ internal static async Task FindGameAsync(string path, CancellationToken token)
+ {
+ using var self = Process.GetCurrentProcess();
+ int session = self.SessionId;
+ while (true)
+ {
+ token.ThrowIfCancellationRequested();
+ var candidates = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(path));
+ Process? match = null;
+ try
+ {
+ foreach (var candidate in candidates)
+ {
+ try
+ {
+ if (candidate.SessionId != session || !string.Equals(candidate.MainModule?.FileName, path, StringComparison.OrdinalIgnoreCase))
+ continue;
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or Win32Exception) { continue; }
+ if (match != null) throw new IOException("Multiple matching game instances. Close extra instances and arm again.");
+ match = candidate;
+ }
+
+ if (match != null)
+ {
+ // Keep the very same process object whose path we checked.
+ candidates = candidates.Where(p => p != match).ToArray();
+ return match;
+ }
+ }
+ finally { foreach (var candidate in candidates) candidate.Dispose(); }
+ await Task.Delay(500, token);
+ }
+ }
+}
diff --git a/Services/ISystemTweaksService.cs b/Services/ISystemTweaksService.cs
index 835dde7..09c1de7 100644
--- a/Services/ISystemTweaksService.cs
+++ b/Services/ISystemTweaksService.cs
@@ -61,6 +61,8 @@ public interface ISystemTweaksService
Task GetMemoryIntegrityStatusAsync();
+ Task GetBackgroundRecordingStatusAsync();
+
Task OpenSettingsAsync(SystemTweak tweak);
}
@@ -109,6 +111,7 @@ public enum SystemTweak
PowerThrottling,
HighSchedulingCategory,
MenuShowDelay,
+ BackgroundRecording,
}
}
diff --git a/Services/PresentMonCsv.cs b/Services/PresentMonCsv.cs
new file mode 100644
index 0000000..740bc94
--- /dev/null
+++ b/Services/PresentMonCsv.cs
@@ -0,0 +1,138 @@
+namespace ThreadPilot.Services;
+
+using System.Globalization;
+using System.IO;
+using Microsoft.VisualBasic.FileIO;
+
+internal sealed record FrameStream(string Application, int Pid, string Chain)
+{
+ public override string ToString() => $"{Application} · PID {Pid} · {Chain}";
+}
+
+internal sealed record FrameSample(FrameStream Stream, double Ms, bool? Dropped);
+
+internal sealed class FrameColumns
+{
+ private readonly int app, pid, chain, ms, dropped, width;
+
+ internal FrameColumns(string[] header)
+ {
+ this.width = header.Length;
+ this.app = Array.IndexOf(header, "Application");
+ this.pid = Array.IndexOf(header, "ProcessID");
+ this.chain = Array.IndexOf(header, "SwapChainAddress");
+ this.ms = Array.FindIndex(header, h => string.Equals(h, "msBetweenPresents", StringComparison.OrdinalIgnoreCase));
+ this.dropped = Array.IndexOf(header, "Dropped");
+ if (new[] { this.app, this.pid, this.chain, this.ms }.Min() < 0 || header.Distinct(StringComparer.OrdinalIgnoreCase).Count() != header.Length)
+ throw new InvalidDataException("Expected PresentMon 2.6.0 --v1_metrics (Application, ProcessID, SwapChainAddress, MsBetweenPresents).");
+ }
+
+ internal FrameSample Read(string[] row)
+ {
+ if (row.Length != this.width || !int.TryParse(row[this.pid], out var id) || id <= 0
+ || row[this.app].Length == 0 || row[this.chain].Length == 0
+ || !double.TryParse(row[this.ms], NumberStyles.Float, CultureInfo.InvariantCulture, out var value)
+ || !double.IsFinite(value) || value < 0 || value > TimeSpan.FromDays(1).TotalMilliseconds)
+ throw new InvalidDataException("Invalid PresentMon interval or process identity.");
+
+ bool? lost = this.dropped < 0 ? null : row[this.dropped] switch
+ {
+ "1" => true, "0" => false, _ => throw new InvalidDataException("Invalid Dropped field."),
+ };
+ return new(new(row[this.app], id, row[this.chain]), value, lost);
+ }
+}
+
+internal sealed record CaptureResult(FrameStream Stream, int Count, int? Dropped, double Seconds,
+ double Median, double P99, double SpikesPerMinute, double[] Peaks)
+{
+ public string Summary => $"{Count:N0} present intervals · {Seconds:F1} s · median {Median:F2} ms · P99 {P99:F2} ms · {Count / Seconds:F1} FPS · {SpikesPerMinute:F1} spikes/min (>33.3 ms)"
+ + (Dropped.HasValue ? $" · displayed {Count - Dropped}, dropped {Dropped}" : " · displayed/dropped unknown")
+ + (Seconds < 30 ? " · short sample (<30 s)" : "");
+
+ // Shared by every stream read from one CSV, so streams of one capture never count as independent runs.
+ internal Guid Capture { get; init; } = Guid.NewGuid();
+}
+
+internal sealed class CapturePairs
+{
+ private readonly List<(CaptureResult A, CaptureResult B)> pairs = new();
+ internal string? Game => this.pairs.FirstOrDefault().A?.Stream.Application;
+ internal bool Supported { get; private set; }
+
+ internal string Add(CaptureResult a, CaptureResult b)
+ {
+ if (!string.Equals(a.Stream.Application, b.Stream.Application, StringComparison.OrdinalIgnoreCase)
+ || (this.Game != null && !string.Equals(a.Stream.Application, this.Game, StringComparison.OrdinalIgnoreCase)))
+ throw new InvalidOperationException("Use independent runs of the same game, or clear the pairs first.");
+ // Allow the boundary interval at the end of a 30-second segment.
+ if (a.Seconds < 29.9 || b.Seconds < 29.9)
+ throw new InvalidOperationException("Each stream needs at least 30 seconds of frame intervals.");
+ if (SameRun(a, b) || this.pairs.Any(p => SameRun(p.A, a) || SameRun(p.B, a) || SameRun(p.A, b) || SameRun(p.B, b)))
+ throw new InvalidOperationException("A matching run has already been selected. Use fresh captures for each pair.");
+ this.pairs.Add((a, b));
+ var aMin = this.pairs.Min(p => p.A.P99);
+ var aMax = this.pairs.Max(p => p.A.P99);
+ var bMin = this.pairs.Min(p => p.B.P99);
+ var bMax = this.pairs.Max(p => p.B.P99);
+ this.Supported = this.pairs.Count >= 3 && (aMax < bMin || bMax < aMin);
+ string decision = this.Supported ? $"{(aMax < bMin ? "A" : "B")} has consistently lower P99. Review its settings before saving a rule."
+ : "Inconclusive. At least three matched pairs and non-overlapping observed P99 ranges are required.";
+ return $"{this.pairs.Count} pairs · P99 A {aMin:F2}–{aMax:F2} ms / B {bMin:F2}–{bMax:F2} ms. {decision}";
+ }
+
+ private static bool SameRun(CaptureResult x, CaptureResult y) => x.Capture == y.Capture || (x.Stream == y.Stream && x.Count == y.Count
+ && x.Seconds == y.Seconds && x.Peaks.SequenceEqual(y.Peaks));
+
+ internal void Clear()
+ {
+ this.pairs.Clear();
+ this.Supported = false;
+ }
+}
+
+internal static class PresentMonCsv
+{
+ public static CaptureResult[] Read(string path, CancellationToken token)
+ {
+ token.ThrowIfCancellationRequested();
+ using var file = File.OpenRead(path);
+ if (file.Length > 512L * 1024 * 1024) throw new InvalidDataException("Maximum CSV size is 512 MiB.");
+ using var parser = new TextFieldParser(file);
+ parser.SetDelimiters(",");
+ var schema = new FrameColumns(parser.ReadFields() ?? []);
+ var groups = new Dictionary Values, int? Lost)>();
+ var count = 0;
+ while (!parser.EndOfData)
+ {
+ token.ThrowIfCancellationRequested();
+ var frame = schema.Read(parser.ReadFields() ?? []);
+ if (frame.Ms == 0) continue;
+ if (++count > 4_000_000) throw new InvalidDataException("Maximum capture length is 4 million intervals.");
+ if (!groups.TryGetValue(frame.Stream, out var group))
+ {
+ if (groups.Count >= 256) throw new InvalidDataException("Maximum number of streams is 256.");
+ group = (new(), frame.Dropped.HasValue ? 0 : null);
+ }
+
+ group.Values.Add(frame.Ms);
+ if (frame.Dropped == true) group.Lost++;
+ groups[frame.Stream] = group;
+ }
+
+ if (groups.Count == 0) throw new InvalidDataException("No valid frame intervals.");
+ var capture = Guid.NewGuid();
+ return groups.Select(pair =>
+ {
+ token.ThrowIfCancellationRequested();
+ var values = pair.Value.Values;
+ var peaks = values.Chunk((values.Count + 239) / 240).Select(chunk => chunk.Max()).ToArray();
+ var seconds = values.Sum() / 1000;
+ var spikes = values.Count(ms => ms > 33.3);
+ values.Sort();
+ return new CaptureResult(pair.Key, values.Count, pair.Value.Lost, seconds,
+ (values[(values.Count - 1) / 2] + values[values.Count / 2]) / 2,
+ values[(int)Math.Ceiling(values.Count * 0.99) - 1], spikes * 60 / seconds, peaks) { Capture = capture };
+ }).ToArray();
+ }
+}
diff --git a/Services/SystemTweaksService.cs b/Services/SystemTweaksService.cs
index 79c3d98..7303333 100644
--- a/Services/SystemTweaksService.cs
+++ b/Services/SystemTweaksService.cs
@@ -247,11 +247,45 @@ public Task GetMemoryIntegrityStatusAsync()
}
}
+ public Task GetBackgroundRecordingStatusAsync()
+ {
+ try
+ {
+ using var policy = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows\GameDVR");
+ var restriction = policy?.GetValue("AllowGameDVR");
+ if (restriction is 0 || !WindowsSessionUser.IsCurrent())
+ return Task.FromResult(new TweakStatus { IsAvailable = true, StatusText = restriction is 0
+ ? "Disabled by Windows policy" : "Unknown (different or unavailable session user)" });
+
+ using var settings = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\GameDVR");
+ using var store = Registry.CurrentUser.OpenSubKey(@"System\GameConfigStore");
+ return Task.FromResult(new TweakStatus
+ {
+ IsAvailable = true,
+ StatusText = DescribeRecording(restriction, settings?.GetValue("AppCaptureEnabled"),
+ store?.GetValue("GameDVR_Enabled"), settings?.GetValue("HistoricalCaptureEnabled")),
+ });
+ }
+ catch (Exception ex) when (ex is UnauthorizedAccessException or SecurityException or System.Security.Principal.IdentityNotMappedException)
+ {
+ return Task.FromResult(new TweakStatus { IsAvailable = true, StatusText = "Unknown (check Windows Captures)" });
+ }
+ }
+
+ internal static string DescribeRecording(object? policy, object? capture, object? gameDvr, object? history)
+ {
+ if (policy is 0) return "Disabled by Windows policy";
+ if (policy is not (null or 1)) return "Unknown Windows policy";
+ if (capture is 0 || gameDvr is 0 || history is 0) return "Disabled";
+ return capture is 1 && gameDvr is 1 && history is 1 ? "Enabled" : "Unknown (check Windows Captures)";
+ }
+
public Task OpenSettingsAsync(SystemTweak tweak)
{
var uri = tweak switch
{
SystemTweak.MemoryIntegrity => "windowsdefender://coreisolation",
+ SystemTweak.BackgroundRecording => "ms-settings:gaming-gamedvr",
SystemTweak.Hags or SystemTweak.WindowedOptimizations => "ms-settings:display-advancedgraphics-default",
_ => null,
};
diff --git a/Services/UninstallCleanup.cs b/Services/UninstallCleanup.cs
index c6c9ca9..248f02f 100644
--- a/Services/UninstallCleanup.cs
+++ b/Services/UninstallCleanup.cs
@@ -128,7 +128,7 @@ internal static int Run(string[] args, Func? recoverGameBoost = null, Acti
var installedPath = install?.GetValue("InstallLocation") is string installDir
? Path.Combine(installDir, "ThreadPilot.exe")
: null;
- var sameUser = IsSessionUser();
+ var sameUser = WindowsSessionUser.IsCurrent();
var shared = StoreDistribution.IsStoreBuild
? installedPath != null
: IsStoreInstalled() || (installedPath != null && !SamePath(installedPath, executable));
@@ -557,33 +557,6 @@ private static bool IsStoreInstalled()
};
}
- 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))
@@ -631,7 +604,7 @@ private static void Report(IReadOnlyList residuals, bool silent, bool fr
if (!silent)
{
- System.Windows.MessageBox.Show(summary, "ThreadPilot cleanup", MessageBoxButton.OK,
+ ThreadPilot.Helpers.AppMessageBox.Show(summary, "ThreadPilot cleanup", MessageBoxButton.OK,
residuals.Count == 0 ? MessageBoxImage.Information : MessageBoxImage.Warning);
}
@@ -675,10 +648,5 @@ private static void Report(IReadOnlyList residuals, bool silent, bool fr
[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/WindowsCpuTopologyProvider.cs b/Services/WindowsCpuTopologyProvider.cs
index d248424..f7f0293 100644
--- a/Services/WindowsCpuTopologyProvider.cs
+++ b/Services/WindowsCpuTopologyProvider.cs
@@ -83,7 +83,7 @@ public Task GetTopologySnapshotAsync(CancellationToken canc
return Task.FromResult(this.CreateSnapshot(cancellationToken));
}
- private CpuTopologySnapshot CreateSnapshot(CancellationToken cancellationToken)
+ internal CpuTopologySnapshot CreateSnapshot(CancellationToken cancellationToken, Dictionary? parking = null)
{
var logicalProcessors = new HashSet();
var cpuSetIds = new Dictionary();
@@ -104,6 +104,7 @@ private CpuTopologySnapshot CreateSnapshot(CancellationToken cancellationToken)
numaNodeIndexes,
lastLevelCacheIndexes,
reservedLogicalProcessorIndexes,
+ parking,
cancellationToken);
this.ReadLogicalProcessorRelationships(
@@ -173,6 +174,7 @@ private void ReadCpuSetInformation(
IDictionary numaNodeIndexes,
IDictionary lastLevelCacheIndexes,
HashSet reservedLogicalProcessorIndexes,
+ Dictionary? parking,
CancellationToken cancellationToken)
{
uint requiredLength = 0;
@@ -214,6 +216,7 @@ private void ReadCpuSetInformation(
var processor = WindowsCpuTopologyNativeLayout.CreateProcessorRef(info.Group, info.LogicalProcessorIndex);
logicalProcessors.Add(processor);
cpuSetIds[processor] = info.Id;
+ if (parking != null) parking[processor] = (info.AllFlags & 1) != 0;
efficiencyClasses[processor] = info.EfficiencyClass;
coreIndexes.TryAdd(processor, info.CoreIndex);
numaNodeIndexes[processor] = info.NumaNodeIndex;
diff --git a/Services/WindowsSessionUser.cs b/Services/WindowsSessionUser.cs
new file mode 100644
index 0000000..ef7bb58
--- /dev/null
+++ b/Services/WindowsSessionUser.cs
@@ -0,0 +1,42 @@
+namespace ThreadPilot.Services;
+
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Security.Principal;
+
+internal static class WindowsSessionUser
+{
+ internal static bool IsCurrent()
+ {
+ 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);
+ }
+ }
+
+ [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/Tests/ThreadPilot.Core.Tests/PresentMonCsvTests.cs b/Tests/ThreadPilot.Core.Tests/PresentMonCsvTests.cs
new file mode 100644
index 0000000..0199227
--- /dev/null
+++ b/Tests/ThreadPilot.Core.Tests/PresentMonCsvTests.cs
@@ -0,0 +1,57 @@
+namespace ThreadPilot.Core.Tests;
+
+using ThreadPilot.Services;
+
+public class PresentMonCsvTests
+{
+ [Fact]
+ public void RepeatabilityRequiresIndependentPairsAndSeparatedRanges()
+ {
+ static CaptureResult Run(int pid, double p99) => new(new("game.exe", pid, "1"), 3000, 0, 40, 13, p99, 2, [p99]);
+ var runs = new CapturePairs();
+ var a = Run(1, 26);
+ var b = Run(2, 20);
+ runs.Add(a, b);
+ Assert.Throws(() => runs.Add(b, a));
+ Assert.Throws(() => runs.Add(a with { Seconds = 1 }, Run(9, 21)));
+ runs.Add(Run(3, 24), Run(4, 19));
+ Assert.False(runs.Supported);
+ runs.Add(Run(5, 25), Run(6, 21));
+ Assert.True(runs.Supported);
+ runs.Add(Run(7, 20), Run(8, 22));
+ Assert.False(runs.Supported);
+ runs.Clear();
+ Assert.Null(runs.Game);
+ }
+
+ [Theory]
+ [InlineData(4)]
+ [InlineData(100000)]
+ public void ImportSeparatesStreamsAndPreservesPeaks(int count)
+ {
+ var path = Path.GetTempFileName();
+ try
+ {
+ using (var writer = File.CreateText(path))
+ {
+ writer.WriteLine("Application,ProcessID,SwapChainAddress,msBetweenPresents,Dropped");
+ for (int i = 0; i < count; i++) writer.WriteLine("\"game, one\",2,0x1,10,0");
+ writer.WriteLine("\"game, one\",2,0x1,200,1");
+ writer.WriteLine("\"game, one\",2,0x2,20,0");
+ }
+
+ var groups = PresentMonCsv.Read(path, default);
+ Assert.Equal(2, groups.Length);
+ var a = groups.Single(g => g.Stream.Chain == "0x1");
+ Assert.Equal(10, a.Median);
+ Assert.Equal(200, a.Peaks.Max());
+ Assert.Equal(1, a.Dropped);
+ Assert.InRange(a.Peaks.Length, 1, 240);
+ Assert.Throws(() => new CapturePairs().Add(groups[0] with { Seconds = 40 }, groups[1] with { Seconds = 40 }));
+ Assert.Throws(() => PresentMonCsv.Read(path, new CancellationToken(true)));
+ File.AppendAllText(path, "bad,row");
+ Assert.Throws(() => PresentMonCsv.Read(path, default));
+ }
+ finally { File.Delete(path); }
+ }
+}
diff --git a/Tests/ThreadPilot.Core.Tests/SystemTweaksViewModelTests.cs b/Tests/ThreadPilot.Core.Tests/SystemTweaksViewModelTests.cs
index 663cb22..839ae73 100644
--- a/Tests/ThreadPilot.Core.Tests/SystemTweaksViewModelTests.cs
+++ b/Tests/ThreadPilot.Core.Tests/SystemTweaksViewModelTests.cs
@@ -7,11 +7,24 @@ namespace ThreadPilot.Core.Tests
public sealed class SystemTweaksViewModelTests
{
+ [Theory]
+ [InlineData(0, 1, 1, 1, "Disabled by Windows policy")]
+ [InlineData(null, null, null, null, "Unknown (check Windows Captures)")]
+ [InlineData(1, 1, 1, 1, "Enabled")]
+ [InlineData(null, 0, 1, 1, "Disabled")]
+ public void RecordingReflectsPolicyAndExplicitValues(int? policy, int? capture, int? store, int? history, string expected)
+ => Assert.Equal(expected, SystemTweaksService.DescribeRecording(policy, capture, store, history));
+
+ [Fact]
+ public void LocalDiagnosticSnapshotIncludesParking()
+ => Assert.Contains("parked logical processors", GameDiagnosticReport.Read());
+
[Fact]
public async Task LoadAsync_QueriesEverySupportedTweakExactlyOnce()
{
var harness = new Harness();
var status = new TweakStatus { IsEnabled = true, IsAvailable = true };
+ harness.Tweaks.Setup(service => service.GetBackgroundRecordingStatusAsync()).ReturnsAsync(status);
harness.Tweaks.Setup(service => service.GetGameModeStatusAsync()).ReturnsAsync(status);
harness.Tweaks.Setup(service => service.GetCoreParkingStatusAsync()).ReturnsAsync(status);
harness.Tweaks.Setup(service => service.GetCStatesStatusAsync()).ReturnsAsync(status);
@@ -33,6 +46,7 @@ public async Task LoadAsync_QueriesEverySupportedTweakExactlyOnce()
Assert.Equal(Enum.GetValues().Length, viewModel.TweakItems.Count);
Assert.All(viewModel.TweakItems.Where(item => !item.IsGuidedAction), item => Assert.True(item.IsEnabled));
Assert.All(viewModel.TweakItems, item => Assert.True(item.IsAvailable));
+ harness.Tweaks.Verify(service => service.GetBackgroundRecordingStatusAsync(), Times.Once);
harness.Tweaks.Verify(service => service.GetGameModeStatusAsync(), Times.Once);
harness.Tweaks.Verify(service => service.GetCoreParkingStatusAsync(), Times.Once);
harness.Tweaks.Verify(service => service.GetCStatesStatusAsync(), Times.Once);
diff --git a/ViewModels/MasksViewModel.cs b/ViewModels/MasksViewModel.cs
index 21a23e6..507ed37 100644
--- a/ViewModels/MasksViewModel.cs
+++ b/ViewModels/MasksViewModel.cs
@@ -141,7 +141,7 @@ private async Task CreateMask()
{
this.logger.LogError(ex, "Failed to create mask");
this.StatusMessage = $"Error creating mask: {ex.Message}";
- MessageBox.Show($"Failed to create mask: {ex.Message}", "Error",
+ ThreadPilot.Helpers.AppMessageBox.Show($"Failed to create mask: {ex.Message}", "Error",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
@@ -162,7 +162,7 @@ private async Task DeleteMask()
// 1. Check if mask is the "All Cores" baseline (cannot be deleted)
if (maskName == "All Cores")
{
- MessageBox.Show(
+ ThreadPilot.Helpers.AppMessageBox.Show(
"The 'All Cores' mask is the baseline mask and cannot be deleted.\n\n" +
"This mask is required as the default fallback for all processes.",
"Cannot Delete Baseline Mask",
@@ -175,7 +175,7 @@ private async Task DeleteMask()
bool isActivelyApplied = await this.coreMaskService.IsMaskActivelyAppliedAsync(maskId);
if (isActivelyApplied)
{
- MessageBox.Show(
+ ThreadPilot.Helpers.AppMessageBox.Show(
$"The mask '{maskName}' is currently applied to one or more running processes.\n\n" +
"You must change the mask on those processes before deleting this mask.\n\n" +
"Go to the Processes tab to change the affinity of the affected processes.",
@@ -195,7 +195,7 @@ private async Task DeleteMask()
profileList += $"\n ... and {referencingProfiles.Count - 10} more";
}
- var result = MessageBox.Show(
+ var result = ThreadPilot.Helpers.AppMessageBox.Show(
$"The mask '{maskName}' is referenced by the following profiles/rules:\n\n" +
$" - {profileList}\n\n" +
"If you delete this mask, these profiles will be updated to use the 'All Cores' mask instead.\n\n" +
@@ -216,7 +216,7 @@ private async Task DeleteMask()
else
{
// Simple confirmation
- var result = MessageBox.Show(
+ var result = ThreadPilot.Helpers.AppMessageBox.Show(
$"Are you sure you want to delete the mask '{maskName}'?",
"Confirm Delete",
MessageBoxButton.YesNo,
@@ -239,7 +239,7 @@ private async Task DeleteMask()
{
this.logger.LogError(ex, "Failed to delete mask");
this.StatusMessage = $"Error deleting mask: {ex.Message}";
- MessageBox.Show($"Failed to delete mask: {ex.Message}", "Error",
+ ThreadPilot.Helpers.AppMessageBox.Show($"Failed to delete mask: {ex.Message}", "Error",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
@@ -267,7 +267,7 @@ private async Task DuplicateMask()
{
this.logger.LogError(ex, "Failed to duplicate mask");
this.StatusMessage = $"Error duplicating mask: {ex.Message}";
- MessageBox.Show($"Failed to duplicate mask: {ex.Message}", "Error",
+ ThreadPilot.Helpers.AppMessageBox.Show($"Failed to duplicate mask: {ex.Message}", "Error",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
diff --git a/ViewModels/PerformanceViewModel.cs b/ViewModels/PerformanceViewModel.cs
index 88720c7..ae42f0c 100644
--- a/ViewModels/PerformanceViewModel.cs
+++ b/ViewModels/PerformanceViewModel.cs
@@ -180,6 +180,20 @@ public PerformanceViewModel(
this.systemTweaksService.TweakStatusChanged += this.OnTweakStatusChanged;
}
+ internal async Task GetCaptureContextAsync()
+ {
+ var lines = this.TimelineEvents.Select(e => (e.Timestamp, Text: $"{e.Category} · {e.Detail}")).ToList();
+ if (this.ActivityAuditService != null)
+ {
+ var entries = await this.ActivityAuditService.GetEntriesAsync(DateTime.Now.AddHours(-2));
+ lines.AddRange(entries.Where(e => e.Category is ActivityAuditCategories.GameBoost or ActivityAuditCategories.Rules
+ or ActivityAuditCategories.PowerPlans or ActivityAuditCategories.Affinity or ActivityAuditCategories.Priority)
+ .Select(e => (e.Timestamp, $"{e.Category} · {e.Message} {e.Details}")));
+ }
+ return string.Join(Environment.NewLine, lines.OrderByDescending(e => e.Timestamp).Take(40)
+ .Select(e => $"{e.Timestamp.ToLocalTime():HH:mm:ss} · {e.Text}"));
+ }
+
public override async Task InitializeAsync()
{
this.MonitoringStateText = "Stopped";
diff --git a/ViewModels/ProcessViewModel.Behaviors.partial.cs b/ViewModels/ProcessViewModel.Behaviors.partial.cs
index 65904b3..e546c71 100644
--- a/ViewModels/ProcessViewModel.Behaviors.partial.cs
+++ b/ViewModels/ProcessViewModel.Behaviors.partial.cs
@@ -2448,7 +2448,7 @@ private async Task ToggleRegistryPriorityAsync(bool enable)
// Show notification about restart requirement
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
- System.Windows.MessageBox.Show(
+ ThreadPilot.Helpers.AppMessageBox.Show(
$"Registry priority has been set for {this.SelectedProcess.Name}.\n\n" +
"The process must be restarted for the registry changes to take effect.\n\n" +
$"{ProcessOperationUserMessages.PersistentLaunchTimePriorityNotice}\n\n" +
diff --git a/ViewModels/SettingsViewModel.cs b/ViewModels/SettingsViewModel.cs
index 2b0e50a..9e2a04b 100644
--- a/ViewModels/SettingsViewModel.cs
+++ b/ViewModels/SettingsViewModel.cs
@@ -579,7 +579,7 @@ private async Task ImportSettingsAsync()
bundle.PersistentProcessRules == null
? this.GetLocalizedString("Settings_ImportKeepRules", "keep existing rules")
: this.GetLocalizedString("Settings_ImportReplaceRules", "replace with {0} imported rules", bundle.PersistentProcessRules.Count));
- if (MessageBox.Show(preview, this.GetLocalizedString("Settings_DialogImportTitle", "Import ThreadPilot Configuration"),
+ if (ThreadPilot.Helpers.AppMessageBox.Show(preview, this.GetLocalizedString("Settings_DialogImportTitle", "Import ThreadPilot Configuration"),
MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) != MessageBoxResult.OK)
{
return;
@@ -794,7 +794,7 @@ private async Task RefreshPowerPlansAsync()
}
internal Func ConfirmPrompt { get; set; } = (message, title) =>
- System.Windows.MessageBox.Show(message, title, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;
+ ThreadPilot.Helpers.AppMessageBox.Show(message, title, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;
// A portable copy cannot autostart safely, so offer the official installer through the verified update
// path; the installed copy turns autostart on at its first start (App.OnStartup).
@@ -911,7 +911,7 @@ private async Task DownloadAndInstallUpdateAsync()
"Settings_UpdateConfirmMessageFormat",
"ThreadPilot will download, verify and install version {0}, then restart automatically. Continue?",
this.availableUpdate.Version);
- var confirmation = System.Windows.MessageBox.Show(
+ var confirmation = ThreadPilot.Helpers.AppMessageBox.Show(
message,
this.GetLocalizedString("Settings_UpdateConfirmTitle", "Install ThreadPilot update"),
MessageBoxButton.YesNo,
diff --git a/ViewModels/SystemTweaksViewModel.GameBoost.cs b/ViewModels/SystemTweaksViewModel.GameBoost.cs
index 30c29ea..c5c50fc 100644
--- a/ViewModels/SystemTweaksViewModel.GameBoost.cs
+++ b/ViewModels/SystemTweaksViewModel.GameBoost.cs
@@ -18,6 +18,31 @@ public partial class SystemTweaksViewModel
private readonly IApplicationSettingsService? settingsService;
private readonly IGameSessionService? gameSessionService;
private bool isLoadingGameBoost;
+ private readonly IPowerPlanService? powerPlanService;
+
+ [ObservableProperty]
+ private string gameDiagnostics = string.Empty;
+
+ [RelayCommand]
+ private async Task InspectGameAsync()
+ {
+ try
+ {
+ var decision = this.gameSessionService == null ? null : await this.gameSessionService.GetDecisionAsync();
+ var report = await Task.Run(() => GameDiagnosticReport.Read(decision));
+ var plan = this.powerPlanService == null ? null : await this.powerPlanService.GetActivePowerPlan();
+ var relevant = this.TweakItems.Where(i => i.TweakType is SystemTweak.GameMode or SystemTweak.MemoryIntegrity
+ or SystemTweak.BackgroundRecording or SystemTweak.Hags or SystemTweak.WindowedOptimizations).ToList();
+ this.GameDiagnostics = report + Environment.NewLine + this.GameBoostDecisionText + Environment.NewLine + $"Power plan: {plan?.Name ?? "Unknown"}"
+ + Environment.NewLine + $"{relevant.Count} related settings (last refresh): "
+ + string.Join(", ", relevant.Select(i => $"{i.Name}: {i.StatusText}"))
+ + Environment.NewLine + "See Performance timeline for applied rules. Unparked CPU Sets indicate availability, not measured execution.";
+ }
+ catch (Exception ex)
+ {
+ this.GameDiagnostics = ex.Message;
+ }
+ }
[ObservableProperty]
private bool isGameBoostAvailable;
diff --git a/ViewModels/SystemTweaksViewModel.cs b/ViewModels/SystemTweaksViewModel.cs
index 5ad64a5..b8d2405 100644
--- a/ViewModels/SystemTweaksViewModel.cs
+++ b/ViewModels/SystemTweaksViewModel.cs
@@ -33,7 +33,8 @@ public SystemTweaksViewModel(
IEnhancedLoggingService? enhancedLoggingService = null,
IActivityAuditService? activityAuditService = null,
IApplicationSettingsService? settingsService = null,
- IGameSessionService? gameSessionService = null)
+ IGameSessionService? gameSessionService = null,
+ IPowerPlanService? powerPlanService = null)
: base(logger, enhancedLoggingService, activityAuditService)
{
this.systemTweaksService = systemTweaksService;
@@ -41,6 +42,7 @@ public SystemTweaksViewModel(
this.localizationService = localizationService;
this.settingsService = settingsService;
this.gameSessionService = gameSessionService;
+ this.powerPlanService = powerPlanService;
this.systemTweaksService.TweakStatusChanged += this.OnTweakStatusChanged;
this.localizationService.LanguageChanged += this.OnLanguageChanged;
@@ -54,7 +56,7 @@ private void InitializeTweakItems()
Enum.GetValues().Select(type => new SystemTweakItem
{
TweakType = type,
- IsGuidedAction = type is SystemTweak.MemoryIntegrity or SystemTweak.Hags or SystemTweak.WindowedOptimizations,
+ IsGuidedAction = type is SystemTweak.MemoryIntegrity or SystemTweak.Hags or SystemTweak.WindowedOptimizations or SystemTweak.BackgroundRecording,
ToggleCommand = new AsyncRelayCommand(this.ToggleTweakAsync),
ActionCommand = new AsyncRelayCommand(this.OpenTweakSettingsAsync),
}));
@@ -112,6 +114,7 @@ private async Task UpdateTweakItemStatusAsync(SystemTweakItem item)
{
TweakStatus status = item.TweakType switch
{
+ SystemTweak.BackgroundRecording => await this.systemTweaksService.GetBackgroundRecordingStatusAsync(),
SystemTweak.GameMode => await this.systemTweaksService.GetGameModeStatusAsync(),
SystemTweak.CoreParking => await this.systemTweaksService.GetCoreParkingStatusAsync(),
SystemTweak.CStates => await this.systemTweaksService.GetCStatesStatusAsync(),
@@ -274,6 +277,7 @@ private void ApplyLocalizedTweakText()
{
var text = item.TweakType switch
{
+ SystemTweak.BackgroundRecording => ("SystemTweak_Recording_Name", "Background recording", "SystemTweak_Recording_Desc", "Open Windows Captures to change background recording for this user."),
SystemTweak.GameMode => ("SystemTweak_GameMode_Name", "Game Mode", "SystemTweak_GameMode_Desc", "Windows Game Mode scheduling optimizations"),
SystemTweak.CoreParking => ("SystemTweak_CoreParking_Name", "Prevent Core Parking", "SystemTweak_CoreParking_Desc", "Keeps all logical processors unparked for the active power plan while plugged in."),
SystemTweak.CStates => ("SystemTweak_CStates_Name", "C-States", "SystemTweak_CStates_Desc", "Controls CPU C-States for power management"),
@@ -295,7 +299,7 @@ private void ApplyLocalizedTweakText()
item.Name = this.Localize(text.Item1, text.Item2);
item.Description = this.Localize(text.Item3, text.Item4);
- if (!string.IsNullOrEmpty(item.StatusText) && item.TweakType is not SystemTweak.Hags and not SystemTweak.WindowedOptimizations)
+ if (!string.IsNullOrEmpty(item.StatusText) && item.TweakType is not SystemTweak.Hags and not SystemTweak.WindowedOptimizations and not SystemTweak.BackgroundRecording)
{
item.StatusText = this.GetStatusText(new TweakStatus { IsAvailable = item.IsAvailable, IsEnabled = item.IsEnabled });
}
diff --git a/Views/CaptureComparisonWindow.xaml b/Views/CaptureComparisonWindow.xaml
new file mode 100644
index 0000000..f87e31e
--- /dev/null
+++ b/Views/CaptureComparisonWindow.xaml
@@ -0,0 +1,50 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Views/CaptureComparisonWindow.xaml.cs b/Views/CaptureComparisonWindow.xaml.cs
new file mode 100644
index 0000000..8fceb8c
--- /dev/null
+++ b/Views/CaptureComparisonWindow.xaml.cs
@@ -0,0 +1,184 @@
+namespace ThreadPilot.Views;
+
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using Microsoft.Win32;
+using ThreadPilot.Services;
+
+public partial class CaptureComparisonWindow : Window
+{
+ private CancellationTokenSource? importing;
+
+ private CancellationTokenSource? recording;
+ private TaskCompletionSource? start;
+ private bool closeAfterCapture;
+
+ protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
+ {
+ if (this.recording != null)
+ {
+ e.Cancel = true;
+ this.closeAfterCapture = true;
+ this.recording.Cancel();
+ }
+ base.OnClosing(e);
+ }
+
+ private void StartSegment(object sender, RoutedEventArgs e)
+ {
+ this.start?.TrySetResult();
+ this.StartMeasurement.IsEnabled = false;
+ }
+
+ private void CancelCapture(object sender, RoutedEventArgs e) => this.recording?.Cancel();
+
+ private async void ArmGame(object sender, RoutedEventArgs e)
+ {
+ var game = new OpenFileDialog { Filter = "Game executable|*.exe" };
+ if (game.ShowDialog(this) != true) return;
+ using var source = new CancellationTokenSource();
+ this.recording = source;
+ this.start = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ this.Arm.IsEnabled = false;
+ this.StopCapture.IsEnabled = true;
+ string? temp = null;
+ try
+ {
+ temp = System.IO.Path.GetTempFileName();
+ var progress = new Progress(message =>
+ {
+ this.RecorderStatus.Text = message;
+ this.StartMeasurement.IsEnabled = this.recording != null && message.StartsWith("Frames detected", StringComparison.Ordinal);
+ });
+ using (var output = System.IO.File.CreateText(temp))
+ {
+ var startTask = this.start.Task;
+ await Task.Run(() => GuidedFrameCapture.RunAsync(game.FileName, output, startTask, progress, source.Token));
+ }
+
+ source.Token.ThrowIfCancellationRequested();
+ var save = new SaveFileDialog { Filter = "PresentMon CSV|*.csv", FileName = "GameBoost-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") };
+ if (save.ShowDialog(this) == true)
+ {
+ using var captured = System.IO.File.OpenRead(temp);
+ await AtomicFileWriter.SaveExportAsync(save.FileName, captured);
+ this.RecorderStatus.Text = "Saved " + save.SafeFileName;
+ }
+ else this.RecorderStatus.Text = "Capture discarded.";
+ }
+ catch (OperationCanceledException) { this.RecorderStatus.Text = source.IsCancellationRequested ? "Capture cancelled." : "Game detection timed out."; }
+ catch (Exception ex) { this.RecorderStatus.Text = ex.Message; }
+ finally
+ {
+ this.recording = null;
+ this.start = null;
+ this.StopCapture.IsEnabled = this.StartMeasurement.IsEnabled = false;
+ this.Arm.IsEnabled = true;
+ try { if (temp != null) System.IO.File.Delete(temp); }
+ catch (System.IO.IOException ex) { this.RecorderStatus.Text = ex.Message; }
+ if (this.closeAfterCapture) this.Close();
+ }
+ }
+
+ private readonly CapturePairs pairs = new();
+ internal string? RuleTarget { get; private set; }
+
+ private async void ReadActivity(object sender, RoutedEventArgs e)
+ {
+ if (this.DataContext is not ViewModels.PerformanceViewModel vm) return;
+ try { this.Activity.Text = await vm.GetCaptureContextAsync(); }
+ catch (Exception ex) { this.Activity.Text = ex.Message; }
+ }
+
+ private void AddPair(object sender, RoutedEventArgs e)
+ {
+ try
+ {
+ if (this.Matched.IsChecked != true || this.StreamA.SelectedItem is not CaptureResult a || this.StreamB.SelectedItem is not CaptureResult b)
+ throw new InvalidOperationException("Choose both streams and confirm matching conditions first.");
+ this.PairResult.Text = this.pairs.Add(a, b);
+ this.ReviewRule.IsEnabled = this.pairs.Supported;
+ this.Matched.IsChecked = false;
+ }
+ catch (InvalidOperationException ex) { this.PairResult.Text = ex.Message; }
+ }
+
+ private void ClearPairs(object sender, RoutedEventArgs e)
+ {
+ this.pairs.Clear();
+ this.PairResult.Text = "";
+ this.ReviewRule.IsEnabled = false;
+ }
+
+ private void OpenRules(object sender, RoutedEventArgs e)
+ {
+ this.RuleTarget = this.pairs.Game;
+ this.Close();
+ }
+
+ public CaptureComparisonWindow()
+ {
+ this.InitializeComponent();
+ this.SourceInitialized += (_, _) => Helpers.DwmHelper.ApplyWindowCaptionTheme(
+ this, this.Background is SolidColorBrush b && b.Color.R + b.Color.G + b.Color.B < 384);
+ }
+
+ protected override void OnClosed(EventArgs e)
+ {
+ this.importing?.Cancel();
+ base.OnClosed(e);
+ }
+
+ private void CancelImport(object sender, RoutedEventArgs e) => this.importing?.Cancel();
+
+ private async void Import(object sender, RoutedEventArgs e)
+ {
+ var picker = new OpenFileDialog { Filter = "PresentMon CSV|*.csv" };
+ if (picker.ShowDialog(this) != true) return;
+ bool first = sender == this.LoadA;
+ var target = first ? this.StreamA : this.StreamB;
+ using var source = new CancellationTokenSource();
+ this.importing = source;
+ this.LoadA.IsEnabled = this.LoadB.IsEnabled = false;
+ this.StopImport.IsEnabled = true;
+ this.Status.Text = "Reading " + picker.SafeFileName;
+ try
+ {
+ var data = await Task.Run(() => PresentMonCsv.Read(picker.FileName, source.Token));
+ source.Token.ThrowIfCancellationRequested();
+ this.Matched.IsChecked = false;
+ target.ItemsSource = data;
+ target.SelectedIndex = data.Length == 1 ? 0 : -1;
+ (first ? this.NotesA : this.NotesB).Text = picker.SafeFileName + " · ";
+ this.Status.Text = data.Length == 1 ? "" : "Choose a process and swap chain.";
+ }
+ catch (OperationCanceledException) { this.Status.Text = "Import cancelled."; }
+ catch (Exception ex) { this.Status.Text = ex.Message; }
+ finally
+ {
+ this.importing = null;
+ this.LoadA.IsEnabled = this.LoadB.IsEnabled = true;
+ this.StopImport.IsEnabled = false;
+ }
+ }
+
+ private void SelectStream(object sender, SelectionChangedEventArgs e)
+ {
+ var a = this.StreamA.SelectedItem as CaptureResult;
+ var b = this.StreamB.SelectedItem as CaptureResult;
+ this.MetricsA.Text = a?.Summary;
+ this.MetricsB.Text = b?.Summary;
+ var max = Math.Max(a?.Peaks.Max() ?? 0, b?.Peaks.Max() ?? 0);
+ this.LineA.Points = Points(a, max);
+ this.LineB.Points = Points(b, max);
+ this.Scale.Text = $"Peak frame intervals · 0–{max:F1} ms · relative frame index · A blue / B orange";
+ this.Assessment.Text = a == null || b == null ? ""
+ : !string.Equals(a.Stream.Application, b.Stream.Application, StringComparison.OrdinalIgnoreCase) ? "Different games. These runs cannot establish a benefit."
+ : $"B − A: median {b.Median - a.Median:+0.00;-0.00;0} ms, P99 {b.P99 - a.P99:+0.00;-0.00;0} ms. Run-to-run variability unknown.";
+ }
+
+ private static PointCollection Points(CaptureResult? capture, double max)
+ => capture == null ? new() : new(capture.Peaks.Select((v, i) =>
+ new System.Windows.Point(i * 479d / Math.Max(1, capture.Peaks.Length - 1), 99 - 98 * v / max)));
+}
diff --git a/Views/PerformanceView.xaml b/Views/PerformanceView.xaml
index a7aa5ff..e6b1bee 100644
--- a/Views/PerformanceView.xaml
+++ b/Views/PerformanceView.xaml
@@ -77,6 +77,7 @@
+
diff --git a/Views/PerformanceView.xaml.cs b/Views/PerformanceView.xaml.cs
index 6efe630..807b5e8 100644
--- a/Views/PerformanceView.xaml.cs
+++ b/Views/PerformanceView.xaml.cs
@@ -10,6 +10,15 @@ public PerformanceView()
this.InitializeComponent();
}
+ private async void CompareCaptures(object sender, System.Windows.RoutedEventArgs e)
+ {
+ var dialog = new CaptureComparisonWindow { Owner = System.Windows.Window.GetWindow(this) };
+ dialog.DataContext = this.DataContext;
+ dialog.ShowDialog();
+ if (dialog.RuleTarget is string game && dialog.Owner is MainWindow main)
+ await main.ReviewGameRulesAsync(game);
+ }
+
public PerformanceView(PerformanceViewModel viewModel)
: this()
{
diff --git a/Views/SystemTweaksView.xaml b/Views/SystemTweaksView.xaml
index 67fd8a2..f1969fc 100644
--- a/Views/SystemTweaksView.xaml
+++ b/Views/SystemTweaksView.xaml
@@ -154,6 +154,11 @@
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
Margin="0,2,0,0"/>
+
+
+
+
+
+