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 reading side and the value labels after each bar, as in the Archive mockup, and /// mirror in a right-to-left language; vertical bars put the categories underneath (skipping labels that would /// collide) and keep them left to right. Optional value gridlines use nice ticks. A bar's opacity can follow its /// value (). Hovering reads out the bar; clicking raises , /// and a handler attached to the chart also gives it the hand cursor and the keyboard. /// 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; /// 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); } /// Raised when a bar is clicked, or chosen with the keyboard and Enter; attach it to the chart itself to make the bars interactive. public event ChartItemEventHandler ItemActivated { add { AddHandler(ItemActivatedEvent, value); TrackActivation(value, added: true); } remove { RemoveHandler(ItemActivatedEvent, value); TrackActivation(value, added: false); } } protected internal override string? AutomationDescription => Items is { Count: > 0 } items ? string.Join(Environment.NewLine, items.Select(ReadoutText)) : null; protected override int ItemCount => Items?.Count ?? 0; 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 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); DrawKeyboardItem(dc); } protected override int ItemAt(Point point) { var count = ItemCount; if (count == 0 || _area.IsEmpty || !(_pitch > 0)) return -1; var index = Orientation == Orientation.Horizontal ? (int)Math.Floor((point.Y - _area.Top) / _pitch) : (int)Math.Floor((point.X - _area.Left) / _pitch); var inside = Orientation == Orientation.Horizontal ? point.X >= 0 && point.X <= ActualWidth : point.Y >= 0 && point.Y <= ActualHeight; return inside && index >= 0 && index < count ? index : -1; } /// A horizontal bar's whole row (label, bar and value), a vertical bar's whole column. protected override Rect ItemBounds(int item) { if (_area.IsEmpty || !(_pitch > 0)) return Rect.Empty; return Orientation == Orientation.Horizontal ? new Rect(1, _area.Top + _pitch * item + 1, Math.Max(0, ActualWidth - 2), Math.Max(0, _pitch - 2)) : new Rect(_area.Left + _pitch * item + 1, 1, Math.Max(0, _pitch - 2), Math.Max(0, ActualHeight - 2)); } protected override string? ItemText(int item) => Items is { } items && item < items.Count ? ReadoutText(items[item]) : null; /// Up/Down move along horizontal bars, Left/Right along vertical ones (left to right in every language). protected override int Navigate(int item, Key key) => (Orientation, key) switch { (Orientation.Horizontal, Key.Up) or (Orientation.Vertical, Key.Left) => Math.Max(0, item - 1), (Orientation.Horizontal, Key.Down) or (Orientation.Vertical, Key.Right) => item + 1, _ => -1, }; protected override void Activate(int item) => RaiseEvent(new ChartItemEventArgs(ItemActivatedEvent, item, -1)); 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); /// /// Laid out from the left and mirrored in a right-to-left language (): labels on /// the reading side, bars growing away from it, each value after its bar's end. /// private void RenderHorizontal(DrawingContext dc, IReadOnlyList items, double max) { var muted = GetBrush("Brush.TextMuted"); 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] = CreateLabel(items[i].Label, LabelSize, muted); labelWidth = Math.Max(labelWidth, labels[i].Width); if (!ShowValues) continue; values[i] = CreateLabel(items[i].ValueText ?? Format(items[i].Value), LabelSize, text); valueWidth = Math.Max(valueWidth, values[i]!.Width); } var width = ActualWidth; var gridHeight = ShowGrid ? 16 : 0; var left = Math.Ceiling(labelWidth) + 8; var right = width - (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); DrawTextAt(dc, labels[i], new Point(FromStart(left - 8 - labels[i].Width, labels[i].Width, 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(FromStart(left, length, width), cy - thickness / 2, length, thickness), 2, 2); dc.Pop(); } if (values[i] is { } value) DrawTextAt(dc, value, new Point(FromStart(left + length + 6, value.Width, width), cy - value.Height / 2)); } } /// Categories run left to right in every language: vertical bars often stand for days or years. private void RenderVertical(DrawingContext dc, IReadOnlyList items, double max) { var muted = GetBrush("Brush.TextMuted"); var sample = CreateText("0", LabelSize, muted); var labelHeight = Math.Ceiling(sample.Height) + 4; var valueHeight = ShowValues ? labelHeight : 0; var axisWidth = 0.0; if (ShowGrid) { var top = CreateText(Format(max), LabelSize, muted); 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 = CreateLabel(item.ValueText ?? Format(item.Value), LabelSize, text); if (value.Width <= _pitch) DrawTextAt(dc, value, new Point(cx - value.Width / 2, _area.Bottom - height - value.Height - 2)); } var label = CreateLabel(item.Label, LabelSize, muted); var x = cx - label.Width / 2; if (x < lastLabelRight + 6) continue; DrawTextAt(dc, label, new Point(x, _area.Bottom + 4)); lastLabelRight = x + label.Width; } } /// /// Gridlines at nice ticks along the value axis, with labels below (horizontal bars, mirrored with them) 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 muted = GetBrush("Brush.TextMuted"); var scale = PixelScale; var width = ActualWidth; for (var i = 0; i < ticks.Count; i++) { var label = CreateText(Format(ticks[i]), LabelSize, muted); if (horizontal) { var x = PixelGrid.SnapLine(FromStart(_area.Left + _area.Width * ticks[i] / max, 0, width), pen.Thickness, scale); dc.DrawLine(pen, new Point(x, _area.Top), new Point(x, _area.Bottom)); dc.DrawText(label, new Point(Math.Clamp(x - label.Width / 2, 0, Math.Max(0, width - 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)); } } } }