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
243 lines
11 KiB
C#
243 lines
11 KiB
C#
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();
|
|
}
|