Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions HardwareMonitor/HardwareMonitor.Tests/PercentileLowWiringTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -241,4 +241,21 @@ public void LowsIgnoreRowsFromAnotherApplication()

Assert.Equal(before, poller.OnePercentLow.Value!.Value);
}

[Fact]
public void ParseData_KeepsUnselectedAppsInPickerAndIgnoresShortRows()
{
var poller = NewPoller();

poller.ParseData("short.exe,0");
poller.ParseData(Row(0, 10).Replace(App, "Application"));
poller.ParseData(Row(0, 10).Replace(App, "other.exe"));

Assert.Equal(new[] { "other.exe" }, poller.SnapshotCurrentApps());
Assert.Equal(0f, poller.Presented.Value);

poller.ParseData(Row(10, 20).Replace(App, "GAME.EXE"));
Assert.Equal(50f, poller.Presented.Value);
Assert.Contains("GAME.EXE", poller.SnapshotCurrentApps());
}
}
4 changes: 4 additions & 0 deletions HardwareMonitor/HardwareMonitor/HardwareMonitor.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
<DebugType>none</DebugType>
</PropertyGroup>

<ItemGroup>
<RuntimeHostConfigurationOption Include="System.GC.ConserveMemory" Value="5" />
</ItemGroup>

<ItemGroup>
<!-- Lets HardwareMonitor.Tests drive PresentMonPoller.ParseData with
synthetic PresentMon CSV rows, so the percentile-low wiring is
Expand Down
35 changes: 9 additions & 26 deletions HardwareMonitor/HardwareMonitor/Monitor/MonitorPoller.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#pragma warning disable CS8601 // Possible null

using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Text.Json;
Expand All @@ -15,6 +14,11 @@ namespace HardwareMonitor.Monitor;

public class MonitorPoller : BackgroundService
{
private static readonly JsonSerializerOptions StatusJsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

private readonly ILogger<MonitorPoller> logger;
private readonly Func<CancellationToken, Task>? _hardwareOverride;
private readonly bool _startPresentMon;
Expand Down Expand Up @@ -131,8 +135,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
using var stream = new MemoryStream();
using var writer = new BinaryWriter(stream);
writer.Write((short)MonitorPacketCommand.HardwareStatus);
writer.Write(JsonSerializer.SerializeToUtf8Bytes(status,
new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }));
writer.Write(JsonSerializer.SerializeToUtf8Bytes(status, StatusJsonOptions));
await _socketHost.SendToAllAsync(stream.ToArray());
}
await Task.Delay(1000, stoppingToken);
Expand Down Expand Up @@ -247,7 +250,6 @@ private async Task PollHardwareCoreAsync(CancellationToken stoppingToken)

using var memoryStream = new MemoryStream();
using var writer = new BinaryWriter(memoryStream);
var accumulator = 0;

WriteDataToStream(writer, sharedMemoryData);
_progress.Ready();
Expand Down Expand Up @@ -289,7 +291,7 @@ private async Task PollHardwareCoreAsync(CancellationToken stoppingToken)
{
try
{
_progress.Begin($"Reading sensors: {hardware.Name}");
_progress.Begin(hardware.ReadStage);
hardware.Update();
}
catch
Expand Down Expand Up @@ -342,27 +344,15 @@ private async Task PollHardwareCoreAsync(CancellationToken stoppingToken)
//logger.LogInformation("No clients connected, not sending data");
}

if (accumulator >= 1000)
{
GC.Collect();
accumulator = 0;
}

// Advance by the interval actually being waited, not a hardcoded
// 500. The accumulator is meant to make this a once-a-second
// collection; with a fixed 500 it instead tracked poll count, so at
// the 33ms floor it forced a full GC roughly every 66ms, about 15x
// too often, and only matched its intent at the default rate.
_progress.Ready();
accumulator += _pollingRate;
await Task.Delay(_pollingRate, stoppingToken);
}

}

private static void WriteDataToStream(BinaryWriter writer, SharedMemoryData sharedMemoryData)
{
writer.Seek(0, SeekOrigin.Begin);
writer.BaseStream.SetLength(0);
writer.Write((short)MonitorPacketCommand.Data);
writer.Write(sharedMemoryData.Hardwares.Count);
writer.Write(sharedMemoryData.Sensors.Count);
Expand All @@ -379,8 +369,7 @@ private static void WriteDataToStream(BinaryWriter writer, SharedMemoryData shar
foreach (var sensor in sharedMemoryData.Sensors)
{
var value = sensor.HardwareSensor.Value ?? 0f;
var floatValue = (IsNaN(value) ? 0f : value).ToString(CultureInfo.InvariantCulture);
sensor.Value = float.Parse(floatValue, CultureInfo.InvariantCulture);
sensor.Value = float.IsNaN(value) ? 0f : value;

writer.Write((short)sensor.Name.Length);
writer.Write((short)sensor.Identifier.Length);
Expand Down Expand Up @@ -896,10 +885,4 @@ public static string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_ .]+", "_", RegexOptions.Compiled);
}

public static unsafe bool IsNaN(float f)
{
int binary = *(int*)(&f);
return ((binary & 0x7F800000) == 0x7F800000) && ((binary & 0x007FFFFF) != 0);
}
}
85 changes: 45 additions & 40 deletions HardwareMonitor/HardwareMonitor/PresentMon/PresentMonPoller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -432,27 +432,26 @@ public void Stop()
internal void ParseData(string? argsData)
{
if (argsData == null) return;
var parts = argsData.Split(",");

// One-shot raw-row dump verifies PresentMon's actual column layout
// matches the hard-coded indices ([0]=app, [9]=frametime,
// [17]=displayed). If PresentMon's CSV format changed, attribution
// would silently read wrong columns — this catches that.
var seen = Interlocked.Increment(ref _rawRowsLogged);
if (seen <= RAW_ROWS_TO_LOG)
var commaCount = argsData.AsSpan().Count(',');
var debug = logger.IsEnabled(LogLevel.Debug);
if (debug)
{
logger.LogDebug("[FPS-DEBUG] Raw row {N} ({Cols} cols): {Line}",
seen, parts.Length, argsData);
// Confirm the real CSV column layout without splitting unrelated rows.
var seen = Interlocked.Increment(ref _rawRowsLogged);
if (seen <= RAW_ROWS_TO_LOG)
logger.LogDebug("[FPS-DEBUG] Raw row {N} ({Cols} cols): {Line}",
seen, commaCount + 1, argsData);

Interlocked.Increment(ref _totalRowCount);
}

Interlocked.Increment(ref _totalRowCount);
if (parts.Length < 18)
if (commaCount < 17)
{
Interlocked.Increment(ref _shortRowCount);
if (debug) Interlocked.Increment(ref _shortRowCount);
return;
}

var rowApp = parts[0];
var rowApp = argsData[..argsData.IndexOf(',')];

// PresentMon writes the CSV header before the first frame row, and it
// is wide enough to survive the length check above. Its first column
Expand Down Expand Up @@ -506,13 +505,15 @@ internal void ParseData(string? argsData)
&& string.Equals(_foregroundAppName, rowApp, StringComparison.OrdinalIgnoreCase);
}

if (match)
_countedByApp[rowApp] = _countedByApp.GetValueOrDefault(rowApp) + 1;
else
_droppedByApp[rowApp] = _droppedByApp.GetValueOrDefault(rowApp) + 1;
if (debug)
{
var counts = match ? _countedByApp : _droppedByApp;
counts[rowApp] = counts.GetValueOrDefault(rowApp) + 1;
}

if (!match) return;

var parts = argsData.Split(',');
// Parse PresentMon's per-frame timestamps. CPUStartTime [8]
// is monotonic ms since capture start; FrameTime [9] is the
// present-to-present interval. fps = N * 1000 / Σ frametime
Expand Down Expand Up @@ -913,13 +914,11 @@ private async Task LogFpsDiagnosticsAsync(CancellationToken cancellationToken)
break;
}

Dictionary<string, int> counted, dropped;
int total, shortRows;
string fg, sel;
int presentedQueue, displayedQueue;
float fps, ft;
var debug = logger.IsEnabled(LogLevel.Debug);
(Dictionary<string, int> Counted, Dictionary<string, int> Dropped,
int Total, int ShortRows, string Foreground, string Selected,
int Presented, int Displayed, float Fps, float Frametime, long LowsFrames)? diagnostics = null;
bool stale;
long lowsFrames;
lock (_stateLock)
{
// Re-trim and recompute under the lock so the overlay value
Expand Down Expand Up @@ -968,18 +967,6 @@ private async Task LogFpsDiagnosticsAsync(CancellationToken cancellationToken)
// between bursts.
}

counted = new Dictionary<string, int>(_countedByApp, StringComparer.OrdinalIgnoreCase);
dropped = new Dictionary<string, int>(_droppedByApp, StringComparer.OrdinalIgnoreCase);
_countedByApp.Clear();
_droppedByApp.Clear();
total = Interlocked.Exchange(ref _totalRowCount, 0);
shortRows = Interlocked.Exchange(ref _shortRowCount, 0);
fg = _foregroundAppName;
sel = _currentSelectedApp;
presentedQueue = _presentedFrames.Count;
displayedQueue = _displayedFrames.Count;
fps = Presented.Value ?? 0f;
ft = Frametime.Value ?? 0f;
// Computed under the lock rather than on a snapshot taken out
// of it. In Recording the walk starts at the slowest frame
// recorded and stops at the 1% crossing, so it reads a few
Expand All @@ -1000,8 +987,25 @@ private async Task LogFpsDiagnosticsAsync(CancellationToken cancellationToken)
// leaving the write out is what makes "frozen" true of the
// published value and not just of its inputs.
PublishLows(_lowsMode);
lowsFrames = _lowsMode == LowsMode.Live ? _lowsLive.FrameCount : _lows.FrameCount;
if (debug)
{
diagnostics = (
new Dictionary<string, int>(_countedByApp, StringComparer.OrdinalIgnoreCase),
new Dictionary<string, int>(_droppedByApp, StringComparer.OrdinalIgnoreCase),
Interlocked.Exchange(ref _totalRowCount, 0),
Interlocked.Exchange(ref _shortRowCount, 0),
_foregroundAppName, _currentSelectedApp,
_presentedFrames.Count, _displayedFrames.Count,
Presented.Value ?? 0f, Frametime.Value ?? 0f,
_lowsMode == LowsMode.Live ? _lowsLive.FrameCount : _lows.FrameCount);
_countedByApp.Clear();
_droppedByApp.Clear();
}
}

if (diagnostics is not { } snapshot) continue;
var (counted, dropped, total, shortRows, fg, sel, presentedQueue,
displayedQueue, fps, ft, lowsFrames) = snapshot;
var countedStr = counted.Count == 0
? "-"
: string.Join(", ", counted.OrderByDescending(kv => kv.Value).Select(kv => $"{kv.Key}:{kv.Value}"));
Expand Down Expand Up @@ -1047,9 +1051,10 @@ private async Task PollForegroundAsync(CancellationToken cancellationToken)
{
if (!string.Equals(newName, _foregroundAppName, StringComparison.OrdinalIgnoreCase))
{
logger.LogDebug("[FPS-DEBUG] Foreground change: {Old} -> {New}",
string.IsNullOrEmpty(_foregroundAppName) ? "(empty)" : _foregroundAppName,
string.IsNullOrEmpty(newName) ? "(empty)" : newName);
if (logger.IsEnabled(LogLevel.Debug))
logger.LogDebug("[FPS-DEBUG] Foreground change: {Old} -> {New}",
string.IsNullOrEmpty(_foregroundAppName) ? "(empty)" : _foregroundAppName,
string.IsNullOrEmpty(newName) ? "(empty)" : newName);
_foregroundAppName = newName;
if (_currentSelectedApp == NO_SELECTED_APP)
{
Expand Down
13 changes: 12 additions & 1 deletion HardwareMonitor/HardwareMonitor/SharedMemory/SharedMemory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,18 @@ public class SharedMemoryHardware
/// nothing to update. See HardwareMonitor.Monitor.GpuReconciler.
/// </summary>
public required IHardware? Hardware;
public required string Name { get; set; }
private string _name = "";
public required string Name
{
get => _name;
set
{
_name = value;
ReadStage = $"Reading sensors: {value}";
}
}

internal string ReadStage { get; private set; } = "";
public required string Identifier { get; set; }
public required HardwareType HardwareType { get; set; }

Expand Down
19 changes: 19 additions & 0 deletions tauri-app/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,16 @@ pub fn bring_to_front(window: &tauri::WebviewWindow) {
let _ = window.set_focus();
}

pub fn show_settings(window: &tauri::WebviewWindow) {
let _ = window.show();
bring_to_front(window);
let app = window.app_handle();
let handle = app.clone();
let _ = app.run_on_main_thread(move || {
crate::pipe_client::replay_settings_snapshot(&handle, false);
});
}

/// Recompute the gate from live window state and apply it.
///
/// The overlay accepts mouse input only while the settings window is visible *and*
Expand Down Expand Up @@ -318,6 +328,15 @@ pub fn set_overlay_visible(visible: bool, app: AppHandle) {
}
}

#[tauri::command]
pub fn toggle_overlay(app: AppHandle) {
if let Some(window) = app.get_webview_window("overlay") {
if let Ok(visible) = window.is_visible() {
set_overlay_visible(!visible, app);
}
}
}

/// Reassert native stacking, not just tao's cached always-on-top flag. Another
/// topmost window can move above the HUD without changing that cached flag.
#[cfg(windows)]
Expand Down
15 changes: 10 additions & 5 deletions tauri-app/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ pub fn run() {
let _ = logger.try_init();

tauri::Builder::default()
.manage(pipe_client::SensorSnapshots::default())
.plugin(tauri_plugin_global_shortcut::Builder::new().build())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_dialog::init())
Expand All @@ -288,8 +289,7 @@ pub fn run() {
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
// Focus the existing settings window when a second instance launches
if let Some(window) = app.get_webview_window("settings") {
let _ = window.show();
commands::bring_to_front(&window);
commands::show_settings(&window);
}
}))
.setup(|app| {
Expand Down Expand Up @@ -369,8 +369,7 @@ pub fn run() {
// Honor "Start minimized": when on, leave the settings window
// hidden (config is visible:false) so the app starts to tray.
if !start_minimized {
let _ = window.show();
commands::bring_to_front(&window);
commands::show_settings(&window);
}
}

Expand Down Expand Up @@ -618,8 +617,11 @@ pub fn run() {
// the HUD, which activated the overlay" (keep it open, a
// drag just started). sync_overlay_interactive tells those
// apart by asking whether any window of ours is in front.
tauri::WindowEvent::Focused(_) => {
tauri::WindowEvent::Focused(focused) => {
commands::sync_overlay_interactive(&app_handle3);
if *focused {
pipe_client::replay_settings_snapshot(&app_handle3, false);
}
}
tauri::WindowEvent::CloseRequested { api, .. } => {
api.prevent_close();
Expand All @@ -640,6 +642,7 @@ pub fn run() {
commands::apply_overlay_interactive(&app_handle3, false);
}
tauri::WindowEvent::Resized(_) => {
pipe_client::replay_settings_snapshot(&app_handle3, false);
if w_for_event.is_maximized().unwrap_or(false) {
let _ = w_for_event.unmaximize();
// Snap to full monitor height (minus taskbar) at 651 wide
Expand Down Expand Up @@ -678,6 +681,8 @@ pub fn run() {
commands::get_preferences,
commands::save_preferences,
commands::set_overlay_visible,
commands::toggle_overlay,
pipe_client::request_settings_sensor_snapshot,
commands::set_overlay_position,
commands::set_overlay_size,
commands::set_overlay_opacity,
Expand Down
Loading
Loading