-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFallbackForm.cs
More file actions
5395 lines (4800 loc) · 227 KB
/
FallbackForm.cs
File metadata and controls
5395 lines (4800 loc) · 227 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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using CUIckScan.Models;
using CUIckScan.Services;
using Microsoft.Data.Sqlite;
namespace CUIckScan;
/// <summary>
/// Pure WinForms fallback UI — used when Edge WebView2 runtime is not installed.
/// Calls ScanService / ScanStateStore directly (no web server involved).
/// </summary>
public sealed class FallbackForm : Form
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
private const int WM_SETREDRAW = 0x000B;
private const int ToastDurationMs = 3500;
private const int MaxSnippetFindings = 40;
private const int GripSize = 6;
// Severity level thresholds — keep in sync with App.jsx getSeverityLevel() and ReportGenerator.SL()
private const int CriticalSeverityThreshold = 40;
private const int HighSeverityThreshold = 25;
private const int MediumSeverityThreshold = 13;
// Score color thresholds — keep in sync with App.jsx scoreColor()
private const int DangerScoreThreshold = 15;
private const int WarningScoreThreshold = 10;
private const int InfoScoreThreshold = 7;
private enum UiScanState { Idle, Running, Paused, Completed, Canceled }
private sealed record ThemePalette(
Color PrimaryBg, Color SecondaryBg, Color TertiaryBg, Color CardBg,
Color Border, Color BorderHover, Color TextPrimary, Color TextSecondary, Color TextMuted,
Color Accent, Color AccentHover, Color Success, Color Warning, Color Danger, Color Info,
Color TagCUI, Color TagCTI, Color TagITAR, Color TagDFARS, Color TagHeuristic);
// Theme colors aligned with React UI (App.jsx themes object)
private static readonly ThemePalette Dark = new(
ColorTranslator.FromHtml("#13141a"), ColorTranslator.FromHtml("#1c1d25"),
ColorTranslator.FromHtml("#24252e"), ColorTranslator.FromHtml("#2a2b35"),
ColorTranslator.FromHtml("#33343e"), ColorTranslator.FromHtml("#4a4b55"),
ColorTranslator.FromHtml("#e8eaed"), ColorTranslator.FromHtml("#8b8d97"),
ColorTranslator.FromHtml("#5c5e68"), // textMuted
ColorTranslator.FromHtml("#4a90e2"), ColorTranslator.FromHtml("#3a7bd5"),
ColorTranslator.FromHtml("#4caf50"), ColorTranslator.FromHtml("#f5a623"),
ColorTranslator.FromHtml("#e74c3c"), ColorTranslator.FromHtml("#4a90e2"),
ColorTranslator.FromHtml("#4a90e2"), ColorTranslator.FromHtml("#9b59b6"),
ColorTranslator.FromHtml("#e74c3c"), ColorTranslator.FromHtml("#1abc9c"),
ColorTranslator.FromHtml("#f5a623"));
private static readonly ThemePalette Light = new(
ColorTranslator.FromHtml("#f0f1f5"), ColorTranslator.FromHtml("#ffffff"),
ColorTranslator.FromHtml("#f8f9fb"), ColorTranslator.FromHtml("#ffffff"),
ColorTranslator.FromHtml("#dde0e6"), ColorTranslator.FromHtml("#b8bcc5"),
ColorTranslator.FromHtml("#1a1c24"), ColorTranslator.FromHtml("#6b6e78"),
ColorTranslator.FromHtml("#9a9da7"), // textMuted
ColorTranslator.FromHtml("#0066cc"), ColorTranslator.FromHtml("#0055aa"),
ColorTranslator.FromHtml("#2e7d32"), ColorTranslator.FromHtml("#e6960b"),
ColorTranslator.FromHtml("#c0392b"), ColorTranslator.FromHtml("#0066cc"),
ColorTranslator.FromHtml("#0066cc"), ColorTranslator.FromHtml("#7b1fa2"),
ColorTranslator.FromHtml("#c0392b"), ColorTranslator.FromHtml("#00897b"),
ColorTranslator.FromHtml("#e6960b"));
private ThemePalette _theme = Dark;
private bool _darkMode = !IsOsLightTheme();
private volatile UiScanState _scanState = UiScanState.Idle;
private readonly string _version;
// ─── Title bar ───
private readonly Panel _titleBar = new() { Height = 36, Dock = DockStyle.Top };
private readonly Label _titleLabel = new() { AutoSize = true };
private Button? _switchUiBtn; // debug-only: switch to React UI
private readonly Button _themeToggle = new() { Text = "☀", Width = 28, Height = 24, FlatStyle = FlatStyle.Flat };
private readonly Button _minBtn = new() { Text = "—", Width = 32, Height = 24, FlatStyle = FlatStyle.Flat };
private readonly Button _maxBtn = new() { Text = "□", Width = 32, Height = 24, FlatStyle = FlatStyle.Flat };
private readonly Button _closeBtn = new() { Text = "✕", Width = 32, Height = 24, FlatStyle = FlatStyle.Flat };
// ─── Control bar Row 1 ───
private readonly TextBox _pathBox = new() { Width = 420 };
private readonly Button _fileExtButton = new() { Text = "File Extensions", Width = 120, Height = 32, Margin = new Padding(3, 0, 3, 0) };
private Panel? _fileExtPopover;
private readonly NumericUpDown _threadsBox = new()
{
Minimum = 1, Maximum = 32,
Value = 2, Width = 60,
TextAlign = HorizontalAlignment.Center
};
private readonly NumericUpDown _maxFileSizeBox = new()
{
Minimum = 1, Maximum = 500,
Value = 10, Width = 60,
TextAlign = HorizontalAlignment.Center
};
// ─── Control bar Row 2 ───
private readonly Button _rulesButton = new() { Width = 280, Height = 32, TextAlign = ContentAlignment.MiddleLeft, Margin = new Padding(3, 0, 3, 0) };
private readonly Button _scanButton = new() { Text = "Start Scan", Width = 100, Height = 32, Margin = new Padding(3, 0, 3, 0) };
private readonly Button _cancelButton = new() { Text = "Stop Scan", Width = 100, Height = 32, Enabled = false, Margin = new Padding(3, 0, 3, 0) };
private readonly Button _pauseButton = new() { Text = "Pause Scan", Width = 100, Height = 32, Enabled = false, Margin = new Padding(3, 0, 3, 0) };
private readonly Button _resumeButton = new() { Text = "Resume Scan", Width = 110, Height = 32, Enabled = false, Margin = new Padding(3, 0, 3, 0) };
private readonly Button _clearResultsButton = new() { Text = "Clear Results", Width = 110, Height = 32, Visible = false, Margin = new Padding(3, 0, 3, 0) };
private readonly Label _settingsWarningLabel = new()
{
Text = "⚠ Settings changed — stop and restart scan to apply",
AutoSize = true, Visible = false, Padding = new Padding(6, 8, 6, 0)
};
// ─── Rule selection popover ───
private Panel? _rulePopover;
private readonly HashSet<string> _enabledRuleLabels = [];
private IReadOnlyList<PatternLibrary.RuleMetadata> _allRuleMeta = [];
// ─── Rule JSON editor ───
private readonly Button _editRulesButton = new() { Text = "Edit Rules", Width = 90, Height = 32, Margin = new Padding(3, 0, 3, 0) };
private Form? _ruleEditorForm;
private RichTextBox? _ruleEditorRtb;
private Panel? _lineNumberGutter;
private Label? _ruleEditorStatus;
private Label? _ruleEditorFooter;
private Button? _ruleEditorSaveBtn;
private bool _ruleEditorDirty;
private bool _suppressEditorEvents; // guard flag to ignore TextChanged during RTF/highlighting updates
private System.Windows.Forms.Timer? _highlightTimer;
// ─── Rule JSON editor search ───
private TextBox? _ruleEditorSearchBox;
private Label? _ruleEditorSearchCount;
private List<int> _searchMatches = [];
private int _searchIndex = -1;
// ─── Results split ───
private SplitContainer? _resultsSplit;
// ─── False Positive reason (inline overlay on ListBox) ───
private TextBox? _fpReasonOverlay;
private string? _fpReasonTrackedPath; // tracks which file's reason is currently displayed
// ─── Results filter bar ───
private readonly TextBox _filterBox = new() { Width = 180, Height = 24 };
private readonly ComboBox _categoryFilterBox = new() { DropDownStyle = ComboBoxStyle.DropDownList, Width = 140 };
private readonly ComboBox _scoreFilterBox = new() { DropDownStyle = ComboBoxStyle.DropDownList, Width = 140 };
private readonly CheckBox _showFalsePositives = new() { Text = "Show False Positives", AutoSize = true, Checked = false, Margin = new Padding(12, 5, 3, 0) };
private readonly Button _clearFiltersButton = new() { Text = "✕ Clear Filters", Width = 100, Height = 24, Visible = false };
// ─── Results ───
private readonly ProgressBar _progressBar = new() { Width = 340, Height = 8, Style = ProgressBarStyle.Continuous };
private readonly Label _statusLabel = new() { AutoSize = true, Text = "Ready" };
private readonly ListBox _resultsList = new() { Dock = DockStyle.Fill, DrawMode = DrawMode.OwnerDrawVariable };
private readonly RichTextBox _snippetBox = new()
{
Dock = DockStyle.Fill, ReadOnly = true,
ScrollBars = RichTextBoxScrollBars.Both,
Font = new Font("Cascadia Code", 10f),
BorderStyle = BorderStyle.None,
DetectUrls = false,
WordWrap = false,
ShortcutsEnabled = true
};
// Cached font variants for snippet formatting (avoids creating Font objects per-append)
private Font? _snippetFontRegular;
private Font? _snippetFontBold;
private Font? _snippetFontItalic;
private Font? _snippetFontBoldItalic;
// ─── Action buttons ───
private readonly Button _exportButton = new() { Text = "Export Paths", Width = 100, Height = 28, Margin = new Padding(3, 0, 3, 0) };
private readonly Button _copyButton = new() { Text = "Copy Files", Width = 95, Height = 28, Margin = new Padding(3, 0, 3, 0) };
private readonly Button _moveButton = new() { Text = "Move Files", Width = 95, Height = 28, Margin = new Padding(3, 0, 3, 0) };
private readonly Button _reportButton = new() { Text = "Generate Report", Width = 130, Height = 32, Margin = new Padding(3, 0, 3, 0) };
private readonly CheckBox _preserveCopyStructure = new() { Text = "Preserve folders", Checked = true, AutoSize = true, Margin = new Padding(0, 4, 6, 0) };
private readonly CheckBox _preserveMoveStructure = new() { Text = "Preserve folders", Checked = true, AutoSize = true, Margin = new Padding(0, 4, 6, 0) };
private readonly Button _openDbButton = new() { Text = "Open Scan DB", Width = 105, Height = 28, Margin = new Padding(3, 0, 3, 0) };
private readonly Button _saveDbButton = new() { Text = "Save Scan DB", Width = 105, Height = 28, Margin = new Padding(3, 0, 3, 0) };
private readonly Button _newScanDbButton = new() { Text = "New Scan DB", Width = 105, Height = 28, Margin = new Padding(3, 0, 3, 0) };
private readonly Button _changePassphraseButton = new() { Text = "Change DB Passphrase", Width = 155, Height = 28, Margin = new Padding(3, 0, 3, 0), Visible = false };
private readonly Label _encryptedIndicator = new() { Text = "🔒 Encrypted", AutoSize = true, Visible = false, Padding = new Padding(6, 6, 6, 0) };
private readonly Panel _actionDivider = new() { Width = 1, Height = 22, Margin = new Padding(16, 3, 16, 0) };
// ─── Toast ───
private readonly Panel _toastHost = new()
{
Width = 320, Height = 200,
Anchor = AnchorStyles.Right | AnchorStyles.Bottom,
BackColor = Color.Transparent
};
// ─── Banner (WebView2 not found) ───
private readonly Panel _bannerPanel = new() { Height = 28, Dock = DockStyle.Top };
// ─── Services ───
private readonly ScanStateStore _stateStore = new();
private readonly ScanService _scanner;
private readonly BindingSource _binding = new();
private IReadOnlyList<ScanResult> _results = [];
private IReadOnlyList<ScanResult> _filteredResults = [];
private CancellationTokenSource? _scanCts;
private string _activeDbPath;
private string? _openedSourcePath;
private readonly bool _debug;
private bool _switchingUi;
private bool _dragging;
private Point _dragOrigin;
private Font? _titleFont;
private ToolTip? _threadsTooltip;
// ─── Cached fonts for owner-draw (avoid per-paint allocation) ───
private readonly Font _drawNameFont = new("Segoe UI", 9f, FontStyle.Bold);
private readonly Font _drawDirFont = new("Cascadia Code", 7.5f);
private readonly Font _drawTagFont = new("Segoe UI", 7.5f, FontStyle.Bold);
private readonly Font _drawInfoFont = new("Segoe UI", 7.5f);
private readonly Font _drawReasonFont = new("Segoe UI", 8.5f);
private readonly Font _drawLabelFont = new("Segoe UI", 6.5f, FontStyle.Bold);
// ─── Session settings debounce persistence ───
private System.Windows.Forms.Timer? _settingsPersistTimer;
// ─── Encryption state ───
private FieldCipher? _activeCipher;
private int _passphraseFailures;
private DateTime _lastFailureUtc = DateTime.MinValue;
// Pending encryption setup — stores passphrase material from startup prompt
// so it can be applied when the actual scan DB is created.
private byte[]? _pendingSalt;
private string? _pendingVerifier;
protected override void Dispose(bool disposing)
{
if (disposing)
{
_scanCts?.Cancel();
_scanCts?.Dispose();
DisposeActiveCipher();
_stateStore.Dispose();
_titleFont?.Dispose();
_threadsTooltip?.Dispose();
_binding?.Dispose();
_drawNameFont.Dispose();
_drawDirFont.Dispose();
_drawTagFont.Dispose();
_drawInfoFont.Dispose();
_drawReasonFont.Dispose();
_drawLabelFont.Dispose();
_drawReviewFont.Dispose();
_settingsPersistTimer?.Dispose();
_ruleEditorForm?.Dispose();
_highlightTimer?.Dispose();
// Dispose cached snippet fonts
_snippetFontRegular?.Dispose();
_snippetFontBold?.Dispose();
_snippetFontItalic?.Dispose();
_snippetFontBoldItalic?.Dispose();
}
base.Dispose(disposing);
}
public FallbackForm(string version, bool debug = false)
{
_version = version;
_debug = debug;
_scanner = new ScanService(_stateStore);
_scanner.Patterns.LoadFromConfig(PatternLibrary.LoadRulesFromDisk());
_activeDbPath = _stateStore.DefaultDatabasePath;
Text = "CUIck Scan";
Width = 1500;
Height = 860;
MinimumSize = new Size(900, 600);
FormBorderStyle = FormBorderStyle.None;
DoubleBuffered = true;
Padding = new Padding(GripSize);
LoadAppIcon();
// Load rule metadata and enable all by default
_allRuleMeta = _scanner.Patterns.GetAllRuleMetadata();
foreach (var r in _allRuleMeta) _enabledRuleLabels.Add(r.Label);
UpdateRulesButtonText();
// Category filter
_categoryFilterBox.Items.AddRange(["All Categories", "CUI", "CTI", "ITAR", "DFARS", "Heuristic"]);
_categoryFilterBox.SelectedIndex = 0;
_categoryFilterBox.SelectedIndexChanged += (_, _) => ApplyResultFilters();
// Score filter
_scoreFilterBox.Items.AddRange(["All Scores", $"Critical ({CriticalSeverityThreshold}+)", $"High ({HighSeverityThreshold}+)", $"Medium ({MediumSeverityThreshold}+)", $"Low (<{MediumSeverityThreshold})"]);
_scoreFilterBox.SelectedIndex = 0;
_scoreFilterBox.SelectedIndexChanged += (_, _) => ApplyResultFilters();
_filterBox.PlaceholderText = "Filter by file name or path…";
_filterBox.TextChanged += (_, _) => ApplyResultFilters();
_showFalsePositives.CheckedChanged += (_, _) => ApplyResultFilters();
_clearFiltersButton.Click += (_, _) =>
{
_filterBox.Text = "";
_categoryFilterBox.SelectedIndex = 0;
_scoreFilterBox.SelectedIndex = 0;
_showFalsePositives.Checked = false;
};
_resultsList.DataSource = _binding;
_resultsList.SelectedIndexChanged += (_, _) => ShowSnippet();
_resultsList.MeasureItem += (_, e) =>
{
var item = e.Index >= 0 && e.Index < _resultsList.Items.Count ? _resultsList.Items[e.Index] as ScanResult : null;
e.ItemHeight = (item?.ReviewStatus == ReviewStatus.FalsePositive) ? 110 : 82;
};
_resultsList.DrawItem += DrawResultItem;
_resultsList.MouseClick += OnResultsListMouseClick;
_rulesButton.Click += (_, _) => ToggleRulePopover();
_editRulesButton.Click += (_, _) => ShowRuleEditor();
_fileExtButton.Click += (_, _) => ToggleFileExtPopover();
_scanButton.Click += (_, _) => _ = RunUiActionAsync(StartScanFlowAsync, "Unable to start scan");
_cancelButton.Click += (_, _) => _scanCts?.Cancel();
_pauseButton.Click += (_, _) => PauseScan();
_resumeButton.Click += (_, _) => ResumeScan();
_clearResultsButton.Click += (_, _) => ClearResults();
_openDbButton.Click += (_, _) => OpenDatabaseForReview();
_saveDbButton.Click += (_, _) => SaveDatabaseAs();
_newScanDbButton.Click += (_, _) => HandleNewScanDb();
_changePassphraseButton.Click += (_, _) => HandleChangePassphrase();
_exportButton.Click += (_, _) => ExportPaths();
_copyButton.Click += (_, _) => CopyOrMoveFiles(move: false);
_moveButton.Click += (_, _) => CopyOrMoveFiles(move: true);
_reportButton.Click += (_, _) => GenerateReport();
_themeToggle.Click += (_, _) => ToggleTheme();
_minBtn.Click += (_, _) => WindowState = FormWindowState.Minimized;
_maxBtn.Click += (_, _) => WindowState = WindowState == FormWindowState.Maximized
? FormWindowState.Normal : FormWindowState.Maximized;
_closeBtn.Click += (_, _) => Close();
KeyPreview = true;
KeyDown += OnHotkeys;
BuildBanner();
BuildTitleBar();
Controls.Add(BuildLayout());
Controls.Add(_bannerPanel);
Controls.Add(_titleBar);
Controls.Add(_toastHost);
Resize += (_, _) =>
{
Padding = WindowState == FormWindowState.Maximized ? new Padding(0) : new Padding(GripSize);
PositionToastHost();
};
PositionToastHost();
SetScanState(UiScanState.Idle); // Set initial button visibility before ApplyTheme
ApplyTheme();
Shown += (_, _) =>
{
// Set 50/50 default split once the layout has computed actual widths
if (_resultsSplit is { Width: > 0 })
_resultsSplit.SplitterDistance = _resultsSplit.Width / 2;
OnStartupSessionCheck();
};
}
// ═══════════════════════════════════════════════════════════
// UI construction
// ═══════════════════════════════════════════════════════════
private void BuildBanner()
{
_bannerPanel.BackColor = ColorTranslator.FromHtml("#5865F2");
var lbl = new Label
{
Text = " ℹ Edge WebView2 runtime not found — running in compatibility mode. Install WebView2 for the full experience.",
Dock = DockStyle.Fill,
ForeColor = Color.White,
Font = new Font("Segoe UI", 8.5f),
TextAlign = ContentAlignment.MiddleLeft,
};
var dismissBtn = new Button
{
Text = "✕", Width = 28, Height = 22, Dock = DockStyle.Right,
FlatStyle = FlatStyle.Flat, ForeColor = Color.White,
};
dismissBtn.FlatAppearance.BorderSize = 0;
dismissBtn.Click += (_, _) =>
{
_bannerPanel.Visible = false;
PerformLayout();
};
_bannerPanel.Controls.Add(lbl);
_bannerPanel.Controls.Add(dismissBtn);
}
private void BuildTitleBar()
{
_titleBar.Padding = new Padding(8, 4, 8, 4);
_titleLabel.Text = $"CUIck Scan — CUI / CTI / ITAR Discovery Scanner v{_version}";
_titleFont = new Font("Segoe UI", 9f, FontStyle.Bold);
_titleLabel.Font = _titleFont;
var icon = new Label { Text = "🛡", AutoSize = true, Padding = new Padding(2, 3, 6, 0) };
var left = new FlowLayoutPanel { Dock = DockStyle.Left, AutoSize = true, WrapContents = false };
left.Controls.Add(icon);
left.Controls.Add(_titleLabel);
var right = new FlowLayoutPanel { Dock = DockStyle.Right, AutoSize = true, WrapContents = false };
// Debug mode: add "Switch to React UI" button
if (_debug)
{
_switchUiBtn = new Button
{
Text = "⇄ React UI",
Width = 80,
Height = 24,
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 7.5f),
Margin = new Padding(0, 0, 6, 0),
};
_switchUiBtn.FlatAppearance.BorderSize = 1;
_switchUiBtn.Click += SwitchToReactUI_Click;
right.Controls.Add(_switchUiBtn);
}
foreach (var b in new[] { _themeToggle, _minBtn, _maxBtn, _closeBtn })
{
b.FlatAppearance.BorderSize = 0;
right.Controls.Add(b);
}
_titleBar.Controls.Add(right);
_titleBar.Controls.Add(left);
_titleBar.MouseDown += (_, e) => { _dragging = true; _dragOrigin = e.Location; };
_titleBar.MouseMove += (_, e) =>
{
if (_dragging) Location = new Point(Location.X + e.X - _dragOrigin.X, Location.Y + e.Y - _dragOrigin.Y);
};
_titleBar.MouseUp += (_, _) => _dragging = false;
_titleBar.MouseDoubleClick += (_, _) =>
WindowState = WindowState == FormWindowState.Maximized ? FormWindowState.Normal : FormWindowState.Maximized;
}
private Control BuildLayout()
{
var root = new TableLayoutPanel
{
Dock = DockStyle.Fill, RowCount = 4, ColumnCount = 1,
Padding = new Padding(0, 4, 0, 0) // small gap below docked title bar + banner
};
root.RowStyles.Add(new RowStyle(SizeType.Absolute, 48)); // Row 1: path/browse/threads
root.RowStyles.Add(new RowStyle(SizeType.Absolute, 48)); // Row 2: rules/scan buttons/threads
root.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); // Row 3: results
root.RowStyles.Add(new RowStyle(SizeType.Absolute, 76)); // Row 4: status/actions
var browseButton = new Button { Text = "Browse", Width = 74, Height = 32, Margin = new Padding(3, 0, 3, 0) };
browseButton.Click += (_, _) => BrowsePath();
// Row 1: Scan Root, Browse, File Extensions, Generate Report
var row1 = new FlowLayoutPanel
{
Dock = DockStyle.Fill, Padding = new Padding(16, 6, 16, 0), WrapContents = false
};
row1.Controls.AddRange([
LabelCaption("SCAN ROOT"), _pathBox, browseButton, _fileExtButton, _reportButton
]);
// Row 2: Select Scan Rules, Scan Threads, Max File Size, Scan/Pause/Resume/Cancel
var threadsLabel = LabelCaption("SCAN THREADS");
var maxFileSizeLabel = LabelCaption("MAX FILE SIZE");
var maxFileSizeUnitLabel = new Label
{
Text = "MB", AutoSize = true,
Font = new Font("Segoe UI", 8f),
Padding = new Padding(0, 8, 0, 0)
};
_threadsTooltip = new ToolTip();
_threadsTooltip.SetToolTip(_threadsBox, "More scanning threads completes the scan faster but adds significant load to the system");
_threadsTooltip.SetToolTip(threadsLabel, "More scanning threads completes the scan faster but adds significant load to the system");
_threadsTooltip.SetToolTip(_maxFileSizeBox, "Maximum file size for structured document parsing (DOCX, XLSX, PPTX, PDF). Larger files fall back to binary text extraction.");
_threadsTooltip.SetToolTip(maxFileSizeLabel, "Maximum file size for structured document parsing (DOCX, XLSX, PPTX, PDF). Larger files fall back to binary text extraction.");
var row2 = new FlowLayoutPanel
{
Dock = DockStyle.Fill, Padding = new Padding(16, 6, 16, 0), WrapContents = false
};
row2.Controls.AddRange([
LabelCaption("SELECT SCAN RULES"), _rulesButton, _editRulesButton,
threadsLabel, _threadsBox,
maxFileSizeLabel, _maxFileSizeBox, maxFileSizeUnitLabel,
_scanButton, _pauseButton, _resumeButton, _cancelButton, _clearResultsButton,
_settingsWarningLabel
]);
// Results area: filter bar + split panel
var resultsContainer = new Panel { Dock = DockStyle.Fill };
// Filter bar above results
var filterBar = new FlowLayoutPanel
{
Dock = DockStyle.Top, Height = 32, Padding = new Padding(16, 4, 16, 4), WrapContents = false
};
filterBar.Controls.AddRange([
_filterBox,
LabelCaption("CATEGORY"), _categoryFilterBox,
LabelCaption("SCORE"), _scoreFilterBox,
_showFalsePositives,
_clearFiltersButton
]);
_resultsSplit = new SplitContainer
{
Dock = DockStyle.Fill, SplitterDistance = 600, Panel1MinSize = 200
};
// FP reason inline overlay — a TextBox positioned over the FP reason area of the selected card
_fpReasonOverlay = new TextBox
{
Visible = false, BorderStyle = BorderStyle.FixedSingle,
Font = new Font("Segoe UI", 8.5f),
PlaceholderText = "Reason for false positive...",
};
_fpReasonOverlay.Leave += OnFpReasonBoxLeave;
_fpReasonOverlay.KeyDown += (_, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; _snippetBox.Focus(); } };
_resultsList.Controls.Add(_fpReasonOverlay); // overlay on ListBox
_resultsSplit.Panel1.Controls.Add(_resultsList);
_resultsSplit.Panel2.Controls.Add(_snippetBox);
resultsContainer.Controls.Add(_resultsSplit);
resultsContainer.Controls.Add(filterBar);
// Status area
var statusArea = new TableLayoutPanel
{
Dock = DockStyle.Fill, RowCount = 2, ColumnCount = 1, Padding = new Padding(10, 4, 10, 2)
};
statusArea.RowStyles.Add(new RowStyle(SizeType.Absolute, 36));
statusArea.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));
// Actions row: left-aligned file/DB ops, right-aligned passphrase button
var actionsLeft = new FlowLayoutPanel { Dock = DockStyle.Fill, WrapContents = false, Padding = new Padding(4, 0, 4, 0) };
actionsLeft.Controls.AddRange([
_exportButton, _copyButton, _preserveCopyStructure,
_moveButton, _preserveMoveStructure,
_actionDivider,
_openDbButton, _saveDbButton, _newScanDbButton
]);
_changePassphraseButton.Dock = DockStyle.Right;
_changePassphraseButton.Margin = new Padding(6, 0, 0, 0);
var actionsRow = new Panel { Dock = DockStyle.Fill };
actionsRow.Controls.Add(actionsLeft); // Fill — takes remaining space
actionsRow.Controls.Add(_changePassphraseButton); // Right — docked to right edge
// Progress row: left progress+status, right-aligned encrypted indicator
var progressLeft = new FlowLayoutPanel { Dock = DockStyle.Fill, WrapContents = false };
progressLeft.Controls.Add(_progressBar);
progressLeft.Controls.Add(_statusLabel);
_encryptedIndicator.Dock = DockStyle.Right;
_encryptedIndicator.Padding = new Padding(6, 4, 0, 0);
var progressRow = new Panel { Dock = DockStyle.Fill };
progressRow.Controls.Add(progressLeft); // Fill
progressRow.Controls.Add(_encryptedIndicator); // Right
statusArea.Controls.Add(actionsRow, 0, 0);
statusArea.Controls.Add(progressRow, 0, 1);
root.Controls.Add(row1, 0, 0);
root.Controls.Add(row2, 0, 1);
root.Controls.Add(resultsContainer, 0, 2);
root.Controls.Add(statusArea, 0, 3);
return root;
}
private static Label LabelCaption(string text) => new()
{
Text = text, AutoSize = true,
Font = new Font("Segoe UI", 8f, FontStyle.Bold),
Padding = new Padding(10, 8, 0, 0)
};
// ═══════════════════════════════════════════════════════════
// Rule selection popover
// ═══════════════════════════════════════════════════════════
private void UpdateRulesButtonText()
{
_rulesButton.Text = _enabledRuleLabels.Count == _allRuleMeta.Count
? $" All rules ({_allRuleMeta.Count}) ▾"
: _enabledRuleLabels.Count == 0
? " No rules selected ▾"
: $" {_enabledRuleLabels.Count} of {_allRuleMeta.Count} rules ▾";
DebouncePersistSessionSettings();
}
private void MarkSettingsChangedIfPaused()
{
if (_scanState != UiScanState.Paused) return;
_settingsWarningLabel.Visible = true;
}
/// <summary>
/// Debounce-persist enabled rules to session database (500ms delay).
/// Matches React UI's useEffect debounce on enabledRules/fileExtensions.
/// </summary>
private void DebouncePersistSessionSettings()
{
_settingsPersistTimer?.Stop();
_settingsPersistTimer?.Dispose();
_settingsPersistTimer = new System.Windows.Forms.Timer { Interval = 500 };
_settingsPersistTimer.Tick += (_, _) =>
{
_settingsPersistTimer?.Stop();
try
{
if (_stateStore.Exists(_activeDbPath))
_stateStore.UpdateSessionMeta(_activeDbPath, enabledRules: _enabledRuleLabels);
}
catch (Exception ex) { CrashLog.Warn("Failed to persist session settings", ex); }
};
_settingsPersistTimer.Start();
}
private Color GetTagColor(string type) => type switch
{
"CUI" => _theme.TagCUI,
"CTI" => _theme.TagCTI,
"ITAR" => _theme.TagITAR,
"DFARS" => _theme.TagDFARS,
"Heuristic" => _theme.TagHeuristic,
_ => _theme.TextSecondary
};
private Color GetScoreColor(int score) =>
score >= DangerScoreThreshold ? _theme.Danger : score >= WarningScoreThreshold ? _theme.Warning : score >= InfoScoreThreshold ? _theme.Info : _theme.TextSecondary;
/// <summary>Blends foreground over background at given opacity (0..1). Simulates alpha tints for RichTextBox.</summary>
private static Color BlendColor(Color fg, Color bg, double opacity) => Color.FromArgb(
Math.Clamp((int)(fg.R * opacity + bg.R * (1 - opacity)), 0, 255),
Math.Clamp((int)(fg.G * opacity + bg.G * (1 - opacity)), 0, 255),
Math.Clamp((int)(fg.B * opacity + bg.B * (1 - opacity)), 0, 255));
/// <summary>Returns a cached Font for the given style, derived from _snippetBox.Font.</summary>
private Font GetSnippetFont(FontStyle style) => style switch
{
FontStyle.Regular => _snippetFontRegular ??= new Font(_snippetBox.Font, FontStyle.Regular),
FontStyle.Bold => _snippetFontBold ??= new Font(_snippetBox.Font, FontStyle.Bold),
FontStyle.Italic => _snippetFontItalic ??= new Font(_snippetBox.Font, FontStyle.Italic),
FontStyle.Bold | FontStyle.Italic => _snippetFontBoldItalic ??= new Font(_snippetBox.Font, FontStyle.Bold | FontStyle.Italic),
_ => _snippetFontRegular ??= new Font(_snippetBox.Font, FontStyle.Regular) // Fall back to cached Regular to avoid per-call GDI leak
};
private void ToggleRulePopover()
{
if (_rulePopover != null)
{
CloseRulePopover();
return;
}
CloseFileExtPopover(); // close file ext popover if open
_rulePopover = new Panel
{
Width = 440, Height = 480,
BorderStyle = BorderStyle.FixedSingle,
BackColor = _theme.SecondaryBg,
};
// Position below the rules button
var loc = _rulesButton.PointToScreen(new Point(0, _rulesButton.Height + 2));
_rulePopover.Location = PointToClient(loc);
// Header: count + Select All / Select None
var header = new FlowLayoutPanel
{
Dock = DockStyle.Top, Height = 32, Padding = new Padding(8, 6, 8, 2), WrapContents = false,
BackColor = _theme.TertiaryBg
};
var countLabel = new Label
{
Text = $"{_enabledRuleLabels.Count}/{_allRuleMeta.Count} rules enabled",
AutoSize = true, Font = new Font("Segoe UI", 9f, FontStyle.Bold),
ForeColor = _theme.TextPrimary
};
var selectAllBtn = new LinkLabel
{
Text = "Select All", AutoSize = true, LinkColor = _theme.Accent,
Padding = new Padding(12, 0, 0, 0)
};
var selectNoneBtn = new LinkLabel
{
Text = "Select None", AutoSize = true, LinkColor = _theme.TextSecondary,
Padding = new Padding(6, 0, 0, 0)
};
header.Controls.AddRange([countLabel, selectAllBtn, selectNoneBtn]);
// ── Quick-select: Aggressiveness tier ──
var tierBar = new FlowLayoutPanel
{
Dock = DockStyle.Top, Height = 32, Padding = new Padding(8, 4, 8, 4),
WrapContents = false, BackColor = _theme.SecondaryBg
};
var tierLabel = new Label
{
Text = "AGGRESSIVENESS:", AutoSize = true,
Font = new Font("Segoe UI", 7.5f, FontStyle.Bold),
ForeColor = _theme.TextMuted, Padding = new Padding(0, 4, 6, 0)
};
tierBar.Controls.Add(tierLabel);
var tierColors = new Dictionary<string, Color>
{
["low"] = ColorTranslator.FromHtml("#22c55e"),
["medium"] = ColorTranslator.FromHtml("#eab308"),
["high"] = ColorTranslator.FromHtml("#ef4444")
};
var tierEmojis = new Dictionary<string, string>
{
["low"] = "Low",
["medium"] = "Medium",
["high"] = "High"
};
var tierButtons = new List<(Button Btn, string Tier)>();
foreach (var tier in new[] { "low", "medium", "high" })
{
var btn = new Button
{
Text = tierEmojis[tier], Height = 24, AutoSize = true,
FlatStyle = FlatStyle.Flat, Cursor = Cursors.Hand,
Font = new Font("Segoe UI", 8.5f, FontStyle.Bold),
Margin = new Padding(2, 0, 2, 0), Padding = new Padding(6, 0, 6, 0)
};
btn.FlatAppearance.BorderSize = 1;
tierButtons.Add((btn, tier));
tierBar.Controls.Add(btn);
}
// ── Quick-select: Category ──
var catBar = new FlowLayoutPanel
{
Dock = DockStyle.Top, Height = 32, Padding = new Padding(8, 4, 8, 4),
WrapContents = false, BackColor = _theme.SecondaryBg
};
var catLabel = new Label
{
Text = "CATEGORY:", AutoSize = true,
Font = new Font("Segoe UI", 7.5f, FontStyle.Bold),
ForeColor = _theme.TextMuted, Padding = new Padding(0, 4, 6, 0)
};
catBar.Controls.Add(catLabel);
var catButtons = new List<(Button Btn, string Cat)>();
foreach (var cat in new[] { "CUI", "CTI", "ITAR", "DFARS" })
{
var btn = new Button
{
Text = cat, Height = 24, AutoSize = true,
FlatStyle = FlatStyle.Flat, Cursor = Cursors.Hand,
Font = new Font("Segoe UI", 8.5f, FontStyle.Bold),
Margin = new Padding(2, 0, 2, 0), Padding = new Padding(6, 0, 6, 0)
};
btn.FlatAppearance.BorderSize = 1;
catButtons.Add((btn, cat));
catBar.Controls.Add(btn);
}
// Scrollable body
var body = new Panel { Dock = DockStyle.Fill, AutoScroll = true };
var list = new FlowLayoutPanel
{
Dock = DockStyle.Top, AutoSize = true, FlowDirection = FlowDirection.TopDown,
WrapContents = false, Width = 420
};
var typeOrder = new[] { "CUI", "CTI", "ITAR", "DFARS", "Heuristic" };
var grouped = _allRuleMeta.GroupBy(r => r.Type)
.ToDictionary(g => g.Key, g => g.OrderByDescending(r => r.Score).ToList());
var ruleCheckboxes = new List<(CheckBox Cb, string Label)>();
var typeCheckboxes = new List<(CheckBox Cb, string Type, List<string> Labels, List<CheckBox> RuleCbs)>();
foreach (var type in typeOrder)
{
if (!grouped.TryGetValue(type, out var rules)) continue;
var clr = GetTagColor(type);
var typeLabels = rules.Select(r => r.Label).ToList();
// Type group header
var groupHeader = new Panel
{
Width = 418, Height = 28, BackColor = Color.FromArgb(20, clr), Padding = new Padding(8, 4, 8, 2)
};
var typeCb = new CheckBox
{
Checked = typeLabels.All(l => _enabledRuleLabels.Contains(l)),
AutoSize = true, ForeColor = clr,
Font = new Font("Segoe UI", 9f, FontStyle.Bold),
Text = $" {type} ({typeLabels.Count(l => _enabledRuleLabels.Contains(l))}/{rules.Count})"
};
groupHeader.Controls.Add(typeCb);
list.Controls.Add(groupHeader);
var capturedTypeLabels = typeLabels;
var capturedRuleCbs = new List<CheckBox>();
// Individual rule rows
foreach (var rule in rules)
{
var ruleRow = new Panel { Width = 418, Height = 24, Padding = new Padding(28, 2, 8, 2) };
var ruleCb = new CheckBox
{
Checked = _enabledRuleLabels.Contains(rule.Label),
Text = rule.Label,
AutoSize = false, Width = 320, Height = 20,
ForeColor = _enabledRuleLabels.Contains(rule.Label) ? _theme.TextPrimary : _theme.TextSecondary,
Font = new Font("Segoe UI", 8.5f)
};
var scoreLabel = new Label
{
Text = $"Score: {rule.Score}",
ForeColor = GetScoreColor(rule.Score),
Font = new Font("Cascadia Code", 9f, FontStyle.Bold),
AutoSize = true, Dock = DockStyle.Right,
TextAlign = ContentAlignment.MiddleRight,
Padding = new Padding(0, 2, 4, 0)
};
capturedRuleCbs.Add(ruleCb);
ruleCheckboxes.Add((ruleCb, rule.Label));
ruleRow.Controls.Add(scoreLabel);
ruleRow.Controls.Add(ruleCb);
list.Controls.Add(ruleRow);
}
typeCheckboxes.Add((typeCb, type, capturedTypeLabels, capturedRuleCbs));
}
// Guard flag to prevent re-entrant CheckedChanged cascades when SyncAllControls updates checkboxes
var suppressRuleSync = false;
// Wire up type checkbox toggling
foreach (var (typeCb, type, labels, ruleCbs) in typeCheckboxes)
{
var capturedLabels = labels;
typeCb.CheckedChanged += (_, _) =>
{
if (suppressRuleSync) return;
foreach (var l in capturedLabels)
{
if (typeCb.Checked) _enabledRuleLabels.Add(l);
else _enabledRuleLabels.Remove(l);
}
suppressRuleSync = true;
try { SyncAllControls(); }
finally { suppressRuleSync = false; }
};
}
// Wire up individual rule checkboxes
foreach (var (cb, label) in ruleCheckboxes)
{
var capturedLabel = label;
cb.CheckedChanged += (_, _) =>
{
if (suppressRuleSync) return;
if (cb.Checked) _enabledRuleLabels.Add(capturedLabel);
else _enabledRuleLabels.Remove(capturedLabel);
suppressRuleSync = true;
try { SyncAllControls(); }
finally { suppressRuleSync = false; }
};
}
// ── Helper: sync all UI controls with current _enabledRuleLabels ──
void SyncAllControls()
{
foreach (var (cb, label) in ruleCheckboxes)
{
cb.Checked = _enabledRuleLabels.Contains(label);
cb.ForeColor = cb.Checked ? _theme.TextPrimary : _theme.TextSecondary;
}
foreach (var (typeCb, type, labels, _) in typeCheckboxes)
{
var enabledCount = labels.Count(l => _enabledRuleLabels.Contains(l));
typeCb.Checked = enabledCount == labels.Count;
typeCb.Text = $" {type} ({enabledCount}/{labels.Count})";
}
countLabel.Text = $"{_enabledRuleLabels.Count}/{_allRuleMeta.Count} rules enabled";
// Style quick-select tier buttons
foreach (var (btn, tier) in tierButtons)
{
var includedTiers = tier == "low" ? new[] { "low" }
: tier == "medium" ? new[] { "low", "medium" }
: new[] { "low", "medium", "high" };
var tierRules = _allRuleMeta.Where(r => includedTiers.Contains(r.Tier)).ToList();
var nonTierRules = _allRuleMeta.Where(r => !includedTiers.Contains(r.Tier)).ToList();
var isActive = tierRules.Count > 0
&& tierRules.All(r => _enabledRuleLabels.Contains(r.Label))
&& nonTierRules.All(r => !_enabledRuleLabels.Contains(r.Label));
var clr = tierColors[tier];
btn.FlatAppearance.BorderColor = isActive ? clr : _theme.Border;
btn.FlatAppearance.BorderSize = isActive ? 2 : 1;
btn.BackColor = isActive ? Color.FromArgb(34, clr) : Color.Transparent;
btn.ForeColor = isActive ? clr : _theme.TextMuted;
}
// Style quick-select category buttons
foreach (var (btn, cat) in catButtons)
{
var catRules = _allRuleMeta.Where(r => r.AppliesTo.Contains(cat)).ToList();
var nonCatRules = _allRuleMeta.Where(r => !r.AppliesTo.Contains(cat)).ToList();
var isActive = catRules.Count > 0
&& catRules.All(r => _enabledRuleLabels.Contains(r.Label))
&& nonCatRules.All(r => !_enabledRuleLabels.Contains(r.Label));
var clr = GetTagColor(cat);
btn.FlatAppearance.BorderColor = isActive ? clr : _theme.Border;
btn.FlatAppearance.BorderSize = isActive ? 2 : 1;
btn.BackColor = isActive ? Color.FromArgb(34, clr) : Color.Transparent;
btn.ForeColor = isActive ? clr : _theme.TextMuted;
}
UpdateRulesButtonText();
MarkSettingsChangedIfPaused();
}
// ── Wire quick-select tier buttons ──
foreach (var (btn, tier) in tierButtons)
{
var capturedTier = tier;
btn.Click += (_, _) =>
{
var includedTiers = capturedTier == "low" ? new[] { "low" }
: capturedTier == "medium" ? new[] { "low", "medium" }
: new[] { "low", "medium", "high" };
_enabledRuleLabels.Clear();
foreach (var r in _allRuleMeta)
if (includedTiers.Contains(r.Tier))
_enabledRuleLabels.Add(r.Label);
SyncAllControls();
};
}
// ── Wire quick-select category buttons ──
foreach (var (btn, cat) in catButtons)
{
var capturedCat = cat;
btn.Click += (_, _) =>
{
_enabledRuleLabels.Clear();
foreach (var r in _allRuleMeta)
if (r.AppliesTo.Contains(capturedCat))
_enabledRuleLabels.Add(r.Label);
SyncAllControls();
};
}
selectAllBtn.LinkClicked += (_, _) =>
{
foreach (var r in _allRuleMeta) _enabledRuleLabels.Add(r.Label);
SyncAllControls();
};
selectNoneBtn.LinkClicked += (_, _) =>
{
_enabledRuleLabels.Clear();
SyncAllControls();
};
// Initial quick-select button styling
SyncAllControls();
body.Controls.Add(list);
_rulePopover.Controls.Add(body);
_rulePopover.Controls.Add(catBar);
_rulePopover.Controls.Add(tierBar);
_rulePopover.Controls.Add(header);
Controls.Add(_rulePopover);
_rulePopover.BringToFront();
}
private void CloseRulePopover()
{
if (_rulePopover == null) return;
Controls.Remove(_rulePopover);
_rulePopover.Dispose();
_rulePopover = null;
}
// ═══════════════════════════════════════════════════════════
// Detection Rules JSON Editor
// ═══════════════════════════════════════════════════════════
private static readonly Regex JsonTokenRegex = new(
@"(""(?:[^""\\]|\\.)*"")\s*:" + // key: "key":