NumberSubstitution refuses the invariant culture as an override, so DrawingElement's type initializer threw and no chart could be created: the screen tests and the capture failed at the first chart. The substitution now keeps the default culture source and only sets the European method, which ignores the culture anyway. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
440 lines
20 KiB
C#
440 lines
20 KiB
C#
using System.Collections.Specialized;
|
||
using System.Windows;
|
||
using System.Windows.Automation;
|
||
using System.Windows.Automation.Peers;
|
||
using System.Windows.Controls;
|
||
using System.Windows.Input;
|
||
using System.Windows.Media;
|
||
using Titano.Core.Localization;
|
||
using Titano.Ui.Controls;
|
||
|
||
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"/>. The element itself is always left-to-right, so time axes and images never
|
||
/// mirror; words (categories, legends, summaries) still read in the UI language's direction
|
||
/// (<see cref="CreateLabel"/>), legends start on its side, and a category chart places its bars from that side
|
||
/// (<see cref="FromStart"/>). Screen readers see a named image (<see cref="DrawingElementAutomationPeer"/>).
|
||
/// <para>
|
||
/// A chart of discrete items (bars, segments, cells) describes them through <see cref="ItemCount"/>,
|
||
/// <see cref="ItemAt"/>, <see cref="ItemBounds"/> and <see cref="ItemText"/>: hovering one reads it out and clicking
|
||
/// it calls <see cref="Activate"/>. Only while a handler of its activation event is attached to the chart
|
||
/// (<see cref="TrackActivation"/>) does an item show the hand cursor and the chart take the keyboard: the arrows
|
||
/// choose an item (<see cref="Navigate"/>), Enter or Space activates it.
|
||
/// </para>
|
||
/// </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;
|
||
private Delegate? _activationHandlers;
|
||
private int _keyboardItem = -1;
|
||
|
||
/// <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>
|
||
/// Text a screen reader hears for the visual when no AutomationProperties.Name is set (its summary, its values);
|
||
/// null leaves the image unnamed.
|
||
/// </summary>
|
||
protected internal virtual string? AutomationDescription => null;
|
||
|
||
/// <summary>The item the keyboard is on, read to screen readers as the image's status; null when none.</summary>
|
||
internal string? KeyboardItemText => IsActivatable && _keyboardItem >= 0 && _keyboardItem < ItemCount ? ItemText(_keyboardItem) : null;
|
||
|
||
/// <summary>Whether a handler of the visual's activation event is attached to the visual itself (not to an ancestor).</summary>
|
||
protected bool IsActivatable => _activationHandlers is not null;
|
||
|
||
/// <summary>Number of discrete items (bars, segments, cells); 0 for visuals without items.</summary>
|
||
protected virtual int ItemCount => 0;
|
||
|
||
/// <summary>Item under <paramref name="point"/>, or −1.</summary>
|
||
protected virtual int ItemAt(Point point) => -1;
|
||
|
||
/// <summary>Where <paramref name="item"/> was last drawn: the keyboard outline follows this rectangle.</summary>
|
||
protected virtual Rect ItemBounds(int item) => Rect.Empty;
|
||
|
||
/// <summary>What the readout says for <paramref name="item"/>.</summary>
|
||
protected virtual string? ItemText(int item) => null;
|
||
|
||
/// <summary>The item an arrow key moves to from <paramref name="item"/>; −1 when the key does not move.</summary>
|
||
protected virtual int Navigate(int item, Key key) => -1;
|
||
|
||
/// <summary>Raises the visual's activation event for <paramref name="item"/>.</summary>
|
||
protected virtual void Activate(int item)
|
||
{
|
||
}
|
||
|
||
/// <summary>Records a handler added to or removed from the activation event; call from the event's accessors.</summary>
|
||
protected void TrackActivation(Delegate handler, bool added)
|
||
{
|
||
_activationHandlers = added ? Delegate.Combine(_activationHandlers, handler) : Delegate.Remove(_activationHandlers, handler);
|
||
SetCurrentValue(FocusableProperty, IsActivatable);
|
||
InvalidateVisual();
|
||
}
|
||
|
||
/// <summary>The cursor the visual shows at <paramref name="point"/>: the hand over an item something activates, otherwise none of its own.</summary>
|
||
internal Cursor? CursorAt(Point point) => IsActivatable && ItemAt(point) >= 0 ? Cursors.Hand : null;
|
||
|
||
/// <summary>Outlines the keyboard's item while the visual has keyboard focus (DESIGN §4: 2 px Accent); call last in OnRender.</summary>
|
||
protected void DrawKeyboardItem(DrawingContext dc)
|
||
{
|
||
if (!IsKeyboardFocused || !IsActivatable || _keyboardItem < 0 || _keyboardItem >= ItemCount) return;
|
||
var bounds = ItemBounds(_keyboardItem);
|
||
if (!bounds.IsEmpty) dc.DrawRoundedRectangle(null, GetPen("Brush.Accent", 2), bounds, 4, 4);
|
||
}
|
||
|
||
/// <summary>Single-line left-to-right text in the UI font (numbers, ticks, times), laid out for this element's DPI and text formatting mode.</summary>
|
||
protected FormattedText CreateText(string text, double emSize, Brush brush, bool semiBold = false) =>
|
||
Format(text, emSize, brush, semiBold, FlowDirection.LeftToRight);
|
||
|
||
/// <summary>
|
||
/// Single-line words (category, legend, summary) in the reading order of the UI language, so right-to-left text
|
||
/// mixed with numbers or Latin units keeps its order. Place it with <see cref="DrawTextAt"/>.
|
||
/// </summary>
|
||
protected FormattedText CreateLabel(string text, double emSize, Brush brush, bool semiBold = false) =>
|
||
Format(text, emSize, brush, semiBold, Bidi.UiDirection);
|
||
|
||
/// <summary>Draws <paramref name="text"/> with its top-left corner at <paramref name="topLeft"/>; right-to-left text is laid out leftwards from its origin.</summary>
|
||
protected static void DrawTextAt(DrawingContext dc, FormattedText text, Point topLeft) =>
|
||
dc.DrawText(text, text.FlowDirection == FlowDirection.RightToLeft ? new Point(topLeft.X + text.Width, topLeft.Y) : topLeft);
|
||
|
||
/// <summary>Position of a <paramref name="width"/>-wide box laid out from the left within [0, <paramref name="extent"/>], mirrored in a right-to-left UI.</summary>
|
||
protected static double FromStart(double x, double width, double extent) => Loc.IsRightToLeft ? extent - x - width : x;
|
||
|
||
/// <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()
|
||
{
|
||
_keyboardItem = Math.Min(_keyboardItem, ItemCount - 1);
|
||
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();
|
||
}
|
||
|
||
protected override void OnMouseMove(MouseEventArgs e)
|
||
{
|
||
base.OnMouseMove(e);
|
||
if (ItemCount == 0) return;
|
||
var p = e.GetPosition(this);
|
||
var item = ItemAt(p);
|
||
Readout.Show(item >= 0 ? ItemText(item) : null, p);
|
||
}
|
||
|
||
protected override void OnMouseLeave(MouseEventArgs e)
|
||
{
|
||
base.OnMouseLeave(e);
|
||
if (ItemCount > 0) Readout.Hide();
|
||
}
|
||
|
||
protected override void OnQueryCursor(QueryCursorEventArgs e)
|
||
{
|
||
base.OnQueryCursor(e);
|
||
if (e.Handled || CursorAt(e.GetPosition(this)) is not { } cursor) return;
|
||
e.Cursor = cursor;
|
||
e.Handled = true;
|
||
}
|
||
|
||
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
|
||
{
|
||
base.OnMouseLeftButtonUp(e);
|
||
if (e.Handled || ItemCount == 0) return;
|
||
var item = ItemAt(e.GetPosition(this));
|
||
if (item < 0) return;
|
||
_keyboardItem = item;
|
||
Activate(item);
|
||
e.Handled = true;
|
||
}
|
||
|
||
protected override void OnKeyDown(KeyEventArgs e)
|
||
{
|
||
base.OnKeyDown(e);
|
||
var count = ItemCount;
|
||
if (e.Handled || !IsActivatable || count == 0) return;
|
||
var current = Math.Clamp(_keyboardItem, 0, count - 1);
|
||
if (e.Key is Key.Enter or Key.Space)
|
||
{
|
||
MoveKeyboardTo(current);
|
||
Activate(current);
|
||
e.Handled = true;
|
||
return;
|
||
}
|
||
var next = e.Key switch
|
||
{
|
||
Key.Home => 0,
|
||
Key.End => count - 1,
|
||
_ => Navigate(current, e.Key),
|
||
};
|
||
if (next < 0) return;
|
||
MoveKeyboardTo(Math.Min(next, count - 1));
|
||
e.Handled = true;
|
||
}
|
||
|
||
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
|
||
{
|
||
base.OnGotKeyboardFocus(e);
|
||
if (IsActivatable && ItemCount > 0 && ReferenceEquals(e.NewFocus, this)) MoveKeyboardTo(Math.Clamp(_keyboardItem, 0, ItemCount - 1));
|
||
}
|
||
|
||
protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
|
||
{
|
||
base.OnLostKeyboardFocus(e);
|
||
if (!IsActivatable) return;
|
||
Readout.Hide();
|
||
InvalidateVisual();
|
||
}
|
||
|
||
/// <summary>Puts the keyboard on <paramref name="item"/>: outlined, read out next to it and announced as the image's status.</summary>
|
||
private void MoveKeyboardTo(int item)
|
||
{
|
||
var before = KeyboardItemText;
|
||
_keyboardItem = item;
|
||
InvalidateVisual();
|
||
var bounds = ItemBounds(item);
|
||
if (!bounds.IsEmpty) Readout.Show(ItemText(item), bounds.BottomLeft);
|
||
UIElementAutomationPeer.FromElement(this)?.RaisePropertyChangedEvent(AutomationElementIdentifiers.ItemStatusProperty, before ?? string.Empty,
|
||
KeyboardItemText ?? string.Empty);
|
||
}
|
||
|
||
/// <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 in reading order from the start side of [<paramref name="left"/>, <paramref name="right"/>]
|
||
/// (swatch, 6 px, text in the entry colour, 16 px between entries); entries that do not fit are left out.
|
||
/// </summary>
|
||
protected void DrawLegend(DrawingContext dc, IReadOnlyList<ChartLegendItem> items, double left, double right, double top, double emSize)
|
||
{
|
||
var offset = 0.0;
|
||
for (var i = 0; i < items.Count; i++)
|
||
{
|
||
var item = items[i];
|
||
var text = CreateLabel(item.Text, emSize, GetBrush(item.BrushKey));
|
||
var width = 16 + 6 + text.Width;
|
||
if (left + offset + width > right) break;
|
||
var cy = top + text.Height / 2;
|
||
var extent = right - left;
|
||
DrawSwatch(dc, item.Swatch, item.BrushKey, new Rect(left + FromStart(offset, 16, extent), cy - 5, 16, 10));
|
||
DrawTextAt(dc, text, new Point(left + FromStart(offset + 22, text.Width, extent), top));
|
||
offset += width + 16;
|
||
}
|
||
}
|
||
|
||
/// <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();
|
||
}
|
||
|
||
protected override AutomationPeer OnCreateAutomationPeer() => new DrawingElementAutomationPeer(this);
|
||
|
||
/// <summary>
|
||
/// Digits as the rest of the UI shows them: with the UI culture alone, Arabic text before a number would turn its
|
||
/// digits into Arabic-Indic ones in charts only.
|
||
/// </summary>
|
||
private static readonly NumberSubstitution EuropeanDigits = new() { Substitution = NumberSubstitutionMethod.European };
|
||
|
||
private FormattedText Format(string text, double emSize, Brush brush, bool semiBold, FlowDirection direction)
|
||
{
|
||
var typeface = semiBold ? _semiBold ??= CreateTypeface(FontWeights.SemiBold) : _regular ??= CreateTypeface(FontWeights.Normal);
|
||
return new FormattedText(text, Loc.Culture, direction, typeface, emSize, brush, EuropeanDigits,
|
||
TextOptions.GetTextFormattingMode(this), VisualTreeHelper.GetDpi(this).PixelsPerDip);
|
||
}
|
||
|
||
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();
|
||
}
|
||
|
||
/// <summary>A chart seen by UI Automation: an image named by AutomationProperties.Name or, failing that, by its description.</summary>
|
||
public class DrawingElementAutomationPeer(DrawingElement owner) : FrameworkElementAutomationPeer(owner)
|
||
{
|
||
protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.Image;
|
||
|
||
protected override string GetClassNameCore() => Owner.GetType().Name;
|
||
|
||
protected override string GetNameCore()
|
||
{
|
||
var name = base.GetNameCore();
|
||
return string.IsNullOrEmpty(name) ? ((DrawingElement)Owner).AutomationDescription ?? string.Empty : name;
|
||
}
|
||
|
||
/// <summary>The item the keyboard is on, unless AutomationProperties.ItemStatus says otherwise.</summary>
|
||
protected override string GetItemStatusCore()
|
||
{
|
||
var status = base.GetItemStatusCore();
|
||
return string.IsNullOrEmpty(status) ? ((DrawingElement)Owner).KeyboardItemText ?? string.Empty : status;
|
||
}
|
||
}
|