123 private static readonly TimeSpan MinimumRefreshInterval = TimeSpan.FromMilliseconds(10);
124 private static readonly TimeSpan MaximumRefreshInterval = TimeSpan.FromMinutes(1);
125 private const int MetricSelectorHeight = 30;
126 private const int MetricSelectorWidth = 92;
127 private const int MetricSelectorMargin = 4;
129 private readonly Dictionary<string, bool> _sourceVisibility =
new(StringComparer.OrdinalIgnoreCase);
130 private readonly Dictionary<string, bool> _measurementVisibility =
new(StringComparer.Ordinal);
131 private readonly Dictionary<string, bool> _sourceMeasurementVisibility =
new(StringComparer.Ordinal);
132 private readonly Dictionary<string, string> _measurementDescriptions =
new(StringComparer.Ordinal);
133 private readonly Dictionary<int, string> _renderedMetricLines = [];
136 private TimeSpan _refreshInterval = TimeSpan.FromMilliseconds(250);
137 private long _lastRefreshTimestamp;
138 private IDisposable? _collectionRequest;
139 private bool _disposed;
140 private string _headerText =
"Gondwana Runtime Profiler";
142 private bool _measurementTooltipsEnabled =
true;
143 private bool _showMetricSelector =
true;
147 private readonly List<MetricSelectorRow> _metricSelectorRows = [];
148 private string? _metricSelectorSignature;
149 private bool _metricSelectorOpen;
150 private int _profilerZOrder;
151 private bool _showHeader =
true;
152 private bool _showSnapshotMetadata =
true;
153 private bool _showSourceHeaders =
true;
154 private bool _showUnavailableMeasurements;
167 string? nickname =
null)
171 ValidateBounds(bounds).Location,
174 ArgumentNullException.ThrowIfNull(view);
177 Rectangle displayBounds = GetDisplayBounds(bounds, showSelector:
true);
183 nickname: $
"{Nickname}.display")
186 VerticalScrollEndPaddingPx = 8f
190 .SetFont(SKTypeface.Default, 15f, minSize: 9f)
199 .SetPadding(12f, 10f)
200 .EnableWrapping(
false);
205 displayBounds.X - bounds.X,
206 displayBounds.Y - bounds.Y));
212 $
"{Nickname}.tooltip");
221 Display.PointerMove += OnProfilerPointerMove;
222 Display.PointerLeave += OnProfilerPointerLeave;
223 Display.MouseWheel += OnProfilerMouseWheel;
225 Display.SetText(
"Gondwana Runtime Profiler\nInactive. Call Show() to collect telemetry.");
243 return new Rectangle(
244 (
int)MathF.Round(position.X),
245 (
int)MathF.Round(position.Y),
274 get => _refreshInterval;
277 if (value < MinimumRefreshInterval || value > MaximumRefreshInterval)
279 throw new ArgumentOutOfRangeException(
282 "Profiler widget refresh interval must be between 10 ms and one minute.");
285 _refreshInterval = value;
294 get => _measurementVisibilityMode;
297 if (!Enum.IsDefined(value))
298 throw new ArgumentOutOfRangeException(nameof(value));
300 if (_measurementVisibilityMode == value)
303 _measurementVisibilityMode = value;
315 ArgumentException.ThrowIfNullOrWhiteSpace(value);
326 set => _showHeader = value;
334 get => _showSnapshotMetadata;
335 set => _showSnapshotMetadata = value;
343 get => _showSourceHeaders;
344 set => _showSourceHeaders = value;
353 get => _showUnavailableMeasurements;
356 if (_showUnavailableMeasurements == value)
359 _showUnavailableMeasurements = value;
368 get => _measurementTooltipsEnabled;
371 if (_measurementTooltipsEnabled == value)
374 _measurementTooltipsEnabled = value;
377 _measurementTooltip.HideTooltip();
391 get => _showMetricSelector;
394 if (_showMetricSelector == value)
397 _showMetricSelector = value;
398 _metricSelectorSignature =
null;
401 DisposeMetricSelector();
405 if (value && _latestSnapshot is not
null)
406 EnsureMetricSelector(_latestSnapshot);
447 ArgumentException.ThrowIfNullOrWhiteSpace(sourceName);
448 _sourceVisibility[sourceName] = visible;
460 ValidateMetricKey(metricKey);
461 _measurementVisibility[metricKey] = visible;
477 ArgumentException.ThrowIfNullOrWhiteSpace(sourceName);
478 ValidateMetricKey(metricKey);
479 _sourceMeasurementVisibility[CreateSourceMetricKey(sourceName, metricKey)] = visible;
489 _sourceVisibility.
Clear();
490 _measurementVisibility.
Clear();
491 _sourceMeasurementVisibility.
Clear();
503 ValidateMetricKey(metricKey);
505 if (
string.IsNullOrWhiteSpace(description))
506 _measurementDescriptions.Remove(metricKey);
508 _measurementDescriptions[metricKey] = description.Trim();
521 ArgumentException.ThrowIfNullOrWhiteSpace(sourceName);
522 ValidateMetricKey(metricKey);
534 Display.SetColors(foreground, background);
547 Display.SetFont(typeface, size, minSize);
558 _profilerZOrder = zOrder;
559 Display.SetLabelZOrder(zOrder);
560 _metricSelectorButton?.SetButtonZOrder(zOrder + 100);
561 _metricSelectorList?.SetListBoxZOrder(zOrder + 200);
562 _measurementTooltip.SetTooltipZOrder(zOrder + 1000);
576 _latestSnapshot = snapshot;
578 string text = FormatSnapshot(snapshot);
579 CaptureRenderedMetricLines(text);
582 if (snapshot is not
null)
583 EnsureMetricSelector(snapshot);
593 if (!_metricSelectorOpen)
594 _metricSelectorList?.Hide();
596 if (_collectionRequest is not
null)
600 _lastRefreshTimestamp = 0;
601 Engine.Instance.AfterBackgroundTasksExecute += OnAfterBackgroundTasksExecute;
608 _measurementTooltip.HideTooltip();
609 _metricSelectorOpen =
false;
610 _metricSelectorList?.Hide();
612 base.ProcessHidden();
625 Display.PointerMove -= OnProfilerPointerMove;
626 Display.PointerLeave -= OnProfilerPointerLeave;
627 Display.MouseWheel -= OnProfilerMouseWheel;
629 _measurementTooltip.HideTooltip();
630 _measurementTooltip.Dispose();
631 DisposeMetricSelector();
636 private void OnAfterBackgroundTasksExecute()
638 if (_collectionRequest is
null)
641 long now = Stopwatch.GetTimestamp();
643 if (_lastRefreshTimestamp != 0 &&
644 Stopwatch.GetElapsedTime(_lastRefreshTimestamp, now) <
RefreshInterval)
649 _lastRefreshTimestamp = now;
653 private void StopCollection()
655 Engine.Instance.AfterBackgroundTasksExecute -= OnAfterBackgroundTasksExecute;
656 _collectionRequest?.Dispose();
657 _collectionRequest =
null;
658 _lastRefreshTimestamp = 0;
663 var text =
new StringBuilder();
670 if (view is not
null)
672 var extensionContext =
new ProfilerWidgetExtensionContext(
677 AppendAdditionalLines(text, extensionContext);
678 AppendRuntimeContext(text, extensionContext);
681 if (snapshot is
null)
683 text.Append(
"Waiting for first completed telemetry window...");
684 return text.ToString().TrimEnd();
689 text.Append(
"Generation ")
690 .Append(snapshot.Generation)
691 .Append(
" | window ")
692 .Append((snapshot.ElapsedSeconds * 1000d).ToString(
"0.0"))
695 if (snapshot.Truncated)
696 text.Append(
" | detail truncated");
701 bool wroteSource =
false;
705 if (!IsSourceVisible(source.Name))
708 var metrics = source.Metrics
709 .Where(pair => ResolveMeasurementVisibility(
712 pair.Value.Availability))
713 .OrderBy(pair => pair.Key, StringComparer.Ordinal)
716 if (metrics.Length == 0)
724 text.Append(source.Name)
726 .Append(source.Backend)
730 foreach (KeyValuePair<string, TelemetrySummary> pair
in metrics)
735 .AppendLine(FormatSummary(pair.Value, snapshot.ElapsedSeconds));
742 text.Append(
"No measurements selected.");
744 return text.ToString().TrimEnd();
747 private void AppendAdditionalLines(
749 ProfilerWidgetExtensionContext context)
756 foreach (
string line
in lines)
757 text.AppendLine(line ??
string.Empty);
760 private void AppendRuntimeContext(
762 ProfilerWidgetExtensionContext context)
766 var scene = context.RenderSurfaceHost.Scene;
767 long gridCells = scene.SceneLayers.Sum(
static layer => (
long)layer.GridColumnCount * layer.GridRowCount);
769 text.Append(
"Animating tiles: ")
770 .AppendLine(Tile.TilesAnimating.Count.ToString(
"N0"));
772 text.Append(
"Layers / grid cells: ")
773 .Append(scene.SceneLayers.Count)
775 .AppendLine(gridCells.ToString(
"N0"));
778 Rectangle viewport = context.View.Viewport.TargetRectPx;
782 PointF camera = context.View.Camera.PositionPx;
784 text.Append(
"Camera: ")
785 .Append(camera.X.ToString(
"0.0"))
787 .Append(camera.Y.ToString(
"0.0"))
788 .Append(
" px; zoom: ")
789 .Append(context.View.Viewport.Zoom.ToString(
"0.000"))
796 if (includeViewport && includeBackbuffer)
798 var backbuffer = context.RenderSurfaceHost.Backbuffer;
800 text.Append(
"Viewport / backbuffer: ")
801 .Append(viewport.Width)
803 .Append(viewport.Height)
805 .Append(backbuffer.Width)
807 .AppendLine(backbuffer.Height.ToString());
809 else if (includeViewport)
811 text.Append(
"Viewport: ")
812 .Append(viewport.Width)
814 .AppendLine(viewport.Height.ToString());
816 else if (includeBackbuffer)
818 var backbuffer = context.RenderSurfaceHost.Backbuffer;
820 text.Append(
"Backbuffer: ")
821 .Append(backbuffer.Width)
823 .AppendLine(backbuffer.Height.ToString());
828 text.Append(
"Target FPS / VSync: ")
829 .Append(Engine.Instance.Configuration.TargetFPS)
831 .AppendLine(Engine.Instance.Configuration.VSync.ToString());
835 context.RenderSurfaceHost.Backbuffer is GpuBackbuffer gpu)
837 text.Append(
"MSAA requested / actual / max: ")
838 .Append(gpu.MsaaSampleCount)
840 .Append(gpu.ActualMsaaSampleCount)
842 .AppendLine(gpu.MaxSupportedMsaaSampleCount.ToString());
846 private void ApplyLayout()
854 displayBounds.X - bounds.X,
855 displayBounds.Y - bounds.Y));
857 Display.Size = displayBounds.Size;
859 if (_metricSelectorButton is not
null || _metricSelectorList is not
null)
861 DisposeMetricSelector();
862 _metricSelectorSignature =
null;
865 EnsureMetricSelector(_latestSnapshot);
869 private static Rectangle GetDisplayBounds(Rectangle bounds,
bool showSelector)
871 int toolbarHeight = showSelector
872 ? Math.Min(MetricSelectorHeight, Math.Max(0, bounds.Height - 1))
877 bounds.Top + toolbarHeight,
879 Math.Max(1, bounds.Height - toolbarHeight));
882 private static Rectangle GetMetricSelectorButtonBounds(Rectangle bounds)
884 int width = Math.Max(
888 Math.Max(1, bounds.Width - MetricSelectorMargin * 2)));
890 int height = Math.Max(
893 MetricSelectorHeight - MetricSelectorMargin * 2,
894 Math.Max(1, bounds.Height)));
897 bounds.Left + MetricSelectorMargin,
898 bounds.Top + MetricSelectorMargin,
903 private static Rectangle GetMetricSelectorListBounds(Rectangle bounds)
905 int width = Math.Max(24, Math.Min(460, Math.Max(24, bounds.Width - MetricSelectorMargin * 2)));
907 int availableHeight = Math.Max(
909 bounds.Height - MetricSelectorHeight - MetricSelectorMargin);
911 int height = Math.Max(28, Math.Min(420, availableHeight));
914 bounds.Left + MetricSelectorMargin,
915 bounds.Top + MetricSelectorHeight,
927 string signature = BuildMetricSelectorSignature(snapshot);
929 if (_metricSelectorButton is
null ||
930 _metricSelectorList is
null ||
931 !
string.Equals(_metricSelectorSignature, signature, StringComparison.Ordinal))
933 bool wasOpen = _metricSelectorOpen;
934 DisposeMetricSelector();
935 _metricSelectorOpen = wasOpen;
938 Rectangle buttonBounds = GetMetricSelectorButtonBounds(bounds);
939 Rectangle listBounds = GetMetricSelectorListBounds(bounds);
941 _metricSelectorButton =
new ButtonWidget(
946 $
"{Nickname}.metric-selector.button")
947 .SetButtonZOrder(_profilerZOrder + 100);
949 _metricSelectorButton.Clicked += ToggleMetricSelector;
951 _metricSelectorList =
new ListBoxWidget(
955 nickname: $
"{Nickname}.metric-selector.list")
958 VerticalScrollBarVisibility = ScrollBarVisibility.Auto
962 .SetListBoxZOrder(_profilerZOrder + 200)
970 _metricSelectorList.SelectionCommitted += OnMetricSelectorSelectionCommitted;
973 _metricSelectorButton,
975 buttonBounds.X - bounds.X,
976 buttonBounds.Y - bounds.Y));
981 listBounds.X - bounds.X,
982 listBounds.Y - bounds.Y));
984 _metricSelectorSignature = signature;
986 if (!_metricSelectorOpen)
987 _metricSelectorList.Hide();
990 RefreshMetricSelectorRows(snapshot);
995 var signature =
new StringBuilder()
1000 foreach (var sourceGroup
in snapshot.Sources
1001 .GroupBy(source => source.Name, StringComparer.OrdinalIgnoreCase)
1002 .OrderBy(group => group.Key, StringComparer.OrdinalIgnoreCase))
1004 signature.Append(
'|').Append(sourceGroup.Key);
1006 foreach (
string backend
in sourceGroup
1007 .Select(source => source.Backend)
1008 .Distinct(StringComparer.Ordinal)
1009 .OrderBy(value => value, StringComparer.Ordinal))
1011 signature.Append(
'[').Append(backend).Append(
']');
1014 foreach (
string metricKey
in sourceGroup
1015 .SelectMany(source => source.Metrics.Keys)
1016 .Distinct(StringComparer.Ordinal)
1017 .OrderBy(value => value, StringComparer.Ordinal))
1019 signature.Append(
';').Append(metricKey);
1023 return signature.ToString();
1028 if (_metricSelectorList is
null)
1031 _metricSelectorRows.Clear();
1035 "Hover definitions",
1043 _metricSelectorRows.Add(
1044 new MetricSelectorRow(
1045 "Show all measurements",
1052 _metricSelectorRows.Add(
1053 new MetricSelectorRow(
1054 "Hide all measurements",
1061 _metricSelectorRows.Add(
new MetricSelectorRow(
"------------------------------",
null));
1063 foreach (var sourceGroup
in snapshot.Sources
1064 .GroupBy(source => source.Name, StringComparer.OrdinalIgnoreCase)
1065 .OrderBy(group => group.Key, StringComparer.OrdinalIgnoreCase))
1067 string sourceName = sourceGroup.Key;
1069 string backend =
string.Join(
1072 .Select(source => source.Backend)
1073 .Distinct(StringComparer.Ordinal)
1074 .OrderBy(value => value, StringComparer.Ordinal));
1076 bool sourceVisible = IsSourceVisible(sourceName);
1080 $
"{sourceName} [{backend}]",
1083 foreach (
string metricKey
in sourceGroup
1084 .SelectMany(source => source.Metrics.Keys)
1085 .Distinct(StringComparer.Ordinal)
1086 .OrderBy(value => value, StringComparer.Ordinal))
1089 .Where(source => source.Metrics.ContainsKey(metricKey))
1090 .Select(source => source.Metrics[metricKey].Availability)
1094 bool metricVisible = ResolveMeasurementVisibility(
1099 string capturedMetricKey = metricKey;
1100 string capturedSourceName = sourceName;
1103 string availabilitySuffix = availability == TelemetryAvailability.Available
1105 : $
" [{FormatAvailability(availability)}]";
1109 $
" {metricKey}{availabilitySuffix}",
1113 !ResolveMeasurementVisibility(
1116 capturedAvailability)));
1120 int topIndex = _metricSelectorList.TopIndex;
1121 _metricSelectorList.SetItems(_metricSelectorRows.Select(row => row.Text));
1123 int maximumTopIndex = Math.Max(
1125 _metricSelectorRows.Count - _metricSelectorList.VisibleItemCount);
1127 _metricSelectorList.TopIndex = Math.Min(topIndex, maximumTopIndex);
1130 private void AddSelectorRow(
bool isChecked,
string text, Action action)
1132 _metricSelectorRows.Add(
1133 new MetricSelectorRow(
1134 $
"[{(isChecked ? 'x' : ' ')}] {text}",
1138 private void ToggleMetricSelector()
1140 if (_metricSelectorList is
null)
1143 _metricSelectorOpen = !_metricSelectorOpen;
1145 if (_metricSelectorOpen)
1147 _metricSelectorList.Show();
1148 _metricSelectorList.Activate();
1152 _metricSelectorList.Hide();
1156 private void OnMetricSelectorSelectionCommitted(
int index)
1158 if (index < 0 || index >= _metricSelectorRows.Count)
1161 MetricSelectorRow row = _metricSelectorRows[index];
1163 if (row.Action is
null)
1170 private void DisposeMetricSelector()
1172 if (_metricSelectorButton is not
null)
1174 _metricSelectorButton.Clicked -= ToggleMetricSelector;
1175 RemoveChild(_metricSelectorButton, dispose:
true);
1176 _metricSelectorButton =
null;
1179 if (_metricSelectorList is not
null)
1181 _metricSelectorList.SelectionCommitted -= OnMetricSelectorSelectionCommitted;
1183 _metricSelectorList =
null;
1186 _metricSelectorRows.Clear();
1187 _metricSelectorSignature =
null;
1190 private void CaptureRenderedMetricLines(
string text)
1192 _renderedMetricLines.Clear();
1194 string[] lines = text
1195 .Replace(
"\r\n",
"\n", StringComparison.Ordinal)
1198 for (
int index = 0; index < lines.Length; index++)
1200 string line = lines[index];
1202 if (!line.StartsWith(
" ", StringComparison.Ordinal))
1205 int colon = line.IndexOf(
':', 2);
1210 string metricKey = line[2..colon].Trim();
1212 if (!
string.IsNullOrWhiteSpace(metricKey))
1213 _renderedMetricLines[index] = metricKey;
1217 private void OnProfilerPointerMove(WidgetPointerEventArgs args)
1221 _measurementTooltip.HideTooltip();
1228 if (!displayBounds.Contains(pointer))
1230 _measurementTooltip.HideTooltip();
1234 float lineHeight =
Display.TextBlock.LineHeight;
1236 if (lineHeight <= 0f)
1238 _measurementTooltip.HideTooltip();
1243 args.ScreenPositionPx.Y -
1245 Display.TextBlock.VerticalPadding +
1246 Display.VerticalScrollOffsetPx;
1250 _measurementTooltip.HideTooltip();
1254 int lineIndex = (int)MathF.Floor(localY / lineHeight);
1256 if (!_renderedMetricLines.TryGetValue(lineIndex, out
string? metricKey))
1258 _measurementTooltip.HideTooltip();
1262 string? description = GetMeasurementDescription(metricKey);
1264 if (
string.IsNullOrWhiteSpace(description))
1266 _measurementTooltip.HideTooltip();
1270 _measurementTooltip.ShowTooltip(
1271 $
"{metricKey}\n{description}",
1275 private void OnProfilerPointerLeave(WidgetPointerEventArgs args)
1278 _measurementTooltip.HideTooltip();
1281 private void OnProfilerMouseWheel(WidgetMouseWheelEventArgs args)
1284 _measurementTooltip.HideTooltip();
1287 private string? GetMeasurementDescription(
string metricKey)
1289 if (_measurementDescriptions.TryGetValue(metricKey, out
string? overrideDescription))
1290 return overrideDescription;
1292 string normalizedKey = NormalizeLayerMetricKey(metricKey);
1294 string? description = normalizedKey
switch
1297 "CPU time for one complete Engine cycle. The sample rate is the Engine cycle rate (CPS).",
1298 "background.cpu.ms" =>
1299 "CPU time spent in background/simulation work for one Engine cycle.",
1300 "foreground.cpu.ms" =>
1301 "CPU time spent in foreground/render-preparation work. The sample rate is foreground frame production.",
1303 "Engine-thread time spent building the render frame or render snapshot.",
1305 "Time spent querying and culling visible drawables. Sorting is reported separately.",
1307 "Time spent sorting queried drawables into render order.",
1309 "Time spent recording render commands after query/sort.",
1311 "Time spent recording view/direct-drawing overlay work.",
1312 "visible.drawables" =>
1313 "Visible drawable instances observed during a render build, including repeated instances across views.",
1315 "Visible tile draw instances observed during a render build.",
1317 "Atlas-backed tile batches generated for a render build.",
1319 "Tiles emitted through atlas-backed batches for a render build.",
1321 "GPU presentation-thread time spent replaying a completed render snapshot.",
1323 "Time spent replaying the recorded Skia picture into the GPU backbuffer.",
1324 "backbuffer.flush.cpu.ms" =>
1325 "Time spent flushing GPU backbuffer drawing after replay.",
1326 "snapshot.cpu.ms" =>
1327 "Time spent snapshotting the current GPU backbuffer for presentation/inspection.",
1328 "snapshot.age.ms" =>
1329 "Age of the consumed render snapshot when GPU replay begins. Higher values indicate producer/consumer lag.",
1330 "mailbox.published.lifetime" =>
1331 "Lifetime count of render snapshots published to the producer/consumer mailbox.",
1332 "mailbox.dropped.lifetime" =>
1333 "Lifetime count of published snapshots superseded before they could be consumed.",
1335 "Current occupied snapshot-mailbox slots.",
1336 "snapshot.commands.approximate" =>
1337 "Approximate command count retained by the latest render snapshot.",
1338 "gate.wait.cpu.ms" =>
1339 "Time spent waiting to enter the shared live render-state gate. Current desktop snapshot replay does not enter this broad gate, so the desktop GPU source reports NotApplicable.",
1340 "gate.held.cpu.ms" =>
1341 "Time spent while holding the shared live render-state gate. Current desktop snapshot replay does not enter this broad gate, so the desktop GPU source reports NotApplicable.",
1342 "presentation.count" =>
1343 "Completed presentation callbacks. Its sample rate is the actual GPU presentation FPS for this render surface.",
1344 "presentation.cpu.ms" =>
1345 "Total CPU duration of one GPU presentation callback.",
1346 "render.snapshot.cpu.ms" =>
1347 "Combined render/snapshot CPU work measured by the GPU presentation path.",
1349 "Platform presentation time spent blitting the completed image.",
1351 "Platform presentation time spent performing the final graphics flush.",
1353 "Number of SceneLayers omitted from detailed per-layer telemetry because the retained layer-detail limit was reached.",
1354 "layer.query.cpu.ms" =>
1355 "Per-layer time spent querying/culling visible content; sorting is excluded.",
1356 "layer.record.cpu.ms" =>
1357 "Per-layer time spent recording render commands.",
1358 "layer.drawables" =>
1359 "Visible drawable instances contributed by this SceneLayer across views.",
1361 "Visible tile draw instances contributed by this SceneLayer.",
1362 "layer.transformed.tiles" =>
1363 "Current count of this layer's visible tiles requiring transform work.",
1364 "layer.tile.width.px" =>
1365 "Current native tile width for this SceneLayer.",
1366 "layer.tile.height.px" =>
1367 "Current native tile height for this SceneLayer.",
1369 "Current SceneLayer Z-order.",
1373 if (description is
null)
1376 if (_latestSnapshot is
null)
1380 .SelectMany(source => source.Metrics)
1381 .Where(pair =>
string.Equals(
1382 NormalizeLayerMetricKey(pair.Key),
1384 StringComparison.Ordinal))
1385 .Select(pair => pair.Value)
1388 return summary?.Kind == TelemetryMetricKind.Sample
1390 "\n\navg/min/max are values observed during the current telemetry window. " +
1391 "samples is how many times this metric was recorded; samples/s is that count " +
1392 "divided by the window duration, not the metric value per second."
1396 private static string NormalizeLayerMetricKey(
string metricKey)
1398 if (!metricKey.StartsWith(
"layer.", StringComparison.Ordinal))
1401 int firstSeparator = metricKey.IndexOf(
'.',
"layer.".Length);
1403 if (firstSeparator < 0 || firstSeparator + 1 >= metricKey.Length)
1406 return "layer." + metricKey[(firstSeparator + 1)..];
1409 private sealed record MetricSelectorRow(
string Text, Action? Action);
1411 private bool IsSourceVisible(
string sourceName)
1413 return !_sourceVisibility.TryGetValue(sourceName, out
bool visible) || visible;
1416 private bool ResolveMeasurementVisibility(
1421 if (!IsSourceVisible(sourceName))
1424 bool explicitlySelected =
false;
1427 if (_sourceMeasurementVisibility.TryGetValue(
1428 CreateSourceMetricKey(sourceName, metricKey),
1429 out
bool sourceMetricVisible))
1431 selected = sourceMetricVisible;
1432 explicitlySelected = sourceMetricVisible;
1434 else if (_measurementVisibility.TryGetValue(metricKey, out
bool metricVisible))
1436 selected = metricVisible;
1437 explicitlySelected = metricVisible;
1447 return availability == TelemetryAvailability.Available ||
1452 private static string FormatSummary(
TelemetrySummary summary,
double elapsedSeconds)
1455 return summary.Availability.ToString();
1457 return summary.Kind
switch
1459 TelemetryMetricKind.Gauge =>
1460 $
"last {FormatNumber(summary.Last)}",
1461 TelemetryMetricKind.LifetimeCounter =>
1462 summary.WindowDelta is { } delta
1463 ? $
"last {FormatNumber(summary.Last)}, delta {FormatNumber(delta)}"
1464 : $
"last {FormatNumber(summary.Last)}, delta n/a",
1466 $
"avg {FormatNumber(summary.Mean)}, min {FormatNumber(summary.Minimum)}, " +
1467 $
"max {FormatNumber(summary.Maximum)}, samples {summary.Count:N0} " +
1468 $
"({FormatRate(summary.Count, elapsedSeconds)} samples/s)"
1472 private static string FormatRate(
long count,
double elapsedSeconds)
1474 return elapsedSeconds > 0d
1475 ? (count / elapsedSeconds).ToString(
"0.0")
1479 private static string FormatNumber(
double? value)
1481 return value?.ToString(
"0.###") ??
"n/a";
1486 return availability
switch
1488 TelemetryAvailability.Unsupported =>
"unsupported",
1489 TelemetryAvailability.NotApplicable =>
"not applicable",
1490 TelemetryAvailability.NotYetSampled =>
"not yet sampled",
1495 private static string CreateSourceMetricKey(
string sourceName,
string metricKey)
1497 return $
"{sourceName.ToUpperInvariant()}\u001f{metricKey}";
1500 private static void ValidateMetricKey(
string metricKey)
1502 ArgumentException.ThrowIfNullOrWhiteSpace(metricKey);
1505 private static Rectangle ValidateBounds(Rectangle bounds)
1507 ValidateSize(bounds.Size);
1511 private static void ValidateSize(
Size size)
1513 if (size.Width <= 0 || size.Height <= 0)
1514 throw new ArgumentOutOfRangeException(nameof(size), size,
"Profiler widget size must be positive.");