using System.Collections.Specialized; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using Titano.Core.Localization; 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 /// . Time axes and images never mirror, so the element is always left-to-right. /// 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; /// 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); /// Single-line text in the UI font, laid out for this element's DPI and text formatting mode. 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); } /// 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() { 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(); } /// 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 left to right from (swatch, 6 px, text in the entry colour, /// 16 px between entries) and stops before . Returns the right edge reached. /// protected double DrawLegend(DrawingContext dc, IReadOnlyList 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; } /// 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(); } 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(); }