Repository navigation
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
4175 lines (3632 loc) · 169 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
4175 lines (3632 loc) · 169 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;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Xml.Linq;
using HttpTraceAnalyser.Model;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Rendering;
using SharpVectors.Converters;
namespace HttpTraceAnalyser
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private HttpTraceFile? _trace;
/// <summary>Currently loaded trace file, if any. Exposed for external automation (e.g. the in-process MCP server).</summary>
public HttpTraceFile? Trace => _trace;
// Cached request/response payload + headers for the currently selected row,
// so switching the payload format doesn't require re-fetching from the DataTable.
private byte[]? _requestPayload;
private IReadOnlyList<KeyValuePair<string, string>>? _requestHeaders;
private byte[]? _responsePayload;
private IReadOnlyList<KeyValuePair<string, string>>? _responseHeaders;
private enum PayloadFormat { PlainText = 0, Json = 1, Xml = 2, Html = 3, JavaScript = 4, Image = 5, Svg = 6, Binary = 7 }
private enum FindScope { AllSessions = 0, RequestHeaders = 1, RequestBody = 2, ResponseHeaders = 3, ResponseBody = 4 }
// Word-wrap state for the RichTextBox viewers (Summary, Mapi). RichTextBox has
// no built-in wrap toggle; we simulate it by pinning Document.PageWidth. State
// is tracked here so that rebuilding the FlowDocument preserves the user's choice.
// Default (checked) = wrap, so no unnecessary horizontal scroll bar is shown.
private bool _summaryWrap = true;
private bool _mapiWrap = true;
private bool _easWrap = true;
private bool _restWrap = true;
private bool _soapWrap = true;
// Cached loader-level summary (e.g. ETL provider event counts). Shown in the
// Summary viewer whenever no row is selected, so it stays visible even when
// the loader extracted no HTTP messages.
private FlowDocument? _loaderSummary;
// Column-sort state. Cycle per column: none -> ascending -> descending -> none.
private GridViewColumn? _sortColumn;
private ListSortDirection? _sortDirection;
private readonly Dictionary<GridViewColumn, string> _originalHeaders = new();
private readonly Dictionary<string, GridViewColumn> _userDefinedGridColumns =
new(StringComparer.OrdinalIgnoreCase);
private readonly List<MenuItem> _userDefinedColumnMenuItems = new();
private const string AscendingArrow = " \u25B2"; // ▲
private const string DescendingArrow = " \u25BC"; // ▼
// Deferred rendering state: track which tabs need their payload editors populated
// when they become visible. This prevents expensive AvalonEdit rendering for invisible tabs.
private bool _requestPayloadNeedsRender;
private bool _responsePayloadNeedsRender;
private PayloadFormat _pendingRequestFormat;
private PayloadFormat _pendingResponseFormat;
private PayloadFormat _base64DecodedFormat;
private byte[]? _base64DecodedPayload;
// Track which tabs have been activated at least once to handle initial visibility
private bool _requestTabEverActivated;
private bool _responseTabEverActivated;
// Large payloads skip pretty-printing/word-wrap/highlighting for performance (see
// LargePayloadThreshold). These track actual size and whether the user chose to
// force full formatting anyway (which also disables Find for that payload, since
// formatting+highlighting a huge body reintroduces the same slowness Find just fixed).
private bool _requestPayloadIsLarge;
private bool _responsePayloadIsLarge;
private bool _requestPayloadFormatOverride;
private bool _responsePayloadFormatOverride;
// Track if we're currently switching tabs to prevent re-entrancy
private bool _isHandlingTabSwitch;
// Track if we're populating viewers to suppress format change events
private bool _isPopulatingViewers;
private bool _isSplitView;
private GridLength _sessionsLeftWidth = new(900);
private GridLength _sessionsTopHeight = new(2, GridUnitType.Star);
private ViewerWindow? _viewerWindow;
private bool _isClosing;
private FrameworkElement[] _middleMouseScrollTargets = [];
private FrameworkElement? _middleMouseScrollTarget;
private ScrollViewer? _middleMouseScrollViewer;
private DispatcherTimer? _middleMouseScrollTimer;
private bool _middleMouseAutoScrollActive;
private Point _middleMouseScrollAnchor;
private Point _middleMouseScrollPosition;
private Cursor? _previousOverrideCursor;
private HwndSource? _windowSource;
private const int WmMouseHorizontalWheel = 0x020E;
// Above this size, pretty-printing, word-wrap, line numbers and syntax highlighting are
// skipped: colorizing (and word-wrapping) a huge single-line JSON/XML body is what makes
// scrolling/selecting (e.g. via Find) feel terrible, since it re-runs regex highlighting
// rules over the whole line on every redraw.
private const int LargePayloadThreshold = 100_000; // 100KB
public MainWindow()
{
InitializeComponent();
_middleMouseScrollTargets =
[
RequestList,
RequestHeadersText,
RequestPayloadEditor,
RequestPayloadImageScroll,
RequestPayloadSvgScroll,
ResponseHeadersText,
ResponsePayloadEditor,
ResponsePayloadImageScroll,
ResponsePayloadSvgScroll,
];
foreach (var target in _middleMouseScrollTargets)
{
target.AddHandler(Mouse.PreviewMouseDownEvent,
new MouseButtonEventHandler(ScrollableViewer_PreviewMouseDown), handledEventsToo: true);
target.AddHandler(Mouse.PreviewMouseMoveEvent,
new MouseEventHandler(ScrollableViewer_PreviewMouseMove), handledEventsToo: true);
target.AddHandler(Mouse.LostMouseCaptureEvent,
new MouseEventHandler(ScrollableViewer_LostMouseCapture), handledEventsToo: true);
}
AddHandler(Keyboard.PreviewKeyDownEvent,
new KeyEventHandler(ScrollableViewer_PreviewKeyDown), handledEventsToo: true);
// Add grid columns + column-chooser entries for any fields contributed by
// plugins loaded during App.OnStartup (see Model/Extensibility/PluginManager).
AddExtendedFieldColumns();
RebuildUserDefinedGridColumns();
// Show which extended (plugin) parsers were loaded/failed on the Summary tab
// as soon as the window opens, before any trace file is loaded.
_loaderSummary = BuildPluginSummary();
SummaryViewer.Document = _loaderSummary ?? new FlowDocument();
ApplyRichTextBoxWrap(SummaryViewer, _summaryWrap);
// Disable link detection after controls are loaded to prevent regex performance issues.
// This is a redundant safety measure in addition to the global handler in App.OnStartup.
Loaded += (_, _) => DisableLinkDetection();
Loaded += async (_, _) =>
{
if (AppSettings.UseSplitView)
await SetViewLayoutAsync(useSplitView: true);
if (AppSettings.IsViewerPoppedOut)
await PopOutViewerAsync();
};
SourceInitialized += MainWindow_SourceInitialized;
Closing += (_, _) => _isClosing = true;
// FilterRuleSet/HighlightRuleSet forward to whichever session is currently active, which
// changes over time (session switch), so subscribe to the active session's collections
// directly and resubscribe whenever the active session changes, rather than relying on
// the static façade's add/remove accessors (those only bind to whatever is "current" at
// subscribe time).
TraceSessionManager.ActiveSessionChanged += OnActiveSessionChanged;
SubscribeToSessionRuleEvents(TraceSessionManager.GetActive());
TraceSessionManager.SessionsChanged += OnSessionsChanged;
TraceSessionManager.ActiveSessionChanged += OnActiveSessionChangedRefreshList;
CustomColumnSet.ColumnsChanged += OnCustomColumnsChanged;
ThemeManager.ThemeChanged += OnThemeChanged;
Closed += (_, _) =>
{
TraceSessionManager.ActiveSessionChanged -= OnActiveSessionChanged;
UnsubscribeFromSessionRuleEvents(TraceSessionManager.GetActive());
TraceSessionManager.SessionsChanged -= OnSessionsChanged;
TraceSessionManager.ActiveSessionChanged -= OnActiveSessionChangedRefreshList;
CustomColumnSet.ColumnsChanged -= OnCustomColumnsChanged;
ThemeManager.ThemeChanged -= OnThemeChanged;
StopMiddleMouseAutoScroll();
_windowSource?.RemoveHook(WindowMessageHook);
if (_viewerWindow is not null)
{
_viewerWindow.Closed -= ViewerWindow_Closed;
_viewerWindow.Close();
}
};
RefreshSessionsList();
}
private void OnSessionsChanged(object? sender, EventArgs e) => RefreshSessionsList();
private void OnActiveSessionChangedRefreshList(object? sender, TraceSession? newSession) => RefreshSessionsList();
private TraceSession? _ruleEventSubscribedSession;
private void SubscribeToSessionRuleEvents(TraceSession? session)
{
if (session is null)
return;
session.Highlights.RulesChanged += OnHighlightRulesChanged;
session.Filters.FiltersChanged += OnFilterRulesChanged;
_ruleEventSubscribedSession = session;
}
private void UnsubscribeFromSessionRuleEvents(TraceSession? session)
{
if (session is null)
return;
session.Highlights.RulesChanged -= OnHighlightRulesChanged;
session.Filters.FiltersChanged -= OnFilterRulesChanged;
}
private void OnActiveSessionChanged(object? sender, TraceSession? newSession)
{
UnsubscribeFromSessionRuleEvents(_ruleEventSubscribedSession);
_ruleEventSubscribedSession = null;
SubscribeToSessionRuleEvents(newSession);
}
/// <summary>
/// Disables link detection in AvalonEdit controls to prevent expensive regex operations
/// that can cause UI hangs when displaying large HTTP trace files.
/// This method is called after window load as a redundant safety measure.
/// </summary>
private void DisableLinkDetection()
{
DisableLinkDetectionForEditor(RequestPayloadEditor);
DisableLinkDetectionForEditor(ResponsePayloadEditor);
DisableLinkDetectionForEditor(Base64SourceEditor);
DisableLinkDetectionForEditor(Base64DecodedEditor);
}
/// <summary>
/// Helper method to safely remove LinkElementGenerator from a TextEditor control.
/// </summary>
private void DisableLinkDetectionForEditor(ICSharpCode.AvalonEdit.TextEditor? editor)
{
if (editor?.TextArea?.TextView == null)
return;
try
{
var generators = editor.TextArea.TextView.ElementGenerators.ToList();
foreach (var generator in generators.OfType<LinkElementGenerator>())
{
editor.TextArea.TextView.ElementGenerators.Remove(generator);
}
}
catch
{
// Silently catch any exceptions during removal to prevent app startup failures
}
}
private void OnThemeChanged(object? sender, EventArgs e)
{
// Row foreground uses a value converter that resolves the theme's
// default brush when the row has no explicit colour, so re-run the
// bindings to pick up the new palette.
RequestList.Items.Refresh();
// Reset syntax highlighting definitions to reload with new theme
SyntaxHighlightingManager.ResetHighlightings();
// Reapply syntax highlighting to visible editors
ReapplySyntaxHighlighting();
}
private void OnFilterRulesChanged(object? sender, EventArgs e)
{
ApplyFilter();
}
private void ApplyFilter()
{
if (_trace is null)
return;
try
{
_trace.View.RowFilter = FilterRuleSet.BuildRowFilter();
}
catch (Exception ex) when (ex is EvaluateException or SyntaxErrorException or InvalidExpressionException)
{
// Malformed rule; leave previous filter in place.
}
}
private void FilterButton_Click(object sender, RoutedEventArgs e)
{
var window = new FilterWindow { Owner = this };
window.ShowDialog();
}
private void FindCommand_Executed(object sender, ExecutedRoutedEventArgs e)
=> OpenFindForCurrentFocus();
private async void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.F && Keyboard.Modifiers == ModifierKeys.Control)
{
OpenFindForCurrentFocus();
e.Handled = true;
}
else if (TryGetFocusedFindScope(out var scope)
&& GetLocalFindControls(scope).Bar.Visibility == Visibility.Visible)
{
if (e.Key == Key.Enter)
{
await FindLocalAsync(scope, forward: (Keyboard.Modifiers & ModifierKeys.Shift) == 0);
e.Handled = true;
}
else if (e.Key == Key.Escape)
{
CloseLocalFind(scope);
e.Handled = true;
}
}
}
private void OpenFindForCurrentFocus()
{
if (TryGetFocusedFindScope(out var scope))
{
OpenLocalFind(scope);
return;
}
FindSessionsBar.Visibility = Visibility.Visible;
FindSessionsText.Focus();
FindSessionsText.SelectAll();
}
private bool TryGetFocusedFindScope(out FindScope scope)
{
if (RequestHeadersPanel.IsKeyboardFocusWithin)
scope = FindScope.RequestHeaders;
else if (RequestBodyPanel.IsKeyboardFocusWithin)
scope = FindScope.RequestBody;
else if (ResponseHeadersPanel.IsKeyboardFocusWithin)
scope = FindScope.ResponseHeaders;
else if (ResponseBodyPanel.IsKeyboardFocusWithin)
scope = FindScope.ResponseBody;
else
{
scope = FindScope.AllSessions;
return false;
}
return true;
}
private void OpenLocalFind(FindScope scope)
{
// Formatting a large payload anyway disables Find for it (see IsFindBlocked) -
// don't even show the find bar in that case.
if (IsFindBlocked(scope))
return;
var (bar, searchBox, _) = GetLocalFindControls(scope);
bar.Visibility = Visibility.Visible;
searchBox.IsEnabled = true;
searchBox.Focus();
searchBox.SelectAll();
}
private async void LocalFindNextButton_Click(object sender, RoutedEventArgs e)
{
if (TryGetFindScope(sender, out var scope))
await FindLocalAsync(scope, forward: true);
}
private async void LocalFindPreviousButton_Click(object sender, RoutedEventArgs e)
{
if (TryGetFindScope(sender, out var scope))
await FindLocalAsync(scope, forward: false);
}
private void LocalFindCloseButton_Click(object sender, RoutedEventArgs e)
{
if (TryGetFindScope(sender, out var scope))
CloseLocalFind(scope);
}
private async void LocalFindText_KeyDown(object sender, KeyEventArgs e)
{
if (!TryGetFindScope(sender, out var scope))
return;
if (e.Key == Key.Escape)
{
CloseLocalFind(scope);
e.Handled = true;
}
else if (e.Key == Key.Enter)
{
await FindLocalAsync(scope, forward: (Keyboard.Modifiers & ModifierKeys.Shift) == 0);
e.Handled = true;
}
}
private void LocalFindText_TextChanged(object sender, TextChangedEventArgs e)
{
if (TryGetFindScope(sender, out var scope))
GetLocalFindControls(scope).Status.Text = string.Empty;
}
private async Task FindLocalAsync(FindScope scope, bool forward)
{
var (_, searchBox, status) = GetLocalFindControls(scope);
if (IsFindBlocked(scope))
{
status.Text = "Find disabled for this large, fully formatted payload";
return;
}
var searchText = searchBox.Text;
if (string.IsNullOrWhiteSpace(searchText))
{
status.Text = string.Empty;
return;
}
switch (scope)
{
case FindScope.RequestHeaders:
SelectTextMatch(RequestHeadersText, searchText, forward, status);
break;
case FindScope.RequestBody:
await PreparePayloadForSearchAsync(request: true);
SelectTextMatch(RequestPayloadEditor, searchText, forward, status);
break;
case FindScope.ResponseHeaders:
SelectTextMatch(ResponseHeadersText, searchText, forward, status);
break;
case FindScope.ResponseBody:
await PreparePayloadForSearchAsync(request: false);
SelectTextMatch(ResponsePayloadEditor, searchText, forward, status);
break;
}
if (status.Text == "Match found")
FocusFindTarget(scope);
else
searchBox.Focus();
}
private void CloseLocalFind(FindScope scope)
{
var (bar, _, status) = GetLocalFindControls(scope);
bar.Visibility = Visibility.Collapsed;
status.Text = string.Empty;
FocusFindTarget(scope);
}
private (Border Bar, TextBox SearchBox, TextBlock Status) GetLocalFindControls(FindScope scope)
=> scope switch
{
FindScope.RequestHeaders => (RequestHeadersFindBar, RequestHeadersFindText, RequestHeadersFindStatus),
FindScope.RequestBody => (RequestBodyFindBar, RequestBodyFindText, RequestBodyFindStatus),
FindScope.ResponseHeaders => (ResponseHeadersFindBar, ResponseHeadersFindText, ResponseHeadersFindStatus),
FindScope.ResponseBody => (ResponseBodyFindBar, ResponseBodyFindText, ResponseBodyFindStatus),
_ => throw new ArgumentOutOfRangeException(nameof(scope)),
};
private static bool TryGetFindScope(object sender, out FindScope scope)
=> Enum.TryParse((sender as FrameworkElement)?.Tag as string, out scope)
&& scope != FindScope.AllSessions;
// Formatting a large payload anyway (see "Format anyway") re-enables word wrap and
// syntax highlighting, which reintroduces the slow scroll/select behavior Find relies
// on - so Find is disabled for that payload in exchange for full formatting.
private bool IsFindBlocked(FindScope scope) => scope switch
{
FindScope.RequestBody => _requestPayloadIsLarge && _requestPayloadFormatOverride,
FindScope.ResponseBody => _responsePayloadIsLarge && _responsePayloadFormatOverride,
_ => false,
};
private void FocusFindTarget(FindScope scope)
{
if (scope == FindScope.RequestHeaders)
RequestHeadersText.Focus();
else if (scope == FindScope.RequestBody)
RequestPayloadEditor.Focus();
else if (scope == FindScope.ResponseHeaders)
ResponseHeadersText.Focus();
else if (scope == FindScope.ResponseBody)
ResponsePayloadEditor.Focus();
}
private async void FindNextButton_Click(object sender, RoutedEventArgs e)
=> await FindAsync(forward: true);
private async void FindPreviousButton_Click(object sender, RoutedEventArgs e)
=> await FindAsync(forward: false);
private void CloseFindButton_Click(object sender, RoutedEventArgs e)
=> CloseFindSessionsBar();
private void FindSessionsText_TextChanged(object sender, TextChangedEventArgs e)
{
FindSessionsStatus.Text = string.Empty;
}
private void FindScopeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (FindSessionsStatus is not null)
FindSessionsStatus.Text = string.Empty;
}
private async void FindSessionsText_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
CloseFindSessionsBar();
e.Handled = true;
}
else if (e.Key == Key.Enter)
{
await FindAsync(forward: (Keyboard.Modifiers & ModifierKeys.Shift) == 0);
e.Handled = true;
}
}
private void CloseFindSessionsBar()
{
FindSessionsBar.Visibility = Visibility.Collapsed;
FindSessionsStatus.Text = string.Empty;
RequestList.Focus();
}
private async Task FindAsync(bool forward)
{
var scope = (FindScope)FindScopeCombo.SelectedIndex;
if (scope == FindScope.AllSessions)
{
FindSession(forward);
return;
}
await FindInSelectedSessionAsync(scope, forward);
FindSessionsText.Focus();
}
private void FindSession(bool forward)
{
var searchText = FindSessionsText.Text;
var count = RequestList.Items.Count;
if (string.IsNullOrWhiteSpace(searchText) || count == 0)
{
FindSessionsStatus.Text = count == 0 ? "No sessions" : string.Empty;
return;
}
var step = forward ? 1 : -1;
var selectedIndex = RequestList.SelectedIndex;
var startIndex = selectedIndex < 0
? (forward ? 0 : count - 1)
: ((selectedIndex + step) % count + count) % count;
for (var offset = 0; offset < count; offset++)
{
var index = ((startIndex + step * offset) % count + count) % count;
if (RequestList.Items[index] is DataRowView row && RowContainsText(row.Row, searchText))
{
RequestList.SelectedItems.Clear();
RequestList.SelectedIndex = index;
RequestList.ScrollIntoView(RequestList.Items[index]);
FindSessionsStatus.Text = $"Session {index + 1} of {count}";
return;
}
}
FindSessionsStatus.Text = "No matches";
}
private async Task FindInSelectedSessionAsync(FindScope scope, bool forward)
{
if (RequestList.SelectedItem is not DataRowView)
{
FindSessionsStatus.Text = "Select a session";
return;
}
if (IsFindBlocked(scope))
{
FindSessionsStatus.Text = "Find disabled for this large, fully formatted payload";
return;
}
var searchText = FindSessionsText.Text;
if (string.IsNullOrWhiteSpace(searchText))
{
FindSessionsStatus.Text = string.Empty;
return;
}
switch (scope)
{
case FindScope.RequestHeaders:
MainTabControl.SelectedIndex = 1;
SelectTextMatch(RequestHeadersText, searchText, forward, FindSessionsStatus);
break;
case FindScope.RequestBody:
await PreparePayloadForSearchAsync(request: true);
SelectTextMatch(RequestPayloadEditor, searchText, forward, FindSessionsStatus);
break;
case FindScope.ResponseHeaders:
MainTabControl.SelectedIndex = 2;
SelectTextMatch(ResponseHeadersText, searchText, forward, FindSessionsStatus);
break;
case FindScope.ResponseBody:
await PreparePayloadForSearchAsync(request: false);
SelectTextMatch(ResponsePayloadEditor, searchText, forward, FindSessionsStatus);
break;
}
}
private async Task PreparePayloadForSearchAsync(bool request)
{
var payload = request ? _requestPayload : _responsePayload;
if (payload is not { Length: > 0 })
return;
var editor = request ? RequestPayloadEditor : ResponsePayloadEditor;
var formatCombo = request ? RequestPayloadFormatCombo : ResponsePayloadFormatCombo;
var format = (PayloadFormat)formatCombo.SelectedIndex;
if (format is PayloadFormat.Image or PayloadFormat.Svg)
{
format = PayloadFormat.PlainText;
_isPopulatingViewers = true;
try
{
formatCombo.SelectedIndex = (int)format;
}
finally
{
_isPopulatingViewers = false;
}
}
if (request)
{
RequestViewerGrid.Visibility = Visibility.Visible;
_requestTabEverActivated = true;
MainTabControl.SelectedIndex = 1;
if (_requestPayloadNeedsRender || string.IsNullOrEmpty(editor.Text))
{
_requestPayloadNeedsRender = false;
await RenderRequestPayload(format);
}
}
else
{
ResponseViewerGrid.Visibility = Visibility.Visible;
_responseTabEverActivated = true;
MainTabControl.SelectedIndex = 2;
if (_responsePayloadNeedsRender || string.IsNullOrEmpty(editor.Text))
{
_responsePayloadNeedsRender = false;
await RenderResponsePayload(format);
}
}
}
private static void SelectTextMatch(TextBox textBox, string searchText, bool forward, TextBlock status)
{
var index = FindTextIndex(textBox.Text, searchText, textBox.SelectionStart, textBox.SelectionLength, forward);
if (index < 0)
{
status.Text = "No matches";
return;
}
textBox.Focus();
textBox.Select(index, searchText.Length);
status.Text = "Match found";
// Deferred: WPF scrolls the caret into view (edge, not centered) in response to
// Select()/Focus(), which would otherwise run after and undo an immediate centering call.
textBox.Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle,
new Action(() => CenterTextMatch(textBox, index, searchText.Length)));
}
private static void SelectTextMatch(ICSharpCode.AvalonEdit.TextEditor editor, string searchText, bool forward, TextBlock status)
{
var index = FindTextIndex(editor.Text, searchText, editor.SelectionStart, editor.SelectionLength, forward);
if (index < 0)
{
status.Text = "No matches";
return;
}
editor.Focus();
editor.Select(index, searchText.Length);
status.Text = "Match found";
// Deferred: AvalonEdit scrolls the caret into view (edge, not centered) in response to
// Select()/Focus(), which would otherwise run after and undo an immediate centering call.
editor.Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle,
new Action(() => CenterTextMatch(editor, index, searchText.Length)));
}
private static void CenterTextMatch(TextBox textBox, int index, int length)
{
textBox.ScrollToLine(textBox.GetLineIndexFromCharacterIndex(index));
textBox.UpdateLayout();
var start = textBox.GetRectFromCharacterIndex(index);
if (start.IsEmpty)
return;
var endIndex = Math.Min(index + length, textBox.Text.Length);
var end = textBox.GetRectFromCharacterIndex(endIndex);
var centerX = !end.IsEmpty && Math.Abs(end.Y - start.Y) < start.Height
? (start.X + end.X) / 2
: start.X;
var centerY = start.Y + start.Height / 2;
textBox.ScrollToHorizontalOffset(Math.Max(0,
textBox.HorizontalOffset + centerX - textBox.ViewportWidth / 2));
textBox.ScrollToVerticalOffset(Math.Max(0,
textBox.VerticalOffset + centerY - textBox.ViewportHeight / 2));
}
private static void CenterTextMatch(ICSharpCode.AvalonEdit.TextEditor editor, int index, int length)
{
var startLocation = editor.Document.GetLocation(index);
editor.ScrollTo(startLocation.Line, startLocation.Column);
editor.UpdateLayout();
var textView = editor.TextArea.TextView;
var scrollInfo = (System.Windows.Controls.Primitives.IScrollInfo)textView;
var start = textView.GetVisualPosition(
new ICSharpCode.AvalonEdit.TextViewPosition(startLocation),
VisualYPosition.LineMiddle);
var endLocation = editor.Document.GetLocation(Math.Min(index + length, editor.Document.TextLength));
var end = textView.GetVisualPosition(
new ICSharpCode.AvalonEdit.TextViewPosition(endLocation),
VisualYPosition.LineMiddle);
var centerX = endLocation.Line == startLocation.Line
? (start.X + end.X) / 2
: start.X;
// GetVisualPosition returns document-absolute coordinates (already independent of the
// current scroll position), so the new offset must not add the existing offset on top.
scrollInfo.SetHorizontalOffset(Math.Max(0, centerX - scrollInfo.ViewportWidth / 2));
scrollInfo.SetVerticalOffset(Math.Max(0, start.Y - scrollInfo.ViewportHeight / 2));
}
private static int FindTextIndex(string text, string searchText, int selectionStart, int selectionLength, bool forward)
{
if (string.IsNullOrEmpty(text))
return -1;
if (forward)
{
var start = Math.Min(selectionStart + selectionLength, text.Length);
var index = text.IndexOf(searchText, start, StringComparison.OrdinalIgnoreCase);
return index >= 0 || start == 0
? index
: text.IndexOf(searchText, 0, StringComparison.OrdinalIgnoreCase);
}
var previousStart = Math.Min(selectionStart - 1, text.Length - 1);
var previous = previousStart >= 0
? text.LastIndexOf(searchText, previousStart, StringComparison.OrdinalIgnoreCase)
: -1;
return previous >= 0
? previous
: text.LastIndexOf(searchText, StringComparison.OrdinalIgnoreCase);
}
private static bool RowContainsText(DataRow row, string searchText)
{
foreach (DataColumn column in row.Table.Columns)
{
if (column.ColumnName is TraceDataSchema.RowBackground or TraceDataSchema.RowForeground)
continue;
var value = row[column];
if (value is byte[] payload)
{
if (payload.Length > 0 && Encoding.UTF8.GetString(payload)
.Contains(searchText, StringComparison.OrdinalIgnoreCase))
return true;
}
else if (value is not DBNull && Convert.ToString(value)?.Contains(
searchText, StringComparison.OrdinalIgnoreCase) == true)
{
return true;
}
}
return false;
}
private void OnHighlightRulesChanged(object? sender, EventArgs e)
{
var highlights = TraceSessionManager.GetActive()?.Highlights;
if (highlights is not null)
_trace?.RecomputeHighlights(highlights);
// The Brush columns changed in-place; nudge the view to redraw.
RequestList.Items.Refresh();
}
private void HighlightsButton_Click(object sender, RoutedEventArgs e)
{
var window = new HighlightsWindow { Owner = this };
window.ShowDialog();
}
private void CustomColumnsButton_Click(object sender, RoutedEventArgs e)
{
var window = new CustomColumnsWindow { Owner = this };
window.ShowDialog();
}
private void OnCustomColumnsChanged(object? sender, EventArgs e)
{
foreach (var rule in FilterRuleSet.Rules
.Where(rule => !TraceColumnCatalog.Names.Contains(
rule.ColumnName,
StringComparer.OrdinalIgnoreCase))
.ToArray())
{
FilterRuleSet.Rules.Remove(rule);
}
foreach (var rule in HighlightRuleSet.Rules
.Where(rule => !TraceColumnCatalog.Names.Contains(
rule.ColumnName,
StringComparer.OrdinalIgnoreCase))
.ToArray())
{
HighlightRuleSet.Rules.Remove(rule);
}
var highlights = TraceSessionManager.GetActive()?.Highlights;
if (highlights is not null)
_trace?.RefreshUserDefinedColumns(highlights);
RebuildUserDefinedGridColumns();
ApplyFilter();
RequestList.Items.Refresh();
}
private async void AppSettingsButton_Click(object sender, RoutedEventArgs e)
{
var window = new AppSettingsWindow(_isSplitView) { Owner = this };
if (window.ShowDialog() != true)
return;
AppSettingsButton.IsEnabled = false;
try
{
var theme = window.SelectedThemePreference switch
{
ThemePreference.Light => AppTheme.Light,
ThemePreference.Dark => AppTheme.Dark,
_ => ThemeManager.GetSystemTheme(),
};
if (ThemeManager.Current != theme)
ThemeManager.Apply(theme);
await SetViewLayoutAsync(window.UseSplitView);
await ApplyMcpSettingsAsync(window.HostMcpServer, window.McpPipeNameSuffix);
McpServerButton.Checked -= McpServerButton_Checked;
McpServerButton.Unchecked -= McpServerButton_Unchecked;
McpServerButton.IsChecked = McpHostManager.IsRunning;
McpServerButton.Content = McpHostManager.IsRunning ? "Disable" : "Enable";
McpServerButton.Tag = McpHostManager.IsRunning ? "\uE8CE" : "\uE8CD";
McpServerButton.Checked += McpServerButton_Checked;
McpServerButton.Unchecked += McpServerButton_Unchecked;
AppSettings.ThemePreference = window.SelectedThemePreference;
AppSettings.UseSplitView = window.UseSplitView;
AppSettings.McpPipeNameSuffix = window.McpPipeNameSuffix;
AppSettings.Save();
}
catch (Exception ex)
{
MessageBox.Show(this, $"Failed to apply app settings:\n{ex.Message}",
"App Settings", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
AppSettingsButton.IsEnabled = true;
}
}
private static async Task ApplyMcpSettingsAsync(bool shouldRun, string? pipeNameSuffix)
{
bool suffixChanged = McpHostManager.PipeNameSuffix != pipeNameSuffix;
if (McpHostManager.IsRunning && (!shouldRun || suffixChanged))
await McpHostManager.StopAsync();
McpHostManager.PipeNameSuffix = pipeNameSuffix;
if (shouldRun && !McpHostManager.IsRunning)
await McpHostManager.StartAsync();
}
private async void ToggleLayoutButton_Click(object sender, RoutedEventArgs e)
{
DockViewer();
bool useSplitView = !_isSplitView;
await SetViewLayoutAsync(useSplitView);
AppSettings.UseSplitView = useSplitView;
AppSettings.Save();
UpdateLayoutToggle();
}
private void UpdateLayoutToggle()
{
ToggleLayoutButton.Content = _isSplitView ? "Vertical" : "Horizontal";
ToggleLayoutButton.ToolTip = _isSplitView
? "Switch to a vertical layout"
: "Switch to a horizontal layout";
}
private async void PopOutViewerButton_Click(object sender, RoutedEventArgs e)
{
if (_viewerWindow is not null)
{
DockViewer();
return;
}
await PopOutViewerAsync();
AppSettings.IsViewerPoppedOut = true;
AppSettings.Save();
}
private async Task PopOutViewerAsync()
{
if (_viewerWindow is not null)
return;
await SetViewLayoutAsync(useSplitView: false);
WorkspaceGrid.Children.Remove(MainTabControl);
_viewerWindow = new ViewerWindow { Owner = this };
_viewerWindow.Host.Content = MainTabControl;
_viewerWindow.Closed += ViewerWindow_Closed;
SessionsPane.SetValue(Grid.ColumnSpanProperty, 3);
PopOutViewerButton.Content = "Dock Viewer";
_viewerWindow.Show();
}
private void DockViewer()
{
_viewerWindow?.Close();
}
private void ViewerWindow_Closed(object? sender, EventArgs e)
{
if (sender is not ViewerWindow viewerWindow)
return;
viewerWindow.Closed -= ViewerWindow_Closed;
viewerWindow.Host.Content = null;
WorkspaceGrid.Children.Add(MainTabControl);
Grid.SetRow(MainTabControl, 0);
Grid.SetColumn(MainTabControl, 5);
SessionsPane.ClearValue(Grid.ColumnSpanProperty);
_viewerWindow = null;
PopOutViewerButton.Content = "Pop Out";
if (!_isClosing)
{
AppSettings.IsViewerPoppedOut = false;
AppSettings.Save();
}
}
private async void McpServerButton_Checked(object sender, RoutedEventArgs e)
{
McpServerButton.IsEnabled = false;
try
{