Repository navigation
Expand file tree
/
Copy pathMainForm.cs
More file actions
847 lines (766 loc) · 33.4 KB
/
Copy pathMainForm.cs
File metadata and controls
847 lines (766 loc) · 33.4 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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ETDucky.AvProfiler.Models;
using ETDucky.AvProfiler.Services;
namespace ETDucky.AvProfiler;
/// <summary>
/// AvProfiler shell. Four tabs:
///
/// Record — operator picks a process filter, hits Start, runs the
/// slow workload, hits Stop.
/// Results — Hot Paths / Hot Processes / Hot Extensions grids;
/// Minifilter stack at the bottom.
/// Recommend — per-vendor exclusion commands with Copy buttons.
/// Help — primer on minifilters + exclusion safety + caveats.
///
/// Designer-free: every control is built in code so the file is the
/// single source of truth (no separate .Designer.cs that drifts).
/// </summary>
public sealed class MainForm : Form
{
// ── Capture state ─────────────────────────────────────────────────
private CaptureSession? _session;
private IrpLatencyCapture? _capture;
private Task? _captureTask;
private BaselineProbe.Result? _baseline;
private CaptureSummary? _summary;
// ── Record tab controls ───────────────────────────────────────────
private TextBox _processFilter = null!;
private TextBox _description = null!;
private Button _startButton = null!;
private Button _stopButton = null!;
private Label _statusLabel = null!;
private Label _eventsLabel = null!;
private System.Windows.Forms.Timer _statsTimer = null!;
// ── Results tab ───────────────────────────────────────────────────
private DataGridView _hotPathsGrid = null!;
private DataGridView _hotProcessesGrid = null!;
private DataGridView _hotExtensionsGrid = null!;
private DataGridView _minifiltersGrid = null!;
// ── Recommend tab ─────────────────────────────────────────────────
private FlowLayoutPanel _recommendationsPanel = null!;
// ── Comparison state (i2.5) ───────────────────────────────────────
// When the user loads a previous report via "Compare to saved...",
// _previousSummary holds it and the grids gain a Δ column showing the
// per-row change since that previous run.
private CaptureSummary? _previousSummary;
private Button? _clearComparisonButton;
public MainForm()
{
Text = "ET Ducky AvProfiler";
Size = new Size(1280, 820);
MinimumSize = new Size(960, 600);
StartPosition = FormStartPosition.CenterScreen;
Icon = LoadEmbeddedIcon() ?? Icon;
BuildUi();
}
// ── UI construction ───────────────────────────────────────────────
private void BuildUi()
{
var tabs = new TabControl { Dock = DockStyle.Fill };
tabs.TabPages.Add(BuildRecordTab());
tabs.TabPages.Add(BuildResultsTab());
tabs.TabPages.Add(BuildRecommendTab());
tabs.TabPages.Add(BuildHelpTab());
Controls.Add(tabs);
}
private TabPage BuildRecordTab()
{
var page = new TabPage("Record");
var layout = new TableLayoutPanel
{
Dock = DockStyle.Fill,
ColumnCount = 2,
RowCount = 6,
Padding = new Padding(16),
};
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 180));
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
for (int i = 0; i < 5; i++)
layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
layout.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
// Process filter
layout.Controls.Add(new Label
{
Text = "Process filter (regex):",
Anchor = AnchorStyles.Left | AnchorStyles.Right,
TextAlign = ContentAlignment.MiddleLeft,
Margin = new Padding(0, 6, 8, 6),
}, 0, 0);
_processFilter = new TextBox
{
Anchor = AnchorStyles.Left | AnchorStyles.Right,
Margin = new Padding(0, 6, 0, 6),
PlaceholderText = "e.g. msbuild|devenv|dotnet (leave blank or * for system-wide)",
};
layout.Controls.Add(_processFilter, 1, 0);
// Description
layout.Controls.Add(new Label
{
Text = "Description (optional):",
Anchor = AnchorStyles.Left | AnchorStyles.Right,
TextAlign = ContentAlignment.MiddleLeft,
Margin = new Padding(0, 6, 8, 6),
}, 0, 1);
_description = new TextBox
{
Anchor = AnchorStyles.Left | AnchorStyles.Right,
Margin = new Padding(0, 6, 0, 6),
PlaceholderText = "e.g. dotnet build of monorepo, cold cache",
};
layout.Controls.Add(_description, 1, 1);
// Buttons
var buttons = new FlowLayoutPanel
{
Dock = DockStyle.Top,
AutoSize = true,
Margin = new Padding(0, 16, 0, 0),
FlowDirection = FlowDirection.LeftToRight,
};
_startButton = new Button { Text = "Start capture", Width = 140, Height = 32 };
_startButton.Click += async (_, _) => await StartCapture();
_stopButton = new Button { Text = "Stop", Width = 100, Height = 32, Enabled = false };
_stopButton.Click += async (_, _) => await StopCapture();
buttons.Controls.Add(_startButton);
buttons.Controls.Add(_stopButton);
layout.Controls.Add(buttons, 1, 2);
// Status
_statusLabel = new Label
{
Text = "Idle. Click Start, run your workload, click Stop.",
Anchor = AnchorStyles.Left | AnchorStyles.Right,
Margin = new Padding(0, 24, 0, 0),
Font = new Font(SystemFonts.DefaultFont, FontStyle.Italic),
ForeColor = SystemColors.GrayText,
};
layout.Controls.Add(_statusLabel, 1, 3);
_eventsLabel = new Label
{
Text = "",
Anchor = AnchorStyles.Left | AnchorStyles.Right,
Margin = new Padding(0, 4, 0, 0),
};
layout.Controls.Add(_eventsLabel, 1, 4);
// Live stats refresher
_statsTimer = new System.Windows.Forms.Timer { Interval = 500 };
_statsTimer.Tick += (_, _) =>
{
if (_session is { IsRunning: true })
{
_eventsLabel.Text =
$"Captured {_session.EventsCaptured:N0} IRPs " +
$"over {_session.DurationSeconds:F1}s";
}
};
page.Controls.Add(layout);
return page;
}
private TabPage BuildResultsTab()
{
var page = new TabPage("Results");
// WinForms docking-order gotcha: when a Dock=Top control is added
// BEFORE a Dock=Fill control, the Fill control gets the full
// client area and the Top control overlays on it, clipping the
// top of the Fill content (the grids' column headers in this
// case). The fix is to add the Fill-docked content FIRST so it
// claims the full area, then add the Top toolbar so it carves
// out its strip and shrinks the Fill content appropriately.
var split = new SplitContainer
{
Dock = DockStyle.Fill,
Orientation = Orientation.Horizontal,
SplitterDistance = 460,
};
// Top half: three grids side-by-side.
var topLayout = new TableLayoutPanel
{
Dock = DockStyle.Fill,
ColumnCount = 3,
RowCount = 2,
};
topLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
topLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25));
topLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25));
topLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 24));
topLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
topLayout.Controls.Add(SectionHeader("Hot Paths (by directory)"), 0, 0);
topLayout.Controls.Add(SectionHeader("Hot Processes"), 1, 0);
topLayout.Controls.Add(SectionHeader("Hot Extensions"), 2, 0);
_hotPathsGrid = BuildHotGrid("Path");
_hotProcessesGrid = BuildHotGrid("Process");
_hotExtensionsGrid = BuildHotGrid("Extension");
// Drill-down: double-clicking a Hot Paths row opens a popup with
// per-file breakdown of the IRPs that contributed to that
// directory's total. Re-aggregated on the fly from RawEvents.
_hotPathsGrid.CellMouseDoubleClick += (_, args) =>
{
if (args.RowIndex < 0 || args.RowIndex >= _hotPathsGrid.Rows.Count) return;
var key = _hotPathsGrid.Rows[args.RowIndex].Cells[0].Value?.ToString();
if (!string.IsNullOrEmpty(key)) ShowPathDrillDown(key);
};
topLayout.Controls.Add(_hotPathsGrid, 0, 1);
topLayout.Controls.Add(_hotProcessesGrid, 1, 1);
topLayout.Controls.Add(_hotExtensionsGrid, 2, 1);
split.Panel1.Controls.Add(topLayout);
// Bottom half: minifilter stack.
var bottomLayout = new TableLayoutPanel
{
Dock = DockStyle.Fill,
ColumnCount = 1,
RowCount = 2,
};
bottomLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 24));
bottomLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
bottomLayout.Controls.Add(
SectionHeader("Minifilter stack (drivers attached to the I/O path; higher altitude = closer to your app)"),
0, 0);
_minifiltersGrid = BuildMinifiltersGrid();
bottomLayout.Controls.Add(_minifiltersGrid, 0, 1);
split.Panel2.Controls.Add(bottomLayout);
page.Controls.Add(split);
// Toolbar — Save / Load / Compare. Added AFTER the Fill-docked
// split so it docks above without clipping the grid headers
// (see the comment at the top of this method).
var toolbar = new FlowLayoutPanel
{
Dock = DockStyle.Top,
Height = 40,
Padding = new Padding(8, 8, 8, 4),
FlowDirection = FlowDirection.LeftToRight,
};
var saveBtn = new Button { Text = "Save report...", Width = 130, Height = 26 };
saveBtn.Click += (_, _) => SaveReport();
var compareBtn = new Button { Text = "Compare to saved...", Width = 160, Height = 26, Margin = new Padding(8, 0, 0, 0) };
compareBtn.Click += (_, _) => CompareToSaved();
var clearBtn = new Button { Text = "Clear comparison", Width = 140, Height = 26, Margin = new Padding(8, 0, 0, 0), Enabled = false };
clearBtn.Click += (_, _) => ClearComparison(clearBtn);
_clearComparisonButton = clearBtn;
toolbar.Controls.Add(saveBtn);
toolbar.Controls.Add(compareBtn);
toolbar.Controls.Add(clearBtn);
page.Controls.Add(toolbar);
return page;
}
private TabPage BuildRecommendTab()
{
var page = new TabPage("Recommend");
// See BuildResultsTab — Fill-docked content added first, then the
// Top-docked header, so the header carves out its strip rather
// than overlaying on the panel.
_recommendationsPanel = new FlowLayoutPanel
{
Dock = DockStyle.Fill,
FlowDirection = FlowDirection.TopDown,
WrapContents = false,
AutoScroll = true,
Padding = new Padding(16, 8, 16, 16),
};
_recommendationsPanel.Resize += (_, _) =>
{
// Make each card the full width of the panel.
foreach (Control c in _recommendationsPanel.Controls)
c.Width = _recommendationsPanel.ClientSize.Width - 32;
};
page.Controls.Add(_recommendationsPanel);
var header = new Label
{
Dock = DockStyle.Top,
Height = 56,
Padding = new Padding(16, 12, 16, 12),
Text = "Recommended exclusions, ranked by observed cost. " +
"Always review the safety note before applying — some hot paths " +
"should NOT be excluded (system folders, user Downloads).",
ForeColor = SystemColors.GrayText,
};
page.Controls.Add(header);
return page;
}
private TabPage BuildHelpTab()
{
var page = new TabPage("Help");
var tb = new TextBox
{
Dock = DockStyle.Fill,
Multiline = true,
ReadOnly = true,
ScrollBars = ScrollBars.Vertical,
Font = new Font("Consolas", 9.5f),
Text = HelpText.Get(),
};
page.Controls.Add(tb);
return page;
}
// ── Grid factories ────────────────────────────────────────────────
private static DataGridView BuildHotGrid(string keyColumn)
{
var g = NewGrid();
g.Columns.Add(NewTextCol("Key", keyColumn, 320, fill: true));
g.Columns.Add(NewTextCol("Count", "Ops", 60));
g.Columns.Add(NewTextCol("Total", "Total (ms)", 90));
g.Columns.Add(NewTextCol("Mean", "Mean (μs)", 80));
g.Columns.Add(NewTextCol("P95", "P95 (μs)", 80));
g.Columns.Add(NewTextCol("Mult", "× baseline", 90));
return g;
}
private static DataGridView BuildMinifiltersGrid()
{
var g = NewGrid();
g.Columns.Add(NewTextCol("Driver", "Driver", 200));
g.Columns.Add(NewTextCol("Vendor", "Vendor / Product", 300, fill: true));
g.Columns.Add(NewTextCol("Altitude", "Altitude", 110));
g.Columns.Add(NewTextCol("Inst", "Instances", 80));
return g;
}
private static DataGridView NewGrid() => new DataGridView
{
Dock = DockStyle.Fill,
ReadOnly = true,
AllowUserToAddRows = false,
AllowUserToDeleteRows = false,
AllowUserToResizeRows = false,
RowHeadersVisible = false,
SelectionMode = DataGridViewSelectionMode.FullRowSelect,
MultiSelect = false,
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None,
ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize,
BackgroundColor = SystemColors.Window,
BorderStyle = BorderStyle.FixedSingle,
};
private static DataGridViewTextBoxColumn NewTextCol(
string name, string header, int width, bool fill = false)
{
return new DataGridViewTextBoxColumn
{
Name = name,
HeaderText = header,
Width = width,
AutoSizeMode = fill ? DataGridViewAutoSizeColumnMode.Fill
: DataGridViewAutoSizeColumnMode.None,
DefaultCellStyle = new DataGridViewCellStyle { WrapMode = DataGridViewTriState.False },
};
}
private static Label SectionHeader(string text) => new Label
{
Text = text,
Dock = DockStyle.Fill,
Padding = new Padding(8, 4, 0, 0),
Font = new Font(SystemFonts.DefaultFont, FontStyle.Bold),
TextAlign = ContentAlignment.MiddleLeft,
};
// ── Capture lifecycle ─────────────────────────────────────────────
private async Task StartCapture()
{
try
{
_startButton.Enabled = false;
_stopButton.Enabled = false;
_statusLabel.Text = "Probing baseline I/O latency...";
_statusLabel.ForeColor = SystemColors.GrayText;
Application.DoEvents();
// Baseline before capture so the probe's own IRPs don't
// pollute the workload measurement. Capped at 10 seconds —
// a healthy probe completes in well under 1 second, so 10s
// is purely defensive against a misbehaving minifilter.
using var probeCancel = new CancellationTokenSource(TimeSpan.FromSeconds(10));
_baseline = await Task.Run(() => BaselineProbe.Measure(probeCancel.Token));
var probeTimedOut = probeCancel.IsCancellationRequested;
var tracker = new ProcessTracker(_processFilter.Text);
_session = new CaptureSession(_processFilter.Text, _description.Text);
_capture = new IrpLatencyCapture(tracker, _session);
_captureTask = Task.Run(() =>
{
try { _capture.Start(); }
catch (UnauthorizedAccessException) { /* surfaced via status */ }
catch { /* swallow; UI shows generic failure */ }
});
var baselinePrefix = probeTimedOut
? "⚠ Baseline probe timed out (multipliers will be approximate). "
: "Capturing. ";
_statusLabel.Text = baselinePrefix +
$"Baseline: Create {_baseline.CreateMicroseconds}μs / " +
$"Read {_baseline.ReadMicroseconds}μs / " +
$"Write {_baseline.WriteMicroseconds}μs / " +
$"Delete {_baseline.DeleteMicroseconds}μs. " +
$"Run your workload now, then click Stop.";
_statusLabel.ForeColor = probeTimedOut ? Color.DarkOrange : Color.DarkGreen;
_stopButton.Enabled = true;
_statsTimer.Start();
}
catch (Exception ex)
{
_statusLabel.Text = $"Could not start: {ex.Message}";
_statusLabel.ForeColor = Color.Firebrick;
_startButton.Enabled = true;
}
}
private async Task StopCapture()
{
if (_session is null || _capture is null) return;
_stopButton.Enabled = false;
_statsTimer.Stop();
_statusLabel.Text = "Stopping capture and analysing...";
_statusLabel.ForeColor = SystemColors.GrayText;
await Task.Run(() =>
{
_capture.Stop();
_capture.Dispose();
_capture = null;
});
// Allow a brief moment for the parse loop to drain.
if (_captureTask is not null)
await Task.WhenAny(_captureTask, Task.Delay(2000));
var events = _session.DrainEvents();
var minifilters = MinifilterEnumerator.Enumerate();
var baseline = _baseline ?? new BaselineProbe.Result(0, 0, 0, 0);
var hotPaths = HotEntryAggregator.ByPath(events, baseline);
var hotProcs = HotEntryAggregator.ByProcess(events, baseline);
var hotExts = HotEntryAggregator.ByExtension(events, baseline);
var vendors = VendorMapper.ActiveVendors(minifilters);
var recs = ExclusionGenerator.Generate(hotPaths, hotProcs, vendors);
var totalLatency = events.Sum(e => e.DurationMicroseconds);
// Tax estimate: fraction of total latency that's above the
// (op-mix-weighted) baseline. Crude but actionable.
var taxFraction = EstimateTaxFraction(events, baseline);
_summary = new CaptureSummary(
CapturedUtc: DateTime.UtcNow,
EventsCaptured: events.Count,
TotalLatencyMicroseconds: totalLatency,
EstimatedAvTaxFraction: taxFraction,
ProcessFilter: _processFilter.Text,
Description: string.IsNullOrWhiteSpace(_description.Text) ? null : _description.Text,
Minifilters: minifilters,
HotPaths: hotPaths,
HotProcesses: hotProcs,
HotExtensions: hotExts,
Recommendations: recs,
RawEvents: events);
RenderResults(_summary);
_statusLabel.Text = $"Done. {events.Count:N0} IRPs analysed; " +
$"~{taxFraction * 100:F0}% of measured I/O time was above baseline.";
_statusLabel.ForeColor = Color.DarkGreen;
_startButton.Enabled = true;
_session = null;
}
private static double EstimateTaxFraction(
IReadOnlyList<IrpLatencyEvent> events, BaselineProbe.Result baseline)
{
if (events.Count == 0) return 0;
long aboveBaseline = 0;
long total = 0;
foreach (var e in events)
{
var bm = e.Operation switch
{
FileOp.Create => baseline.CreateMicroseconds,
FileOp.Read => baseline.ReadMicroseconds,
FileOp.Write => baseline.WriteMicroseconds,
FileOp.Cleanup => baseline.DeleteMicroseconds,
FileOp.Close => baseline.DeleteMicroseconds,
_ => baseline.ReadMicroseconds,
};
total += e.DurationMicroseconds;
if (e.DurationMicroseconds > bm)
aboveBaseline += e.DurationMicroseconds - bm;
}
return total > 0 ? (double)aboveBaseline / total : 0;
}
private void RenderResults(CaptureSummary s)
{
// When a previous report is loaded, the corresponding lookup is
// passed in so each grid can render a Δ% next to the Mean. When
// there's no comparison the second arg is null and the column
// shows raw values only.
PopulateHotGrid(_hotPathsGrid, s.HotPaths,
_previousSummary?.HotPaths.ToDictionary(r => r.Key, StringComparer.OrdinalIgnoreCase));
PopulateHotGrid(_hotProcessesGrid, s.HotProcesses,
_previousSummary?.HotProcesses.ToDictionary(r => r.Key, StringComparer.OrdinalIgnoreCase));
PopulateHotGrid(_hotExtensionsGrid, s.HotExtensions,
_previousSummary?.HotExtensions.ToDictionary(r => r.Key, StringComparer.OrdinalIgnoreCase));
_minifiltersGrid.Rows.Clear();
foreach (var m in s.Minifilters)
{
_minifiltersGrid.Rows.Add(
m.DriverName,
string.IsNullOrEmpty(m.VendorProduct) ? "(unknown)" : m.VendorProduct,
m.Altitude.ToString("F0"),
m.Instances);
}
_recommendationsPanel.Controls.Clear();
if (s.Recommendations.Count == 0)
{
_recommendationsPanel.Controls.Add(new Label
{
Text =
"No exclusion recommendations. Either nothing was meaningfully slow, " +
"or the slowness was in paths/processes we won't auto-recommend " +
"excluding (system paths, user data). Review the Results tab manually.",
AutoSize = true,
ForeColor = SystemColors.GrayText,
Padding = new Padding(4),
});
}
else
{
foreach (var r in s.Recommendations)
_recommendationsPanel.Controls.Add(BuildRecommendationCard(r));
}
}
private static void PopulateHotGrid(
DataGridView g,
IReadOnlyList<HotEntry> rows,
IReadOnlyDictionary<string, HotEntry>? previousByKey = null)
{
g.Rows.Clear();
foreach (var r in rows)
{
// When a previous report is loaded and contains the same key,
// suffix the Mean cell with the % change. Improvements (lower
// mean) render as -X%, regressions as +X%. Keys missing from
// the previous report show "(new)" so users can spot freshly-
// appearing hot paths.
string meanCell = r.MeanLatencyMicroseconds.ToString();
if (previousByKey is not null)
{
if (previousByKey.TryGetValue(r.Key, out var prev) && prev.MeanLatencyMicroseconds > 0)
{
var deltaPct = (double)(r.MeanLatencyMicroseconds - prev.MeanLatencyMicroseconds)
/ prev.MeanLatencyMicroseconds * 100.0;
var sign = deltaPct > 0 ? "+" : "";
meanCell = $"{r.MeanLatencyMicroseconds} ({sign}{deltaPct:F0}%)";
}
else
{
meanCell = $"{r.MeanLatencyMicroseconds} (new)";
}
}
g.Rows.Add(
r.Key,
r.EventCount,
(r.TotalLatencyMicroseconds / 1000.0).ToString("F1"),
meanCell,
r.P95LatencyMicroseconds,
r.BaselineMultiplier.ToString("F1") + "x");
}
}
private static Panel BuildRecommendationCard(ExclusionRecommendation r)
{
var card = new Panel
{
BorderStyle = BorderStyle.FixedSingle,
Margin = new Padding(0, 0, 0, 12),
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
Padding = new Padding(12),
BackColor = Color.WhiteSmoke,
};
var stack = new FlowLayoutPanel
{
FlowDirection = FlowDirection.TopDown,
AutoSize = true,
WrapContents = false,
Dock = DockStyle.Fill,
};
stack.Controls.Add(new Label
{
Text = (r.PreferProcess ? "Process exclusion: " : "Path exclusion: ") + r.Target,
AutoSize = true,
Font = new Font(SystemFonts.DefaultFont, FontStyle.Bold),
Padding = new Padding(0, 0, 0, 6),
});
stack.Controls.Add(new Label
{
Text = r.Rationale,
AutoSize = true,
MaximumSize = new Size(900, 0),
Padding = new Padding(0, 0, 0, 6),
});
if (!string.IsNullOrEmpty(r.SafetyNote))
{
stack.Controls.Add(new Label
{
Text = "⚠ " + r.SafetyNote,
AutoSize = true,
MaximumSize = new Size(900, 0),
ForeColor = Color.Firebrick,
Padding = new Padding(0, 0, 0, 6),
});
}
foreach (var (vendor, cmd) in r.Commands)
{
var box = new TextBox
{
Multiline = true,
ReadOnly = true,
ScrollBars = ScrollBars.None,
Font = new Font("Consolas", 9.25f),
Text = cmd,
Width = 900,
Height = MeasureMultilineHeight(cmd),
Margin = new Padding(0, 6, 0, 0),
};
var hdr = new FlowLayoutPanel
{
FlowDirection = FlowDirection.LeftToRight,
AutoSize = true,
Margin = new Padding(0, 10, 0, 0),
};
hdr.Controls.Add(new Label
{
Text = vendor.ToString(),
AutoSize = true,
Font = new Font(SystemFonts.DefaultFont, FontStyle.Bold),
Margin = new Padding(0, 6, 12, 0),
});
var copy = new Button { Text = "Copy", Width = 60, Height = 24 };
copy.Click += (_, _) =>
{
try { Clipboard.SetText(cmd); } catch { }
};
hdr.Controls.Add(copy);
stack.Controls.Add(hdr);
stack.Controls.Add(box);
}
card.Controls.Add(stack);
return card;
}
private static int MeasureMultilineHeight(string text)
{
var lines = text.Split('\n').Length;
return Math.Min(400, 18 + lines * 16);
}
// ── Save / Load / Compare (i2.3 + i2.5) ───────────────────────────
private void SaveReport()
{
if (_summary is null)
{
MessageBox.Show(this, "Run a capture first.", "Nothing to save",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
using var dlg = new SaveFileDialog
{
Filter = "AvProfiler report (*.json)|*.json|All files (*.*)|*.*",
FileName = $"avprofiler_{DateTime.Now:yyyyMMdd_HHmmss}.json",
DefaultExt = "json",
};
if (dlg.ShowDialog(this) != DialogResult.OK) return;
try
{
ResultExporter.Save(_summary, dlg.FileName);
_statusLabel.Text = "Report saved: " + dlg.FileName;
_statusLabel.ForeColor = Color.DarkGreen;
}
catch (Exception ex)
{
MessageBox.Show(this, "Save failed: " + ex.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CompareToSaved()
{
if (_summary is null)
{
MessageBox.Show(this, "Run a capture first, then load a previous report to compare against.",
"No current capture", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
using var dlg = new OpenFileDialog
{
Filter = "AvProfiler report (*.json)|*.json|All files (*.*)|*.*",
};
if (dlg.ShowDialog(this) != DialogResult.OK) return;
try
{
var prev = ResultExporter.Load(dlg.FileName);
if (prev is null)
{
MessageBox.Show(this, "File did not contain a valid report.", "Load failed",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
_previousSummary = prev;
if (_clearComparisonButton is not null) _clearComparisonButton.Enabled = true;
RenderResults(_summary); // re-render with Δ overlay
_statusLabel.Text =
$"Comparing against {Path.GetFileName(dlg.FileName)} " +
$"({prev.EventsCaptured:N0} IRPs, captured {prev.CapturedUtc:yyyy-MM-dd HH:mm} UTC).";
_statusLabel.ForeColor = Color.DarkBlue;
}
catch (Exception ex)
{
MessageBox.Show(this, "Load failed: " + ex.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ClearComparison(Button btn)
{
_previousSummary = null;
btn.Enabled = false;
if (_summary is not null) RenderResults(_summary);
_statusLabel.Text = "Comparison cleared.";
_statusLabel.ForeColor = SystemColors.GrayText;
}
// ── Drill-down popup (i2.4) ───────────────────────────────────────
private void ShowPathDrillDown(string directory)
{
if (_summary is null) return;
// Re-aggregate the raw events for just this directory, one row
// per individual file. We don't pre-compute this because the cost
// of per-file aggregation across every directory would be O(N²)
// on big captures; on-demand per click is fine.
var rows = _summary.RawEvents
.Where(e => string.Equals(
PathNormalizer.DirectoryOf(e.Path), directory,
StringComparison.OrdinalIgnoreCase))
.GroupBy(e => e.Path)
.Select(g => new
{
File = Path.GetFileName(g.Key),
Count = g.Count(),
Total = g.Sum(e => e.DurationMicroseconds) / 1000.0, // ms
Mean = g.Sum(e => e.DurationMicroseconds) / g.Count(),
})
.OrderByDescending(r => r.Total)
.Take(500)
.ToList();
using var dlg = new Form
{
Text = "Files in " + directory,
Size = new Size(900, 500),
StartPosition = FormStartPosition.CenterParent,
Icon = Icon,
ShowInTaskbar = false,
MinimizeBox = false,
MaximizeBox = true,
};
var grid = NewGrid();
grid.Columns.Add(NewTextCol("File", "File", 480, fill: true));
grid.Columns.Add(NewTextCol("Count", "Ops", 80));
grid.Columns.Add(NewTextCol("Total", "Total (ms)", 120));
grid.Columns.Add(NewTextCol("Mean", "Mean (μs)", 100));
foreach (var r in rows)
grid.Rows.Add(r.File, r.Count, r.Total.ToString("F1"), r.Mean);
dlg.Controls.Add(grid);
dlg.ShowDialog(this);
}
// ── Icon ──────────────────────────────────────────────────────────
private static Icon? LoadEmbeddedIcon()
{
try
{
var asm = Assembly.GetExecutingAssembly();
var name = asm.GetName().Name + ".app.ico";
using var s = asm.GetManifestResourceStream(name);
return s is null ? null : new Icon(s);
}
catch { return null; }
}
}