-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathQuerySessionControl.axaml.cs
More file actions
1574 lines (1364 loc) · 54.5 KB
/
QuerySessionControl.axaml.cs
File metadata and controls
1574 lines (1364 loc) · 54.5 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.Diagnostics;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.TextMate;
using Microsoft.Data.SqlClient;
using PlanViewer.App.Dialogs;
using PlanViewer.App.Services;
using PlanViewer.Core.Interfaces;
using PlanViewer.Core.Models;
using PlanViewer.Core.Output;
using PlanViewer.Core.Services;
using TextMateSharp.Grammars;
namespace PlanViewer.App.Controls;
public partial class QuerySessionControl : UserControl
{
private readonly ICredentialService _credentialService;
private readonly ConnectionStore _connectionStore;
private ServerConnection? _serverConnection;
private string? _connectionString;
private string? _selectedDatabase;
private int _planCounter;
private CancellationTokenSource? _executionCts;
private ServerMetadata? _serverMetadata;
// TextMate installation for syntax highlighting
private TextMate.Installation? _textMateInstallation;
private CancellationTokenSource? _statusClearCts;
private CompletionWindow? _completionWindow;
public QuerySessionControl(ICredentialService credentialService, ConnectionStore connectionStore)
{
_credentialService = credentialService;
_connectionStore = connectionStore;
InitializeComponent();
// Initialize editor with empty text so the document is ready
QueryEditor.Text = "";
ZoomBox.SelectedIndex = 2; // 100%
SetupSyntaxHighlighting();
SetupEditorContextMenu();
// Keybindings: F5/Ctrl+E for Execute, Ctrl+L for Estimated Plan
KeyDown += OnKeyDown;
// Ctrl+mousewheel for font zoom
QueryEditor.PointerWheelChanged += OnEditorPointerWheel;
// Code completion
QueryEditor.TextArea.TextEntering += OnTextEntering;
QueryEditor.TextArea.TextEntered += OnTextEntered;
// Focus the editor when the control is attached to the visual tree
AttachedToVisualTree += (_, _) =>
{
QueryEditor.Focus();
QueryEditor.TextArea.Focus();
};
// Focus the editor when the Editor tab is selected; toggle plan-dependent buttons
SubTabControl.SelectionChanged += (_, _) =>
{
if (SubTabControl.SelectedIndex == 0)
{
QueryEditor.Focus();
QueryEditor.TextArea.Focus();
}
UpdatePlanTabButtonState();
};
}
private void SetupSyntaxHighlighting()
{
var registryOptions = new RegistryOptions(ThemeName.DarkPlus);
_textMateInstallation = QueryEditor.InstallTextMate(registryOptions);
_textMateInstallation.SetGrammar(registryOptions.GetScopeByLanguageId("sql"));
}
private void SetupEditorContextMenu()
{
var cutItem = new MenuItem { Header = "Cut" };
cutItem.Click += async (_, _) =>
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard == null) return;
var selection = QueryEditor.TextArea.Selection;
if (selection.IsEmpty) return;
var text = selection.GetText();
await clipboard.SetTextAsync(text);
selection.ReplaceSelectionWithText("");
};
var copyItem = new MenuItem { Header = "Copy" };
copyItem.Click += async (_, _) =>
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard == null) return;
var selection = QueryEditor.TextArea.Selection;
if (selection.IsEmpty) return;
await clipboard.SetTextAsync(selection.GetText());
};
var pasteItem = new MenuItem { Header = "Paste" };
pasteItem.Click += async (_, _) =>
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard == null) return;
var text = await clipboard.TryGetTextAsync();
if (string.IsNullOrEmpty(text)) return;
QueryEditor.TextArea.PerformTextInput(text);
};
var selectAllItem = new MenuItem { Header = "Select All" };
selectAllItem.Click += (_, _) =>
{
QueryEditor.SelectAll();
};
var executeFromCursorItem = new MenuItem { Header = "Execute from Cursor" };
executeFromCursorItem.Click += async (_, _) =>
{
var text = GetTextFromCursor();
if (!string.IsNullOrWhiteSpace(text))
await CaptureAndShowPlan(estimated: false, queryTextOverride: text);
};
var executeCurrentBatchItem = new MenuItem { Header = "Execute Current Batch" };
executeCurrentBatchItem.Click += async (_, _) =>
{
var text = GetCurrentBatch();
if (!string.IsNullOrWhiteSpace(text))
await CaptureAndShowPlan(estimated: false, queryTextOverride: text);
};
QueryEditor.TextArea.ContextMenu = new ContextMenu
{
Items = { cutItem, copyItem, pasteItem, new Separator(), selectAllItem, new Separator(), executeFromCursorItem, executeCurrentBatchItem }
};
}
private void OnKeyDown(object? sender, KeyEventArgs e)
{
// F5 or Ctrl+E → Execute (actual plan)
if ((e.Key == Key.F5 || (e.Key == Key.E && e.KeyModifiers == KeyModifiers.Control))
&& ExecuteButton.IsEnabled)
{
Execute_Click(this, new RoutedEventArgs());
e.Handled = true;
}
// Ctrl+L → Estimated plan
else if (e.Key == Key.L && e.KeyModifiers == KeyModifiers.Control
&& ExecuteEstButton.IsEnabled)
{
ExecuteEstimated_Click(this, new RoutedEventArgs());
e.Handled = true;
}
// Escape → Cancel running query
else if (e.Key == Key.Escape && _executionCts != null && !_executionCts.IsCancellationRequested)
{
_executionCts.Cancel();
e.Handled = true;
}
}
private void OnEditorPointerWheel(object? sender, PointerWheelEventArgs e)
{
if (e.KeyModifiers != KeyModifiers.Control) return;
var delta = e.Delta.Y > 0 ? 1 : -1;
var newSize = QueryEditor.FontSize + delta;
QueryEditor.FontSize = Math.Clamp(newSize, 7, 52);
SyncZoomDropdown();
e.Handled = true;
}
private void Zoom_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (ZoomBox.SelectedItem is ComboBoxItem item && item.Tag is string tagStr
&& int.TryParse(tagStr, out var size))
{
QueryEditor.FontSize = size;
}
}
private void SyncZoomDropdown()
{
// Find the closest matching zoom level
var fontSize = (int)Math.Round(QueryEditor.FontSize);
int bestIdx = 2; // default 100%
int bestDist = int.MaxValue;
for (int i = 0; i < ZoomBox.Items.Count; i++)
{
if (ZoomBox.Items[i] is ComboBoxItem item && item.Tag is string tagStr
&& int.TryParse(tagStr, out var size))
{
var dist = Math.Abs(size - fontSize);
if (dist < bestDist) { bestDist = dist; bestIdx = i; }
}
}
ZoomBox.SelectionChanged -= Zoom_SelectionChanged;
ZoomBox.SelectedIndex = bestIdx;
ZoomBox.SelectionChanged += Zoom_SelectionChanged;
}
private void OnTextEntering(object? sender, TextInputEventArgs e)
{
if (_completionWindow == null || string.IsNullOrEmpty(e.Text)) return;
// If the user types a non-identifier character, let the completion window
// decide whether to commit (it handles Tab/Enter/Space automatically)
var ch = e.Text[0];
if (!char.IsLetterOrDigit(ch) && ch != '_')
{
_completionWindow.CompletionList.RequestInsertion(e);
}
}
private void OnTextEntered(object? sender, TextInputEventArgs e)
{
if (_completionWindow != null) return;
if (string.IsNullOrEmpty(e.Text) || !char.IsLetter(e.Text[0])) return;
var (prefix, wordStart) = GetWordBeforeCaret();
if (prefix.Length < 2) return;
var matches = SqlKeywords.All
.Where(k => k.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
.ToArray();
if (matches.Length == 0) return;
_completionWindow = new CompletionWindow(QueryEditor.TextArea);
_completionWindow.StartOffset = wordStart;
_completionWindow.Closed += (_, _) => _completionWindow = null;
foreach (var kw in matches)
_completionWindow.CompletionList.CompletionData.Add(new SqlCompletionData(kw));
_completionWindow.Show();
}
private (string prefix, int startOffset) GetWordBeforeCaret()
{
var doc = QueryEditor.Document;
var offset = QueryEditor.CaretOffset;
var start = offset;
while (start > 0)
{
var ch = doc.GetCharAt(start - 1);
if (char.IsLetterOrDigit(ch) || ch == '_')
start--;
else
break;
}
return (doc.GetText(start, offset - start), start);
}
private string? GetSelectedTextOrNull()
{
var selection = QueryEditor.TextArea.Selection;
if (selection.IsEmpty) return null;
return selection.GetText();
}
private string GetTextFromCursor()
{
var doc = QueryEditor.Document;
var offset = QueryEditor.CaretOffset;
return doc.GetText(offset, doc.TextLength - offset);
}
private string? GetCurrentBatch()
{
var doc = QueryEditor.Document;
var caretOffset = QueryEditor.CaretOffset;
var text = doc.Text;
var goPattern = new Regex(@"^\s*GO\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
var matches = goPattern.Matches(text);
int batchStart = 0;
int batchEnd = text.Length;
foreach (Match m in matches)
{
if (m.Index + m.Length <= caretOffset)
{
batchStart = m.Index + m.Length;
}
else if (m.Index >= caretOffset)
{
batchEnd = m.Index;
break;
}
}
return text[batchStart..batchEnd].Trim();
}
private void SetStatus(string text, bool autoClear = true)
{
_statusClearCts?.Cancel();
StatusText.Text = text;
if (autoClear && !string.IsNullOrEmpty(text))
{
_statusClearCts = new CancellationTokenSource();
var token = _statusClearCts.Token;
_ = Task.Delay(3000, token).ContinueWith(_ =>
{
Avalonia.Threading.Dispatcher.UIThread.Post(() => StatusText.Text = "");
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
}
private async void Connect_Click(object? sender, RoutedEventArgs e)
{
var dialog = new ConnectionDialog(_credentialService, _connectionStore);
var result = await dialog.ShowDialog<bool?>(GetParentWindow());
if (result == true && dialog.ResultConnection != null)
{
_serverConnection = dialog.ResultConnection;
_selectedDatabase = dialog.ResultDatabase;
_connectionString = _serverConnection.GetConnectionString(_credentialService, _selectedDatabase);
ServerLabel.Text = _serverConnection.ServerName;
ServerLabel.Foreground = Brushes.LimeGreen;
ConnectButton.Content = "Reconnect";
// Populate database dropdown
await PopulateDatabases();
// Collect server metadata for advice output
await FetchServerMetadataAsync();
// Select the database chosen in the dialog
if (_selectedDatabase != null)
{
for (int i = 0; i < DatabaseBox.Items.Count; i++)
{
if (DatabaseBox.Items[i]?.ToString() == _selectedDatabase)
{
DatabaseBox.SelectedIndex = i;
break;
}
}
}
// Collect database metadata for the initial database
await FetchDatabaseMetadataAsync();
ExecuteButton.IsEnabled = true;
ExecuteEstButton.IsEnabled = true;
}
}
private async Task ShowConnectionDialogAsync()
{
var dialog = new ConnectionDialog(_credentialService, _connectionStore);
var result = await dialog.ShowDialog<bool?>(GetParentWindow());
if (result == true && dialog.ResultConnection != null)
{
_serverConnection = dialog.ResultConnection;
_selectedDatabase = dialog.ResultDatabase;
_connectionString = _serverConnection.GetConnectionString(_credentialService, _selectedDatabase);
ServerLabel.Text = _serverConnection.ServerName;
ServerLabel.Foreground = Brushes.LimeGreen;
ConnectButton.Content = "Reconnect";
await PopulateDatabases();
await FetchServerMetadataAsync();
if (_selectedDatabase != null)
{
for (int i = 0; i < DatabaseBox.Items.Count; i++)
{
if (DatabaseBox.Items[i]?.ToString() == _selectedDatabase)
{
DatabaseBox.SelectedIndex = i;
break;
}
}
}
await FetchDatabaseMetadataAsync();
ExecuteButton.IsEnabled = true;
ExecuteEstButton.IsEnabled = true;
}
}
private async Task PopulateDatabases()
{
if (_serverConnection == null) return;
try
{
var connStr = _serverConnection.GetConnectionString(_credentialService, "master");
await using var conn = new SqlConnection(connStr);
await conn.OpenAsync();
var databases = new List<string>();
using var cmd = new SqlCommand(
"SELECT name FROM sys.databases WHERE state_desc = 'ONLINE' ORDER BY name", conn);
using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
databases.Add(reader.GetString(0));
DatabaseBox.ItemsSource = databases;
DatabaseBox.IsEnabled = true;
}
catch
{
DatabaseBox.IsEnabled = false;
}
}
private async void Database_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (_serverConnection == null || DatabaseBox.SelectedItem == null) return;
_selectedDatabase = DatabaseBox.SelectedItem.ToString();
_connectionString = _serverConnection.GetConnectionString(_credentialService, _selectedDatabase);
// Refresh database metadata for the new context
await FetchDatabaseMetadataAsync();
}
private bool IsAzureConnection =>
_serverConnection != null &&
(_serverConnection.ServerName.Contains(".database.windows.net", StringComparison.OrdinalIgnoreCase) ||
_serverConnection.ServerName.Contains(".database.azure.com", StringComparison.OrdinalIgnoreCase));
private async Task FetchServerMetadataAsync()
{
if (_connectionString == null) return;
try
{
_serverMetadata = await ServerMetadataService.FetchServerMetadataAsync(
_connectionString, IsAzureConnection);
}
catch
{
// Non-fatal — advice will just lack server context
_serverMetadata = null;
}
}
private async Task FetchDatabaseMetadataAsync()
{
if (_connectionString == null || _serverMetadata == null) return;
try
{
_serverMetadata.Database = await ServerMetadataService.FetchDatabaseMetadataAsync(
_connectionString, _serverMetadata.SupportsScopedConfigs);
}
catch
{
// Non-fatal — advice will just lack database context
}
}
private async void Execute_Click(object? sender, RoutedEventArgs e)
{
await CaptureAndShowPlan(estimated: false);
}
private async void ExecuteEstimated_Click(object? sender, RoutedEventArgs e)
{
await CaptureAndShowPlan(estimated: true);
}
private async Task CaptureAndShowPlan(bool estimated, string? queryTextOverride = null)
{
if (_connectionString == null || _selectedDatabase == null)
{
SetStatus("Connect to a server first", autoClear: false);
return;
}
var queryText = queryTextOverride?.Trim()
?? GetSelectedTextOrNull()?.Trim()
?? QueryEditor.Text?.Trim();
if (string.IsNullOrEmpty(queryText))
{
SetStatus("Enter a query", autoClear: false);
return;
}
_executionCts?.Cancel();
_executionCts = new CancellationTokenSource();
var ct = _executionCts.Token;
var planType = estimated ? "Estimated" : "Actual";
// Create loading tab with cancel button
var loadingPanel = new StackPanel
{
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
Width = 300
};
var progressBar = new ProgressBar
{
IsIndeterminate = true,
Height = 4,
Margin = new Avalonia.Thickness(0, 0, 0, 12)
};
var statusLabel = new TextBlock
{
Text = $"Capturing {planType.ToLower()} plan...",
FontSize = 14,
Foreground = new SolidColorBrush(Color.Parse("#B0B6C0")),
HorizontalAlignment = HorizontalAlignment.Center
};
var cancelBtn = new Button
{
Content = "\u25A0 Cancel",
Height = 32,
Width = 120,
Padding = new Avalonia.Thickness(16, 0),
FontSize = 13,
Margin = new Avalonia.Thickness(0, 16, 0, 0),
HorizontalAlignment = HorizontalAlignment.Center,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Theme = (Avalonia.Styling.ControlTheme)this.FindResource("AppButton")!
};
cancelBtn.Click += (_, _) => _executionCts?.Cancel();
loadingPanel.Children.Add(progressBar);
loadingPanel.Children.Add(statusLabel);
loadingPanel.Children.Add(cancelBtn);
var loadingContainer = new Grid
{
Background = new SolidColorBrush(Color.Parse("#1A1D23")),
Focusable = true,
Children = { loadingPanel }
};
loadingContainer.KeyDown += (_, ke) =>
{
if (ke.Key == Key.Escape) { _executionCts?.Cancel(); ke.Handled = true; }
};
// Add loading tab and switch to it
_planCounter++;
var tabLabel = estimated ? $"Est Plan {_planCounter}" : $"Plan {_planCounter}";
var headerText = new TextBlock
{
Text = tabLabel,
VerticalAlignment = VerticalAlignment.Center,
FontSize = 12
};
var closeBtn = new Button
{
Content = "\u2715",
MinWidth = 22, MinHeight = 22, Width = 22, Height = 22,
Padding = new Avalonia.Thickness(0),
FontSize = 11,
Margin = new Avalonia.Thickness(6, 0, 0, 0),
Background = Brushes.Transparent,
BorderThickness = new Avalonia.Thickness(0),
Foreground = new SolidColorBrush(Color.FromRgb(0xE4, 0xE6, 0xEB)),
VerticalAlignment = VerticalAlignment.Center,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center
};
var header = new StackPanel
{
Orientation = Orientation.Horizontal,
Children = { headerText, closeBtn }
};
var loadingTab = new TabItem { Header = header, Content = loadingContainer };
closeBtn.Tag = loadingTab;
closeBtn.Click += ClosePlanTab_Click;
SubTabControl.Items.Add(loadingTab);
SubTabControl.SelectedItem = loadingTab;
loadingContainer.Focus();
try
{
var sw = Stopwatch.StartNew();
string? planXml;
var isAzure = _serverConnection!.ServerName.Contains(".database.windows.net",
StringComparison.OrdinalIgnoreCase) ||
_serverConnection.ServerName.Contains(".database.azure.com",
StringComparison.OrdinalIgnoreCase);
if (estimated)
{
planXml = await EstimatedPlanExecutor.GetEstimatedPlanAsync(
_connectionString, _selectedDatabase, queryText, timeoutSeconds: 0, ct);
}
else
{
planXml = await ActualPlanExecutor.ExecuteForActualPlanAsync(
_connectionString, _selectedDatabase, queryText,
planXml: null, isolationLevel: null,
isAzureSqlDb: isAzure, timeoutSeconds: 0, ct);
}
sw.Stop();
if (string.IsNullOrEmpty(planXml))
{
statusLabel.Text = $"No plan returned ({sw.Elapsed.TotalSeconds:F1}s)";
progressBar.IsVisible = false;
cancelBtn.IsVisible = false;
return;
}
// Replace loading content with the plan viewer
SetStatus($"{planType} plan captured ({sw.Elapsed.TotalSeconds:F1}s)");
var viewer = new PlanViewerControl();
viewer.Metadata = _serverMetadata;
viewer.LoadPlan(planXml, tabLabel, queryText);
loadingTab.Content = viewer;
HumanAdviceButton.IsEnabled = true;
RobotAdviceButton.IsEnabled = true;
}
catch (OperationCanceledException)
{
SetStatus("Cancelled");
SubTabControl.Items.Remove(loadingTab);
}
catch (SqlException ex)
{
statusLabel.Text = ex.Message.Length > 100 ? ex.Message[..100] + "..." : ex.Message;
progressBar.IsVisible = false;
cancelBtn.IsVisible = false;
}
catch (Exception ex)
{
statusLabel.Text = ex.Message.Length > 100 ? ex.Message[..100] + "..." : ex.Message;
progressBar.IsVisible = false;
cancelBtn.IsVisible = false;
}
}
private AnalysisResult? GetCurrentAnalysis()
{
// Find the currently selected plan tab's PlanViewerControl
if (SubTabControl.SelectedItem is TabItem tab && tab.Content is PlanViewerControl viewer
&& viewer.CurrentPlan != null)
{
return ResultMapper.Map(viewer.CurrentPlan, "query editor", _serverMetadata);
}
// Fallback: find the most recent plan tab
for (int i = SubTabControl.Items.Count - 1; i >= 0; i--)
{
if (SubTabControl.Items[i] is TabItem planTab && planTab.Content is PlanViewerControl v
&& v.CurrentPlan != null)
{
return ResultMapper.Map(v.CurrentPlan, "query editor");
}
}
return null;
}
private void HumanAdvice_Click(object? sender, RoutedEventArgs e)
{
var analysis = GetCurrentAnalysis();
if (analysis == null) { SetStatus("No plan to analyze", autoClear: false); return; }
var text = TextFormatter.Format(analysis);
ShowAdviceWindow("Advice for Humans", text, analysis);
}
private void RobotAdvice_Click(object? sender, RoutedEventArgs e)
{
var analysis = GetCurrentAnalysis();
if (analysis == null) { SetStatus("No plan to analyze", autoClear: false); return; }
var json = JsonSerializer.Serialize(analysis, new JsonSerializerOptions { WriteIndented = true });
ShowAdviceWindow("Advice for Robots", json);
}
private void ShowAdviceWindow(string title, string content, AnalysisResult? analysis = null)
{
var styledContent = AdviceContentBuilder.Build(content, analysis);
var scrollViewer = new ScrollViewer
{
Content = styledContent,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto
};
var copyBtn = new Button
{
Content = "Copy to Clipboard",
Height = 32,
Padding = new Avalonia.Thickness(16, 0),
FontSize = 12,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Theme = (Avalonia.Styling.ControlTheme)this.FindResource("AppButton")!
};
var closeBtn = new Button
{
Content = "Close",
Height = 32,
Padding = new Avalonia.Thickness(16, 0),
FontSize = 12,
Margin = new Avalonia.Thickness(8, 0, 0, 0),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Theme = (Avalonia.Styling.ControlTheme)this.FindResource("AppButton")!
};
var buttonPanel = new StackPanel
{
Orientation = Avalonia.Layout.Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Right,
Margin = new Avalonia.Thickness(0, 8, 0, 0)
};
buttonPanel.Children.Add(copyBtn);
buttonPanel.Children.Add(closeBtn);
var panel = new DockPanel { Margin = new Avalonia.Thickness(12) };
DockPanel.SetDock(buttonPanel, Dock.Bottom);
panel.Children.Add(buttonPanel);
panel.Children.Add(scrollViewer);
var window = new Window
{
Title = $"Performance Studio — {title}",
Width = 700,
Height = 600,
MinWidth = 400,
MinHeight = 300,
Icon = GetParentWindow().Icon,
Background = new SolidColorBrush(Color.Parse("#1A1D23")),
Foreground = new SolidColorBrush(Color.Parse("#E4E6EB")),
Content = panel
};
copyBtn.Click += async (_, _) =>
{
var clipboard = window.Clipboard;
if (clipboard != null)
{
await clipboard.SetTextAsync(content);
copyBtn.Content = "Copied!";
await Task.Delay(1500);
copyBtn.Content = "Copy to Clipboard";
}
};
closeBtn.Click += (_, _) => window.Close();
window.Show(GetParentWindow());
}
private void AddPlanTab(string planXml, string queryText, bool estimated, string? labelOverride = null)
{
_planCounter++;
var label = labelOverride ?? (estimated ? $"Est Plan {_planCounter}" : $"Plan {_planCounter}");
var viewer = new PlanViewerControl();
viewer.Metadata = _serverMetadata;
viewer.LoadPlan(planXml, label, queryText);
// Build tab header with close button and right-click rename
var headerText = new TextBlock
{
Text = label,
VerticalAlignment = VerticalAlignment.Center,
FontSize = 12
};
var closeBtn = new Button
{
Content = "\u2715",
MinWidth = 22,
MinHeight = 22,
Width = 22,
Height = 22,
Padding = new Avalonia.Thickness(0),
FontSize = 11,
Margin = new Avalonia.Thickness(6, 0, 0, 0),
Background = Brushes.Transparent,
BorderThickness = new Avalonia.Thickness(0),
Foreground = new SolidColorBrush(Color.FromRgb(0xE4, 0xE6, 0xEB)),
VerticalAlignment = VerticalAlignment.Center,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center
};
var header = new StackPanel
{
Orientation = Orientation.Horizontal,
Children = { headerText, closeBtn }
};
var tab = new TabItem { Header = header, Content = viewer };
closeBtn.Tag = tab;
closeBtn.Click += ClosePlanTab_Click;
// Right-click context menu
var contextMenu = new ContextMenu
{
Items =
{
new MenuItem { Header = "Rename Tab", Tag = new object[] { header, headerText } },
new Separator(),
new MenuItem { Header = "Close", Tag = tab, InputGesture = new KeyGesture(Key.W, KeyModifiers.Control) },
new MenuItem { Header = "Close Other Tabs", Tag = tab },
new MenuItem { Header = "Close All Tabs" }
}
};
foreach (var item in contextMenu.Items.OfType<MenuItem>())
item.Click += PlanTabContextMenu_Click;
header.ContextMenu = contextMenu;
SubTabControl.Items.Add(tab);
SubTabControl.SelectedItem = tab;
UpdateCompareButtonState();
}
private void StartRename(StackPanel header, TextBlock headerText)
{
var textBox = new TextBox
{
Text = headerText.Text,
FontSize = 12,
MinWidth = 80,
Padding = new Avalonia.Thickness(2, 0),
VerticalAlignment = VerticalAlignment.Center
};
headerText.IsVisible = false;
header.Children.Insert(0, textBox);
textBox.Focus();
textBox.SelectAll();
void CommitRename()
{
var newName = textBox.Text?.Trim();
if (!string.IsNullOrEmpty(newName))
headerText.Text = newName;
headerText.IsVisible = true;
header.Children.Remove(textBox);
}
textBox.KeyDown += (_, ke) =>
{
if (ke.Key == Key.Enter || ke.Key == Key.Escape)
{
if (ke.Key == Key.Escape)
textBox.Text = headerText.Text;
CommitRename();
ke.Handled = true;
}
};
textBox.LostFocus += (_, _) => CommitRename();
}
private void ClosePlanTab_Click(object? sender, RoutedEventArgs e)
{
if (sender is Button btn && btn.Tag is TabItem tab)
{
SubTabControl.Items.Remove(tab);
UpdateCompareButtonState();
}
}
private void PlanTabContextMenu_Click(object? sender, RoutedEventArgs e)
{
if (sender is not MenuItem item) return;
switch (item.Header?.ToString())
{
case "Rename Tab":
if (item.Tag is object[] parts)
StartRename((StackPanel)parts[0], (TextBlock)parts[1]);
break;
case "Close":
if (item.Tag is TabItem tab)
{
SubTabControl.Items.Remove(tab);
UpdateCompareButtonState();
}
break;
case "Close Other Tabs":
if (item.Tag is TabItem keepTab)
{
// Keep the Editor tab (index 0) and the selected tab
var others = SubTabControl.Items.Cast<object>()
.OfType<TabItem>()
.Where(t => t != keepTab && t.Content is PlanViewerControl)
.ToList();
foreach (var t in others)
SubTabControl.Items.Remove(t);
SubTabControl.SelectedItem = keepTab;
UpdateCompareButtonState();
}
break;
case "Close All Tabs":
var planTabs = SubTabControl.Items.Cast<object>()
.OfType<TabItem>()
.Where(t => t.Content is PlanViewerControl)
.ToList();
foreach (var t in planTabs)
SubTabControl.Items.Remove(t);
SubTabControl.SelectedIndex = 0; // back to Editor
UpdateCompareButtonState();
break;
}
}
private void UpdateCompareButtonState()
{
int planCount = 0;
foreach (var item in SubTabControl.Items)
{
if (item is TabItem t && t.Content is PlanViewerControl v && v.CurrentPlan != null)
planCount++;
}
ComparePlansButton.IsEnabled = planCount >= 2;
}
public IEnumerable<(string label, PlanViewerControl viewer)> GetPlanTabs()
{
foreach (var item in SubTabControl.Items)
{
if (item is TabItem tab && tab.Content is PlanViewerControl viewer
&& viewer.CurrentPlan != null)
{
yield return (GetTabLabel(tab), viewer);
}
}
}
private static string GetTabLabel(TabItem tab)
{
if (tab.Header is StackPanel sp && sp.Children.Count > 0 && sp.Children[0] is TextBlock tb)
return tb.Text ?? "Plan";
if (tab.Header is string s)
return s;
return "Plan";
}
private async void QueryStore_Click(object? sender, RoutedEventArgs e)
{
if (_connectionString == null || _selectedDatabase == null)
{
// No connection — open the connection dialog and wait for it
await ShowConnectionDialogAsync();
if (_connectionString == null || _selectedDatabase == null)
return;
}
// Check if Query Store is enabled
SetStatus("Checking Query Store...");
try
{
var (enabled, state) = await QueryStoreService.CheckEnabledAsync(_connectionString);
if (!enabled)
{
SetStatus($"Query Store not enabled ({state ?? "unknown"})");