diff --git a/src/Titano.Ui/Visuals/ChartTypes.cs b/src/Titano.Ui/Visuals/ChartTypes.cs new file mode 100644 index 00000000..1e67e4b4 --- /dev/null +++ b/src/Titano.Ui/Visuals/ChartTypes.cs @@ -0,0 +1,116 @@ +using System.Windows; + +namespace Titano.Ui.Visuals; + +/// Stroke pattern of a series or legend swatch. +public enum LineDash +{ + Solid, + + /// 5–4 dashes (sky region curve). + Dashed, + + /// 2–3 dots. + Dotted, +} + +/// One per-frame line of a . Values are indexed by frame; NaN leaves a gap. +public sealed class ChartSeries +{ + public ChartSeries(string? title, ReadOnlyMemory values, string brushKey) + { + Title = title; + Values = values; + BrushKey = brushKey; + } + + /// Legend and readout text (localized by the caller). + public string? Title { get; init; } + + public ReadOnlyMemory Values { get; init; } + + /// Theme brush resource key, e.g. Brush.Sun; re-resolved when the theme changes. + public string BrushKey { get; init; } + + /// Stroke width in DIPs. + public double Thickness { get; init; } = 1.5; + + public LineDash Dash { get; init; } = LineDash.Solid; + + /// Whether the automatic legend lists this series. + public bool ShowInLegend { get; init; } = true; +} + +/// Shape drawn before a legend entry. +public enum LegendSwatch +{ + Line, + DashedLine, + DottedLine, + + /// ▼ (exposure steps). + Triangle, + + /// ◆ (keyframes). + Diamond, + + Square, +} + +/// A legend entry: swatch in a theme brush followed by text. +public sealed record ChartLegendItem(string Text, string BrushKey, LegendSwatch Swatch = LegendSwatch.Line); + +/// What a timeline marker stands for; the kind fixes its colour and glyph. +public enum MarkerKind +{ + /// ISO/shutter/aperture step as received: ▼ in Sun. + ExposureStep, + + /// ▼ in Warning. + Warning, + + /// ▼ in Error. + Error, + + /// Virtual-camera or remap keyframe: ◆ in Accent. + Keyframe, +} + +/// A frame-anchored marker shown above the filmstrip and as a dashed line in series charts. +public readonly record struct TimelineMarker(int Index, MarkerKind Kind, string? Label = null) +{ + /// Theme brush key of a marker kind. + public static string BrushKeyOf(MarkerKind kind) => kind switch + { + MarkerKind.ExposureStep => "Brush.Sun", + MarkerKind.Warning => "Brush.Warning", + MarkerKind.Error => "Brush.Error", + _ => "Brush.Accent", + }; +} + +/// A labelled value of a bar or proportion chart. +/// Category text (year, camera, format…). +/// Magnitude; negative values draw as zero. +/// Formatted value shown next to the bar; null uses the chart formatter. +/// Hover text; null shows label and value. +/// Theme brush key overriding the chart brush. +public sealed record ChartItem(string Label, double Value, string? ValueText = null, string? ToolTip = null, string? BrushKey = null); + +/// A labelled row of values (a heatmap year, a timeline band); NaN marks "no data". +/// Row text (e.g. the year). +/// One value per column (e.g. 12 months). +/// Optional hover text per column. +public sealed record ChartRow(string Label, IReadOnlyList Values, IReadOnlyList? ToolTips = null); + +/// Identifies the item a chart interaction refers to. +public sealed class ChartItemEventArgs(RoutedEvent routedEvent, int row, int column) : RoutedEventArgs(routedEvent) +{ + /// Item index (bars, segments) or row index (heatmap, bands). + public int Row { get; } = row; + + /// Column index for grids (heatmap month, band slot); −1 for single-index charts. + public int Column { get; } = column; +} + +public delegate void ChartItemEventHandler(object sender, ChartItemEventArgs e); diff --git a/src/Titano.Ui/Visuals/DrawingElement.cs b/src/Titano.Ui/Visuals/DrawingElement.cs new file mode 100644 index 00000000..9126bb54 --- /dev/null +++ b/src/Titano.Ui/Visuals/DrawingElement.cs @@ -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; + +/// +/// 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(); +} diff --git a/src/Titano.Ui/Visuals/HoverReadout.cs b/src/Titano.Ui/Visuals/HoverReadout.cs new file mode 100644 index 00000000..53d50b80 --- /dev/null +++ b/src/Titano.Ui/Visuals/HoverReadout.cs @@ -0,0 +1,51 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; + +namespace Titano.Ui.Visuals; + +/// +/// 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. +/// +public sealed class HoverReadout(FrameworkElement owner) +{ + private ToolTip? _tip; + private object? _savedEnabled; + + public bool IsOpen => _tip?.IsOpen == true; + + /// Shows next to (owner coordinates); empty text hides the readout. + 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; + } +}