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;
///
/// 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
/// . 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
/// (), legends start on its side, and a category chart places its bars from that side
/// (). Screen readers see a named image ().
///
/// A chart of discrete items (bars, segments, cells) describes them through ,
/// , and : hovering one reads it out and clicking
/// it calls . Only while a handler of its activation event is attached to the chart
/// () does an item show the hand cursor and the chart take the keyboard: the arrows
/// choose an item (), Enter or Space activates it.
///
///
public abstract class DrawingElement : FrameworkElement
{
/// Follows a token brush; its change signals a theme switch.
private static readonly DependencyProperty ThemeProbeProperty = DependencyProperty.Register(
"ThemeProbe", typeof(object), typeof(DrawingElement), new PropertyMetadata(null, OnThemeProbeChanged));
private readonly Dictionary _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;
/// Creates the overlay layer drawn by .
protected DrawingElement(bool hasOverlay = false)
{
if (hasOverlay)
{
_overlay = new DrawingVisual();
AddVisualChild(_overlay);
}
FlowDirection = FlowDirection.LeftToRight;
SetResourceReference(ThemeProbeProperty, "Brush.Text");
Unloaded += (_, _) => _readout?.Hide();
}
/// Device pixels per DIP on the monitor showing the element.
protected double PixelScale => VisualTreeHelper.GetDpi(this).DpiScaleX;
/// Tooltip-styled readout that follows the mouse.
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));
/// Frozen theme brush for (transparent when the key is unknown).
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;
}
/// Frozen pen in the theme brush , cached until the theme or DPI changes.
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;
}
/// Uncached frozen pen, for thicknesses that vary continuously (e.g. compensating a zoom).
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;
}
/// Pen covering whole device pixels, for gridlines and edges drawn at positions.
protected Pen GetHairline(string key, LineDash dash = LineDash.Solid) => GetPen(key, PixelGrid.SnapThickness(1, PixelScale), dash);
///
/// Text a screen reader hears for the visual when no AutomationProperties.Name is set (its summary, its values);
/// null leaves the image unnamed.
///
protected internal virtual string? AutomationDescription => null;
/// The item the keyboard is on, read to screen readers as the image's status; null when none.
internal string? KeyboardItemText => IsActivatable && _keyboardItem >= 0 && _keyboardItem < ItemCount ? ItemText(_keyboardItem) : null;
/// Whether a handler of the visual's activation event is attached to the visual itself (not to an ancestor).
protected bool IsActivatable => _activationHandlers is not null;
/// Number of discrete items (bars, segments, cells); 0 for visuals without items.
protected virtual int ItemCount => 0;
/// Item under , or −1.
protected virtual int ItemAt(Point point) => -1;
/// Where was last drawn: the keyboard outline follows this rectangle.
protected virtual Rect ItemBounds(int item) => Rect.Empty;
/// What the readout says for .
protected virtual string? ItemText(int item) => null;
/// The item an arrow key moves to from ; −1 when the key does not move.
protected virtual int Navigate(int item, Key key) => -1;
/// Raises the visual's activation event for .
protected virtual void Activate(int item)
{
}
/// Records a handler added to or removed from the activation event; call from the event's accessors.
protected void TrackActivation(Delegate handler, bool added)
{
_activationHandlers = added ? Delegate.Combine(_activationHandlers, handler) : Delegate.Remove(_activationHandlers, handler);
SetCurrentValue(FocusableProperty, IsActivatable);
InvalidateVisual();
}
/// The cursor the visual shows at : the hand over an item something activates, otherwise none of its own.
internal Cursor? CursorAt(Point point) => IsActivatable && ItemAt(point) >= 0 ? Cursors.Hand : null;
/// Outlines the keyboard's item while the visual has keyboard focus (DESIGN §4: 2 px Accent); call last in OnRender.
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);
}
/// Single-line left-to-right text in the UI font (numbers, ticks, times), laid out for this element's DPI and text formatting mode.
protected FormattedText CreateText(string text, double emSize, Brush brush, bool semiBold = false) =>
Format(text, emSize, brush, semiBold, FlowDirection.LeftToRight);
///
/// 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 .
///
protected FormattedText CreateLabel(string text, double emSize, Brush brush, bool semiBold = false) =>
Format(text, emSize, brush, semiBold, Bidi.UiDirection);
/// Draws with its top-left corner at ; right-to-left text is laid out leftwards from its origin.
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);
/// Position of a -wide box laid out from the left within [0, ], mirrored in a right-to-left UI.
protected static double FromStart(double x, double width, double extent) => Loc.IsRightToLeft ? extent - x - width : x;
/// Redraws the overlay layer; call after any change that only affects playhead or hover state.
protected void RenderOverlay()
{
if (_overlay is null) return;
using var dc = _overlay.RenderOpen();
if (ActualWidth > 0 && ActualHeight > 0) OnRenderOverlay(dc);
}
/// Draws the overlay layer (above the static content).
protected virtual void OnRenderOverlay(DrawingContext dc)
{
}
/// Called after the theme brushes changed; the default redraws everything.
protected virtual void OnThemeChanged()
{
InvalidateVisual();
if (_overlay is not null) RenderOverlay();
}
/// Called when a data property or a watched collection changed; the default re-measures and redraws.
protected virtual void OnDataChanged()
{
_keyboardItem = Math.Min(_keyboardItem, ItemCount - 1);
InvalidateMeasure();
InvalidateVisual();
}
/// Property-changed callback for data properties: watches observable collections weakly and calls .
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();
}
/// Puts the keyboard on : outlined, read out next to it and announced as the image's status.
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);
}
/// Fills the whole element with a transparent brush so empty areas still receive the mouse.
protected void DrawHitArea(DrawingContext dc) => dc.DrawRectangle(Brushes.Transparent, null, new Rect(RenderSize));
/// Adds a ▼ of width whose top edge is centred at (, ).
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);
}
/// Adds a ◆ of width centred at (, ).
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);
}
///
/// Draws legend entries in reading order from the start side of [, ]
/// (swatch, 6 px, text in the entry colour, 16 px between entries); entries that do not fit are left out.
///
protected void DrawLegend(DrawingContext dc, IReadOnlyList 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;
}
}
/// Draws a legend swatch centred in .
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);
///
/// 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.
///
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();
}
/// A chart seen by UI Automation: an image named by AutomationProperties.Name or, failing that, by its description.
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;
}
/// The item the keyboard is on, unless AutomationProperties.ItemStatus says otherwise.
protected override string GetItemStatusCore()
{
var status = base.GetItemStatusCore();
return string.IsNullOrEmpty(status) ? ((DrawingElement)Owner).KeyboardItemText ?? string.Empty : status;
}
}