Repository navigation
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
543 lines (480 loc) · 21.6 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
543 lines (480 loc) · 21.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using SystemMonitorApp.Models;
using SystemMonitorApp.Services;
using SystemMonitorApp.ViewModels;
using SystemMonitorApp.Views;
namespace SystemMonitorApp
{
/// <summary>
/// View layer. All hardware access happens in HardwareService; all state lives in
/// MainViewModel. This code-behind renders panels imperatively from snapshots —
/// Sprint 4 will replace the imperative panel rendering with XAML binding + ItemsControl.
/// </summary>
public partial class MainWindow : Window
{
private MainViewModel? _viewModel;
private bool _panelsInitialized;
// Cached TextBlocks — built once, updated per snapshot to avoid GC pressure.
private TextBlock[] _cpuCoreTextBlocks = Array.Empty<TextBlock>();
private TextBlock? _memoryInfoText;
private TextBlock? _gpuInfoText;
private TextBlock? _systemStatusText;
private TextBlock? _systemUptimeText;
private TextBlock? _hardwareInfoText;
private readonly Dictionary<string, TextBlock> _thermalTextBlocks = new();
private readonly Dictionary<string, TextBlock> _fanTextBlocks = new();
public MainWindow()
{
InitializeComponent();
}
/// <summary>Called from App.xaml.cs after splash so heavy init runs off the UI thread.</summary>
public async Task InitializeAsync()
{
var hardware = new HardwareService();
_viewModel = new MainViewModel(hardware);
DataContext = _viewModel;
InitializePanels(Environment.ProcessorCount, hardware.HardwareInfoText);
_viewModel.SnapshotChanged += OnSnapshotChanged;
await _viewModel.StartAsync();
// Hardware info becomes available after StartAsync — refresh the cached panel text.
if (_hardwareInfoText != null)
_hardwareInfoText.Text = _viewModel.HardwareInfoText;
Loaded += OnLoaded;
StateChanged += OnWindowStateChanged;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
// Reserved for future Loaded-time work.
}
/// <summary>
/// Triggers hardware diagnostic report writing in the background. Called by App
/// after the main window is shown so it doesn't add to perceived startup time.
/// </summary>
public void ScheduleBackgroundDiagnostics()
=> _viewModel?.ScheduleBackgroundDiagnostics();
private void OnWindowStateChanged(object? sender, EventArgs e)
{
if (_viewModel == null) return;
if (!SettingsService.Current.PauseWhenMinimized) return;
if (WindowState == WindowState.Minimized)
_viewModel.PauseTimer();
else
_viewModel.ResumeTimer();
}
private void OnSnapshotChanged(object? sender, SystemSnapshot snapshot)
{
if (!_panelsInitialized) return;
try
{
// Hero card values are already bound via DataContext in XAML for simple ones;
// since XAML still uses x:Name for these, we set directly. Sprint 4 converts to binding.
CpuValueText.Text = _viewModel?.CpuUsageDisplay ?? "";
MemoryValueText.Text = _viewModel?.MemoryUsageDisplay ?? "";
MemoryProgressBar.Value = snapshot.MemoryUsagePercent;
GpuValueText.Text = _viewModel?.GpuUsageDisplay ?? "";
TempValueText.Text = _viewModel?.TemperatureDisplay ?? "";
UpdateCpuCoresPanel(snapshot.CpuCores);
UpdateMemoryPanel(snapshot);
UpdateGpuInfoPanel(snapshot.GpuInfoText);
UpdateThermalPanel(snapshot.Thermals);
UpdateCpuCoolingPanel(snapshot.CpuCooling);
UpdateGpuCoolingPanel(snapshot.GpuCooling);
UpdateSystemPanel(snapshot);
}
catch (Exception ex)
{
Logger.Warn("MainWindow.OnSnapshotChanged failed", ex);
}
}
private void InitializePanels(int coreCount, string hardwareInfoText)
{
int displayCount = Math.Min(coreCount, 16);
_cpuCoreTextBlocks = new TextBlock[displayCount];
CpuCoresPanel.Children.Clear();
for (int i = 0; i < displayCount; i++)
{
var tb = new TextBlock
{
Style = (Style)FindResource("DataText"),
Margin = new Thickness(0, 2, 0, 0),
Text = $"Core {i}: 0%"
};
_cpuCoreTextBlocks[i] = tb;
CpuCoresPanel.Children.Add(tb);
}
MemoryPanel.Children.Clear();
_memoryInfoText = new TextBlock { Style = (Style)FindResource("DataText") };
MemoryPanel.Children.Add(_memoryInfoText);
GpuInfoPanel.Children.Clear();
_gpuInfoText = new TextBlock
{
Style = (Style)FindResource("DataText"),
TextWrapping = TextWrapping.Wrap
};
GpuInfoPanel.Children.Add(_gpuInfoText);
SystemPanel.Children.Clear();
_systemStatusText = new TextBlock { Style = (Style)FindResource("DataText") };
_systemUptimeText = new TextBlock
{
Style = (Style)FindResource("DataText"),
Foreground = (SolidColorBrush)FindResource("TextMutedBrush")
};
SystemPanel.Children.Add(_systemStatusText);
SystemPanel.Children.Add(_systemUptimeText);
HardwarePanel.Children.Clear();
_hardwareInfoText = new TextBlock
{
Style = (Style)FindResource("DataText"),
TextWrapping = TextWrapping.Wrap,
Text = hardwareInfoText
};
HardwarePanel.Children.Add(_hardwareInfoText);
_panelsInitialized = true;
}
private void UpdateCpuCoresPanel(IReadOnlyList<CpuCoreInfo> cores)
{
for (int i = 0; i < _cpuCoreTextBlocks.Length && i < cores.Count; i++)
{
var tb = _cpuCoreTextBlocks[i];
var core = cores[i];
tb.Text = $"{core.Name}: {core.UsagePercent:F1}%";
if (core.UsagePercent > 80)
tb.Foreground = (SolidColorBrush)FindResource("ErrorBrush");
else if (core.UsagePercent > 60)
tb.Foreground = (SolidColorBrush)FindResource("WarnBrush");
else
tb.Foreground = (SolidColorBrush)FindResource("AccentBrush");
}
}
private void UpdateMemoryPanel(SystemSnapshot s)
{
if (_memoryInfoText == null) return;
_memoryInfoText.Text = $"Used: {s.UsedMemoryGB:F1} GB / {s.TotalMemoryGB:F1} GB\n" +
$"Available: {s.AvailableMemoryGB:F1} GB";
}
private void UpdateGpuInfoPanel(string text)
{
if (_gpuInfoText == null) return;
_gpuInfoText.Text = text;
}
private void UpdateThermalPanel(IReadOnlyDictionary<string, float> thermals)
{
foreach (var kvp in thermals)
{
if (!_thermalTextBlocks.TryGetValue(kvp.Key, out var tb))
{
tb = new TextBlock
{
Style = (Style)FindResource("DataText"),
Margin = new Thickness(0, 2, 0, 0),
TextWrapping = TextWrapping.Wrap
};
_thermalTextBlocks[kvp.Key] = tb;
ThermalPanel.Children.Add(tb);
}
string tempName = kvp.Key.Length > 25 ? kvp.Key.Substring(0, 22) + "..." : kvp.Key;
SolidColorBrush brush;
if (kvp.Value > 80) brush = (SolidColorBrush)FindResource("ErrorBrush");
else if (kvp.Value > 60) brush = (SolidColorBrush)FindResource("WarnBrush");
else brush = (SolidColorBrush)FindResource("AccentBrush");
// Color-coded text — no emoji icons (Sprint 4 UI update).
tb.Text = $"{tempName}: {kvp.Value:F0}°C";
tb.Foreground = brush;
}
var toRemove = _thermalTextBlocks.Keys.Where(k => !thermals.ContainsKey(k)).ToList();
foreach (var key in toRemove)
{
ThermalPanel.Children.Remove(_thermalTextBlocks[key]);
_thermalTextBlocks.Remove(key);
}
if (_thermalTextBlocks.Count == 0 && ThermalPanel.Children.Count == 0)
{
ThermalPanel.Children.Add(new TextBlock
{
Text = "Temperature data not available",
Style = (Style)FindResource("DataText"),
Foreground = (SolidColorBrush)FindResource("TextMutedBrush")
});
}
}
// Render the CPU cooling panel. Uses CoolingReadout entries which work on
// every Windows 11 system because they come from CPU MSR + NVIDIA driver API,
// not motherboard SuperIO (which may be blocked by Windows security or other apps).
private void UpdateCpuCoolingPanel(IReadOnlyList<CoolingReadout> readouts)
{
CpuFansPanel.Children.Clear();
if (readouts.Count == 0)
{
CpuFansPanel.Children.Add(new TextBlock
{
Text = "Waiting for CPU sensors...",
Style = (Style)FindResource("DataText"),
Foreground = (SolidColorBrush)FindResource("TextMutedBrush")
});
return;
}
foreach (var r in readouts)
CpuFansPanel.Children.Add(BuildCoolingRow(r));
// If no fan readouts are present among CPU cooling data, show a concise
// "why no RPM" note. SuperIO-based RPM reading requires BIOS to hand
// over PWM control to the OS (Smart Fan 5 → Full Speed on Gigabyte).
bool hasFanRow = false;
foreach (var r in readouts)
{
if (r.DisplayValue.Contains("RPM") || r.DisplayValue.EndsWith("%"))
{ hasFanRow = true; break; }
}
if (!hasFanRow)
{
var hint = new TextBlock
{
Style = (Style)FindResource("DataText"),
Foreground = (SolidColorBrush)FindResource("TextMutedBrush"),
TextWrapping = TextWrapping.Wrap,
Margin = new Thickness(0, 12, 0, 0),
Text = "Fan RPM not available.\n" +
"Enable in BIOS: Smart Fan 5 / Q-Fan / Fan Xpert → \"Manual\" or \"Full Speed\"."
};
CpuFansPanel.Children.Add(hint);
}
}
private void UpdateGpuCoolingPanel(IReadOnlyList<CoolingReadout> readouts)
{
SystemFansPanel.Children.Clear();
if (readouts.Count == 0)
{
SystemFansPanel.Children.Add(new TextBlock
{
Text = "No GPU sensor available",
Style = (Style)FindResource("DataText"),
Foreground = (SolidColorBrush)FindResource("TextMutedBrush")
});
return;
}
foreach (var r in readouts)
SystemFansPanel.Children.Add(BuildCoolingRow(r));
}
private TextBlock BuildCoolingRow(CoolingReadout readout)
{
SolidColorBrush brush = readout.Severity switch
{
CoolingSeverity.Critical => (SolidColorBrush)FindResource("ErrorBrush"),
CoolingSeverity.Warning => (SolidColorBrush)FindResource("WarnBrush"),
CoolingSeverity.Healthy => (SolidColorBrush)FindResource("AccentBrush"),
CoolingSeverity.Idle => (SolidColorBrush)FindResource("TextMutedBrush"),
_ => (SolidColorBrush)FindResource("TextSecondaryBrush")
};
string label = readout.Label.Length > 26
? readout.Label.Substring(0, 23) + "..."
: readout.Label;
return new TextBlock
{
Text = $"{label}: {readout.DisplayValue}",
Style = (Style)FindResource("DataText"),
Foreground = brush,
Margin = new Thickness(0, 2, 0, 0),
TextWrapping = TextWrapping.NoWrap
};
}
private void UpdateFanPanels(IReadOnlyDictionary<string, FanReading> fans)
{
foreach (var kvp in fans)
{
string key = kvp.Key;
FanReading reading = kvp.Value;
string displayName = key.Length > 20 ? key.Substring(0, 17) + "..." : key;
if (!_fanTextBlocks.TryGetValue(key, out var tb))
{
tb = new TextBlock
{
Style = (Style)FindResource("DataText"),
TextWrapping = TextWrapping.Wrap,
Margin = new Thickness(0, 1, 0, 1)
};
_fanTextBlocks[key] = tb;
bool routeToGpuPanel = reading.IsGpu
|| key.Contains("gpu", StringComparison.OrdinalIgnoreCase)
|| key.Contains("nvidia", StringComparison.OrdinalIgnoreCase)
|| key.Contains("geforce", StringComparison.OrdinalIgnoreCase)
|| key.Contains("radeon", StringComparison.OrdinalIgnoreCase);
if (routeToGpuPanel) SystemFansPanel.Children.Add(tb);
else CpuFansPanel.Children.Add(tb);
}
FormatFanText(tb, displayName, reading);
}
var toRemove = _fanTextBlocks.Keys.Where(k => !fans.ContainsKey(k)).ToList();
foreach (var key in toRemove)
{
var tb = _fanTextBlocks[key];
CpuFansPanel.Children.Remove(tb);
SystemFansPanel.Children.Remove(tb);
_fanTextBlocks.Remove(key);
}
EnsureFanEmptyPlaceholders();
}
private void FormatFanText(TextBlock tb, string displayName, FanReading reading)
{
// Color-coded text — no emoji icons (Sprint 4 UI update).
if (reading.IsPercent)
{
tb.Text = $"{displayName}: {reading.RawValue:F0}%";
tb.Foreground = reading.RawValue > 70
? (SolidColorBrush)FindResource("WarnBrush")
: (SolidColorBrush)FindResource("AccentBrush");
return;
}
if (reading.RawValue > 2000)
{
tb.Text = $"{displayName}: {reading.RawValue:F0} RPM";
tb.Foreground = (SolidColorBrush)FindResource("AccentBrush");
}
else if (reading.RawValue > 800)
{
tb.Text = $"{displayName}: {reading.RawValue:F0} RPM";
tb.Foreground = (SolidColorBrush)FindResource("WarnBrush");
}
else if (reading.RawValue > 0)
{
tb.Text = $"{displayName}: {reading.RawValue:F0} RPM";
tb.Foreground = (SolidColorBrush)FindResource("ErrorBrush");
}
else
{
if (reading.IsGpu)
{
tb.Text = $"{displayName}: Zero RPM Mode";
tb.Foreground = (SolidColorBrush)FindResource("AccentBrush");
}
else
{
tb.Text = $"{displayName}: Inactive";
tb.Foreground = (SolidColorBrush)FindResource("TextMutedBrush");
}
}
}
private void EnsureFanEmptyPlaceholders()
{
string reportHint = HardwareDiagnostics.LastReportPath != null
? $"\n\nDiagnostikrapport: {HardwareDiagnostics.LastReportPath}"
: "";
if (CpuFansPanel.Children.Count == 0)
{
CpuFansPanel.Children.Add(new TextBlock
{
Text = "No CPU/system fans detected\n\n" +
"The motherboard's SuperIO chip (ITE / Nuvoton) is normally read for\n" +
"fan data, but can be blocked by:\n" +
"• Windows 11 Insider / 25H2 restricts port I/O to the LPC bus\n" +
"• Motherboard is in LHM's database but the SuperIO chip is not\n" +
" mapped for your specific variant/revision\n" +
"• Another application (AORUS Engine, ASUS AI Suite, Armoury Crate)\n" +
" has exclusive access to SuperIO\n" +
"• Fans are directly connected to PSU without an RPM pin\n\n" +
"Troubleshooting:\n" +
"1. Run HWiNFO64 — if it also cannot find the fans, this is a\n" +
" Windows or BIOS limitation\n" +
"2. Close other hardware monitoring apps and restart\n" +
"3. Update BIOS" +
reportHint,
Style = (Style)FindResource("DataText"),
Foreground = (SolidColorBrush)FindResource("TextMutedBrush"),
TextWrapping = TextWrapping.Wrap
});
}
if (SystemFansPanel.Children.Count == 0)
{
SystemFansPanel.Children.Add(new TextBlock
{
Text = "No GPU fans detected\n\n" +
"Common on modern GPUs:\n" +
"• Zero-RPM Mode — fans stop below ~55°C\n" +
"• Hybrid graphics where the dGPU is powered off\n" +
"• Driver does not expose a load sensor",
Style = (Style)FindResource("DataText"),
Foreground = (SolidColorBrush)FindResource("TextMutedBrush"),
TextWrapping = TextWrapping.Wrap
});
}
}
private void UpdateSystemPanel(SystemSnapshot s)
{
if (_systemStatusText == null || _systemUptimeText == null) return;
SolidColorBrush color = s.SystemStatus switch
{
SystemStatusEvaluator.High => (SolidColorBrush)FindResource("ErrorBrush"),
SystemStatusEvaluator.Medium => (SolidColorBrush)FindResource("WarnBrush"),
_ => (SolidColorBrush)FindResource("AccentBrush")
};
_systemStatusText.Text = $"Status: {s.SystemStatus}";
_systemStatusText.Foreground = color;
_systemUptimeText.Text = $"Updated: {s.Timestamp:HH:mm:ss}";
}
// ===== UI chrome handlers =====
// Note: WindowChrome handles drag-to-move and double-click-to-maximize natively —
// no explicit DragMove handler needed.
private void MinimizeButton_Click(object sender, RoutedEventArgs e)
=> this.WindowState = WindowState.Minimized;
private void MaximizeButton_Click(object sender, RoutedEventArgs e)
=> this.WindowState = this.WindowState == WindowState.Maximized
? WindowState.Normal
: WindowState.Maximized;
private void CloseButton_Click(object sender, RoutedEventArgs e) => this.Close();
private void SettingsButton_Click(object sender, RoutedEventArgs e)
{
try
{
var dlg = new SettingsWindow { Owner = this };
if (dlg.ShowDialog() == true)
{
// Settings changed — propagate poll-interval change to the running timer.
_viewModel?.ApplyUpdatedSettings();
}
}
catch (Exception ex)
{
Logger.Warn("Open SettingsWindow failed", ex);
MessageBox.Show("Could not open settings. See the log for details.",
"SystemFlow Pro", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void AboutButton_Click(object sender, RoutedEventArgs e)
{
try
{
var dlg = new AboutWindow { Owner = this };
dlg.ShowDialog();
}
catch (Exception ex)
{
Logger.Warn("Open AboutWindow failed", ex);
MessageBox.Show("Could not open the About dialog. See the log for details.",
"SystemFlow Pro", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
protected override void OnClosed(EventArgs e)
{
try
{
StateChanged -= OnWindowStateChanged;
Loaded -= OnLoaded;
if (_viewModel != null)
{
_viewModel.SnapshotChanged -= OnSnapshotChanged;
_viewModel.Dispose();
_viewModel = null;
}
}
catch (Exception ex)
{
Logger.Warn("MainWindow.OnClosed cleanup failed", ex);
}
base.OnClosed(e);
}
}
}