diff --git a/src/Titano.Ui/Visuals/BarChart.cs b/src/Titano.Ui/Visuals/BarChart.cs new file mode 100644 index 00000000..2d075d32 --- /dev/null +++ b/src/Titano.Ui/Visuals/BarChart.cs @@ -0,0 +1,277 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; +using Titano.Core.Localization; + +namespace Titano.Ui.Visuals; + +/// +/// Bars for labelled values (Archive: storage by year, by camera, by format; uploads per day). Horizontal bars put +/// the category labels on the left and the value labels after each bar, as in the Archive mockup; vertical bars +/// put the categories underneath (skipping labels that would collide). Optional value gridlines use nice ticks. +/// A bar's opacity can follow its value (). Hovering reads out the bar; clicking raises +/// . +/// +public sealed class BarChart : DrawingElement +{ + public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register( + nameof(Items), typeof(IReadOnlyList), typeof(BarChart), new PropertyMetadata(null, OnDataPropertyChanged)); + + public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register( + nameof(Orientation), typeof(Orientation), typeof(BarChart), + new FrameworkPropertyMetadata(Orientation.Horizontal, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure)); + + public static readonly DependencyProperty BrushKeyProperty = DependencyProperty.Register( + nameof(BrushKey), typeof(string), typeof(BarChart), new FrameworkPropertyMetadata("Brush.Accent", FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty MinimumOpacityProperty = DependencyProperty.Register( + nameof(MinimumOpacity), typeof(double), typeof(BarChart), new FrameworkPropertyMetadata(1.0, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty ShowValuesProperty = DependencyProperty.Register( + nameof(ShowValues), typeof(bool), typeof(BarChart), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty ShowGridProperty = DependencyProperty.Register( + nameof(ShowGrid), typeof(bool), typeof(BarChart), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register( + nameof(Maximum), typeof(double), typeof(BarChart), new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty BarThicknessProperty = DependencyProperty.Register( + nameof(BarThickness), typeof(double), typeof(BarChart), + new FrameworkPropertyMetadata(14.0, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure)); + + public static readonly DependencyProperty ValueFormatterProperty = DependencyProperty.Register( + nameof(ValueFormatter), typeof(Func), typeof(BarChart), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly RoutedEvent ItemActivatedEvent = EventManager.RegisterRoutedEvent( + nameof(ItemActivated), RoutingStrategy.Bubble, typeof(ChartItemEventHandler), typeof(BarChart)); + + private const double LabelSize = 11; + private const double RowGap = 8; + + private Rect _area; + private double _pitch; + private int _hover = -1; + + /// Bars in display order. + public IReadOnlyList? Items { get => (IReadOnlyList?)GetValue(ItemsProperty); set => SetValue(ItemsProperty, value); } + + public Orientation Orientation { get => (Orientation)GetValue(OrientationProperty); set => SetValue(OrientationProperty, value); } + + /// Theme brush key of the bars (items may override). + public string BrushKey { get => (string)GetValue(BrushKeyProperty); set => SetValue(BrushKeyProperty, value); } + + /// Opacity of a zero bar; bars ramp linearly to 1 at the maximum (1 = flat colour). + public double MinimumOpacity { get => (double)GetValue(MinimumOpacityProperty); set => SetValue(MinimumOpacityProperty, value); } + + public bool ShowValues { get => (bool)GetValue(ShowValuesProperty); set => SetValue(ShowValuesProperty, value); } + + /// Value-axis gridlines and tick labels. + public bool ShowGrid { get => (bool)GetValue(ShowGridProperty); set => SetValue(ShowGridProperty, value); } + + /// Value at full length; NaN = the largest value (or the nice tick above it with the grid on). + public double Maximum { get => (double)GetValue(MaximumProperty); set => SetValue(MaximumProperty, value); } + + /// Maximum bar thickness in DIPs. + public double BarThickness { get => (double)GetValue(BarThicknessProperty); set => SetValue(BarThicknessProperty, value); } + + /// Culture-aware value formatting for value labels, ticks and readouts. + public Func? ValueFormatter { get => (Func?)GetValue(ValueFormatterProperty); set => SetValue(ValueFormatterProperty, value); } + + public event ChartItemEventHandler ItemActivated + { + add => AddHandler(ItemActivatedEvent, value); + remove => RemoveHandler(ItemActivatedEvent, value); + } + + protected override Size MeasureOverride(Size availableSize) + { + var count = Items?.Count ?? 0; + return Orientation == Orientation.Horizontal ? new Size(0, count * (BarThickness + RowGap)) : new Size(0, 120); + } + + protected override void OnDataChanged() + { + _hover = -1; + base.OnDataChanged(); + } + + protected override void OnRender(DrawingContext dc) + { + DrawHitArea(dc); + _area = Rect.Empty; + if (Items is not { Count: > 0 } items) return; + var max = ScaleMaximum(items); + if (Orientation == Orientation.Horizontal) RenderHorizontal(dc, items, max); + else RenderVertical(dc, items, max); + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + var p = e.GetPosition(this); + _hover = HitTest(p); + Readout.Show(_hover >= 0 && Items is { } items ? ReadoutText(items[_hover]) : null, p); + } + + protected override void OnQueryCursor(QueryCursorEventArgs e) + { + base.OnQueryCursor(e); + if (e.Handled || _hover < 0) return; + e.Cursor = Cursors.Hand; + e.Handled = true; + } + + protected override void OnMouseLeave(MouseEventArgs e) + { + base.OnMouseLeave(e); + _hover = -1; + Readout.Hide(); + } + + protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonUp(e); + var index = HitTest(e.GetPosition(this)); + if (index < 0) return; + RaiseEvent(new ChartItemEventArgs(ItemActivatedEvent, index, -1)); + e.Handled = true; + } + + private string Format(double value) => (ValueFormatter ?? DefaultFormat)(value); + + private static string DefaultFormat(double value) => value.ToString("N0", Loc.Culture); + + private string ReadoutText(ChartItem item) => item.ToolTip ?? item.Label + " · " + (item.ValueText ?? Format(item.Value)); + + private double ScaleMaximum(IReadOnlyList items) + { + if (double.IsFinite(Maximum) && Maximum > 0) return Maximum; + var max = 0.0; + for (var i = 0; i < items.Count; i++) max = Math.Max(max, items[i].Value); + if (max <= 0) return 1; + return ShowGrid ? NiceScale.Outer(0, max, 5).Last : max; + } + + private double OpacityOf(double value, double max) => + MinimumOpacity >= 1 ? 1 : MinimumOpacity + (1 - MinimumOpacity) * Math.Clamp(value / max, 0, 1); + + private void RenderHorizontal(DrawingContext dc, IReadOnlyList items, double max) + { + var faint = GetBrush("Brush.TextFaint"); + var text = GetBrush("Brush.Text"); + var labels = new FormattedText[items.Count]; + var values = new FormattedText?[items.Count]; + double labelWidth = 0, valueWidth = 0; + for (var i = 0; i < items.Count; i++) + { + labels[i] = CreateText(items[i].Label, LabelSize, faint); + labelWidth = Math.Max(labelWidth, labels[i].Width); + if (!ShowValues) continue; + values[i] = CreateText(items[i].ValueText ?? Format(items[i].Value), LabelSize, text); + valueWidth = Math.Max(valueWidth, values[i]!.Width); + } + var gridHeight = ShowGrid ? 16 : 0; + var left = Math.Ceiling(labelWidth) + 8; + var right = ActualWidth - (ShowValues ? valueWidth + 6 : 0); + _area = new Rect(left, 0, Math.Max(0, right - left), Math.Max(0, ActualHeight - gridHeight)); + _pitch = Math.Min(_area.Height / items.Count, BarThickness + RowGap); + var thickness = Math.Max(1, Math.Min(BarThickness, _pitch - 2)); + if (ShowGrid) DrawValueGrid(dc, max, horizontal: true); + + for (var i = 0; i < items.Count; i++) + { + var item = items[i]; + var cy = _area.Top + _pitch * (i + 0.5); + dc.DrawText(labels[i], new Point(left - 8 - labels[i].Width, cy - labels[i].Height / 2)); + var length = _area.Width * Math.Clamp(item.Value / max, 0, 1); + if (length > 0) + { + dc.PushOpacity(OpacityOf(item.Value, max)); + dc.DrawRoundedRectangle(GetBrush(item.BrushKey ?? BrushKey), null, new Rect(left, cy - thickness / 2, length, thickness), 2, 2); + dc.Pop(); + } + if (values[i] is { } value) dc.DrawText(value, new Point(left + length + 6, cy - value.Height / 2)); + } + } + + private void RenderVertical(DrawingContext dc, IReadOnlyList items, double max) + { + var faint = GetBrush("Brush.TextFaint"); + var sample = CreateText("0", LabelSize, faint); + var labelHeight = Math.Ceiling(sample.Height) + 4; + var valueHeight = ShowValues ? labelHeight : 0; + var axisWidth = 0.0; + if (ShowGrid) + { + var top = CreateText(Format(max), LabelSize, faint); + axisWidth = Math.Ceiling(top.Width) + 8; + } + _area = new Rect(axisWidth, valueHeight, Math.Max(0, ActualWidth - axisWidth), Math.Max(0, ActualHeight - labelHeight - valueHeight)); + _pitch = _area.Width / items.Count; + var width = Math.Max(1, Math.Min(BarThickness * 2, _pitch * 0.7)); + if (ShowGrid) DrawValueGrid(dc, max, horizontal: false); + + var text = GetBrush("Brush.Text"); + var lastLabelRight = double.NegativeInfinity; + for (var i = 0; i < items.Count; i++) + { + var item = items[i]; + var cx = _area.Left + _pitch * (i + 0.5); + var height = _area.Height * Math.Clamp(item.Value / max, 0, 1); + if (height > 0) + { + dc.PushOpacity(OpacityOf(item.Value, max)); + dc.DrawRoundedRectangle(GetBrush(item.BrushKey ?? BrushKey), null, new Rect(cx - width / 2, _area.Bottom - height, width, height), 2, 2); + dc.Pop(); + } + if (ShowValues && _pitch >= 24) + { + var value = CreateText(item.ValueText ?? Format(item.Value), LabelSize, text); + if (value.Width <= _pitch) dc.DrawText(value, new Point(cx - value.Width / 2, _area.Bottom - height - value.Height - 2)); + } + var label = CreateText(item.Label, LabelSize, faint); + var x = cx - label.Width / 2; + if (x < lastLabelRight + 6) continue; + dc.DrawText(label, new Point(x, _area.Bottom + 4)); + lastLabelRight = x + label.Width; + } + } + + /// Gridlines at nice ticks along the value axis, with labels below (horizontal bars) or left (vertical bars). + private void DrawValueGrid(DrawingContext dc, double max, bool horizontal) + { + var ticks = NiceScale.Inner(0, max, horizontal ? Math.Max(2, (int)(_area.Width / 80)) : Math.Max(2, (int)(_area.Height / 36))); + var pen = GetHairline("Brush.Stroke"); + var faint = GetBrush("Brush.TextFaint"); + var scale = PixelScale; + for (var i = 0; i < ticks.Count; i++) + { + var label = CreateText(Format(ticks[i]), LabelSize, faint); + if (horizontal) + { + var x = PixelGrid.SnapLine(_area.Left + _area.Width * ticks[i] / max, pen.Thickness, scale); + dc.DrawLine(pen, new Point(x, _area.Top), new Point(x, _area.Bottom)); + dc.DrawText(label, new Point(Math.Min(x - label.Width / 2, ActualWidth - label.Width), _area.Bottom + 2)); + } + else + { + var y = PixelGrid.SnapLine(_area.Bottom - _area.Height * ticks[i] / max, pen.Thickness, scale); + dc.DrawLine(pen, new Point(_area.Left, y), new Point(_area.Right, y)); + dc.DrawText(label, new Point(_area.Left - 8 - label.Width, y - label.Height / 2)); + } + } + } + + private int HitTest(Point p) + { + var count = Items?.Count ?? 0; + if (count == 0 || _area.IsEmpty || !(_pitch > 0)) return -1; + var index = Orientation == Orientation.Horizontal + ? (int)Math.Floor((p.Y - _area.Top) / _pitch) + : (int)Math.Floor((p.X - _area.Left) / _pitch); + var inside = Orientation == Orientation.Horizontal ? p.X >= 0 && p.X <= ActualWidth : p.Y >= 0 && p.Y <= ActualHeight; + return inside && index >= 0 && index < count ? index : -1; + } +} diff --git a/src/Titano.Ui/Visuals/HeatmapStrip.cs b/src/Titano.Ui/Visuals/HeatmapStrip.cs new file mode 100644 index 00000000..35fe46dc --- /dev/null +++ b/src/Titano.Ui/Visuals/HeatmapStrip.cs @@ -0,0 +1,241 @@ +using System.Windows; +using System.Windows.Input; +using System.Windows.Media; +using Titano.Core.Localization; + +namespace Titano.Ui.Visuals; + +/// +/// Density grid (Archive: photos per month, one row per year × 12 months). Each value is a square cell in the +/// brush colour whose opacity grows with the value; NaN cells ("no data", e.g. future months) use the card fill. +/// Column labels sit above, row labels on the left, an optional min–max scale below. Hovering reads out the cell +/// (its tooltip or "row column · value"); clicking raises . +/// +public sealed class HeatmapStrip : DrawingElement +{ + public static readonly DependencyProperty RowsProperty = DependencyProperty.Register( + nameof(Rows), typeof(IReadOnlyList), typeof(HeatmapStrip), new PropertyMetadata(null, OnDataPropertyChanged)); + + public static readonly DependencyProperty ColumnLabelsProperty = DependencyProperty.Register( + nameof(ColumnLabels), typeof(IReadOnlyList), typeof(HeatmapStrip), new PropertyMetadata(null, OnDataPropertyChanged)); + + public static readonly DependencyProperty BrushKeyProperty = DependencyProperty.Register( + nameof(BrushKey), typeof(string), typeof(HeatmapStrip), new FrameworkPropertyMetadata("Brush.Accent", FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register( + nameof(Maximum), typeof(double), typeof(HeatmapStrip), new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty MinimumOpacityProperty = DependencyProperty.Register( + nameof(MinimumOpacity), typeof(double), typeof(HeatmapStrip), new FrameworkPropertyMetadata(0.08, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty MaxCellSizeProperty = DependencyProperty.Register( + nameof(MaxCellSize), typeof(double), typeof(HeatmapStrip), + new FrameworkPropertyMetadata(24.0, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure)); + + public static readonly DependencyProperty CellGapProperty = DependencyProperty.Register( + nameof(CellGap), typeof(double), typeof(HeatmapStrip), + new FrameworkPropertyMetadata(3.0, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure)); + + public static readonly DependencyProperty ShowScaleProperty = DependencyProperty.Register( + nameof(ShowScale), typeof(bool), typeof(HeatmapStrip), + new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure)); + + public static readonly DependencyProperty ValueFormatterProperty = DependencyProperty.Register( + nameof(ValueFormatter), typeof(Func), typeof(HeatmapStrip), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly RoutedEvent CellActivatedEvent = EventManager.RegisterRoutedEvent( + nameof(CellActivated), RoutingStrategy.Bubble, typeof(ChartItemEventHandler), typeof(HeatmapStrip)); + + private const double LabelSize = 11; + + private CellGridLayout _grid; + private bool _hovering; + + /// One row per year (label + 12 monthly values). + public IReadOnlyList? Rows { get => (IReadOnlyList?)GetValue(RowsProperty); set => SetValue(RowsProperty, value); } + + /// Column headers (culture-aware month initials); also fixes the column count. + public IReadOnlyList? ColumnLabels { get => (IReadOnlyList?)GetValue(ColumnLabelsProperty); set => SetValue(ColumnLabelsProperty, value); } + + public string BrushKey { get => (string)GetValue(BrushKeyProperty); set => SetValue(BrushKeyProperty, value); } + + /// Value drawn at full opacity; NaN = the largest value. + public double Maximum { get => (double)GetValue(MaximumProperty); set => SetValue(MaximumProperty, value); } + + /// Opacity of a zero cell. + public double MinimumOpacity { get => (double)GetValue(MinimumOpacityProperty); set => SetValue(MinimumOpacityProperty, value); } + + public double MaxCellSize { get => (double)GetValue(MaxCellSizeProperty); set => SetValue(MaxCellSizeProperty, value); } + + public double CellGap { get => (double)GetValue(CellGapProperty); set => SetValue(CellGapProperty, value); } + + /// Min–max colour scale under the grid. + public bool ShowScale { get => (bool)GetValue(ShowScaleProperty); set => SetValue(ShowScaleProperty, value); } + + /// Culture-aware value formatting (scale ends and readouts). + public Func? ValueFormatter { get => (Func?)GetValue(ValueFormatterProperty); set => SetValue(ValueFormatterProperty, value); } + + public event ChartItemEventHandler CellActivated + { + add => AddHandler(CellActivatedEvent, value); + remove => RemoveHandler(CellActivatedEvent, value); + } + + private int RowCount => Rows?.Count ?? 0; + + private int ColumnCount + { + get + { + if (ColumnLabels is { Count: > 0 } labels) return labels.Count; + var max = 0; + if (Rows is { } rows) + for (var r = 0; r < rows.Count; r++) max = Math.Max(max, rows[r].Values.Count); + return max; + } + } + + protected override Size MeasureOverride(Size availableSize) + { + if (RowCount == 0 || ColumnCount == 0) return new Size(0, 0); + var layout = Layout(availableSize.Width, double.PositiveInfinity); + return new Size(0, layout.Top + layout.Height + ScaleHeight()); + } + + protected override void OnRender(DrawingContext dc) + { + DrawHitArea(dc); + if (Rows is not { Count: > 0 } rows || ColumnCount == 0) return; + _grid = Layout(ActualWidth, ActualHeight - ScaleHeight()); + var faint = GetBrush("Brush.TextFaint"); + var max = ScaleMaximum(rows); + + if (ColumnLabels is { } columns) + { + for (var c = 0; c < columns.Count; c++) + { + var label = CreateText(columns[c], LabelSize, faint); + var (x, _) = _grid.CellOrigin(0, c); + dc.DrawText(label, new Point(x + (_grid.CellSize - label.Width) / 2, 0)); + } + } + + var fill = GetBrush(BrushKey); + var empty = GetBrush("Brush.Card"); + var radius = Math.Min(2, _grid.CellSize / 4); + for (var r = 0; r < rows.Count; r++) + { + var row = rows[r]; + var label = CreateText(row.Label, LabelSize, faint); + var (_, y) = _grid.CellOrigin(r, 0); + dc.DrawText(label, new Point(_grid.Left - 8 - label.Width, y + (_grid.CellSize - label.Height) / 2)); + for (var c = 0; c < _grid.Columns; c++) + { + var (x, _) = _grid.CellOrigin(r, c); + var cell = new Rect(x, y, _grid.CellSize, _grid.CellSize); + var value = c < row.Values.Count ? row.Values[c] : double.NaN; + if (!double.IsFinite(value)) + { + dc.DrawRoundedRectangle(empty, null, cell, radius, radius); + continue; + } + dc.PushOpacity(MinimumOpacity + (1 - MinimumOpacity) * Math.Clamp(value / max, 0, 1)); + dc.DrawRoundedRectangle(fill, null, cell, radius, radius); + dc.Pop(); + } + } + if (ShowScale) DrawScale(dc, fill, max); + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + var p = e.GetPosition(this); + _hovering = _grid.TryHit(p.X, p.Y, out var row, out var column) && row < RowCount; + Readout.Show(_hovering ? ReadoutText(row, column) : null, p); + } + + protected override void OnMouseLeave(MouseEventArgs e) + { + base.OnMouseLeave(e); + _hovering = false; + Readout.Hide(); + } + + protected override void OnQueryCursor(QueryCursorEventArgs e) + { + base.OnQueryCursor(e); + if (e.Handled || !_hovering) return; + e.Cursor = Cursors.Hand; + e.Handled = true; + } + + protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonUp(e); + var p = e.GetPosition(this); + if (!_grid.TryHit(p.X, p.Y, out var row, out var column) || row >= RowCount) return; + RaiseEvent(new ChartItemEventArgs(CellActivatedEvent, row, column)); + e.Handled = true; + } + + private string Format(double value) => (ValueFormatter ?? DefaultFormat)(value); + + private static string DefaultFormat(double value) => value.ToString("N0", Loc.Culture); + + private double LabelHeight() => Math.Ceiling(CreateText("0", LabelSize, Brushes.Transparent).Height); + + private double ScaleHeight() => ShowScale ? LabelHeight() + 8 : 0; + + private CellGridLayout Layout(double width, double height) + { + var faint = Brushes.Transparent; + var labelWidth = 0.0; + if (Rows is { } rows) + for (var r = 0; r < rows.Count; r++) labelWidth = Math.Max(labelWidth, CreateText(rows[r].Label, LabelSize, faint).Width); + var left = Math.Ceiling(labelWidth) + 8; + var top = ColumnLabels is { Count: > 0 } ? LabelHeight() + 4 : 0; + var cell = CellGridLayout.FitCellSize(width - left, height - top, RowCount, ColumnCount, CellGap, MaxCellSize); + return new CellGridLayout(left, top, RowCount, ColumnCount, cell, CellGap); + } + + private double ScaleMaximum(IReadOnlyList rows) + { + if (double.IsFinite(Maximum) && Maximum > 0) return Maximum; + var max = 0.0; + for (var r = 0; r < rows.Count; r++) + { + var values = rows[r].Values; + for (var c = 0; c < values.Count; c++) + if (double.IsFinite(values[c])) max = Math.Max(max, values[c]); + } + return max > 0 ? max : 1; + } + + /// "min ▭ max" right-aligned under the grid, with a gradient from the zero opacity to full colour. + private void DrawScale(DrawingContext dc, Brush fill, double max) + { + var muted = GetBrush("Brush.TextMuted"); + var low = CreateText(Format(0), LabelSize, muted); + var high = CreateText(Format(max), LabelSize, muted); + var right = _grid.Left + _grid.Width; + var y = _grid.Top + _grid.Height + 8; + var x = right - high.Width; + dc.DrawText(high, new Point(x, y)); + x -= 66; + var color = fill is SolidColorBrush solid ? solid.Color : Colors.Transparent; + var gradient = new LinearGradientBrush(Color.FromArgb((byte)(color.A * MinimumOpacity), color.R, color.G, color.B), color, 0); + gradient.Freeze(); + dc.DrawRoundedRectangle(gradient, null, new Rect(x, y + (high.Height - 8) / 2, 60, 8), 2, 2); + dc.DrawText(low, new Point(x - 6 - low.Width, y)); + } + + private string ReadoutText(int row, int column) + { + var data = Rows![row]; + if (data.ToolTips is { } tips && column < tips.Count && !string.IsNullOrEmpty(tips[column])) return tips[column]!; + var value = column < data.Values.Count ? data.Values[column] : double.NaN; + var columnLabel = ColumnLabels is { } labels && column < labels.Count ? " " + labels[column] : string.Empty; + return data.Label + columnLabel + (double.IsFinite(value) ? " · " + Format(value) : string.Empty); + } +} diff --git a/src/Titano.Ui/Visuals/SeriesChart.cs b/src/Titano.Ui/Visuals/SeriesChart.cs new file mode 100644 index 00000000..a2e1dbd8 --- /dev/null +++ b/src/Titano.Ui/Visuals/SeriesChart.cs @@ -0,0 +1,428 @@ +using System.Text; +using System.Windows; +using System.Windows.Input; +using System.Windows.Media; +using Titano.Core.Localization; + +namespace Titano.Ui.Visuals; + +/// +/// Per-frame line chart of the editor (BRIEF §12.3: measured luminance in Sun, target curve in Accent, sky region +/// dashed in Region…). Draws a legend row (series titles or , plus a right-aligned +/// ), gridlines on nice Y ticks with labels, dashed vertical markers, and every series +/// decimated to at most two points per device-pixel column so 100k+ frames stay fast. The playhead follows +/// ; clicking or dragging in the plot seeks; hovering shows a crosshair, dots on the +/// series and a readout tooltip with the values under the cursor. The Y range is automatic with padding unless +/// / are set. +/// +public sealed class SeriesChart : DrawingElement +{ + public static readonly DependencyProperty SeriesProperty = DependencyProperty.Register( + nameof(Series), typeof(IReadOnlyList), typeof(SeriesChart), new PropertyMetadata(null, OnDataPropertyChanged)); + + public static readonly DependencyProperty MarkersProperty = DependencyProperty.Register( + nameof(Markers), typeof(IReadOnlyList), typeof(SeriesChart), new PropertyMetadata(null, OnDataPropertyChanged)); + + public static readonly DependencyProperty LegendProperty = DependencyProperty.Register( + nameof(Legend), typeof(IReadOnlyList), typeof(SeriesChart), new PropertyMetadata(null, OnDataPropertyChanged)); + + public static readonly DependencyProperty SummaryProperty = DependencyProperty.Register( + nameof(Summary), typeof(string), typeof(SeriesChart), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty ShowLegendProperty = DependencyProperty.Register( + nameof(ShowLegend), typeof(bool), typeof(SeriesChart), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty ShowYLabelsProperty = DependencyProperty.Register( + nameof(ShowYLabels), typeof(bool), typeof(SeriesChart), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty CurrentIndexProperty = DependencyProperty.Register( + nameof(CurrentIndex), typeof(int), typeof(SeriesChart), + new FrameworkPropertyMetadata(-1, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnOverlayPropertyChanged)); + + public static readonly DependencyProperty IsSeekEnabledProperty = DependencyProperty.Register( + nameof(IsSeekEnabled), typeof(bool), typeof(SeriesChart), new PropertyMetadata(true)); + + public static readonly DependencyProperty YMinimumProperty = DependencyProperty.Register( + nameof(YMinimum), typeof(double), typeof(SeriesChart), new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty YMaximumProperty = DependencyProperty.Register( + nameof(YMaximum), typeof(double), typeof(SeriesChart), new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty YPaddingProperty = DependencyProperty.Register( + nameof(YPadding), typeof(double), typeof(SeriesChart), new FrameworkPropertyMetadata(0.08, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty YLabelFormatterProperty = DependencyProperty.Register( + nameof(YLabelFormatter), typeof(Func), typeof(SeriesChart), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty XLabelFormatterProperty = DependencyProperty.Register( + nameof(XLabelFormatter), typeof(Func), typeof(SeriesChart), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure)); + + private const double LabelSize = 11; + private const double LegendHeight = 24; + private const double XAxisHeight = 18; + + private int[] _decimated = []; + private Rect _plot; + private double _yLow; + private double _yHigh = 1; + private int _count; + private double _dataMin; + private double _dataMax; + private int _hover = -1; + private string? _hoverText; + private bool _dragging; + + public SeriesChart() + : base(hasOverlay: true) + { + } + + /// Lines to draw; replace the list (or use an observable collection) to update. + public IReadOnlyList? Series { get => (IReadOnlyList?)GetValue(SeriesProperty); set => SetValue(SeriesProperty, value); } + + /// Frame markers drawn as dashed vertical lines in the marker colour. + public IReadOnlyList? Markers { get => (IReadOnlyList?)GetValue(MarkersProperty); set => SetValue(MarkersProperty, value); } + + /// Explicit legend entries; null lists the titled series. + public IReadOnlyList? Legend { get => (IReadOnlyList?)GetValue(LegendProperty); set => SetValue(LegendProperty, value); } + + /// Right-aligned text of the legend row (e.g. "flicker −67 % · max step 0.21 EV"). + public string? Summary { get => (string?)GetValue(SummaryProperty); set => SetValue(SummaryProperty, value); } + + public bool ShowLegend { get => (bool)GetValue(ShowLegendProperty); set => SetValue(ShowLegendProperty, value); } + + public bool ShowYLabels { get => (bool)GetValue(ShowYLabelsProperty); set => SetValue(ShowYLabelsProperty, value); } + + /// Playhead frame (two-way); −1 hides it. + public int CurrentIndex { get => (int)GetValue(CurrentIndexProperty); set => SetValue(CurrentIndexProperty, value); } + + /// Whether clicking or dragging sets . + public bool IsSeekEnabled { get => (bool)GetValue(IsSeekEnabledProperty); set => SetValue(IsSeekEnabledProperty, value); } + + /// Fixed bottom of the Y axis; NaN = automatic. + public double YMinimum { get => (double)GetValue(YMinimumProperty); set => SetValue(YMinimumProperty, value); } + + /// Fixed top of the Y axis; NaN = automatic. + public double YMaximum { get => (double)GetValue(YMaximumProperty); set => SetValue(YMaximumProperty, value); } + + /// Fraction of the data span added above and below an automatic range. + public double YPadding { get => (double)GetValue(YPaddingProperty); set => SetValue(YPaddingProperty, value); } + + /// Culture-aware formatting of values (axis labels and readout). + public Func? YLabelFormatter { get => (Func?)GetValue(YLabelFormatterProperty); set => SetValue(YLabelFormatterProperty, value); } + + /// Formatting of frame indices (readout header and, when set, X axis labels). + public Func? XLabelFormatter { get => (Func?)GetValue(XLabelFormatterProperty); set => SetValue(XLabelFormatterProperty, value); } + + protected override Size MeasureOverride(Size availableSize) => new(0, 160); + + protected override void OnDataChanged() + { + _count = 0; + _dataMin = double.PositiveInfinity; + _dataMax = double.NegativeInfinity; + if (Series is { } series) + { + for (var s = 0; s < series.Count; s++) + { + var values = series[s].Values.Span; + _count = Math.Max(_count, values.Length); + for (var i = 0; i < values.Length; i++) + { + var v = values[i]; + if (!double.IsFinite(v)) continue; + if (v < _dataMin) _dataMin = v; + if (v > _dataMax) _dataMax = v; + } + } + } + _hover = -1; + _hoverText = null; + base.OnDataChanged(); + } + + protected override void OnRender(DrawingContext dc) + { + DrawHitArea(dc); + var size = RenderSize; + var scale = PixelScale; + var top = ShowLegend ? DrawLegendRow(dc, size.Width) : 0; + var bottom = size.Height - (XLabelFormatter is null ? 0 : XAxisHeight); + (_yLow, _yHigh) = YRange(); + + var ticks = NiceScale.Inner(_yLow, _yHigh, Math.Max(2, (int)((bottom - top) / 36))); + var format = YLabelFormatter ?? DefaultFormat; + var labels = new FormattedText?[ticks.Count]; + var labelWidth = 0.0; + if (ShowYLabels) + { + var labelBrush = GetBrush("Brush.TextFaint"); + for (var i = 0; i < ticks.Count; i++) + { + labels[i] = CreateText(format(ticks[i]), LabelSize, labelBrush); + labelWidth = Math.Max(labelWidth, labels[i]!.Width); + } + } + var left = labelWidth > 0 ? Math.Ceiling(labelWidth) + 8 : 0; + _plot = new Rect(left, top, Math.Max(0, size.Width - left), Math.Max(0, bottom - top)); + if (_plot.Width < 1 || _plot.Height < 1) + { + RenderOverlay(); + return; + } + + var grid = GetHairline("Brush.Stroke"); + for (var i = 0; i < ticks.Count; i++) + { + var y = PixelGrid.SnapLine(Y(ticks[i]), grid.Thickness, scale); + dc.DrawLine(grid, new Point(_plot.Left, y), new Point(_plot.Right, y)); + if (labels[i] is { } label) dc.DrawText(label, new Point(left - 8 - label.Width, y - label.Height / 2)); + } + if (XLabelFormatter is { } xFormat) DrawXLabels(dc, xFormat); + DrawMarkers(dc, scale); + + dc.PushClip(new RectangleGeometry(_plot)); + if (Series is { } series) + for (var s = 0; s < series.Count; s++) DrawSeries(dc, series[s], scale); + dc.Pop(); + RenderOverlay(); + } + + protected override void OnRenderOverlay(DrawingContext dc) + { + if (_plot.Width < 1 || _count == 0) return; + var scale = PixelScale; + if (_hover >= 0) + { + var hair = GetHairline("Brush.TextFaint"); + var x = PixelGrid.SnapLine(X(_hover), hair.Thickness, scale); + dc.DrawLine(hair, new Point(x, _plot.Top), new Point(x, _plot.Bottom)); + if (Series is { } series) + { + for (var s = 0; s < series.Count; s++) + { + var values = series[s].Values.Span; + if (_hover >= values.Length || !double.IsFinite(values[_hover])) continue; + dc.DrawEllipse(GetBrush(series[s].BrushKey), null, new Point(X(_hover), Y(values[_hover])), 3, 3); + } + } + } + if (CurrentIndex >= 0 && CurrentIndex < _count) + { + var pen = GetHairline("Brush.Accent"); + var x = PixelGrid.SnapLine(X(CurrentIndex), pen.Thickness, scale); + dc.DrawLine(pen, new Point(x, _plot.Top), new Point(x, _plot.Bottom)); + } + } + + protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonDown(e); + var p = e.GetPosition(this); + if (!IsSeekEnabled || _count == 0 || !_plot.Contains(p)) return; + _dragging = CaptureMouse(); + SetCurrentValue(CurrentIndexProperty, IndexAt(p.X)); + e.Handled = true; + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + var p = e.GetPosition(this); + if (_dragging) SetCurrentValue(CurrentIndexProperty, IndexAt(p.X)); + if (_count == 0 || !_plot.Contains(p)) + { + ClearHover(); + return; + } + var index = IndexAt(p.X); + if (index != _hover) + { + _hover = index; + _hoverText = ReadoutText(index, p.X); + RenderOverlay(); + } + Readout.Show(_hoverText, p); + } + + protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonUp(e); + if (_dragging) ReleaseMouseCapture(); + } + + protected override void OnLostMouseCapture(MouseEventArgs e) + { + base.OnLostMouseCapture(e); + _dragging = false; + } + + protected override void OnMouseLeave(MouseEventArgs e) + { + base.OnMouseLeave(e); + ClearHover(); + } + + private static string DefaultFormat(double value) => value.ToString("G4", Loc.Culture); + + private static void OnOverlayPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((SeriesChart)d).RenderOverlay(); + + private (double Low, double High) YRange() + { + var (low, high) = _dataMin <= _dataMax ? NiceScale.Pad(_dataMin, _dataMax, YPadding) : (0.0, 1.0); + if (double.IsFinite(YMinimum)) low = YMinimum; + if (double.IsFinite(YMaximum)) high = YMaximum; + return high > low ? (low, high) : NiceScale.Pad(low, low, 0); + } + + private double X(double index) => _count <= 1 ? _plot.Left + _plot.Width / 2 : _plot.Left + index * _plot.Width / (_count - 1); + + private double Y(double value) => _plot.Bottom - (value - _yLow) / (_yHigh - _yLow) * _plot.Height; + + private int IndexAt(double x) + { + if (_count <= 1 || _plot.Width <= 0) return 0; + return (int)Math.Clamp(Math.Round((x - _plot.Left) / _plot.Width * (_count - 1)), 0, _count - 1); + } + + /// Draws the legend row and returns the plot top. + private double DrawLegendRow(DrawingContext dc, double width) + { + var items = Legend ?? AutoLegend(); + if (items.Count == 0 && string.IsNullOrEmpty(Summary)) return 0; + var right = width; + if (!string.IsNullOrEmpty(Summary)) + { + var summary = CreateText(Summary, LabelSize, GetBrush("Brush.TextMuted")); + right -= summary.Width; + dc.DrawText(summary, new Point(right, 0)); + right -= 16; + } + DrawLegend(dc, items, new Point(0, 0), right, LabelSize); + return LegendHeight; + } + + private List AutoLegend() + { + var items = new List(); + if (Series is not { } series) return items; + for (var s = 0; s < series.Count; s++) + { + var item = series[s]; + if (!item.ShowInLegend || string.IsNullOrEmpty(item.Title)) continue; + var swatch = item.Dash switch + { + LineDash.Dashed => LegendSwatch.DashedLine, + LineDash.Dotted => LegendSwatch.DottedLine, + _ => LegendSwatch.Line, + }; + items.Add(new ChartLegendItem(item.Title, item.BrushKey, swatch)); + } + return items; + } + + private void DrawXLabels(DrawingContext dc, Func format) + { + if (_count < 2) return; + var ticks = NiceScale.Inner(0, _count - 1, Math.Max(2, (int)(_plot.Width / 90))); + var brush = GetBrush("Brush.TextFaint"); + var lastRight = double.NegativeInfinity; + for (var i = 0; i < ticks.Count; i++) + { + var v = ticks[i]; + if (Math.Abs(v - Math.Round(v)) > 1e-9) continue; + var text = CreateText(format(v), LabelSize, brush); + var x = Math.Clamp(X(v) - text.Width / 2, 0, Math.Max(0, ActualWidth - text.Width)); + if (x < lastRight + 8) continue; + dc.DrawText(text, new Point(x, _plot.Bottom + 4)); + lastRight = x + text.Width; + } + } + + private void DrawMarkers(DrawingContext dc, double scale) + { + if (Markers is not { Count: > 0 } markers) return; + var thickness = PixelGrid.SnapThickness(1, scale); + for (var i = 0; i < markers.Count; i++) + { + var m = markers[i]; + if (m.Index < 0 || m.Index >= _count) continue; + var pen = GetPen(TimelineMarker.BrushKeyOf(m.Kind), thickness, LineDash.Dashed); + var x = PixelGrid.SnapLine(X(m.Index), thickness, scale); + dc.DrawLine(pen, new Point(x, _plot.Top), new Point(x, _plot.Bottom)); + } + } + + private void DrawSeries(DrawingContext dc, ChartSeries series, double scale) + { + var values = series.Values.Span; + if (values.Length == 0) return; + var columns = Math.Max(1, (int)Math.Ceiling(_plot.Width * scale)); + var capacity = MinMaxDecimator.Capacity(values.Length, columns); + if (_decimated.Length < capacity) _decimated = new int[capacity]; + var n = MinMaxDecimator.Decimate(values, columns, _decimated); + + var geometry = new StreamGeometry(); + using (var ctx = geometry.Open()) + { + var open = false; + for (var k = 0; k < n; k++) + { + var i = _decimated[k]; + if (i == MinMaxDecimator.Gap) + { + open = false; + continue; + } + var p = new Point(X(i), Y(values[i])); + if (open) + { + ctx.LineTo(p, true, true); + } + else + { + ctx.BeginFigure(p, false, false); + open = true; + } + } + } + geometry.Freeze(); + dc.DrawGeometry(null, GetPen(series.BrushKey, series.Thickness, series.Dash), geometry); + } + + private string? ReadoutText(int index, double x) + { + var format = YLabelFormatter ?? DefaultFormat; + var text = new StringBuilder(XLabelFormatter?.Invoke(index) ?? index.ToString("N0", Loc.Culture)); + if (Series is { } series) + { + for (var s = 0; s < series.Count; s++) + { + var values = series[s].Values.Span; + if (index >= values.Length || !double.IsFinite(values[index])) continue; + text.AppendLine(); + if (!string.IsNullOrEmpty(series[s].Title)) text.Append(series[s].Title).Append(": "); + text.Append(format(values[index])); + } + } + if (Markers is { } markers) + { + for (var i = 0; i < markers.Count; i++) + { + var m = markers[i]; + if (string.IsNullOrEmpty(m.Label) || m.Index < 0 || m.Index >= _count || Math.Abs(X(m.Index) - x) > 4) continue; + text.AppendLine().Append(m.Label); + } + } + return text.ToString(); + } + + private void ClearHover() + { + Readout.Hide(); + if (_hover < 0) return; + _hover = -1; + _hoverText = null; + RenderOverlay(); + } +} diff --git a/src/Titano.Ui/Visuals/StackedBar.cs b/src/Titano.Ui/Visuals/StackedBar.cs new file mode 100644 index 00000000..42a497dc --- /dev/null +++ b/src/Titano.Ui/Visuals/StackedBar.cs @@ -0,0 +1,203 @@ +using System.Windows; +using System.Windows.Input; +using System.Windows.Media; +using Titano.Core.Localization; + +namespace Titano.Ui.Visuals; + +/// +/// One bar split into proportional segments (by camera, by format) with a wrapping legend underneath +/// ("■ label share"). Segments share one theme colour and fade by rank (items may set their own brush), so no new +/// colours are introduced; 2-px gaps separate them. Hovering a segment or legend entry reads it out; clicking +/// raises . +/// +public sealed class StackedBar : DrawingElement +{ + public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register( + nameof(Items), typeof(IReadOnlyList), typeof(StackedBar), new PropertyMetadata(null, OnDataPropertyChanged)); + + public static readonly DependencyProperty BrushKeyProperty = DependencyProperty.Register( + nameof(BrushKey), typeof(string), typeof(StackedBar), new FrameworkPropertyMetadata("Brush.Accent", FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty BarHeightProperty = DependencyProperty.Register( + nameof(BarHeight), typeof(double), typeof(StackedBar), + new FrameworkPropertyMetadata(12.0, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure)); + + public static readonly DependencyProperty ShowLegendProperty = DependencyProperty.Register( + nameof(ShowLegend), typeof(bool), typeof(StackedBar), + new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure)); + + public static readonly DependencyProperty ShareFormatterProperty = DependencyProperty.Register( + nameof(ShareFormatter), typeof(Func), typeof(StackedBar), + new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure)); + + public static readonly RoutedEvent ItemActivatedEvent = EventManager.RegisterRoutedEvent( + nameof(ItemActivated), RoutingStrategy.Bubble, typeof(ChartItemEventHandler), typeof(StackedBar)); + + private const double LabelSize = 11; + private const double SegmentGap = 2; + private const double LegendGap = 10; + private const double LegendLine = 18; + private const double EntryGap = 14; + + private readonly List _segments = []; + private readonly List _entries = []; + private int _hover = -1; + + /// Parts in display order (largest first reads best). + public IReadOnlyList? Items { get => (IReadOnlyList?)GetValue(ItemsProperty); set => SetValue(ItemsProperty, value); } + + public string BrushKey { get => (string)GetValue(BrushKeyProperty); set => SetValue(BrushKeyProperty, value); } + + public double BarHeight { get => (double)GetValue(BarHeightProperty); set => SetValue(BarHeightProperty, value); } + + public bool ShowLegend { get => (bool)GetValue(ShowLegendProperty); set => SetValue(ShowLegendProperty, value); } + + /// Formats a share 0…1 for the legend (default: culture percent without decimals). + public Func? ShareFormatter { get => (Func?)GetValue(ShareFormatterProperty); set => SetValue(ShareFormatterProperty, value); } + + public event ChartItemEventHandler ItemActivated + { + add => AddHandler(ItemActivatedEvent, value); + remove => RemoveHandler(ItemActivatedEvent, value); + } + + protected override Size MeasureOverride(Size availableSize) + { + if (Items is not { Count: > 0 } items) return new Size(0, 0); + var lines = ShowLegend ? LayoutLegend(items, availableSize.Width, null) : 0; + return new Size(0, BarHeight + (lines > 0 ? LegendGap + lines * LegendLine : 0)); + } + + protected override void OnDataChanged() + { + _hover = -1; + base.OnDataChanged(); + } + + protected override void OnRender(DrawingContext dc) + { + DrawHitArea(dc); + _segments.Clear(); + _entries.Clear(); + if (Items is not { Count: > 0 } items) return; + var total = Total(items); + var width = ActualWidth; + var radius = Math.Min(3, BarHeight / 2); + dc.PushClip(new RectangleGeometry(new Rect(0, 0, width, BarHeight), radius, radius)); + dc.DrawRectangle(GetBrush("Brush.Track"), null, new Rect(0, 0, width, BarHeight)); + var available = Math.Max(0, width - SegmentGap * (items.Count - 1)); + var x = 0.0; + for (var i = 0; i < items.Count; i++) + { + var share = total > 0 ? Math.Max(0, items[i].Value) / total : 0; + var segment = new Rect(x, 0, available * share, BarHeight); + _segments.Add(segment); + dc.PushOpacity(OpacityOf(i, items)); + dc.DrawRectangle(GetBrush(items[i].BrushKey ?? BrushKey), null, segment); + dc.Pop(); + x = segment.Right + SegmentGap; + } + dc.Pop(); + if (ShowLegend) LayoutLegend(items, width, dc); + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + var p = e.GetPosition(this); + _hover = HitTest(p); + Readout.Show(_hover >= 0 ? ReadoutText(_hover) : null, p); + } + + protected override void OnMouseLeave(MouseEventArgs e) + { + base.OnMouseLeave(e); + _hover = -1; + Readout.Hide(); + } + + protected override void OnQueryCursor(QueryCursorEventArgs e) + { + base.OnQueryCursor(e); + if (e.Handled || _hover < 0) return; + e.Cursor = Cursors.Hand; + e.Handled = true; + } + + protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonUp(e); + var index = HitTest(e.GetPosition(this)); + if (index < 0) return; + RaiseEvent(new ChartItemEventArgs(ItemActivatedEvent, index, -1)); + e.Handled = true; + } + + private static double Total(IReadOnlyList items) + { + var total = 0.0; + for (var i = 0; i < items.Count; i++) total += Math.Max(0, items[i].Value); + return total; + } + + /// Rank fade 1 → 0.35 for items in the shared colour; items with their own brush stay opaque. + private static double OpacityOf(int index, IReadOnlyList items) => + items[index].BrushKey is not null || items.Count < 2 ? 1 : 1 - 0.65 * index / (items.Count - 1); + + private string Share(double share) => ShareFormatter?.Invoke(share) ?? share.ToString("P0", Loc.Culture); + + /// Flows legend entries into lines of the given width; draws them when is set. Returns the line count. + private int LayoutLegend(IReadOnlyList items, double width, DrawingContext? dc) + { + var total = Total(items); + var muted = GetBrush("Brush.TextMuted"); + var text = GetBrush("Brush.Text"); + double x = 0; + var line = 0; + var top = BarHeight + LegendGap; + for (var i = 0; i < items.Count; i++) + { + var label = CreateText(items[i].Label, LabelSize, muted); + var value = CreateText(items[i].ValueText ?? Share(total > 0 ? Math.Max(0, items[i].Value) / total : 0), LabelSize, text); + var entryWidth = 8 + 6 + label.Width + 4 + value.Width; + if (x > 0 && double.IsFinite(width) && x + entryWidth > width) + { + x = 0; + line++; + } + if (dc is not null) + { + var y = top + line * LegendLine; + var cy = y + label.Height / 2; + dc.PushOpacity(OpacityOf(i, items)); + dc.DrawRoundedRectangle(GetBrush(items[i].BrushKey ?? BrushKey), null, new Rect(x, cy - 4, 8, 8), 2, 2); + dc.Pop(); + dc.DrawText(label, new Point(x + 14, y)); + dc.DrawText(value, new Point(x + 14 + label.Width + 4, y)); + _entries.Add(new Rect(x, y, entryWidth, LegendLine)); + } + x += entryWidth + EntryGap; + } + return line + 1; + } + + private int HitTest(Point p) + { + for (var i = 0; i < _segments.Count; i++) + if (p.Y >= 0 && p.Y <= BarHeight && p.X >= _segments[i].Left && p.X <= _segments[i].Right + SegmentGap) return i; + for (var i = 0; i < _entries.Count; i++) + if (_entries[i].Contains(p)) return i; + return -1; + } + + private string ReadoutText(int index) + { + var items = Items!; + var item = items[index]; + if (item.ToolTip is not null) return item.ToolTip; + var total = Total(items); + var share = Share(total > 0 ? Math.Max(0, item.Value) / total : 0); + return item.Label + " · " + (item.ValueText is null ? share : item.ValueText + " · " + share); + } +} diff --git a/src/Titano.Ui/Visuals/TimelineBands.cs b/src/Titano.Ui/Visuals/TimelineBands.cs new file mode 100644 index 00000000..a2e743b9 --- /dev/null +++ b/src/Titano.Ui/Visuals/TimelineBands.cs @@ -0,0 +1,202 @@ +using System.Windows; +using System.Windows.Input; +using System.Windows.Media; +using Titano.Core.Localization; + +namespace Titano.Ui.Visuals; + +/// +/// Library timeline mode (BRIEF §12.2): one band per year with its label on the left and a density bar per slot +/// (month) on a scale shared by all bands, slot labels underneath and a divider between bands. The current slot +/// (, ) is outlined in Accent; clicking a slot makes it current +/// and raises . Desired height = bands × , so the control +/// scrolls inside a ScrollViewer. +/// +public sealed class TimelineBands : DrawingElement +{ + public static readonly DependencyProperty BandsProperty = DependencyProperty.Register( + nameof(Bands), typeof(IReadOnlyList), typeof(TimelineBands), new PropertyMetadata(null, OnDataPropertyChanged)); + + public static readonly DependencyProperty SlotLabelsProperty = DependencyProperty.Register( + nameof(SlotLabels), typeof(IReadOnlyList), typeof(TimelineBands), new PropertyMetadata(null, OnDataPropertyChanged)); + + public static readonly DependencyProperty BrushKeyProperty = DependencyProperty.Register( + nameof(BrushKey), typeof(string), typeof(TimelineBands), new FrameworkPropertyMetadata("Brush.Accent", FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty BandHeightProperty = DependencyProperty.Register( + nameof(BandHeight), typeof(double), typeof(TimelineBands), + new FrameworkPropertyMetadata(64.0, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure), v => v is double d && d >= 24); + + public static readonly DependencyProperty CurrentBandProperty = DependencyProperty.Register( + nameof(CurrentBand), typeof(int), typeof(TimelineBands), + new FrameworkPropertyMetadata(-1, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty CurrentSlotProperty = DependencyProperty.Register( + nameof(CurrentSlot), typeof(int), typeof(TimelineBands), + new FrameworkPropertyMetadata(-1, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty ValueFormatterProperty = DependencyProperty.Register( + nameof(ValueFormatter), typeof(Func), typeof(TimelineBands), new PropertyMetadata(null)); + + public static readonly RoutedEvent SlotActivatedEvent = EventManager.RegisterRoutedEvent( + nameof(SlotActivated), RoutingStrategy.Bubble, typeof(ChartItemEventHandler), typeof(TimelineBands)); + + private const double LabelColumn = 64; + private const double LabelSize = 11; + + private (int Band, int Slot) _hover = (-1, -1); + + /// One band per year: label + one value per slot. + public IReadOnlyList? Bands { get => (IReadOnlyList?)GetValue(BandsProperty); set => SetValue(BandsProperty, value); } + + /// Slot captions (culture-aware month initials); also fixes the slot count. + public IReadOnlyList? SlotLabels { get => (IReadOnlyList?)GetValue(SlotLabelsProperty); set => SetValue(SlotLabelsProperty, value); } + + public string BrushKey { get => (string)GetValue(BrushKeyProperty); set => SetValue(BrushKeyProperty, value); } + + public double BandHeight { get => (double)GetValue(BandHeightProperty); set => SetValue(BandHeightProperty, value); } + + /// Band of the current slot (two-way); −1 = none. + public int CurrentBand { get => (int)GetValue(CurrentBandProperty); set => SetValue(CurrentBandProperty, value); } + + /// Current slot inside (two-way); −1 = none. + public int CurrentSlot { get => (int)GetValue(CurrentSlotProperty); set => SetValue(CurrentSlotProperty, value); } + + /// Culture-aware value formatting for readouts. + public Func? ValueFormatter { get => (Func?)GetValue(ValueFormatterProperty); set => SetValue(ValueFormatterProperty, value); } + + public event ChartItemEventHandler SlotActivated + { + add => AddHandler(SlotActivatedEvent, value); + remove => RemoveHandler(SlotActivatedEvent, value); + } + + private int SlotCount + { + get + { + if (SlotLabels is { Count: > 0 } labels) return labels.Count; + var max = 0; + if (Bands is { } bands) + for (var b = 0; b < bands.Count; b++) max = Math.Max(max, bands[b].Values.Count); + return max; + } + } + + private double SlotPitch => SlotCount == 0 ? 0 : Math.Max(0, ActualWidth - LabelColumn) / SlotCount; + + protected override Size MeasureOverride(Size availableSize) => new(0, (Bands?.Count ?? 0) * BandHeight); + + protected override void OnDataChanged() + { + _hover = (-1, -1); + base.OnDataChanged(); + } + + protected override void OnRender(DrawingContext dc) + { + DrawHitArea(dc); + if (Bands is not { Count: > 0 } bands || SlotCount == 0) return; + var slots = SlotCount; + var pitch = SlotPitch; + var scale = PixelScale; + var max = 0.0; + for (var b = 0; b < bands.Count; b++) + for (var s = 0; s < bands[b].Values.Count; s++) + if (double.IsFinite(bands[b].Values[s])) max = Math.Max(max, bands[b].Values[s]); + if (max <= 0) max = 1; + + var text = GetBrush("Brush.Text"); + var faint = GetBrush("Brush.TextFaint"); + var fill = GetBrush(BrushKey); + var divider = GetHairline("Brush.Stroke"); + var captionHeight = Math.Ceiling(CreateText("0", LabelSize, faint).Height); + var barWidth = Math.Max(1, Math.Min(pitch * 0.6, 28)); + + for (var b = 0; b < bands.Count; b++) + { + var band = bands[b]; + var top = b * BandHeight; + var baseline = top + BandHeight - captionHeight - 8; + var barSpace = baseline - top - 8; + var title = CreateText(band.Label, 13, text, semiBold: true); + dc.DrawText(title, new Point(0, top + (BandHeight - title.Height) / 2)); + for (var s = 0; s < slots; s++) + { + var cx = LabelColumn + pitch * (s + 0.5); + var value = s < band.Values.Count ? band.Values[s] : double.NaN; + if (double.IsFinite(value) && value > 0) + { + var h = Math.Max(1, barSpace * Math.Clamp(value / max, 0, 1)); + dc.DrawRoundedRectangle(fill, null, new Rect(cx - barWidth / 2, baseline - h, barWidth, h), 2, 2); + } + if (SlotLabels is { } labels && s < labels.Count) + { + var caption = CreateText(labels[s], LabelSize, faint); + dc.DrawText(caption, new Point(cx - caption.Width / 2, baseline + 4)); + } + if (b == CurrentBand && s == CurrentSlot) + dc.DrawRoundedRectangle(null, GetPen("Brush.Accent", 1.5), new Rect(cx - pitch / 2 + 2, top + 4, pitch - 4, BandHeight - 8), 4, 4); + } + if (b < bands.Count - 1) + { + var y = PixelGrid.SnapLine(top + BandHeight, divider.Thickness, scale); + dc.DrawLine(divider, new Point(0, y), new Point(ActualWidth, y)); + } + } + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + var p = e.GetPosition(this); + _hover = HitTest(p); + Readout.Show(_hover.Band >= 0 ? ReadoutText(_hover.Band, _hover.Slot) : null, p); + } + + protected override void OnMouseLeave(MouseEventArgs e) + { + base.OnMouseLeave(e); + _hover = (-1, -1); + Readout.Hide(); + } + + protected override void OnQueryCursor(QueryCursorEventArgs e) + { + base.OnQueryCursor(e); + if (e.Handled || _hover.Band < 0) return; + e.Cursor = Cursors.Hand; + e.Handled = true; + } + + protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonUp(e); + var (band, slot) = HitTest(e.GetPosition(this)); + if (band < 0) return; + SetCurrentValue(CurrentBandProperty, band); + SetCurrentValue(CurrentSlotProperty, slot); + RaiseEvent(new ChartItemEventArgs(SlotActivatedEvent, band, slot)); + e.Handled = true; + } + + private (int Band, int Slot) HitTest(Point p) + { + var count = Bands?.Count ?? 0; + var pitch = SlotPitch; + if (count == 0 || pitch <= 0 || p.X < LabelColumn) return (-1, -1); + var band = (int)Math.Floor(p.Y / BandHeight); + var slot = (int)Math.Floor((p.X - LabelColumn) / pitch); + return band >= 0 && band < count && slot >= 0 && slot < SlotCount ? (band, slot) : (-1, -1); + } + + private string ReadoutText(int band, int slot) + { + var row = Bands![band]; + if (row.ToolTips is { } tips && slot < tips.Count && !string.IsNullOrEmpty(tips[slot])) return tips[slot]!; + var value = slot < row.Values.Count ? row.Values[slot] : double.NaN; + var caption = SlotLabels is { } labels && slot < labels.Count ? " " + labels[slot] : string.Empty; + var format = ValueFormatter ?? (v => v.ToString("N0", Loc.Culture)); + return row.Label + caption + (double.IsFinite(value) ? " · " + format(value) : string.Empty); + } +}