feat(ui-visuals): add retained-mode drawing base and chart data types
DrawingElement resolves theme brushes by key (re-resolved on theme swap via a resource-reference probe), caches frozen pens per theme and DPI, lays out text in the UI font and offers an overlay layer redrawn without touching the static content. HoverReadout is a mouse-following tooltip for values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
3 files changed
+409
No files matched your search
@@ -0,0 +1,116 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>Stroke pattern of a series or legend swatch.</summary>
|
||||
public enum LineDash
|
||||
{
|
||||
Solid,
|
||||
|
||||
/// <summary>5–4 dashes (sky region curve).</summary>
|
||||
Dashed,
|
||||
|
||||
/// <summary>2–3 dots.</summary>
|
||||
Dotted,
|
||||
}
|
||||
|
||||
/// <summary>One per-frame line of a <see cref="SeriesChart"/>. Values are indexed by frame; NaN leaves a gap.</summary>
|
||||
public sealed class ChartSeries
|
||||
{
|
||||
public ChartSeries(string? title, ReadOnlyMemory<double> values, string brushKey)
|
||||
{
|
||||
Title = title;
|
||||
Values = values;
|
||||
BrushKey = brushKey;
|
||||
}
|
||||
|
||||
/// <summary>Legend and readout text (localized by the caller).</summary>
|
||||
public string? Title { get; init; }
|
||||
|
||||
public ReadOnlyMemory<double> Values { get; init; }
|
||||
|
||||
/// <summary>Theme brush resource key, e.g. <c>Brush.Sun</c>; re-resolved when the theme changes.</summary>
|
||||
public string BrushKey { get; init; }
|
||||
|
||||
/// <summary>Stroke width in DIPs.</summary>
|
||||
public double Thickness { get; init; } = 1.5;
|
||||
|
||||
public LineDash Dash { get; init; } = LineDash.Solid;
|
||||
|
||||
/// <summary>Whether the automatic legend lists this series.</summary>
|
||||
public bool ShowInLegend { get; init; } = true;
|
||||
}
|
||||
|
||||
/// <summary>Shape drawn before a legend entry.</summary>
|
||||
public enum LegendSwatch
|
||||
{
|
||||
Line,
|
||||
DashedLine,
|
||||
DottedLine,
|
||||
|
||||
/// <summary>▼ (exposure steps).</summary>
|
||||
Triangle,
|
||||
|
||||
/// <summary>◆ (keyframes).</summary>
|
||||
Diamond,
|
||||
|
||||
Square,
|
||||
}
|
||||
|
||||
/// <summary>A legend entry: swatch in a theme brush followed by text.</summary>
|
||||
public sealed record ChartLegendItem(string Text, string BrushKey, LegendSwatch Swatch = LegendSwatch.Line);
|
||||
|
||||
/// <summary>What a timeline marker stands for; the kind fixes its colour and glyph.</summary>
|
||||
public enum MarkerKind
|
||||
{
|
||||
/// <summary>ISO/shutter/aperture step as received: ▼ in Sun.</summary>
|
||||
ExposureStep,
|
||||
|
||||
/// <summary>▼ in Warning.</summary>
|
||||
Warning,
|
||||
|
||||
/// <summary>▼ in Error.</summary>
|
||||
Error,
|
||||
|
||||
/// <summary>Virtual-camera or remap keyframe: ◆ in Accent.</summary>
|
||||
Keyframe,
|
||||
}
|
||||
|
||||
/// <summary>A frame-anchored marker shown above the filmstrip and as a dashed line in series charts.</summary>
|
||||
public readonly record struct TimelineMarker(int Index, MarkerKind Kind, string? Label = null)
|
||||
{
|
||||
/// <summary>Theme brush key of a marker kind.</summary>
|
||||
public static string BrushKeyOf(MarkerKind kind) => kind switch
|
||||
{
|
||||
MarkerKind.ExposureStep => "Brush.Sun",
|
||||
MarkerKind.Warning => "Brush.Warning",
|
||||
MarkerKind.Error => "Brush.Error",
|
||||
_ => "Brush.Accent",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A labelled value of a bar or proportion chart.</summary>
|
||||
/// <param name="Label">Category text (year, camera, format…).</param>
|
||||
/// <param name="Value">Magnitude; negative values draw as zero.</param>
|
||||
/// <param name="ValueText">Formatted value shown next to the bar; null uses the chart formatter.</param>
|
||||
/// <param name="ToolTip">Hover text; null shows label and value.</param>
|
||||
/// <param name="BrushKey">Theme brush key overriding the chart brush.</param>
|
||||
public sealed record ChartItem(string Label, double Value, string? ValueText = null, string? ToolTip = null, string? BrushKey = null);
|
||||
|
||||
/// <summary>A labelled row of values (a heatmap year, a timeline band); NaN marks "no data".</summary>
|
||||
/// <param name="Label">Row text (e.g. the year).</param>
|
||||
/// <param name="Values">One value per column (e.g. 12 months).</param>
|
||||
/// <param name="ToolTips">Optional hover text per column.</param>
|
||||
public sealed record ChartRow(string Label, IReadOnlyList<double> Values, IReadOnlyList<string?>? ToolTips = null);
|
||||
|
||||
/// <summary>Identifies the item a chart interaction refers to.</summary>
|
||||
public sealed class ChartItemEventArgs(RoutedEvent routedEvent, int row, int column) : RoutedEventArgs(routedEvent)
|
||||
{
|
||||
/// <summary>Item index (bars, segments) or row index (heatmap, bands).</summary>
|
||||
public int Row { get; } = row;
|
||||
|
||||
/// <summary>Column index for grids (heatmap month, band slot); −1 for single-index charts.</summary>
|
||||
public int Column { get; } = column;
|
||||
}
|
||||
|
||||
public delegate void ChartItemEventHandler(object sender, ChartItemEventArgs e);
|
||||
@@ -0,0 +1,242 @@
|
||||
using System.Collections.Specialized;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Media;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// Base of the retained-mode visuals. Brushes are looked up by theme resource key and re-resolved when the token
|
||||
/// dictionary is swapped (frozen pens are cached per theme); text is laid out with the UI font at the element's
|
||||
/// DPI; an optional overlay layer (playhead, hover) is redrawn without re-rendering the static content drawn in
|
||||
/// <see cref="UIElement.OnRender"/>. Time axes and images never mirror, so the element is always left-to-right.
|
||||
/// </summary>
|
||||
public abstract class DrawingElement : FrameworkElement
|
||||
{
|
||||
/// <summary>Follows a token brush; its change signals a theme switch.</summary>
|
||||
private static readonly DependencyProperty ThemeProbeProperty = DependencyProperty.Register(
|
||||
"ThemeProbe", typeof(object), typeof(DrawingElement), new PropertyMetadata(null, OnThemeProbeChanged));
|
||||
|
||||
private readonly Dictionary<string, Brush> _brushes = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<(string Key, double Thickness, LineDash Dash), Pen> _pens = [];
|
||||
private readonly DrawingVisual? _overlay;
|
||||
private HoverReadout? _readout;
|
||||
private Typeface? _regular;
|
||||
private Typeface? _semiBold;
|
||||
|
||||
/// <param name="hasOverlay">Creates the overlay layer drawn by <see cref="OnRenderOverlay"/>.</param>
|
||||
protected DrawingElement(bool hasOverlay = false)
|
||||
{
|
||||
if (hasOverlay)
|
||||
{
|
||||
_overlay = new DrawingVisual();
|
||||
AddVisualChild(_overlay);
|
||||
}
|
||||
FlowDirection = FlowDirection.LeftToRight;
|
||||
SetResourceReference(ThemeProbeProperty, "Brush.Text");
|
||||
Unloaded += (_, _) => _readout?.Hide();
|
||||
}
|
||||
|
||||
/// <summary>Device pixels per DIP on the monitor showing the element.</summary>
|
||||
protected double PixelScale => VisualTreeHelper.GetDpi(this).DpiScaleX;
|
||||
|
||||
/// <summary>Tooltip-styled readout that follows the mouse.</summary>
|
||||
protected HoverReadout Readout => _readout ??= new HoverReadout(this);
|
||||
|
||||
protected override int VisualChildrenCount => _overlay is null ? 0 : 1;
|
||||
|
||||
protected override Visual GetVisualChild(int index) =>
|
||||
_overlay is not null && index == 0 ? _overlay : throw new ArgumentOutOfRangeException(nameof(index));
|
||||
|
||||
/// <summary>Frozen theme brush for <paramref name="key"/> (transparent when the key is unknown).</summary>
|
||||
protected Brush GetBrush(string key)
|
||||
{
|
||||
if (_brushes.TryGetValue(key, out var brush)) return brush;
|
||||
// A frozen copy: drawing never notifies, and freezing pens never freezes the shared resource itself.
|
||||
brush = TryFindResource(key) switch
|
||||
{
|
||||
Brush { IsFrozen: true } frozen => frozen,
|
||||
Brush { CanFreeze: true } live => (Brush)live.GetCurrentValueAsFrozen(),
|
||||
Brush live => live,
|
||||
_ => Brushes.Transparent,
|
||||
};
|
||||
_brushes[key] = brush;
|
||||
return brush;
|
||||
}
|
||||
|
||||
/// <summary>Frozen pen in the theme brush <paramref name="key"/>, cached until the theme or DPI changes.</summary>
|
||||
protected Pen GetPen(string key, double thickness, LineDash dash = LineDash.Solid)
|
||||
{
|
||||
if (_pens.TryGetValue((key, thickness, dash), out var pen)) return pen;
|
||||
pen = CreatePen(key, thickness, dash);
|
||||
_pens[(key, thickness, dash)] = pen;
|
||||
return pen;
|
||||
}
|
||||
|
||||
/// <summary>Uncached frozen pen, for thicknesses that vary continuously (e.g. compensating a zoom).</summary>
|
||||
protected Pen CreatePen(string key, double thickness, LineDash dash = LineDash.Solid)
|
||||
{
|
||||
var pen = new Pen(GetBrush(key), thickness)
|
||||
{
|
||||
DashStyle = DashFor(dash, thickness),
|
||||
LineJoin = PenLineJoin.Round,
|
||||
StartLineCap = dash == LineDash.Solid ? PenLineCap.Round : PenLineCap.Flat,
|
||||
EndLineCap = dash == LineDash.Solid ? PenLineCap.Round : PenLineCap.Flat,
|
||||
};
|
||||
if (pen.CanFreeze) pen.Freeze();
|
||||
return pen;
|
||||
}
|
||||
|
||||
/// <summary>Pen covering whole device pixels, for gridlines and edges drawn at <see cref="PixelGrid.SnapLine"/> positions.</summary>
|
||||
protected Pen GetHairline(string key, LineDash dash = LineDash.Solid) => GetPen(key, PixelGrid.SnapThickness(1, PixelScale), dash);
|
||||
|
||||
/// <summary>Single-line text in the UI font, laid out for this element's DPI and text formatting mode.</summary>
|
||||
protected FormattedText CreateText(string text, double emSize, Brush brush, bool semiBold = false)
|
||||
{
|
||||
var typeface = semiBold ? _semiBold ??= CreateTypeface(FontWeights.SemiBold) : _regular ??= CreateTypeface(FontWeights.Normal);
|
||||
return new FormattedText(text, Loc.Culture, FlowDirection.LeftToRight, typeface, emSize, brush, null,
|
||||
TextOptions.GetTextFormattingMode(this), VisualTreeHelper.GetDpi(this).PixelsPerDip);
|
||||
}
|
||||
|
||||
/// <summary>Redraws the overlay layer; call after any change that only affects playhead or hover state.</summary>
|
||||
protected void RenderOverlay()
|
||||
{
|
||||
if (_overlay is null) return;
|
||||
using var dc = _overlay.RenderOpen();
|
||||
if (ActualWidth > 0 && ActualHeight > 0) OnRenderOverlay(dc);
|
||||
}
|
||||
|
||||
/// <summary>Draws the overlay layer (above the static content).</summary>
|
||||
protected virtual void OnRenderOverlay(DrawingContext dc)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Called after the theme brushes changed; the default redraws everything.</summary>
|
||||
protected virtual void OnThemeChanged()
|
||||
{
|
||||
InvalidateVisual();
|
||||
if (_overlay is not null) RenderOverlay();
|
||||
}
|
||||
|
||||
/// <summary>Called when a data property or a watched collection changed; the default re-measures and redraws.</summary>
|
||||
protected virtual void OnDataChanged()
|
||||
{
|
||||
InvalidateMeasure();
|
||||
InvalidateVisual();
|
||||
}
|
||||
|
||||
/// <summary>Property-changed callback for data properties: watches observable collections weakly and calls <see cref="OnDataChanged"/>.</summary>
|
||||
protected static void OnDataPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
var element = (DrawingElement)d;
|
||||
if (e.OldValue is INotifyCollectionChanged oldCollection) CollectionChangedEventManager.RemoveHandler(oldCollection, element.OnWatchedCollectionChanged);
|
||||
if (e.NewValue is INotifyCollectionChanged newCollection) CollectionChangedEventManager.AddHandler(newCollection, element.OnWatchedCollectionChanged);
|
||||
element.OnDataChanged();
|
||||
}
|
||||
|
||||
protected override void OnDpiChanged(DpiScale oldDpi, DpiScale newDpi)
|
||||
{
|
||||
base.OnDpiChanged(oldDpi, newDpi);
|
||||
_pens.Clear();
|
||||
_regular = _semiBold = null;
|
||||
OnThemeChanged();
|
||||
}
|
||||
|
||||
/// <summary>Fills the whole element with a transparent brush so empty areas still receive the mouse.</summary>
|
||||
protected void DrawHitArea(DrawingContext dc) => dc.DrawRectangle(Brushes.Transparent, null, new Rect(RenderSize));
|
||||
|
||||
/// <summary>Adds a ▼ of width <paramref name="size"/> whose top edge is centred at (<paramref name="cx"/>, <paramref name="top"/>).</summary>
|
||||
protected static void AddTriangleDown(StreamGeometryContext ctx, double cx, double top, double size)
|
||||
{
|
||||
ctx.BeginFigure(new Point(cx - size / 2, top), true, true);
|
||||
ctx.LineTo(new Point(cx + size / 2, top), false, false);
|
||||
ctx.LineTo(new Point(cx, top + size * 0.8), false, false);
|
||||
}
|
||||
|
||||
/// <summary>Adds a ◆ of width <paramref name="size"/> centred at (<paramref name="cx"/>, <paramref name="cy"/>).</summary>
|
||||
protected static void AddDiamond(StreamGeometryContext ctx, double cx, double cy, double size)
|
||||
{
|
||||
var h = size / 2;
|
||||
ctx.BeginFigure(new Point(cx, cy - h), true, true);
|
||||
ctx.LineTo(new Point(cx + h, cy), false, false);
|
||||
ctx.LineTo(new Point(cx, cy + h), false, false);
|
||||
ctx.LineTo(new Point(cx - h, cy), false, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Draws legend entries left to right from <paramref name="origin"/> (swatch, 6 px, text in the entry colour,
|
||||
/// 16 px between entries) and stops before <paramref name="maxRight"/>. Returns the right edge reached.
|
||||
/// </summary>
|
||||
protected double DrawLegend(DrawingContext dc, IReadOnlyList<ChartLegendItem> items, Point origin, double maxRight, double emSize)
|
||||
{
|
||||
var x = origin.X;
|
||||
for (var i = 0; i < items.Count; i++)
|
||||
{
|
||||
var item = items[i];
|
||||
var brush = GetBrush(item.BrushKey);
|
||||
var text = CreateText(item.Text, emSize, brush);
|
||||
var width = 16 + 6 + text.Width;
|
||||
if (x + width > maxRight) break;
|
||||
var cy = origin.Y + text.Height / 2;
|
||||
DrawSwatch(dc, item.Swatch, item.BrushKey, new Rect(x, cy - 5, 16, 10));
|
||||
dc.DrawText(text, new Point(x + 22, origin.Y));
|
||||
x += width + 16;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
/// <summary>Draws a legend swatch centred in <paramref name="box"/>.</summary>
|
||||
protected void DrawSwatch(DrawingContext dc, LegendSwatch swatch, string brushKey, Rect box)
|
||||
{
|
||||
var cy = box.Top + box.Height / 2;
|
||||
var cx = box.Left + box.Width / 2;
|
||||
switch (swatch)
|
||||
{
|
||||
case LegendSwatch.Line:
|
||||
case LegendSwatch.DashedLine:
|
||||
case LegendSwatch.DottedLine:
|
||||
var dash = swatch == LegendSwatch.Line ? LineDash.Solid : swatch == LegendSwatch.DashedLine ? LineDash.Dashed : LineDash.Dotted;
|
||||
dc.DrawLine(GetPen(brushKey, 2, dash), new Point(box.Left + 1, cy), new Point(box.Right - 1, cy));
|
||||
break;
|
||||
case LegendSwatch.Square:
|
||||
dc.DrawRoundedRectangle(GetBrush(brushKey), null, new Rect(cx - 4, cy - 4, 8, 8), 2, 2);
|
||||
break;
|
||||
default:
|
||||
var geometry = new StreamGeometry();
|
||||
using (var ctx = geometry.Open())
|
||||
{
|
||||
if (swatch == LegendSwatch.Triangle) AddTriangleDown(ctx, cx, cy - 3.5, 9);
|
||||
else AddDiamond(ctx, cx, cy, 9);
|
||||
}
|
||||
geometry.Freeze();
|
||||
dc.DrawGeometry(GetBrush(brushKey), null, geometry);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static DashStyle DashFor(LineDash dash, double thickness)
|
||||
{
|
||||
if (dash == LineDash.Solid || !(thickness > 0)) return DashStyles.Solid;
|
||||
// DashStyle lengths are multiples of the pen thickness; the patterns are specified in DIPs.
|
||||
var style = dash == LineDash.Dashed
|
||||
? new DashStyle([5 / thickness, 4 / thickness], 0)
|
||||
: new DashStyle([2 / thickness, 3 / thickness], 0);
|
||||
style.Freeze();
|
||||
return style;
|
||||
}
|
||||
|
||||
private static void OnThemeProbeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
var element = (DrawingElement)d;
|
||||
element._brushes.Clear();
|
||||
element._pens.Clear();
|
||||
element._regular = element._semiBold = null;
|
||||
element.OnThemeChanged();
|
||||
}
|
||||
|
||||
private Typeface CreateTypeface(FontWeight weight) =>
|
||||
new(TryFindResource("Font.Ui") as FontFamily ?? SystemFonts.MessageFontFamily, FontStyles.Normal, weight, FontStretches.Normal);
|
||||
|
||||
private void OnWatchedCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) => OnDataChanged();
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// A tooltip (same style as every other) that opens at once and follows the mouse to read out the value under
|
||||
/// the cursor. While it shows, the owner's own tooltip (which describes the action) is suppressed.
|
||||
/// </summary>
|
||||
public sealed class HoverReadout(FrameworkElement owner)
|
||||
{
|
||||
private ToolTip? _tip;
|
||||
private object? _savedEnabled;
|
||||
|
||||
public bool IsOpen => _tip?.IsOpen == true;
|
||||
|
||||
/// <summary>Shows <paramref name="text"/> next to <paramref name="position"/> (owner coordinates); empty text hides the readout.</summary>
|
||||
public void Show(string? text, Point position)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
Hide();
|
||||
return;
|
||||
}
|
||||
_tip ??= new ToolTip
|
||||
{
|
||||
Placement = PlacementMode.Relative,
|
||||
PlacementTarget = owner,
|
||||
IsHitTestVisible = false,
|
||||
Focusable = false,
|
||||
};
|
||||
if (!Equals(_tip.Content, text)) _tip.Content = text;
|
||||
// Below-right of the cursor so the popup never sits under the mouse (which would end the hover).
|
||||
_tip.HorizontalOffset = position.X + 12;
|
||||
_tip.VerticalOffset = position.Y + 18;
|
||||
if (_tip.IsOpen) return;
|
||||
_savedEnabled = owner.ReadLocalValue(ToolTipService.IsEnabledProperty);
|
||||
ToolTipService.SetIsEnabled(owner, false);
|
||||
_tip.IsOpen = true;
|
||||
}
|
||||
|
||||
public void Hide()
|
||||
{
|
||||
if (_tip is not { IsOpen: true }) return;
|
||||
_tip.IsOpen = false;
|
||||
if (_savedEnabled is null || _savedEnabled == DependencyProperty.UnsetValue) owner.ClearValue(ToolTipService.IsEnabledProperty);
|
||||
else owner.SetValue(ToolTipService.IsEnabledProperty, _savedEnabled);
|
||||
_savedEnabled = null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user