-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathPlanViewerControl.axaml.cs
More file actions
3824 lines (3391 loc) · 158 KB
/
PlanViewerControl.axaml.cs
File metadata and controls
3824 lines (3391 loc) · 158 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.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Platform.Storage;
using AvaloniaEdit.TextMate;
using Microsoft.Data.SqlClient;
using PlanViewer.App.Dialogs;
using PlanViewer.Core.Interfaces;
using PlanViewer.App.Helpers;
using PlanViewer.App.Services;
using PlanViewer.App.Mcp;
using PlanViewer.Core.Models;
using PlanViewer.Core.Output;
using PlanViewer.Core.Services;
using AvaloniaPath = Avalonia.Controls.Shapes.Path;
namespace PlanViewer.App.Controls;
public class StatementRow
{
public int Index { get; set; }
public string QueryText { get; set; } = "";
public string FullQueryText { get; set; } = "";
public long CpuMs { get; set; }
public long ElapsedMs { get; set; }
public long UdfMs { get; set; }
public double EstCost { get; set; }
public int Critical { get; set; }
public int Warnings { get; set; }
public PlanStatement Statement { get; set; } = null!;
// Display helpers
public string CpuDisplay => FormatDuration(CpuMs);
public string ElapsedDisplay => FormatDuration(ElapsedMs);
public string UdfDisplay => UdfMs > 0 ? FormatDuration(UdfMs) : "";
public string CostDisplay => EstCost > 0 ? $"{EstCost:F2}" : "";
private static string FormatDuration(long ms)
{
if (ms < 1000) return $"{ms}ms";
if (ms < 60_000) return $"{ms / 1000.0:F1}s";
return $"{ms / 60_000}m {(ms % 60_000) / 1000}s";
}
}
public partial class PlanViewerControl : UserControl
{
private readonly string _mcpSessionId = Guid.NewGuid().ToString();
private ParsedPlan? _currentPlan;
private PlanStatement? _currentStatement;
private string? _queryText;
private ServerMetadata? _serverMetadata;
private double _zoomLevel = 1.0;
private const double ZoomStep = 0.15;
private const double MinZoom = 0.1;
private const double MaxZoom = 3.0;
private string _label = "";
/// <summary>
/// Full path on disk when the plan was loaded from a file.
/// </summary>
public string? SourceFilePath { get; set; }
// Node selection
private Border? _selectedNodeBorder;
private IBrush? _selectedNodeOriginalBorder;
private Thickness _selectedNodeOriginalThickness;
// Border -> PlanNode mapping (replaces WPF Tag pattern)
private readonly Dictionary<Border, PlanNode> _nodeBorderMap = new();
// Brushes
private static readonly SolidColorBrush SelectionBrush = new(Color.FromRgb(0x4F, 0xA3, 0xFF));
private static readonly SolidColorBrush TooltipBgBrush = new(Color.FromRgb(0x1A, 0x1D, 0x23));
private static readonly SolidColorBrush TooltipBorderBrush = new(Color.FromRgb(0x3A, 0x3D, 0x45));
private static readonly SolidColorBrush TooltipFgBrush = new(Color.FromRgb(0xE4, 0xE6, 0xEB));
private static readonly SolidColorBrush EdgeBrush = new(Color.FromRgb(0x6B, 0x72, 0x80));
private static readonly SolidColorBrush SectionHeaderBrush = new(Color.FromRgb(0x4F, 0xA3, 0xFF));
private static readonly SolidColorBrush PropSeparatorBrush = new(Color.FromRgb(0x2A, 0x2D, 0x35));
private static readonly SolidColorBrush OrangeRedBrush = new(Colors.OrangeRed);
private static readonly SolidColorBrush OrangeBrush = new(Colors.Orange);
// Track all property section grids for synchronized column resize
private readonly List<ColumnDefinition> _sectionLabelColumns = new();
private double _propertyLabelWidth = 140;
private bool _isSyncingColumnWidth;
private Grid? _currentSectionGrid;
private int _currentSectionRowIndex;
// Non-control named elements that Avalonia codegen doesn't auto-generate fields for
private readonly ColumnDefinition _statementsColumn;
private readonly ColumnDefinition _statementsSplitterColumn;
private readonly ColumnDefinition _splitterColumn;
private readonly ColumnDefinition _propertiesColumn;
private readonly ScaleTransform _zoomTransform;
// Statement grid data
private List<PlanStatement>? _allStatements;
// Pan state
private bool _isPanning;
private Point _panStart;
private double _panStartOffsetX;
private double _panStartOffsetY;
public PlanViewerControl()
{
InitializeComponent();
// Use Tunnel routing so Ctrl+wheel zoom fires before ScrollViewer consumes the event
PlanScrollViewer.AddHandler(PointerWheelChangedEvent, PlanScrollViewer_PointerWheelChanged, Avalonia.Interactivity.RoutingStrategies.Tunnel);
// Use Tunnel routing so pan handlers fire before ScrollViewer consumes the events
PlanScrollViewer.AddHandler(PointerPressedEvent, PlanScrollViewer_PointerPressed, Avalonia.Interactivity.RoutingStrategies.Tunnel);
PlanScrollViewer.AddHandler(PointerMovedEvent, PlanScrollViewer_PointerMoved, Avalonia.Interactivity.RoutingStrategies.Tunnel);
PlanScrollViewer.AddHandler(PointerReleasedEvent, PlanScrollViewer_PointerReleased, Avalonia.Interactivity.RoutingStrategies.Tunnel);
// Resolve non-control elements by traversal (Avalonia doesn't support x:Name on these types)
// The Grid in Row 4 has 5 ColumnDefinitions:
// [0]=Statements(0), [1]=StmtSplitter(0), [2]=Canvas(*), [3]=PropsSplitter(0), [4]=Props(0)
var planGrid = (Grid)PlanScrollViewer.Parent!;
_statementsColumn = planGrid.ColumnDefinitions[0];
_statementsSplitterColumn = planGrid.ColumnDefinitions[1];
_splitterColumn = planGrid.ColumnDefinitions[3];
_propertiesColumn = planGrid.ColumnDefinitions[4];
// ScaleTransform is the LayoutTransform of the wrapper around PlanCanvas
var layoutTransform = this.FindControl<Avalonia.Controls.LayoutTransformControl>("PlanLayoutTransform")!;
_zoomTransform = (ScaleTransform)layoutTransform.LayoutTransform!;
}
/// <summary>
/// Exposes the raw XML so MainWindow can implement Save functionality.
/// </summary>
public string? RawXml => _currentPlan?.RawXml;
/// <summary>
/// Exposes the parsed and analyzed plan for advice generation.
/// </summary>
public ParsedPlan? CurrentPlan => _currentPlan;
/// <summary>
/// Exposes the query text associated with this plan (if any).
/// </summary>
public string? QueryText => _queryText;
/// <summary>
/// Server metadata for advice generation and Plan Insights display.
/// </summary>
public ServerMetadata? Metadata
{
get => _serverMetadata;
set
{
_serverMetadata = value;
if (_currentStatement != null)
ShowServerContext();
}
}
/// <summary>
/// Connection string for schema lookups. Set when the plan was loaded from a connected session.
/// </summary>
public string? ConnectionString { get; set; }
// Connection state for plans that connect via the toolbar
private ServerConnection? _planConnection;
private ICredentialService? _planCredentialService;
private ConnectionStore? _planConnectionStore;
private string? _planSelectedDatabase;
/// <summary>
/// Provide credential service and connection store so the plan viewer can show a connection dialog.
/// </summary>
public void SetConnectionServices(ICredentialService credentialService, ConnectionStore connectionStore)
{
_planCredentialService = credentialService;
_planConnectionStore = connectionStore;
}
/// <summary>
/// Update the connection UI to reflect an active connection (used when connection is inherited).
/// </summary>
public void SetConnectionStatus(string serverName, string? database)
{
PlanServerLabel.Text = serverName;
PlanServerLabel.Foreground = Brushes.LimeGreen;
PlanConnectButton.Content = "Reconnect";
if (database != null)
_planSelectedDatabase = database;
}
// Events for MainWindow to wire up advice/repro actions
public event EventHandler? HumanAdviceRequested;
public event EventHandler? RobotAdviceRequested;
public event EventHandler? CopyReproRequested;
public event EventHandler<string>? OpenInEditorRequested;
/// <summary>
/// Navigates to a specific plan node by ID: selects it, zooms to show it,
/// and scrolls to center it in the viewport.
/// </summary>
public void NavigateToNode(int nodeId)
{
// Find the Border for this node
Border? targetBorder = null;
PlanNode? targetNode = null;
foreach (var (border, node) in _nodeBorderMap)
{
if (node.NodeId == nodeId)
{
targetBorder = border;
targetNode = node;
break;
}
}
if (targetBorder == null || targetNode == null)
return;
// Activate the parent window so the plan viewer becomes visible
var topLevel = TopLevel.GetTopLevel(this);
if (topLevel is Window parentWindow)
parentWindow.Activate();
// Select the node (highlights it and shows properties)
SelectNode(targetBorder, targetNode);
// Ensure zoom level makes the node comfortably visible
var viewWidth = PlanScrollViewer.Bounds.Width;
var viewHeight = PlanScrollViewer.Bounds.Height;
if (viewWidth <= 0 || viewHeight <= 0)
return;
// If the node is too small at the current zoom, zoom in so it's ~1/3 of the viewport
var nodeW = PlanLayoutEngine.NodeWidth;
var nodeH = PlanLayoutEngine.GetNodeHeight(targetNode);
var minVisibleZoom = Math.Min(viewWidth / (nodeW * 4), viewHeight / (nodeH * 4));
if (_zoomLevel < minVisibleZoom)
SetZoom(Math.Min(minVisibleZoom, 1.0));
// Scroll to center the node in the viewport
var centerX = (targetNode.X + nodeW / 2) * _zoomLevel - viewWidth / 2;
var centerY = (targetNode.Y + nodeH / 2) * _zoomLevel - viewHeight / 2;
centerX = Math.Max(0, centerX);
centerY = Math.Max(0, centerY);
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
PlanScrollViewer.Offset = new Vector(centerX, centerY);
});
}
public void LoadPlan(string planXml, string label, string? queryText = null)
{
_label = label;
_queryText = queryText;
// Query text stored for copy/repro but no longer shown in a
// separate expander — it's already visible in the Statements grid.
_currentPlan = ShowPlanParser.Parse(planXml);
PlanAnalyzer.Analyze(_currentPlan, ConfigLoader.Load());
BenefitScorer.Score(_currentPlan);
var allStatements = _currentPlan.Batches
.SelectMany(b => b.Statements)
.Where(s => s.RootNode != null)
.ToList();
if (allStatements.Count == 0)
{
EmptyState.IsVisible = true;
PlanScrollViewer.IsVisible = false;
return;
}
EmptyState.IsVisible = false;
PlanScrollViewer.IsVisible = true;
// Always show statement grid — useful summary even for single-statement plans
_allStatements = allStatements;
PopulateStatementsGrid(allStatements);
ShowStatementsPanel();
StatementsGrid.SelectedIndex = 0;
// Register with MCP session manager for AI tool access
// Count warnings from both statement-level PlanWarnings and all node Warnings
int warningCount = 0, criticalCount = 0;
foreach (var s in allStatements)
{
warningCount += s.PlanWarnings.Count;
criticalCount += s.PlanWarnings.Count(w => w.Severity == PlanWarningSeverity.Critical);
if (s.RootNode != null)
CountNodeWarnings(s.RootNode, ref warningCount, ref criticalCount);
}
PlanSessionManager.Instance.Register(_mcpSessionId, new PlanSession
{
SessionId = _mcpSessionId,
Label = label,
Source = "file",
Plan = _currentPlan,
QueryText = queryText,
StatementCount = allStatements.Count,
HasActualStats = allStatements.Any(s => s.QueryTimeStats != null),
WarningCount = warningCount,
CriticalWarningCount = criticalCount,
MissingIndexCount = _currentPlan.AllMissingIndexes.Count
});
}
public void Clear()
{
PlanSessionManager.Instance.Unregister(_mcpSessionId);
PlanCanvas.Children.Clear();
_nodeBorderMap.Clear();
_currentPlan = null;
_currentStatement = null;
_queryText = null;
_selectedNodeBorder = null;
EmptyState.IsVisible = true;
PlanScrollViewer.IsVisible = false;
InsightsPanel.IsVisible = false;
CostText.Text = "";
CloseStatementsPanel();
StatementsButton.IsVisible = false;
StatementsButtonSeparator.IsVisible = false;
ClosePropertiesPanel();
}
private static void CountNodeWarnings(PlanNode node, ref int total, ref int critical)
{
total += node.Warnings.Count;
critical += node.Warnings.Count(w => w.Severity == PlanWarningSeverity.Critical);
foreach (var child in node.Children)
CountNodeWarnings(child, ref total, ref critical);
}
private void RenderStatement(PlanStatement statement)
{
_currentStatement = statement;
PlanCanvas.Children.Clear();
_nodeBorderMap.Clear();
_selectedNodeBorder = null;
if (statement.RootNode == null) return;
// Layout
PlanLayoutEngine.Layout(statement);
var (width, height) = PlanLayoutEngine.GetExtents(statement.RootNode);
PlanCanvas.Width = width;
PlanCanvas.Height = height;
// Render edges first (behind nodes)
RenderEdges(statement.RootNode);
// Render nodes — pass total warning count to root node for badge
var allWarnings = new List<PlanWarning>();
CollectWarnings(statement.RootNode, allWarnings);
RenderNodes(statement.RootNode, allWarnings.Count);
// Update banners
ShowMissingIndexes(statement.MissingIndexes);
ShowParameters(statement);
ShowWaitStats(statement.WaitStats, statement.QueryTimeStats != null);
ShowRuntimeSummary(statement);
UpdateInsightsHeader();
// Scroll to top-left so the plan root is immediately visible
PlanScrollViewer.Offset = new Avalonia.Vector(0, 0);
// Canvas-level context menu (zoom, advice, repro, save)
// Set on ScrollViewer, not Canvas — Canvas has no background so it's not hit-testable
PlanScrollViewer.ContextMenu = BuildCanvasContextMenu();
CostText.Text = "";
}
#region Node Rendering
private void RenderNodes(PlanNode node, int totalWarningCount = -1)
{
var visual = CreateNodeVisual(node, totalWarningCount);
Canvas.SetLeft(visual, node.X);
Canvas.SetTop(visual, node.Y);
PlanCanvas.Children.Add(visual);
foreach (var child in node.Children)
RenderNodes(child);
}
private Border CreateNodeVisual(PlanNode node, int totalWarningCount = -1)
{
var isExpensive = node.IsExpensive;
var bgBrush = isExpensive
? new SolidColorBrush(Color.FromArgb(0x30, 0xE5, 0x73, 0x73))
: FindBrushResource("BackgroundLightBrush");
var borderBrush = isExpensive
? OrangeRedBrush
: FindBrushResource("BorderBrush");
var border = new Border
{
Width = PlanLayoutEngine.NodeWidth,
MinHeight = PlanLayoutEngine.NodeHeightMin,
Background = bgBrush,
BorderBrush = borderBrush,
BorderThickness = new Thickness(isExpensive ? 2 : 1),
CornerRadius = new CornerRadius(4),
Padding = new Thickness(6, 4, 6, 4),
Cursor = new Cursor(StandardCursorType.Hand)
};
// Map border to node (replaces WPF Tag)
_nodeBorderMap[border] = node;
// Tooltip — root node gets all collected warnings so the tooltip shows them
if (totalWarningCount > 0)
{
var allWarnings = new List<PlanWarning>();
if (_currentStatement != null)
allWarnings.AddRange(_currentStatement.PlanWarnings);
CollectWarnings(node, allWarnings);
ToolTip.SetTip(border, BuildNodeTooltipContent(node, allWarnings));
}
else
{
ToolTip.SetTip(border, BuildNodeTooltipContent(node));
}
// Click to select + show properties
border.PointerPressed += Node_Click;
// Right-click context menu
border.ContextMenu = BuildNodeContextMenu(node);
var stack = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center };
// Icon row: icon + optional warning/parallel indicators
var iconRow = new StackPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Center
};
var iconBitmap = IconHelper.LoadIcon(node.IconName);
if (iconBitmap != null)
{
iconRow.Children.Add(new Image
{
Source = iconBitmap,
Width = 32,
Height = 32,
Margin = new Thickness(0, 0, 0, 2)
});
}
// Warning indicator badge (orange triangle with !)
if (node.HasWarnings)
{
var warnBadge = new Grid
{
Width = 20, Height = 20,
Margin = new Thickness(4, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center
};
warnBadge.Children.Add(new AvaloniaPath
{
Data = StreamGeometry.Parse("M 10,0 L 20,18 L 0,18 Z"),
Fill = OrangeBrush
});
warnBadge.Children.Add(new TextBlock
{
Text = "!",
FontSize = 12,
FontWeight = FontWeight.ExtraBold,
Foreground = Brushes.White,
HorizontalAlignment = HorizontalAlignment.Center,
Margin = new Thickness(0, 3, 0, 0)
});
iconRow.Children.Add(warnBadge);
}
// Parallel indicator badge (amber circle with arrows)
if (node.Parallel)
{
var parBadge = new Grid
{
Width = 20, Height = 20,
Margin = new Thickness(4, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center
};
parBadge.Children.Add(new Ellipse
{
Width = 20, Height = 20,
Fill = new SolidColorBrush(Color.FromRgb(0xFF, 0xC1, 0x07))
});
parBadge.Children.Add(new TextBlock
{
Text = "\u21C6",
FontSize = 12,
FontWeight = FontWeight.Bold,
Foreground = new SolidColorBrush(Color.FromRgb(0x33, 0x33, 0x33)),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
});
iconRow.Children.Add(parBadge);
}
// Nonclustered index count badge (modification operators maintaining multiple NC indexes)
if (node.NonClusteredIndexCount > 0)
{
var ncBadge = new Border
{
Background = new SolidColorBrush(Color.FromRgb(0x6C, 0x75, 0x7D)),
CornerRadius = new CornerRadius(4),
Padding = new Thickness(4, 1),
Margin = new Thickness(4, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center,
Child = new TextBlock
{
Text = $"+{node.NonClusteredIndexCount} NC",
FontSize = 10,
FontWeight = FontWeight.SemiBold,
Foreground = Brushes.White
}
};
iconRow.Children.Add(ncBadge);
}
stack.Children.Add(iconRow);
// Operator name
var fgBrush = FindBrushResource("ForegroundBrush");
// Operator name — for exchanges, show "Parallelism" + "(Gather Streams)" etc.
var opLabel = node.PhysicalOp;
if (node.PhysicalOp == "Parallelism" && !string.IsNullOrEmpty(node.LogicalOp)
&& node.LogicalOp != "Parallelism")
{
opLabel = $"Parallelism\n({node.LogicalOp})";
}
stack.Children.Add(new TextBlock
{
Text = opLabel,
FontSize = 10,
FontWeight = FontWeight.SemiBold,
Foreground = fgBrush,
TextAlignment = TextAlignment.Center,
TextWrapping = TextWrapping.Wrap,
MaxWidth = PlanLayoutEngine.NodeWidth - 16,
HorizontalAlignment = HorizontalAlignment.Center
});
// Cost percentage — only highlight in estimated plans; actual plans use duration/CPU colors
IBrush costColor = !node.HasActualStats && node.CostPercent >= 50 ? OrangeRedBrush
: !node.HasActualStats && node.CostPercent >= 25 ? OrangeBrush
: fgBrush;
stack.Children.Add(new TextBlock
{
Text = $"Cost: {node.CostPercent}%",
FontSize = 10,
Foreground = costColor,
TextAlignment = TextAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center
});
// Actual plan stats: elapsed time, CPU time, and row counts
if (node.HasActualStats)
{
// Compute own time (subtract children in row mode)
var ownElapsedMs = GetOwnElapsedMs(node);
var ownCpuMs = GetOwnCpuMs(node);
// Elapsed time -- color based on own time, not cumulative
var ownElapsedSec = ownElapsedMs / 1000.0;
IBrush elapsedBrush = ownElapsedSec >= 1.0 ? OrangeRedBrush
: ownElapsedSec >= 0.1 ? OrangeBrush : fgBrush;
stack.Children.Add(new TextBlock
{
Text = $"{ownElapsedSec:F3}s",
FontSize = 10,
Foreground = elapsedBrush,
TextAlignment = TextAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center
});
// CPU time -- color based on own time
var ownCpuSec = ownCpuMs / 1000.0;
IBrush cpuBrush = ownCpuSec >= 1.0 ? OrangeRedBrush
: ownCpuSec >= 0.1 ? OrangeBrush : fgBrush;
stack.Children.Add(new TextBlock
{
Text = $"CPU: {ownCpuSec:F3}s",
FontSize = 10,
Foreground = cpuBrush,
TextAlignment = TextAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center
});
// Actual rows of Estimated rows (accuracy %) -- red if off by 10x+
var estRows = node.EstimateRows;
var accuracyRatio = estRows > 0 ? node.ActualRows / estRows : (node.ActualRows > 0 ? double.MaxValue : 1.0);
IBrush rowBrush = (accuracyRatio < 0.1 || accuracyRatio > 10.0) ? OrangeRedBrush : fgBrush;
var accuracy = estRows > 0
? $" ({accuracyRatio * 100:F0}%)"
: "";
stack.Children.Add(new TextBlock
{
Text = $"{node.ActualRows:N0} of {estRows:N0}{accuracy}",
FontSize = 10,
Foreground = rowBrush,
TextAlignment = TextAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
TextTrimming = TextTrimming.CharacterEllipsis,
MaxWidth = PlanLayoutEngine.NodeWidth - 16
});
}
// Object name -- show full object name, wrap if needed
if (!string.IsNullOrEmpty(node.ObjectName))
{
var objBlock = new TextBlock
{
Text = node.FullObjectName ?? node.ObjectName,
FontSize = 10,
Foreground = fgBrush,
TextAlignment = TextAlignment.Center,
TextWrapping = TextWrapping.Wrap,
MaxWidth = PlanLayoutEngine.NodeWidth - 16,
HorizontalAlignment = HorizontalAlignment.Center
};
stack.Children.Add(objBlock);
}
// Total warning count badge on root node
if (totalWarningCount > 0)
{
var badgeRow = new StackPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Center,
Margin = new Thickness(0, 2, 0, 0)
};
badgeRow.Children.Add(new TextBlock
{
Text = "\u26A0",
FontSize = 13,
Foreground = OrangeBrush,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 4, 0)
});
badgeRow.Children.Add(new TextBlock
{
Text = $"{totalWarningCount} warning{(totalWarningCount == 1 ? "" : "s")}",
FontSize = 12,
FontWeight = FontWeight.SemiBold,
Foreground = OrangeBrush,
VerticalAlignment = VerticalAlignment.Center
});
stack.Children.Add(badgeRow);
}
border.Child = stack;
return border;
}
#endregion
#region Edge Rendering
private void RenderEdges(PlanNode node)
{
foreach (var child in node.Children)
{
var path = CreateElbowConnector(node, child);
PlanCanvas.Children.Add(path);
RenderEdges(child);
}
}
private AvaloniaPath CreateElbowConnector(PlanNode parent, PlanNode child)
{
var parentRight = parent.X + PlanLayoutEngine.NodeWidth;
var parentCenterY = parent.Y + PlanLayoutEngine.GetNodeHeight(parent) / 2;
var childLeft = child.X;
var childCenterY = child.Y + PlanLayoutEngine.GetNodeHeight(child) / 2;
// Arrow thickness based on row estimate (logarithmic)
var rows = child.HasActualStats ? child.ActualRows : child.EstimateRows;
var thickness = Math.Max(2, Math.Min(Math.Floor(Math.Log(Math.Max(1, rows))), 12));
var midX = (parentRight + childLeft) / 2;
var geometry = new PathGeometry();
var figure = new PathFigure
{
StartPoint = new Point(parentRight, parentCenterY),
IsClosed = false
};
figure.Segments!.Add(new LineSegment { Point = new Point(midX, parentCenterY) });
figure.Segments.Add(new LineSegment { Point = new Point(midX, childCenterY) });
figure.Segments.Add(new LineSegment { Point = new Point(childLeft, childCenterY) });
geometry.Figures!.Add(figure);
var path = new AvaloniaPath
{
Data = geometry,
Stroke = EdgeBrush,
StrokeThickness = thickness,
StrokeJoin = PenLineJoin.Round
};
ToolTip.SetTip(path, BuildEdgeTooltipContent(child));
return path;
}
private object BuildEdgeTooltipContent(PlanNode child)
{
var panel = new StackPanel { MinWidth = 240 };
void AddRow(string label, string value)
{
var row = new Grid();
row.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
row.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Auto));
var lbl = new TextBlock
{
Text = label,
Foreground = new SolidColorBrush(Color.FromRgb(0xE0, 0xE0, 0xE0)),
FontSize = 12,
Margin = new Thickness(0, 1, 12, 1)
};
var val = new TextBlock
{
Text = value,
Foreground = new SolidColorBrush(Color.FromRgb(0xFF, 0xFF, 0xFF)),
FontSize = 12,
FontWeight = FontWeight.SemiBold,
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,
Margin = new Thickness(0, 1, 0, 1)
};
Grid.SetColumn(lbl, 0);
Grid.SetColumn(val, 1);
row.Children.Add(lbl);
row.Children.Add(val);
panel.Children.Add(row);
}
if (child.HasActualStats)
AddRow("Actual Number of Rows for All Executions", $"{child.ActualRows:N0}");
AddRow("Estimated Number of Rows Per Execution", $"{child.EstimateRows:N0}");
var executions = 1.0 + child.EstimateRebinds + child.EstimateRewinds;
var estimatedRowsAllExec = child.EstimateRows * executions;
AddRow("Estimated Number of Rows for All Executions", $"{estimatedRowsAllExec:N0}");
if (child.EstimatedRowSize > 0)
{
AddRow("Estimated Row Size", FormatBytes(child.EstimatedRowSize));
var dataSize = estimatedRowsAllExec * child.EstimatedRowSize;
AddRow("Estimated Data Size", FormatBytes(dataSize));
}
return new Border
{
Background = new SolidColorBrush(Color.FromRgb(0x1E, 0x1E, 0x2E)),
BorderBrush = new SolidColorBrush(Color.FromRgb(0x3A, 0x3A, 0x5A)),
BorderThickness = new Thickness(1),
Padding = new Thickness(10, 6),
CornerRadius = new CornerRadius(4),
Child = panel
};
}
private static string FormatBytes(double bytes)
{
if (bytes < 1024) return $"{bytes:N0} B";
if (bytes < 1024 * 1024) return $"{bytes / 1024:N0} KB";
if (bytes < 1024L * 1024 * 1024) return $"{bytes / (1024 * 1024):N0} MB";
return $"{bytes / (1024L * 1024 * 1024):N1} GB";
}
#endregion
#region Node Selection & Properties Panel
private void Node_Click(object? sender, PointerPressedEventArgs e)
{
if (sender is Border border
&& e.GetCurrentPoint(border).Properties.IsLeftButtonPressed
&& _nodeBorderMap.TryGetValue(border, out var node))
{
SelectNode(border, node);
e.Handled = true;
}
}
private void SelectNode(Border border, PlanNode node)
{
// Deselect previous
if (_selectedNodeBorder != null)
{
_selectedNodeBorder.BorderBrush = _selectedNodeOriginalBorder;
_selectedNodeBorder.BorderThickness = _selectedNodeOriginalThickness;
}
// Select new
_selectedNodeOriginalBorder = border.BorderBrush;
_selectedNodeOriginalThickness = border.BorderThickness;
_selectedNodeBorder = border;
border.BorderBrush = SelectionBrush;
border.BorderThickness = new Thickness(2);
ShowPropertiesPanel(node);
}
private ContextMenu BuildNodeContextMenu(PlanNode node)
{
var menu = new ContextMenu();
var propsItem = new MenuItem { Header = "Properties" };
propsItem.Click += (_, _) =>
{
foreach (var child in PlanCanvas.Children)
{
if (child is Border b && _nodeBorderMap.TryGetValue(b, out var n) && n == node)
{
SelectNode(b, node);
break;
}
}
};
menu.Items.Add(propsItem);
menu.Items.Add(new Separator());
var copyOpItem = new MenuItem { Header = "Copy Operator Name" };
copyOpItem.Click += async (_, _) => await SetClipboardTextAsync(node.PhysicalOp);
menu.Items.Add(copyOpItem);
if (!string.IsNullOrEmpty(node.FullObjectName))
{
var copyObjItem = new MenuItem { Header = "Copy Object Name" };
copyObjItem.Click += async (_, _) => await SetClipboardTextAsync(node.FullObjectName!);
menu.Items.Add(copyObjItem);
}
if (!string.IsNullOrEmpty(node.Predicate))
{
var copyPredItem = new MenuItem { Header = "Copy Predicate" };
copyPredItem.Click += async (_, _) => await SetClipboardTextAsync(node.Predicate!);
menu.Items.Add(copyPredItem);
}
if (!string.IsNullOrEmpty(node.SeekPredicates))
{
var copySeekItem = new MenuItem { Header = "Copy Seek Predicate" };
copySeekItem.Click += async (_, _) => await SetClipboardTextAsync(node.SeekPredicates!);
menu.Items.Add(copySeekItem);
}
// Schema lookup items (Show Indexes, Show Table Definition)
AddSchemaMenuItems(menu, node);
return menu;
}
private ContextMenu BuildCanvasContextMenu()
{
var menu = new ContextMenu();
// Zoom
var zoomInItem = new MenuItem { Header = "Zoom In" };
zoomInItem.Click += (_, _) => SetZoom(_zoomLevel + ZoomStep);
menu.Items.Add(zoomInItem);
var zoomOutItem = new MenuItem { Header = "Zoom Out" };
zoomOutItem.Click += (_, _) => SetZoom(_zoomLevel - ZoomStep);
menu.Items.Add(zoomOutItem);
var fitItem = new MenuItem { Header = "Fit to View" };
fitItem.Click += ZoomFit_Click;
menu.Items.Add(fitItem);
menu.Items.Add(new Separator());
// Advice
var humanAdviceItem = new MenuItem { Header = "Human Advice" };
humanAdviceItem.Click += (_, _) => HumanAdviceRequested?.Invoke(this, EventArgs.Empty);
menu.Items.Add(humanAdviceItem);
var robotAdviceItem = new MenuItem { Header = "Robot Advice" };
robotAdviceItem.Click += (_, _) => RobotAdviceRequested?.Invoke(this, EventArgs.Empty);
menu.Items.Add(robotAdviceItem);
menu.Items.Add(new Separator());
// Repro & Save
var copyReproItem = new MenuItem { Header = "Copy Repro Script" };
copyReproItem.Click += (_, _) => CopyReproRequested?.Invoke(this, EventArgs.Empty);
menu.Items.Add(copyReproItem);
var saveItem = new MenuItem { Header = "Save .sqlplan" };
saveItem.Click += SavePlan_Click;
menu.Items.Add(saveItem);
return menu;
}
private async System.Threading.Tasks.Task SetClipboardTextAsync(string text)
{
var topLevel = TopLevel.GetTopLevel(this);
if (topLevel?.Clipboard != null)
await topLevel.Clipboard.SetTextAsync(text);
}
private void ShowPropertiesPanel(PlanNode node)
{
PropertiesContent.Children.Clear();
_sectionLabelColumns.Clear();
_currentSectionGrid = null;
_currentSectionRowIndex = 0;
// Header
var headerText = node.PhysicalOp;
if (node.LogicalOp != node.PhysicalOp && !string.IsNullOrEmpty(node.LogicalOp)
&& !node.PhysicalOp.Contains(node.LogicalOp, StringComparison.OrdinalIgnoreCase))
headerText += $" ({node.LogicalOp})";
PropertiesHeader.Text = headerText;
PropertiesSubHeader.Text = $"Node ID: {node.NodeId}";
// === General Section ===
AddPropertySection("General");
AddPropertyRow("Physical Operation", node.PhysicalOp);
AddPropertyRow("Logical Operation", node.LogicalOp);
AddPropertyRow("Node ID", $"{node.NodeId}");
if (!string.IsNullOrEmpty(node.ExecutionMode))
AddPropertyRow("Execution Mode", node.ExecutionMode);
if (!string.IsNullOrEmpty(node.ActualExecutionMode) && node.ActualExecutionMode != node.ExecutionMode)
AddPropertyRow("Actual Exec Mode", node.ActualExecutionMode);
AddPropertyRow("Parallel", node.Parallel ? "True" : "False");
if (node.Partitioned)
AddPropertyRow("Partitioned", "True");
if (node.EstimatedDOP > 0)
AddPropertyRow("Estimated DOP", $"{node.EstimatedDOP}");
// Scan/seek-related properties
if (!string.IsNullOrEmpty(node.FullObjectName))
{
AddPropertyRow("Ordered", node.Ordered ? "True" : "False");
if (!string.IsNullOrEmpty(node.ScanDirection))
AddPropertyRow("Scan Direction", node.ScanDirection);
AddPropertyRow("Forced Index", node.ForcedIndex ? "True" : "False");
AddPropertyRow("ForceScan", node.ForceScan ? "True" : "False");
AddPropertyRow("ForceSeek", node.ForceSeek ? "True" : "False");
AddPropertyRow("NoExpandHint", node.NoExpandHint ? "True" : "False");
if (node.Lookup)
AddPropertyRow("Lookup", "True");
if (node.DynamicSeek)
AddPropertyRow("Dynamic Seek", "True");
}
if (!string.IsNullOrEmpty(node.StorageType))
AddPropertyRow("Storage", node.StorageType);
if (node.IsAdaptive)
AddPropertyRow("Adaptive", "True");
if (node.SpillOccurredDetail)
AddPropertyRow("Spill Occurred", "True");
// === Object Section ===
if (!string.IsNullOrEmpty(node.FullObjectName))
{
AddPropertySection("Object");
AddPropertyRow("Full Name", node.FullObjectName, isCode: true);
if (!string.IsNullOrEmpty(node.ServerName))
AddPropertyRow("Server", node.ServerName);
if (!string.IsNullOrEmpty(node.DatabaseName))
AddPropertyRow("Database", node.DatabaseName);
if (!string.IsNullOrEmpty(node.ObjectAlias))
AddPropertyRow("Alias", node.ObjectAlias);