merge: visual controls (virtualizing card grid, filmstrip, charts, preview viewport, curve editor)
This commit is contained in:
37 files changed
+5950
No files matched your search
@@ -9,6 +9,7 @@
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Titano.Ui;component/Themes/Typography.xaml" />
|
||||
<ResourceDictionary Source="pack://application:,,,/Titano.Ui;component/Icons/Icons.xaml" />
|
||||
<ResourceDictionary Source="pack://application:,,,/Titano.Ui;component/Themes/Visuals.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<BooleanToVisibilityConverter x:Key="BoolToVisibility" />
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls"
|
||||
xmlns:v="clr-namespace:Titano.Ui.Visuals">
|
||||
<!--
|
||||
Styles of the high-performance visuals (Titano.Ui.Visuals), merged by Controls.xaml. Brushes and the shared
|
||||
button templates of Controls.xaml are DynamicResource (they live in the parent dictionary); sizes, radii and
|
||||
fonts are StaticResource from Typography.xaml, merged here so they resolve while this dictionary loads.
|
||||
-->
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Titano.Ui;component/Themes/Typography.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<!-- ===================== Library grid: card container and list ===================== -->
|
||||
<Style x:Key="ListBoxItem.Card" TargetType="ListBoxItem">
|
||||
<Setter Property="FocusVisualStyle" Value="{DynamicResource Focus.Ring}" />
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="Margin" Value="0" />
|
||||
<Setter Property="MinHeight" Value="0" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ListBoxItem">
|
||||
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Virtualized, recycling card grid (BRIEF §12.2). Item template: a v:SequenceCard bound to the item. -->
|
||||
<Style x:Key="ListBox.Cards" TargetType="ListBox">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
|
||||
<Setter Property="SelectionMode" Value="Extended" />
|
||||
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
|
||||
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
|
||||
<Setter Property="ScrollViewer.CanContentScroll" Value="True" />
|
||||
<Setter Property="ScrollViewer.PanningMode" Value="VerticalOnly" />
|
||||
<Setter Property="VirtualizingPanel.IsVirtualizing" Value="True" />
|
||||
<Setter Property="VirtualizingPanel.VirtualizationMode" Value="Recycling" />
|
||||
<Setter Property="ItemContainerStyle" Value="{StaticResource ListBoxItem.Card}" />
|
||||
<Setter Property="ItemsPanel">
|
||||
<Setter.Value>
|
||||
<ItemsPanelTemplate>
|
||||
<v:VirtualizingWrapPanel Padding="20,4,20,12" />
|
||||
</ItemsPanelTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- ===================== Sequence card (DESIGN §4 Cards) ===================== -->
|
||||
<DataTemplate x:Key="Template.CardStatus" DataType="{x:Type v:CardStatus}">
|
||||
<ui:StatusGlyph Kind="{Binding Kind}" Text="{Binding Text}" ToolTip="{Binding ToolTip}" Margin="0,0,8,0" />
|
||||
</DataTemplate>
|
||||
|
||||
<Style TargetType="v:SequenceCard">
|
||||
<Setter Property="Width" Value="236" />
|
||||
<Setter Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Stroke}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
<Setter Property="FontFamily" Value="{StaticResource Font.Ui}" />
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.Body}" />
|
||||
<Setter Property="Focusable" Value="False" />
|
||||
<Setter Property="SnapsToDevicePixels" Value="True" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Title, RelativeSource={RelativeSource Self}}" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="v:SequenceCard">
|
||||
<Grid>
|
||||
<Border x:Name="Glow" Margin="-3" CornerRadius="11" BorderThickness="3" BorderBrush="{DynamicResource Brush.AccentSelected}" Visibility="Collapsed" />
|
||||
<Border x:Name="Frame" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1"
|
||||
CornerRadius="{StaticResource Radius.Card}">
|
||||
<StackPanel>
|
||||
<v:AspectRatioDecorator>
|
||||
<Grid x:Name="PART_Thumbnail" Background="Transparent">
|
||||
<Border CornerRadius="7,7,0,0" Background="{DynamicResource Brush.Preview}" />
|
||||
<Border CornerRadius="7,7,0,0">
|
||||
<Border.Background>
|
||||
<ImageBrush ImageSource="{Binding DisplayedThumbnail, RelativeSource={RelativeSource TemplatedParent}}" Stretch="UniformToFill" />
|
||||
</Border.Background>
|
||||
</Border>
|
||||
<Border x:Name="ScrubTrack" Height="2" VerticalAlignment="Bottom" Background="{DynamicResource Brush.Accent}" RenderTransformOrigin="0,0.5" Visibility="Collapsed">
|
||||
<Border.RenderTransform>
|
||||
<ScaleTransform ScaleX="{Binding ScrubPosition, RelativeSource={RelativeSource TemplatedParent}}" />
|
||||
</Border.RenderTransform>
|
||||
</Border>
|
||||
<CheckBox x:Name="Select" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="8" Focusable="False" Visibility="Collapsed"
|
||||
IsChecked="{Binding IsSelected, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" ToolTip="{TemplateBinding SelectToolTip}" />
|
||||
<Grid HorizontalAlignment="Right" VerticalAlignment="Top" Margin="8"
|
||||
Visibility="{Binding Badge, RelativeSource={RelativeSource TemplatedParent}, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
|
||||
<Border Background="{DynamicResource Brush.Chrome}" Opacity="0.85" CornerRadius="4" />
|
||||
<TextBlock Text="{TemplateBinding Badge}" Margin="6,2" FontSize="{StaticResource Size.Chip}" Typography.NumeralAlignment="Tabular" />
|
||||
</Grid>
|
||||
<ContentPresenter x:Name="Actions" Content="{TemplateBinding ActionsContent}" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="8" Visibility="Collapsed" />
|
||||
</Grid>
|
||||
</v:AspectRatioDecorator>
|
||||
<StackPanel Margin="10,8,10,8">
|
||||
<TextBlock Text="{TemplateBinding Title}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{TemplateBinding Subtitle}" Margin="0,4,0,0" FontSize="{StaticResource Size.Secondary}" Foreground="{DynamicResource Brush.TextMuted}"
|
||||
TextTrimming="CharacterEllipsis" Typography.NumeralAlignment="Tabular" />
|
||||
<ItemsControl ItemsSource="{TemplateBinding Statuses}" ItemTemplate="{StaticResource Template.CardStatus}" Margin="0,4,0,0" Focusable="False">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Select" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Actions" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Frame" Property="BorderBrush" Value="{DynamicResource Brush.StrokeStrong}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsScrubbing" Value="True">
|
||||
<Setter TargetName="ScrubTrack" Property="Visibility" Value="Visible" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="Select" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Frame" Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter TargetName="Glow" Property="Visibility" Value="Visible" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Opacity" Value="0.4" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- ===================== Focusable drawn visuals ===================== -->
|
||||
<Style TargetType="v:Filmstrip">
|
||||
<Setter Property="FocusVisualStyle" Value="{DynamicResource Focus.Ring}" />
|
||||
</Style>
|
||||
|
||||
<Style TargetType="v:CurveEditor">
|
||||
<Setter Property="FocusVisualStyle" Value="{DynamicResource Focus.Ring}" />
|
||||
</Style>
|
||||
|
||||
<!-- ===================== Preview viewport (BRIEF §12.3) ===================== -->
|
||||
<Style TargetType="v:PreviewViewport">
|
||||
<Setter Property="Background" Value="{DynamicResource Brush.Preview}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
<Setter Property="FontFamily" Value="{StaticResource Font.Ui}" />
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.Secondary}" />
|
||||
<Setter Property="FlowDirection" Value="LeftToRight" />
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="v:PreviewViewport">
|
||||
<Border Background="{TemplateBinding Background}" CornerRadius="{StaticResource Radius.Card}">
|
||||
<Grid>
|
||||
<v:PreviewSurface x:Name="PART_Surface" CornerRadius="8" />
|
||||
<ContentPresenter Content="{TemplateBinding ToolsContent}" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="12" />
|
||||
<Grid x:Name="Info" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="12" IsHitTestVisible="False">
|
||||
<Border Background="{DynamicResource Brush.Chrome}" Opacity="0.85" CornerRadius="{StaticResource Radius.Control}" />
|
||||
<TextBlock Text="{TemplateBinding InfoText}" Margin="10,6" Typography.NumeralAlignment="Tabular" TextTrimming="CharacterEllipsis" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="InfoText" Value="{x:Null}">
|
||||
<Setter TargetName="Info" Property="Visibility" Value="Collapsed" />
|
||||
</Trigger>
|
||||
<Trigger Property="InfoText" Value="">
|
||||
<Setter TargetName="Info" Property="Visibility" Value="Collapsed" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- ===================== Segmented control (Library view switcher) ===================== -->
|
||||
<Style TargetType="v:SegmentedControl">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="v:SegmentedControl">
|
||||
<StackPanel Orientation="Horizontal" IsItemsHost="True" />
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="v:SegmentedItem">
|
||||
<Setter Property="FocusVisualStyle" Value="{DynamicResource Focus.Ring}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
<Setter Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Stroke}" />
|
||||
<Setter Property="FontFamily" Value="{StaticResource Font.Ui}" />
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.Body}" />
|
||||
<Setter Property="Height" Value="{StaticResource Height.Control}" />
|
||||
<Setter Property="MinWidth" Value="32" />
|
||||
<Setter Property="Padding" Value="8,0" />
|
||||
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="v:SegmentedItem">
|
||||
<Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1"
|
||||
CornerRadius="{StaticResource Radius.Control}" SnapsToDevicePixels="True">
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="{TemplateBinding Padding}">
|
||||
<ui:Icon x:Name="Glyph" Glyph="{TemplateBinding Glyph}" VerticalAlignment="Center" />
|
||||
<ContentPresenter x:Name="Content" Margin="6,0,0,0" VerticalAlignment="Center" RecognizesAccessKey="True" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="Position" Value="First">
|
||||
<Setter TargetName="Bd" Property="CornerRadius" Value="6,0,0,6" />
|
||||
</Trigger>
|
||||
<Trigger Property="Position" Value="Middle">
|
||||
<Setter TargetName="Bd" Property="CornerRadius" Value="0" />
|
||||
<Setter Property="Margin" Value="-1,0,0,0" />
|
||||
</Trigger>
|
||||
<Trigger Property="Position" Value="Last">
|
||||
<Setter TargetName="Bd" Property="CornerRadius" Value="0,6,6,0" />
|
||||
<Setter Property="Margin" Value="-1,0,0,0" />
|
||||
</Trigger>
|
||||
<Trigger Property="Glyph" Value="{x:Null}">
|
||||
<Setter TargetName="Glyph" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Content" Property="Margin" Value="0" />
|
||||
</Trigger>
|
||||
<Trigger Property="Content" Value="{x:Null}">
|
||||
<Setter TargetName="Content" Property="Visibility" Value="Collapsed" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.CardHover}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.AccentSubtle}" />
|
||||
<Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="Panel.ZIndex" Value="1" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Opacity" Value="0.4" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- ===================== Split button (Render ▾) ===================== -->
|
||||
<Style x:Key="SplitButton.ArrowPrimary" TargetType="ToggleButton">
|
||||
<Setter Property="Template" Value="{DynamicResource Template.Button}" />
|
||||
<Setter Property="FocusVisualStyle" Value="{DynamicResource Focus.Ring}" />
|
||||
<Setter Property="Background" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.AccentPressed}" />
|
||||
<Setter Property="BorderThickness" Value="1,0,0,0" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.OnAccent}" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
<Setter Property="ui:ControlState.HoverBackground" Value="{DynamicResource Brush.AccentHover}" />
|
||||
<Setter Property="ui:ControlState.HoverBorderBrush" Value="{DynamicResource Brush.AccentPressed}" />
|
||||
<Setter Property="ui:ControlState.PressedBackground" Value="{DynamicResource Brush.AccentPressed}" />
|
||||
</Style>
|
||||
|
||||
<Style TargetType="v:SplitButton">
|
||||
<Setter Property="Height" Value="{StaticResource Height.Control}" />
|
||||
<Setter Property="FontFamily" Value="{StaticResource Font.Ui}" />
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.Body}" />
|
||||
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="v:SplitButton">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Button x:Name="Main" Style="{DynamicResource Button.Base}" Height="{TemplateBinding Height}" ui:ControlState.CornerRadius="6,0,0,6"
|
||||
Content="{TemplateBinding Content}" Command="{TemplateBinding Command}" CommandParameter="{TemplateBinding CommandParameter}"
|
||||
CommandTarget="{TemplateBinding CommandTarget}" />
|
||||
<ToggleButton x:Name="Arrow" Style="{DynamicResource Button.Base}" Height="{TemplateBinding Height}" Width="28" MinWidth="28" Padding="0" Margin="-1,0,0,0"
|
||||
ClickMode="Press" ui:ControlState.CornerRadius="0,6,6,0" ui:ButtonIcon.Glyph="{DynamicResource Icon.ChevronDown}"
|
||||
IsChecked="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" ToolTip="{TemplateBinding DropDownToolTip}" />
|
||||
</StackPanel>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsPrimary" Value="True">
|
||||
<Setter TargetName="Main" Property="Style" Value="{DynamicResource Button.Primary}" />
|
||||
<Setter TargetName="Arrow" Property="Style" Value="{StaticResource SplitButton.ArrowPrimary}" />
|
||||
<Setter TargetName="Arrow" Property="Margin" Value="0" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>Sizes its child to the available width and a height of width ÷ <see cref="Ratio"/> (card thumbnails are 16:9).</summary>
|
||||
public sealed class AspectRatioDecorator : Decorator
|
||||
{
|
||||
public static readonly DependencyProperty RatioProperty = DependencyProperty.Register(
|
||||
nameof(Ratio), typeof(double), typeof(AspectRatioDecorator),
|
||||
new FrameworkPropertyMetadata(16.0 / 9.0, FrameworkPropertyMetadataOptions.AffectsMeasure),
|
||||
v => v is double d && double.IsFinite(d) && d > 0);
|
||||
|
||||
/// <summary>Width ÷ height.</summary>
|
||||
public double Ratio { get => (double)GetValue(RatioProperty); set => SetValue(RatioProperty, value); }
|
||||
|
||||
protected override Size MeasureOverride(Size constraint)
|
||||
{
|
||||
var size = Fit(constraint);
|
||||
Child?.Measure(size);
|
||||
return size;
|
||||
}
|
||||
|
||||
protected override Size ArrangeOverride(Size arrangeSize)
|
||||
{
|
||||
var size = Fit(arrangeSize);
|
||||
Child?.Arrange(new Rect(size));
|
||||
return size;
|
||||
}
|
||||
|
||||
private Size Fit(Size available)
|
||||
{
|
||||
var width = double.IsInfinity(available.Width) ? 0 : available.Width;
|
||||
return new Size(width, width / Ratio);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="MinimumOpacity"/>). Hovering reads out the bar; clicking raises
|
||||
/// <see cref="ItemActivatedEvent"/>.
|
||||
/// </summary>
|
||||
public sealed class BarChart : DrawingElement
|
||||
{
|
||||
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
|
||||
nameof(Items), typeof(IReadOnlyList<ChartItem>), 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<double, string>), 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;
|
||||
|
||||
/// <summary>Bars in display order.</summary>
|
||||
public IReadOnlyList<ChartItem>? Items { get => (IReadOnlyList<ChartItem>?)GetValue(ItemsProperty); set => SetValue(ItemsProperty, value); }
|
||||
|
||||
public Orientation Orientation { get => (Orientation)GetValue(OrientationProperty); set => SetValue(OrientationProperty, value); }
|
||||
|
||||
/// <summary>Theme brush key of the bars (items may override).</summary>
|
||||
public string BrushKey { get => (string)GetValue(BrushKeyProperty); set => SetValue(BrushKeyProperty, value); }
|
||||
|
||||
/// <summary>Opacity of a zero bar; bars ramp linearly to 1 at the maximum (1 = flat colour).</summary>
|
||||
public double MinimumOpacity { get => (double)GetValue(MinimumOpacityProperty); set => SetValue(MinimumOpacityProperty, value); }
|
||||
|
||||
public bool ShowValues { get => (bool)GetValue(ShowValuesProperty); set => SetValue(ShowValuesProperty, value); }
|
||||
|
||||
/// <summary>Value-axis gridlines and tick labels.</summary>
|
||||
public bool ShowGrid { get => (bool)GetValue(ShowGridProperty); set => SetValue(ShowGridProperty, value); }
|
||||
|
||||
/// <summary>Value at full length; NaN = the largest value (or the nice tick above it with the grid on).</summary>
|
||||
public double Maximum { get => (double)GetValue(MaximumProperty); set => SetValue(MaximumProperty, value); }
|
||||
|
||||
/// <summary>Maximum bar thickness in DIPs.</summary>
|
||||
public double BarThickness { get => (double)GetValue(BarThicknessProperty); set => SetValue(BarThicknessProperty, value); }
|
||||
|
||||
/// <summary>Culture-aware value formatting for value labels, ticks and readouts.</summary>
|
||||
public Func<double, string>? ValueFormatter { get => (Func<double, string>?)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<ChartItem> 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<ChartItem> 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<ChartItem> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Gridlines at nice ticks along the value axis, with labels below (horizontal bars) or left (vertical bars).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>Stroke pattern of a series or legend swatch.</summary>
|
||||
public enum LineDash
|
||||
{
|
||||
Solid,
|
||||
|
||||
/// <summary>5–4 dashes (sky region curve).</summary>
|
||||
Dashed,
|
||||
|
||||
/// <summary>2–3 dots.</summary>
|
||||
Dotted,
|
||||
}
|
||||
|
||||
/// <summary>One per-frame line of a <see cref="SeriesChart"/>. Values are indexed by frame; NaN leaves a gap.</summary>
|
||||
public sealed class ChartSeries
|
||||
{
|
||||
public ChartSeries(string? title, ReadOnlyMemory<double> values, string brushKey)
|
||||
{
|
||||
Title = title;
|
||||
Values = values;
|
||||
BrushKey = brushKey;
|
||||
}
|
||||
|
||||
/// <summary>Legend and readout text (localized by the caller).</summary>
|
||||
public string? Title { get; init; }
|
||||
|
||||
public ReadOnlyMemory<double> Values { get; init; }
|
||||
|
||||
/// <summary>Theme brush resource key, e.g. <c>Brush.Sun</c>; re-resolved when the theme changes.</summary>
|
||||
public string BrushKey { get; init; }
|
||||
|
||||
/// <summary>Stroke width in DIPs.</summary>
|
||||
public double Thickness { get; init; } = 1.5;
|
||||
|
||||
public LineDash Dash { get; init; } = LineDash.Solid;
|
||||
|
||||
/// <summary>Whether the automatic legend lists this series.</summary>
|
||||
public bool ShowInLegend { get; init; } = true;
|
||||
}
|
||||
|
||||
/// <summary>Shape drawn before a legend entry.</summary>
|
||||
public enum LegendSwatch
|
||||
{
|
||||
Line,
|
||||
DashedLine,
|
||||
DottedLine,
|
||||
|
||||
/// <summary>▼ (exposure steps).</summary>
|
||||
Triangle,
|
||||
|
||||
/// <summary>◆ (keyframes).</summary>
|
||||
Diamond,
|
||||
|
||||
Square,
|
||||
}
|
||||
|
||||
/// <summary>A legend entry: swatch in a theme brush followed by text.</summary>
|
||||
public sealed record ChartLegendItem(string Text, string BrushKey, LegendSwatch Swatch = LegendSwatch.Line);
|
||||
|
||||
/// <summary>What a timeline marker stands for; the kind fixes its colour and glyph.</summary>
|
||||
public enum MarkerKind
|
||||
{
|
||||
/// <summary>ISO/shutter/aperture step as received: ▼ in Sun.</summary>
|
||||
ExposureStep,
|
||||
|
||||
/// <summary>▼ in Warning.</summary>
|
||||
Warning,
|
||||
|
||||
/// <summary>▼ in Error.</summary>
|
||||
Error,
|
||||
|
||||
/// <summary>Virtual-camera or remap keyframe: ◆ in Accent.</summary>
|
||||
Keyframe,
|
||||
}
|
||||
|
||||
/// <summary>A frame-anchored marker shown above the filmstrip and as a dashed line in series charts.</summary>
|
||||
public readonly record struct TimelineMarker(int Index, MarkerKind Kind, string? Label = null)
|
||||
{
|
||||
/// <summary>Theme brush key of a marker kind.</summary>
|
||||
public static string BrushKeyOf(MarkerKind kind) => kind switch
|
||||
{
|
||||
MarkerKind.ExposureStep => "Brush.Sun",
|
||||
MarkerKind.Warning => "Brush.Warning",
|
||||
MarkerKind.Error => "Brush.Error",
|
||||
_ => "Brush.Accent",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A labelled value of a bar or proportion chart.</summary>
|
||||
/// <param name="Label">Category text (year, camera, format…).</param>
|
||||
/// <param name="Value">Magnitude; negative values draw as zero.</param>
|
||||
/// <param name="ValueText">Formatted value shown next to the bar; null uses the chart formatter.</param>
|
||||
/// <param name="ToolTip">Hover text; null shows label and value.</param>
|
||||
/// <param name="BrushKey">Theme brush key overriding the chart brush.</param>
|
||||
public sealed record ChartItem(string Label, double Value, string? ValueText = null, string? ToolTip = null, string? BrushKey = null);
|
||||
|
||||
/// <summary>A labelled row of values (a heatmap year, a timeline band); NaN marks "no data".</summary>
|
||||
/// <param name="Label">Row text (e.g. the year).</param>
|
||||
/// <param name="Values">One value per column (e.g. 12 months).</param>
|
||||
/// <param name="ToolTips">Optional hover text per column.</param>
|
||||
public sealed record ChartRow(string Label, IReadOnlyList<double> Values, IReadOnlyList<string?>? ToolTips = null);
|
||||
|
||||
/// <summary>Identifies the item a chart interaction refers to.</summary>
|
||||
public sealed class ChartItemEventArgs(RoutedEvent routedEvent, int row, int column) : RoutedEventArgs(routedEvent)
|
||||
{
|
||||
/// <summary>Item index (bars, segments) or row index (heatmap, bands).</summary>
|
||||
public int Row { get; } = row;
|
||||
|
||||
/// <summary>Column index for grids (heatmap month, band slot); −1 for single-index charts.</summary>
|
||||
public int Column { get; } = column;
|
||||
}
|
||||
|
||||
public delegate void ChartItemEventHandler(object sender, ChartItemEventArgs e);
|
||||
@@ -0,0 +1,379 @@
|
||||
using System.Collections.Specialized;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>Editing rules of a <see cref="CurveEditor"/>.</summary>
|
||||
public enum CurveEditMode
|
||||
{
|
||||
/// <summary>Keyframes ordered by time (virtual camera): X stays increasing, the ends may move.</summary>
|
||||
Keyframes,
|
||||
|
||||
/// <summary>Time remap: X stays increasing and the end points are pinned to X = 0 and X = 1.</summary>
|
||||
TimeRemap,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spline/keyframe editor in normalised [0, 1]² space (BRIEF §12.3: Time remap curve, Camera keyframes).
|
||||
/// Control points come from <see cref="Points"/> and are edited in place (double-click adds, drag moves with the
|
||||
/// X order constrained by <see cref="CurveMath"/>, Delete removes, arrows nudge); the curve itself is drawn by
|
||||
/// sampling <see cref="Evaluator"/> once per device-pixel column, so the engine's Fritsch–Carlson spline is what
|
||||
/// the user sees. Grid, optional identity diagonal and a playhead are drawn; hovering or dragging a point reads
|
||||
/// out its coordinates. <see cref="EditCompletedEvent"/> fires after each add, delete, nudge or finished drag.
|
||||
/// </summary>
|
||||
public sealed class CurveEditor : DrawingElement
|
||||
{
|
||||
public static readonly DependencyProperty PointsProperty = DependencyProperty.Register(
|
||||
nameof(Points), typeof(IList<Point>), typeof(CurveEditor), new PropertyMetadata(null, OnDataPropertyChanged));
|
||||
|
||||
public static readonly DependencyProperty EvaluatorProperty = DependencyProperty.Register(
|
||||
nameof(Evaluator), typeof(Func<double, double>), typeof(CurveEditor), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
|
||||
|
||||
public static readonly DependencyProperty ModeProperty = DependencyProperty.Register(
|
||||
nameof(Mode), typeof(CurveEditMode), typeof(CurveEditor), new PropertyMetadata(CurveEditMode.Keyframes));
|
||||
|
||||
public static readonly DependencyProperty SelectedIndexProperty = DependencyProperty.Register(
|
||||
nameof(SelectedIndex), typeof(int), typeof(CurveEditor),
|
||||
new FrameworkPropertyMetadata(-1, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.AffectsRender, null, CoerceSelectedIndex));
|
||||
|
||||
public static readonly DependencyProperty PlayheadPositionProperty = DependencyProperty.Register(
|
||||
nameof(PlayheadPosition), typeof(double), typeof(CurveEditor), new PropertyMetadata(double.NaN, (d, _) => ((CurveEditor)d).RenderOverlay()));
|
||||
|
||||
public static readonly DependencyProperty ShowDiagonalProperty = DependencyProperty.Register(
|
||||
nameof(ShowDiagonal), typeof(bool), typeof(CurveEditor), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
|
||||
|
||||
public static readonly DependencyProperty MinimumGapProperty = DependencyProperty.Register(
|
||||
nameof(MinimumGap), typeof(double), typeof(CurveEditor), new PropertyMetadata(CurveMath.DefaultMinGap));
|
||||
|
||||
public static readonly DependencyProperty XLabelFormatterProperty = DependencyProperty.Register(
|
||||
nameof(XLabelFormatter), typeof(Func<double, string>), typeof(CurveEditor), new PropertyMetadata(null));
|
||||
|
||||
public static readonly DependencyProperty YLabelFormatterProperty = DependencyProperty.Register(
|
||||
nameof(YLabelFormatter), typeof(Func<double, string>), typeof(CurveEditor), new PropertyMetadata(null));
|
||||
|
||||
public static readonly RoutedEvent EditCompletedEvent = EventManager.RegisterRoutedEvent(
|
||||
nameof(EditCompleted), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CurveEditor));
|
||||
|
||||
private const double Inset = 7;
|
||||
private const double PointRadius = 4.5;
|
||||
private const double HitRadius = 8;
|
||||
|
||||
private double[] _xs = [];
|
||||
private double[] _ys = [];
|
||||
private double[] _viewX = [];
|
||||
private double[] _viewY = [];
|
||||
private int _count;
|
||||
private Rect _plot;
|
||||
private int _hover = -1;
|
||||
private bool _dragging;
|
||||
private bool _moved;
|
||||
|
||||
static CurveEditor()
|
||||
{
|
||||
FocusableProperty.OverrideMetadata(typeof(CurveEditor), new FrameworkPropertyMetadata(true));
|
||||
}
|
||||
|
||||
public CurveEditor()
|
||||
: base(hasOverlay: true)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Control points in [0, 1]², ordered by X; edited in place unless the list is read-only.</summary>
|
||||
public IList<Point>? Points { get => (IList<Point>?)GetValue(PointsProperty); set => SetValue(PointsProperty, value); }
|
||||
|
||||
/// <summary>The curve through the points (x → y in [0, 1]); null draws straight segments.</summary>
|
||||
public Func<double, double>? Evaluator { get => (Func<double, double>?)GetValue(EvaluatorProperty); set => SetValue(EvaluatorProperty, value); }
|
||||
|
||||
public CurveEditMode Mode { get => (CurveEditMode)GetValue(ModeProperty); set => SetValue(ModeProperty, value); }
|
||||
|
||||
/// <summary>Selected point (two-way); −1 = none.</summary>
|
||||
public int SelectedIndex { get => (int)GetValue(SelectedIndexProperty); set => SetValue(SelectedIndexProperty, value); }
|
||||
|
||||
/// <summary>Playhead X in [0, 1]; NaN hides it.</summary>
|
||||
public double PlayheadPosition { get => (double)GetValue(PlayheadPositionProperty); set => SetValue(PlayheadPositionProperty, value); }
|
||||
|
||||
/// <summary>Dashed identity line (y = x), the "no remap" reference.</summary>
|
||||
public bool ShowDiagonal { get => (bool)GetValue(ShowDiagonalProperty); set => SetValue(ShowDiagonalProperty, value); }
|
||||
|
||||
/// <summary>Minimum X distance between neighbouring points.</summary>
|
||||
public double MinimumGap { get => (double)GetValue(MinimumGapProperty); set => SetValue(MinimumGapProperty, value); }
|
||||
|
||||
/// <summary>Culture-aware formatting of X in readouts (e.g. output time).</summary>
|
||||
public Func<double, string>? XLabelFormatter { get => (Func<double, string>?)GetValue(XLabelFormatterProperty); set => SetValue(XLabelFormatterProperty, value); }
|
||||
|
||||
/// <summary>Culture-aware formatting of Y in readouts (e.g. source time).</summary>
|
||||
public Func<double, string>? YLabelFormatter { get => (Func<double, string>?)GetValue(YLabelFormatterProperty); set => SetValue(YLabelFormatterProperty, value); }
|
||||
|
||||
public event RoutedEventHandler EditCompleted
|
||||
{
|
||||
add => AddHandler(EditCompletedEvent, value);
|
||||
remove => RemoveHandler(EditCompletedEvent, value);
|
||||
}
|
||||
|
||||
private bool PinEnds => Mode == CurveEditMode.TimeRemap;
|
||||
|
||||
private bool IsEditable => Points is { IsReadOnly: false };
|
||||
|
||||
protected override Size MeasureOverride(Size availableSize) => new(0, 160);
|
||||
|
||||
protected override void OnDataChanged()
|
||||
{
|
||||
var points = Points;
|
||||
_count = points?.Count ?? 0;
|
||||
if (_xs.Length < _count)
|
||||
{
|
||||
_xs = new double[_count];
|
||||
_ys = new double[_count];
|
||||
_viewX = new double[_count];
|
||||
_viewY = new double[_count];
|
||||
}
|
||||
for (var i = 0; i < _count; i++)
|
||||
{
|
||||
_xs[i] = points![i].X;
|
||||
_ys[i] = points[i].Y;
|
||||
}
|
||||
_hover = -1;
|
||||
CoerceValue(SelectedIndexProperty);
|
||||
base.OnDataChanged();
|
||||
}
|
||||
|
||||
protected override void OnRender(DrawingContext dc)
|
||||
{
|
||||
DrawHitArea(dc);
|
||||
_plot = new Rect(Inset, Inset, Math.Max(0, ActualWidth - 2 * Inset), Math.Max(0, ActualHeight - 2 * Inset));
|
||||
if (_plot.Width < 1 || _plot.Height < 1) return;
|
||||
var scale = PixelScale;
|
||||
var grid = GetHairline("Brush.Stroke");
|
||||
for (var i = 0; i <= 4; i++)
|
||||
{
|
||||
var x = PixelGrid.SnapLine(X(i / 4.0), grid.Thickness, scale);
|
||||
var y = PixelGrid.SnapLine(Y(i / 4.0), grid.Thickness, scale);
|
||||
dc.DrawLine(grid, new Point(x, _plot.Top), new Point(x, _plot.Bottom));
|
||||
dc.DrawLine(grid, new Point(_plot.Left, y), new Point(_plot.Right, y));
|
||||
}
|
||||
if (ShowDiagonal) dc.DrawLine(GetPen("Brush.TextFaint", 1, LineDash.Dashed), new Point(X(0), Y(0)), new Point(X(1), Y(1)));
|
||||
|
||||
dc.PushClip(new RectangleGeometry(new Rect(0, 0, ActualWidth, ActualHeight)));
|
||||
DrawCurve(dc, scale);
|
||||
dc.Pop();
|
||||
|
||||
var fill = GetBrush("Brush.Surface");
|
||||
var accent = GetBrush("Brush.Accent");
|
||||
var stroke = GetPen("Brush.Accent", 1.5);
|
||||
for (var i = 0; i < _count; i++)
|
||||
{
|
||||
var selected = i == SelectedIndex;
|
||||
var radius = i == _hover || selected ? PointRadius + 1 : PointRadius;
|
||||
dc.DrawEllipse(selected ? accent : fill, stroke, new Point(X(_xs[i]), Y(_ys[i])), radius, radius);
|
||||
}
|
||||
RenderOverlay();
|
||||
}
|
||||
|
||||
protected override void OnRenderOverlay(DrawingContext dc)
|
||||
{
|
||||
var position = PlayheadPosition;
|
||||
if (!double.IsFinite(position) || _plot.Width < 1) return;
|
||||
var pen = GetHairline("Brush.Accent");
|
||||
var x = PixelGrid.SnapLine(X(Math.Clamp(position, 0, 1)), pen.Thickness, PixelScale);
|
||||
dc.DrawLine(pen, new Point(x, _plot.Top), new Point(x, _plot.Bottom));
|
||||
}
|
||||
|
||||
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
|
||||
{
|
||||
base.OnMouseLeftButtonDown(e);
|
||||
Focus();
|
||||
var p = e.GetPosition(this);
|
||||
var hit = HitTest(p);
|
||||
if (hit >= 0)
|
||||
{
|
||||
SetCurrentValue(SelectedIndexProperty, hit);
|
||||
_moved = false;
|
||||
_dragging = IsEditable && CaptureMouse();
|
||||
}
|
||||
else if (e.ClickCount == 2)
|
||||
{
|
||||
Add(p);
|
||||
}
|
||||
else
|
||||
{
|
||||
SetCurrentValue(SelectedIndexProperty, -1);
|
||||
}
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
protected override void OnMouseMove(MouseEventArgs e)
|
||||
{
|
||||
base.OnMouseMove(e);
|
||||
var p = e.GetPosition(this);
|
||||
if (_dragging && SelectedIndex >= 0)
|
||||
{
|
||||
_moved |= Move(SelectedIndex, ToX(p.X), ToY(p.Y));
|
||||
Readout.Show(ReadoutText(SelectedIndex), p);
|
||||
return;
|
||||
}
|
||||
var hover = HitTest(p);
|
||||
if (hover != _hover)
|
||||
{
|
||||
_hover = hover;
|
||||
InvalidateVisual();
|
||||
}
|
||||
Readout.Show(hover >= 0 ? ReadoutText(hover) : null, p);
|
||||
}
|
||||
|
||||
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
|
||||
{
|
||||
base.OnMouseLeftButtonUp(e);
|
||||
if (_dragging) ReleaseMouseCapture();
|
||||
}
|
||||
|
||||
protected override void OnLostMouseCapture(MouseEventArgs e)
|
||||
{
|
||||
base.OnLostMouseCapture(e);
|
||||
if (!_dragging) return;
|
||||
_dragging = false;
|
||||
if (_moved) RaiseEvent(new RoutedEventArgs(EditCompletedEvent));
|
||||
_moved = false;
|
||||
}
|
||||
|
||||
protected override void OnMouseLeave(MouseEventArgs e)
|
||||
{
|
||||
base.OnMouseLeave(e);
|
||||
if (_dragging) return;
|
||||
Readout.Hide();
|
||||
if (_hover < 0) return;
|
||||
_hover = -1;
|
||||
InvalidateVisual();
|
||||
}
|
||||
|
||||
protected override void OnQueryCursor(QueryCursorEventArgs e)
|
||||
{
|
||||
base.OnQueryCursor(e);
|
||||
if (e.Handled || (!_dragging && _hover < 0)) return;
|
||||
e.Cursor = _dragging ? Cursors.SizeAll : Cursors.Hand;
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
protected override void OnKeyDown(KeyEventArgs e)
|
||||
{
|
||||
base.OnKeyDown(e);
|
||||
var index = SelectedIndex;
|
||||
if (e.Handled || index < 0 || index >= _count || !IsEditable) return;
|
||||
var step = (Keyboard.Modifiers & ModifierKeys.Shift) != 0 ? 0.1 : 0.01;
|
||||
var changed = e.Key switch
|
||||
{
|
||||
Key.Delete or Key.Back => Remove(index),
|
||||
Key.Left => Move(index, _xs[index] - step, _ys[index]),
|
||||
Key.Right => Move(index, _xs[index] + step, _ys[index]),
|
||||
Key.Up => Move(index, _xs[index], _ys[index] + step),
|
||||
Key.Down => Move(index, _xs[index], _ys[index] - step),
|
||||
_ => (bool?)null,
|
||||
};
|
||||
if (changed is null) return;
|
||||
e.Handled = true;
|
||||
if (changed.Value) RaiseEvent(new RoutedEventArgs(EditCompletedEvent));
|
||||
}
|
||||
|
||||
private static object CoerceSelectedIndex(DependencyObject d, object value)
|
||||
{
|
||||
var index = (int)value;
|
||||
return index >= 0 && index < ((CurveEditor)d)._count ? index : -1;
|
||||
}
|
||||
|
||||
private double X(double x) => _plot.Left + x * _plot.Width;
|
||||
|
||||
private double Y(double y) => _plot.Bottom - y * _plot.Height;
|
||||
|
||||
private double ToX(double x) => _plot.Width > 0 ? (x - _plot.Left) / _plot.Width : 0;
|
||||
|
||||
private double ToY(double y) => _plot.Height > 0 ? (_plot.Bottom - y) / _plot.Height : 0;
|
||||
|
||||
private void DrawCurve(DrawingContext dc, double scale)
|
||||
{
|
||||
var evaluator = Evaluator;
|
||||
if (evaluator is null && _count < 2) return;
|
||||
var geometry = new StreamGeometry();
|
||||
using (var ctx = geometry.Open())
|
||||
{
|
||||
if (evaluator is not null)
|
||||
{
|
||||
var columns = Math.Max(2, (int)Math.Ceiling(_plot.Width * scale) + 1);
|
||||
for (var c = 0; c < columns; c++)
|
||||
{
|
||||
var x = c / (double)(columns - 1);
|
||||
var p = new Point(X(x), Y(evaluator(x)));
|
||||
if (c == 0) ctx.BeginFigure(p, false, false);
|
||||
else ctx.LineTo(p, true, true);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ctx.BeginFigure(new Point(X(_xs[0]), Y(_ys[0])), false, false);
|
||||
for (var i = 1; i < _count; i++) ctx.LineTo(new Point(X(_xs[i]), Y(_ys[i])), true, true);
|
||||
}
|
||||
}
|
||||
geometry.Freeze();
|
||||
dc.DrawGeometry(null, GetPen("Brush.Accent", 2), geometry);
|
||||
}
|
||||
|
||||
private int HitTest(Point p)
|
||||
{
|
||||
if (_count == 0 || _plot.Width < 1) return -1;
|
||||
for (var i = 0; i < _count; i++)
|
||||
{
|
||||
_viewX[i] = X(_xs[i]);
|
||||
_viewY[i] = Y(_ys[i]);
|
||||
}
|
||||
return CurveMath.HitTest(_viewX.AsSpan(0, _count), _viewY.AsSpan(0, _count), p.X, p.Y, HitRadius);
|
||||
}
|
||||
|
||||
/// <summary>Moves point <paramref name="index"/> towards (x, y) within the constraints; true when it changed.</summary>
|
||||
private bool Move(int index, double x, double y)
|
||||
{
|
||||
if (Points is not { IsReadOnly: false } points) return false;
|
||||
var cx = CurveMath.ConstrainX(_xs.AsSpan(0, _count), index, x, MinimumGap, PinEnds);
|
||||
var cy = CurveMath.ConstrainY(y);
|
||||
if (cx == _xs[index] && cy == _ys[index]) return false;
|
||||
points[index] = new Point(cx, cy);
|
||||
AfterEdit(points);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Add(Point at)
|
||||
{
|
||||
if (Points is not { IsReadOnly: false } points) return;
|
||||
var x = ToX(at.X);
|
||||
var index = CurveMath.InsertionIndex(_xs.AsSpan(0, _count), x, MinimumGap, PinEnds);
|
||||
if (index < 0) return;
|
||||
points.Insert(index, new Point(x, CurveMath.ConstrainY(ToY(at.Y))));
|
||||
AfterEdit(points);
|
||||
SetCurrentValue(SelectedIndexProperty, index);
|
||||
RaiseEvent(new RoutedEventArgs(EditCompletedEvent));
|
||||
}
|
||||
|
||||
private bool Remove(int index)
|
||||
{
|
||||
if (Points is not { IsReadOnly: false } points || !CurveMath.CanRemove(_count, index, PinEnds)) return false;
|
||||
points.RemoveAt(index);
|
||||
AfterEdit(points);
|
||||
SetCurrentValue(SelectedIndexProperty, Math.Min(index, _count - 1));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Observable lists notify through the collection watcher; plain lists are re-read here.</summary>
|
||||
private void AfterEdit(IList<Point> points)
|
||||
{
|
||||
if (points is not INotifyCollectionChanged) OnDataChanged();
|
||||
}
|
||||
|
||||
private string ReadoutText(int index)
|
||||
{
|
||||
var x = XLabelFormatter ?? DefaultFormat;
|
||||
var y = YLabelFormatter ?? DefaultFormat;
|
||||
return x(_xs[index]) + " → " + y(_ys[index]);
|
||||
}
|
||||
|
||||
private static string DefaultFormat(double value) => value.ToString("0.###", Loc.Culture);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// Editing rules of <see cref="CurveEditor"/> in normalised [0, 1]² space: control points stay ordered by X with
|
||||
/// a minimum gap, optionally with the end points pinned to X = 0 and X = 1 (time remap).
|
||||
/// </summary>
|
||||
public static class CurveMath
|
||||
{
|
||||
/// <summary>Default minimum X distance between two control points.</summary>
|
||||
public const double DefaultMinGap = 0.001;
|
||||
|
||||
/// <summary>
|
||||
/// X the point <paramref name="index"/> may take when dragged to <paramref name="proposedX"/>: strictly between its
|
||||
/// neighbours (by at least <paramref name="minGap"/>), inside [0, 1], and fixed at 0 or 1 for the end points
|
||||
/// when <paramref name="pinEnds"/>.
|
||||
/// </summary>
|
||||
public static double ConstrainX(ReadOnlySpan<double> xs, int index, double proposedX, double minGap, bool pinEnds)
|
||||
{
|
||||
var n = xs.Length;
|
||||
if (index < 0 || index >= n) throw new ArgumentOutOfRangeException(nameof(index));
|
||||
if (pinEnds && n > 1)
|
||||
{
|
||||
if (index == 0) return 0;
|
||||
if (index == n - 1) return 1;
|
||||
}
|
||||
var gap = Math.Max(0, minGap);
|
||||
var low = index > 0 ? xs[index - 1] + gap : 0;
|
||||
var high = index < n - 1 ? xs[index + 1] - gap : 1;
|
||||
low = Math.Max(0, low);
|
||||
high = Math.Min(1, high);
|
||||
if (low > high) return Math.Clamp((low + high) / 2, 0, 1);
|
||||
return Math.Clamp(double.IsNaN(proposedX) ? xs[index] : proposedX, low, high);
|
||||
}
|
||||
|
||||
/// <summary>Clamps a Y value to [0, 1].</summary>
|
||||
public static double ConstrainY(double y) => double.IsNaN(y) ? 0 : Math.Clamp(y, 0, 1);
|
||||
|
||||
/// <summary>
|
||||
/// Index at which a new point at <paramref name="x"/> keeps <paramref name="xs"/> ascending, or −1 when it would
|
||||
/// sit closer than <paramref name="minGap"/> to an existing point, outside [0, 1], or outside the pinned ends.
|
||||
/// </summary>
|
||||
public static int InsertionIndex(ReadOnlySpan<double> xs, double x, double minGap, bool pinEnds)
|
||||
{
|
||||
if (double.IsNaN(x) || x < 0 || x > 1) return -1;
|
||||
var gap = Math.Max(0, minGap);
|
||||
var index = 0;
|
||||
while (index < xs.Length && xs[index] < x) index++;
|
||||
if (index > 0 && x - xs[index - 1] < gap) return -1;
|
||||
if (index < xs.Length && xs[index] - x < gap) return -1;
|
||||
if (pinEnds && xs.Length >= 2 && (index == 0 || index == xs.Length)) return -1;
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <summary>Whether point <paramref name="index"/> may be deleted: two points always remain and pinned ends stay.</summary>
|
||||
public static bool CanRemove(int count, int index, bool pinEnds) =>
|
||||
count > 2 && index >= 0 && index < count && (!pinEnds || (index > 0 && index < count - 1));
|
||||
|
||||
/// <summary>Index of the point nearest to (<paramref name="x"/>, <paramref name="y"/>) within <paramref name="radius"/>, or −1; coordinates in one space.</summary>
|
||||
public static int HitTest(ReadOnlySpan<double> xs, ReadOnlySpan<double> ys, double x, double y, double radius)
|
||||
{
|
||||
var best = -1;
|
||||
var bestDistance = radius * radius;
|
||||
var n = Math.Min(xs.Length, ys.Length);
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var dx = xs[i] - x;
|
||||
var dy = ys[i] - y;
|
||||
var d = dx * dx + dy * dy;
|
||||
if (d <= bestDistance)
|
||||
{
|
||||
bestDistance = d;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="UIElement.OnRender"/>. Time axes and images never mirror, so the element is always left-to-right.
|
||||
/// </summary>
|
||||
public abstract class DrawingElement : FrameworkElement
|
||||
{
|
||||
/// <summary>Follows a token brush; its change signals a theme switch.</summary>
|
||||
private static readonly DependencyProperty ThemeProbeProperty = DependencyProperty.Register(
|
||||
"ThemeProbe", typeof(object), typeof(DrawingElement), new PropertyMetadata(null, OnThemeProbeChanged));
|
||||
|
||||
private readonly Dictionary<string, Brush> _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;
|
||||
|
||||
/// <param name="hasOverlay">Creates the overlay layer drawn by <see cref="OnRenderOverlay"/>.</param>
|
||||
protected DrawingElement(bool hasOverlay = false)
|
||||
{
|
||||
if (hasOverlay)
|
||||
{
|
||||
_overlay = new DrawingVisual();
|
||||
AddVisualChild(_overlay);
|
||||
}
|
||||
FlowDirection = FlowDirection.LeftToRight;
|
||||
SetResourceReference(ThemeProbeProperty, "Brush.Text");
|
||||
Unloaded += (_, _) => _readout?.Hide();
|
||||
}
|
||||
|
||||
/// <summary>Device pixels per DIP on the monitor showing the element.</summary>
|
||||
protected double PixelScale => VisualTreeHelper.GetDpi(this).DpiScaleX;
|
||||
|
||||
/// <summary>Tooltip-styled readout that follows the mouse.</summary>
|
||||
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));
|
||||
|
||||
/// <summary>Frozen theme brush for <paramref name="key"/> (transparent when the key is unknown).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Frozen pen in the theme brush <paramref name="key"/>, cached until the theme or DPI changes.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Uncached frozen pen, for thicknesses that vary continuously (e.g. compensating a zoom).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Pen covering whole device pixels, for gridlines and edges drawn at <see cref="PixelGrid.SnapLine"/> positions.</summary>
|
||||
protected Pen GetHairline(string key, LineDash dash = LineDash.Solid) => GetPen(key, PixelGrid.SnapThickness(1, PixelScale), dash);
|
||||
|
||||
/// <summary>Single-line text in the UI font, laid out for this element's DPI and text formatting mode.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Redraws the overlay layer; call after any change that only affects playhead or hover state.</summary>
|
||||
protected void RenderOverlay()
|
||||
{
|
||||
if (_overlay is null) return;
|
||||
using var dc = _overlay.RenderOpen();
|
||||
if (ActualWidth > 0 && ActualHeight > 0) OnRenderOverlay(dc);
|
||||
}
|
||||
|
||||
/// <summary>Draws the overlay layer (above the static content).</summary>
|
||||
protected virtual void OnRenderOverlay(DrawingContext dc)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Called after the theme brushes changed; the default redraws everything.</summary>
|
||||
protected virtual void OnThemeChanged()
|
||||
{
|
||||
InvalidateVisual();
|
||||
if (_overlay is not null) RenderOverlay();
|
||||
}
|
||||
|
||||
/// <summary>Called when a data property or a watched collection changed; the default re-measures and redraws.</summary>
|
||||
protected virtual void OnDataChanged()
|
||||
{
|
||||
InvalidateMeasure();
|
||||
InvalidateVisual();
|
||||
}
|
||||
|
||||
/// <summary>Property-changed callback for data properties: watches observable collections weakly and calls <see cref="OnDataChanged"/>.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Fills the whole element with a transparent brush so empty areas still receive the mouse.</summary>
|
||||
protected void DrawHitArea(DrawingContext dc) => dc.DrawRectangle(Brushes.Transparent, null, new Rect(RenderSize));
|
||||
|
||||
/// <summary>Adds a ▼ of width <paramref name="size"/> whose top edge is centred at (<paramref name="cx"/>, <paramref name="top"/>).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Adds a ◆ of width <paramref name="size"/> centred at (<paramref name="cx"/>, <paramref name="cy"/>).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Draws legend entries left to right from <paramref name="origin"/> (swatch, 6 px, text in the entry colour,
|
||||
/// 16 px between entries) and stops before <paramref name="maxRight"/>. Returns the right edge reached.
|
||||
/// </summary>
|
||||
protected double DrawLegend(DrawingContext dc, IReadOnlyList<ChartLegendItem> 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;
|
||||
}
|
||||
|
||||
/// <summary>Draws a legend swatch centred in <paramref name="box"/>.</summary>
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Titano.Core.Diagnostics;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// Strip of thumbnails sampled across a sequence (BRIEF §12.3, Editor mockup) with frame markers above it
|
||||
/// (exposure steps ▼ in Sun/Warning, keyframes ◆ in Accent). The cell holding <see cref="CurrentIndex"/> is outlined
|
||||
/// in Accent and an accent ▼ marks the exact frame. Click or drag seeks, the wheel and arrow keys step one frame
|
||||
/// (PageUp/PageDown one cell, Home/End the ends). Thumbnails load asynchronously from <see cref="Source"/> into an
|
||||
/// LRU cache; cells show a placeholder until their image arrives. Hovering a marker reads out its label.
|
||||
/// </summary>
|
||||
public sealed class Filmstrip : DrawingElement
|
||||
{
|
||||
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
|
||||
nameof(Source), typeof(IThumbnailSource), typeof(Filmstrip), new PropertyMetadata(null, OnSourceChanged));
|
||||
|
||||
public static readonly DependencyProperty CurrentIndexProperty = DependencyProperty.Register(
|
||||
nameof(CurrentIndex), typeof(int), typeof(Filmstrip),
|
||||
new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnCurrentIndexChanged, CoerceCurrentIndex));
|
||||
|
||||
public static readonly DependencyProperty MarkersProperty = DependencyProperty.Register(
|
||||
nameof(Markers), typeof(IReadOnlyList<TimelineMarker>), typeof(Filmstrip), new PropertyMetadata(null, OnDataPropertyChanged));
|
||||
|
||||
public static readonly DependencyProperty CellWidthProperty = DependencyProperty.Register(
|
||||
nameof(CellWidth), typeof(double), typeof(Filmstrip),
|
||||
new FrameworkPropertyMetadata(38.0, FrameworkPropertyMetadataOptions.AffectsRender), v => v is double d && d >= 4);
|
||||
|
||||
public static readonly DependencyProperty CacheCapacityProperty = DependencyProperty.Register(
|
||||
nameof(CacheCapacity), typeof(int), typeof(Filmstrip), new PropertyMetadata(256, OnCacheCapacityChanged), v => v is int i && i > 0);
|
||||
|
||||
private const double MarkerRow = 11;
|
||||
private const double Gap = 2;
|
||||
private const double Radius = 4;
|
||||
private const double CellHeight = 44;
|
||||
|
||||
private static readonly MarkerKind[] Kinds = Enum.GetValues<MarkerKind>();
|
||||
|
||||
/// <summary>The current-frame ▼ at x = 0; moved by <see cref="_markerShift"/> so seeking allocates no geometry.</summary>
|
||||
private static readonly Geometry CurrentMarker = CreateCurrentMarker();
|
||||
|
||||
private LruCache<int, CachedFrame> _cache = new(256);
|
||||
private readonly HashSet<int> _pending = [];
|
||||
private CancellationTokenSource _loads = new();
|
||||
private StripLayout _strip;
|
||||
private Rect _cells;
|
||||
private bool _dragging;
|
||||
private int _wheelDelta;
|
||||
private readonly TranslateTransform _markerShift = new();
|
||||
|
||||
static Filmstrip()
|
||||
{
|
||||
FocusableProperty.OverrideMetadata(typeof(Filmstrip), new FrameworkPropertyMetadata(true));
|
||||
CursorProperty.OverrideMetadata(typeof(Filmstrip), new FrameworkPropertyMetadata(Cursors.Hand));
|
||||
}
|
||||
|
||||
public Filmstrip()
|
||||
: base(hasOverlay: true)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Frames of the sequence.</summary>
|
||||
public IThumbnailSource? Source { get => (IThumbnailSource?)GetValue(SourceProperty); set => SetValue(SourceProperty, value); }
|
||||
|
||||
/// <summary>Current frame (two-way): set by clicks, drags, wheel and keys.</summary>
|
||||
public int CurrentIndex { get => (int)GetValue(CurrentIndexProperty); set => SetValue(CurrentIndexProperty, value); }
|
||||
|
||||
/// <summary>Markers drawn above the cells.</summary>
|
||||
public IReadOnlyList<TimelineMarker>? Markers { get => (IReadOnlyList<TimelineMarker>?)GetValue(MarkersProperty); set => SetValue(MarkersProperty, value); }
|
||||
|
||||
/// <summary>Target cell width; the cells stretch to fill the strip exactly.</summary>
|
||||
public double CellWidth { get => (double)GetValue(CellWidthProperty); set => SetValue(CellWidthProperty, value); }
|
||||
|
||||
/// <summary>Decoded thumbnails kept in memory.</summary>
|
||||
public int CacheCapacity { get => (int)GetValue(CacheCapacityProperty); set => SetValue(CacheCapacityProperty, value); }
|
||||
|
||||
private int FrameCount => Source?.Count ?? 0;
|
||||
|
||||
protected override Size MeasureOverride(Size availableSize) => new(0, MarkerRow + 3 + CellHeight);
|
||||
|
||||
protected override void OnRender(DrawingContext dc)
|
||||
{
|
||||
DrawHitArea(dc);
|
||||
var width = ActualWidth;
|
||||
_cells = new Rect(0, MarkerRow + 3, width, Math.Max(0, ActualHeight - MarkerRow - 3));
|
||||
_strip = new StripLayout(width, CellWidth, Gap, FrameCount);
|
||||
if (_strip.CellCount == 0 || _cells.Height <= 0)
|
||||
{
|
||||
dc.DrawRoundedRectangle(GetBrush("Brush.Card"), null, _cells, Radius, Radius);
|
||||
RenderOverlay();
|
||||
return;
|
||||
}
|
||||
|
||||
var scale = PixelScale;
|
||||
// Request enough pixels to cover the cell for frames up to 16:9 (UniformToFill crop).
|
||||
var pixelWidth = (int)Math.Ceiling(Math.Max(_strip.CellWidth, _cells.Height * 16 / 9) * scale);
|
||||
var placeholder = GetBrush("Brush.Card");
|
||||
dc.PushClip(new RectangleGeometry(_cells, Radius, Radius));
|
||||
for (var c = 0; c < _strip.CellCount; c++)
|
||||
{
|
||||
var cell = new Rect(PixelGrid.Snap(_strip.CellLeft(c), scale), _cells.Top, 0, _cells.Height);
|
||||
cell.Width = PixelGrid.Snap(_strip.CellLeft(c) + _strip.CellWidth, scale) - cell.Left;
|
||||
var frame = _strip.FrameForCell(c);
|
||||
if (TryGetFrame(frame, pixelWidth, out var image)) DrawCover(dc, image, cell);
|
||||
else dc.DrawRectangle(placeholder, null, cell);
|
||||
}
|
||||
dc.Pop();
|
||||
DrawMarkers(dc);
|
||||
RenderOverlay();
|
||||
}
|
||||
|
||||
protected override void OnRenderOverlay(DrawingContext dc)
|
||||
{
|
||||
if (_strip.CellCount == 0) return;
|
||||
var frame = Math.Clamp(CurrentIndex, 0, _strip.FrameCount - 1);
|
||||
var cellIndex = _strip.CellForFrame(frame);
|
||||
var scale = PixelScale;
|
||||
var left = PixelGrid.Snap(_strip.CellLeft(cellIndex), scale);
|
||||
var right = PixelGrid.Snap(_strip.CellLeft(cellIndex) + _strip.CellWidth, scale);
|
||||
// 2-px accent outline drawn inside the cell.
|
||||
var outline = new Rect(left + 1, _cells.Top + 1, Math.Max(0, right - left - 2), Math.Max(0, _cells.Height - 2));
|
||||
dc.DrawRectangle(null, GetPen("Brush.Accent", 2), outline);
|
||||
|
||||
_markerShift.X = _strip.XForFrame(frame);
|
||||
dc.PushTransform(_markerShift);
|
||||
dc.DrawGeometry(GetBrush("Brush.Accent"), null, CurrentMarker);
|
||||
dc.Pop();
|
||||
}
|
||||
|
||||
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
|
||||
{
|
||||
base.OnMouseLeftButtonDown(e);
|
||||
if (_strip.FrameCount == 0) return;
|
||||
Focus();
|
||||
_dragging = CaptureMouse();
|
||||
Seek(e.GetPosition(this).X);
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
protected override void OnMouseMove(MouseEventArgs e)
|
||||
{
|
||||
base.OnMouseMove(e);
|
||||
var p = e.GetPosition(this);
|
||||
if (_dragging)
|
||||
{
|
||||
Seek(p.X);
|
||||
Readout.Hide();
|
||||
return;
|
||||
}
|
||||
Readout.Show(p.Y < _cells.Top ? MarkerLabelAt(p.X) : null, 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);
|
||||
Readout.Hide();
|
||||
}
|
||||
|
||||
protected override void OnMouseWheel(MouseWheelEventArgs e)
|
||||
{
|
||||
base.OnMouseWheel(e);
|
||||
if (_strip.FrameCount == 0) return;
|
||||
// Accumulate so precision touchpads step once per notch-equivalent; wheel down moves forward.
|
||||
_wheelDelta += e.Delta;
|
||||
var steps = _wheelDelta / Mouse.MouseWheelDeltaForOneLine;
|
||||
_wheelDelta -= steps * Mouse.MouseWheelDeltaForOneLine;
|
||||
if (steps != 0) SetCurrentValue(CurrentIndexProperty, CurrentIndex - steps);
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
protected override void OnKeyDown(KeyEventArgs e)
|
||||
{
|
||||
base.OnKeyDown(e);
|
||||
var count = FrameCount;
|
||||
if (count == 0) return;
|
||||
var cellFrames = Math.Max(1, count / Math.Max(1, _strip.CellCount));
|
||||
int? target = e.Key switch
|
||||
{
|
||||
Key.Left => CurrentIndex - 1,
|
||||
Key.Right => CurrentIndex + 1,
|
||||
Key.PageUp => CurrentIndex - cellFrames,
|
||||
Key.PageDown => CurrentIndex + cellFrames,
|
||||
Key.Home => 0,
|
||||
Key.End => count - 1,
|
||||
_ => null,
|
||||
};
|
||||
if (target is null) return;
|
||||
SetCurrentValue(CurrentIndexProperty, target.Value);
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
var strip = (Filmstrip)d;
|
||||
strip.ResetCache();
|
||||
strip.CoerceValue(CurrentIndexProperty);
|
||||
strip.InvalidateVisual();
|
||||
}
|
||||
|
||||
private static void OnCurrentIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((Filmstrip)d).RenderOverlay();
|
||||
|
||||
private static object CoerceCurrentIndex(DependencyObject d, object value)
|
||||
{
|
||||
var count = ((Filmstrip)d).FrameCount;
|
||||
return count == 0 ? 0 : Math.Clamp((int)value, 0, count - 1);
|
||||
}
|
||||
|
||||
private static void OnCacheCapacityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) =>
|
||||
((Filmstrip)d)._cache.Capacity = (int)e.NewValue;
|
||||
|
||||
private static StreamGeometry CreateCurrentMarker()
|
||||
{
|
||||
var geometry = new StreamGeometry();
|
||||
using (var ctx = geometry.Open()) AddTriangleDown(ctx, 0, 1, 9);
|
||||
geometry.Freeze();
|
||||
return geometry;
|
||||
}
|
||||
|
||||
/// <summary>Draws <paramref name="image"/> scaled to cover <paramref name="cell"/>, centred and cropped.</summary>
|
||||
private static void DrawCover(DrawingContext dc, ImageSource image, Rect cell)
|
||||
{
|
||||
var w = image.Width;
|
||||
var h = image.Height;
|
||||
if (!(w > 0) || !(h > 0)) return;
|
||||
var s = Math.Max(cell.Width / w, cell.Height / h);
|
||||
var target = new Rect(cell.Left + (cell.Width - w * s) / 2, cell.Top + (cell.Height - h * s) / 2, w * s, h * s);
|
||||
dc.PushClip(new RectangleGeometry(cell));
|
||||
dc.DrawImage(image, target);
|
||||
dc.Pop();
|
||||
}
|
||||
|
||||
private void DrawMarkers(DrawingContext dc)
|
||||
{
|
||||
if (Markers is not { Count: > 0 } markers) return;
|
||||
foreach (var kind in Kinds)
|
||||
{
|
||||
StreamGeometry? geometry = null;
|
||||
StreamGeometryContext? ctx = null;
|
||||
for (var i = 0; i < markers.Count; i++)
|
||||
{
|
||||
var m = markers[i];
|
||||
if (m.Kind != kind || m.Index < 0 || m.Index >= _strip.FrameCount) continue;
|
||||
if (ctx is null)
|
||||
{
|
||||
geometry = new StreamGeometry();
|
||||
ctx = geometry.Open();
|
||||
}
|
||||
var x = _strip.XForFrame(m.Index);
|
||||
if (kind == MarkerKind.Keyframe) AddDiamond(ctx, x, MarkerRow / 2, 8);
|
||||
else AddTriangleDown(ctx, x, 1, 9);
|
||||
}
|
||||
if (ctx is null || geometry is null) continue;
|
||||
ctx.Close();
|
||||
geometry.Freeze();
|
||||
dc.DrawGeometry(GetBrush(TimelineMarker.BrushKeyOf(kind)), null, geometry);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Labels of the markers within 5 px of <paramref name="x"/>, one per line.</summary>
|
||||
private string? MarkerLabelAt(double x)
|
||||
{
|
||||
if (Markers is not { Count: > 0 } markers || _strip.FrameCount == 0) return null;
|
||||
string? text = null;
|
||||
for (var i = 0; i < markers.Count; i++)
|
||||
{
|
||||
var m = markers[i];
|
||||
if (string.IsNullOrEmpty(m.Label) || Math.Abs(_strip.XForFrame(m.Index) - x) > 5) continue;
|
||||
text = text is null ? m.Label : text + Environment.NewLine + m.Label;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
private void Seek(double x)
|
||||
{
|
||||
var frame = _strip.FrameAt(x);
|
||||
if (frame >= 0) SetCurrentValue(CurrentIndexProperty, frame);
|
||||
}
|
||||
|
||||
private bool TryGetFrame(int frame, int pixelWidth, [NotNullWhen(true)] out ImageSource? image)
|
||||
{
|
||||
if (_cache.TryGet(frame, out var cached))
|
||||
{
|
||||
// An image narrower than 80 % of the need (e.g. after a resize) stays on screen while a sharper one loads.
|
||||
if (cached.PixelWidth < pixelWidth * 0.8) Request(frame, pixelWidth);
|
||||
image = cached.Image;
|
||||
return true;
|
||||
}
|
||||
Request(frame, pixelWidth);
|
||||
image = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void Request(int frame, int pixelWidth)
|
||||
{
|
||||
if (Source is not { } source || !_pending.Add(frame)) return;
|
||||
_ = LoadAsync(source, frame, pixelWidth, _loads.Token);
|
||||
}
|
||||
|
||||
private async Task LoadAsync(IThumbnailSource source, int frame, int pixelWidth, CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Requests are issued while rendering; leave the render pass before touching the cache.
|
||||
await Task.Yield();
|
||||
token.ThrowIfCancellationRequested();
|
||||
var image = await source.GetAsync(frame, pixelWidth, token);
|
||||
if (token.IsCancellationRequested || image is null) return;
|
||||
_cache.Set(frame, new CachedFrame(image, pixelWidth));
|
||||
InvalidateVisual();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("ui.filmstrip", $"Thumbnail {frame} failed", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!token.IsCancellationRequested) _pending.Remove(frame);
|
||||
}
|
||||
}
|
||||
|
||||
private void ResetCache()
|
||||
{
|
||||
// Not disposed: loads still in flight may observe the token after this point.
|
||||
_loads.Cancel();
|
||||
_loads = new CancellationTokenSource();
|
||||
_pending.Clear();
|
||||
_cache = new LruCache<int, CachedFrame>(CacheCapacity);
|
||||
}
|
||||
|
||||
private readonly record struct CachedFrame(ImageSource Image, int PixelWidth);
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="CellActivatedEvent"/>.
|
||||
/// </summary>
|
||||
public sealed class HeatmapStrip : DrawingElement
|
||||
{
|
||||
public static readonly DependencyProperty RowsProperty = DependencyProperty.Register(
|
||||
nameof(Rows), typeof(IReadOnlyList<ChartRow>), typeof(HeatmapStrip), new PropertyMetadata(null, OnDataPropertyChanged));
|
||||
|
||||
public static readonly DependencyProperty ColumnLabelsProperty = DependencyProperty.Register(
|
||||
nameof(ColumnLabels), typeof(IReadOnlyList<string>), 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<double, string>), 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;
|
||||
|
||||
/// <summary>One row per year (label + 12 monthly values).</summary>
|
||||
public IReadOnlyList<ChartRow>? Rows { get => (IReadOnlyList<ChartRow>?)GetValue(RowsProperty); set => SetValue(RowsProperty, value); }
|
||||
|
||||
/// <summary>Column headers (culture-aware month initials); also fixes the column count.</summary>
|
||||
public IReadOnlyList<string>? ColumnLabels { get => (IReadOnlyList<string>?)GetValue(ColumnLabelsProperty); set => SetValue(ColumnLabelsProperty, value); }
|
||||
|
||||
public string BrushKey { get => (string)GetValue(BrushKeyProperty); set => SetValue(BrushKeyProperty, value); }
|
||||
|
||||
/// <summary>Value drawn at full opacity; NaN = the largest value.</summary>
|
||||
public double Maximum { get => (double)GetValue(MaximumProperty); set => SetValue(MaximumProperty, value); }
|
||||
|
||||
/// <summary>Opacity of a zero cell.</summary>
|
||||
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); }
|
||||
|
||||
/// <summary>Min–max colour scale under the grid.</summary>
|
||||
public bool ShowScale { get => (bool)GetValue(ShowScaleProperty); set => SetValue(ShowScaleProperty, value); }
|
||||
|
||||
/// <summary>Culture-aware value formatting (scale ends and readouts).</summary>
|
||||
public Func<double, string>? ValueFormatter { get => (Func<double, string>?)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<ChartRow> 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;
|
||||
}
|
||||
|
||||
/// <summary>"min ▭ max" right-aligned under the grid, with a gradient from the zero opacity to full colour.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class HoverReadout(FrameworkElement owner)
|
||||
{
|
||||
private ToolTip? _tip;
|
||||
private object? _savedEnabled;
|
||||
|
||||
public bool IsOpen => _tip?.IsOpen == true;
|
||||
|
||||
/// <summary>Shows <paramref name="text"/> next to <paramref name="position"/> (owner coordinates); empty text hides the readout.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// Frames of a sequence as decoded thumbnails, loaded off the UI thread (filmstrip cells, card hover scrubbing).
|
||||
/// Implementations return frozen images (or images created on the UI thread) and honour cancellation: a request
|
||||
/// is cancelled as soon as the control no longer needs it.
|
||||
/// </summary>
|
||||
public interface IThumbnailSource
|
||||
{
|
||||
/// <summary>Number of frames.</summary>
|
||||
int Count { get; }
|
||||
|
||||
/// <summary>Thumbnail of frame <paramref name="index"/> (0…Count−1) at least <paramref name="pixelWidth"/> device pixels wide; null when unavailable.</summary>
|
||||
ValueTask<ImageSource?> GetAsync(int index, int pixelWidth, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>Fixed-capacity map that evicts the least recently used entry (decoded thumbnails).</summary>
|
||||
public sealed class LruCache<TKey, TValue>
|
||||
where TKey : notnull
|
||||
{
|
||||
private readonly Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> _map;
|
||||
private readonly LinkedList<KeyValuePair<TKey, TValue>> _order = new();
|
||||
private int _capacity;
|
||||
|
||||
public LruCache(int capacity)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1);
|
||||
_capacity = capacity;
|
||||
_map = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(capacity);
|
||||
}
|
||||
|
||||
public int Count => _map.Count;
|
||||
|
||||
/// <summary>Maximum entries; lowering it evicts the oldest entries at once.</summary>
|
||||
public int Capacity
|
||||
{
|
||||
get => _capacity;
|
||||
set
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(value, 1);
|
||||
_capacity = value;
|
||||
Trim();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Looks up <paramref name="key"/> and marks it as the most recently used.</summary>
|
||||
public bool TryGet(TKey key, out TValue value)
|
||||
{
|
||||
if (_map.TryGetValue(key, out var node))
|
||||
{
|
||||
_order.Remove(node);
|
||||
_order.AddFirst(node);
|
||||
value = node.Value.Value;
|
||||
return true;
|
||||
}
|
||||
value = default!;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Inserts or replaces <paramref name="key"/> as the most recently used entry.</summary>
|
||||
public void Set(TKey key, TValue value)
|
||||
{
|
||||
if (_map.TryGetValue(key, out var node))
|
||||
{
|
||||
_order.Remove(node);
|
||||
node.Value = new KeyValuePair<TKey, TValue>(key, value);
|
||||
_order.AddFirst(node);
|
||||
return;
|
||||
}
|
||||
_map[key] = _order.AddFirst(new KeyValuePair<TKey, TValue>(key, value));
|
||||
Trim();
|
||||
}
|
||||
|
||||
public bool Remove(TKey key)
|
||||
{
|
||||
if (!_map.Remove(key, out var node)) return false;
|
||||
_order.Remove(node);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_map.Clear();
|
||||
_order.Clear();
|
||||
}
|
||||
|
||||
private void Trim()
|
||||
{
|
||||
while (_map.Count > _capacity && _order.Last is { } oldest)
|
||||
{
|
||||
_order.RemoveLast();
|
||||
_map.Remove(oldest.Value.Key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// Reduces a long series to at most two samples per pixel column (its minimum and maximum, in index order) so a
|
||||
/// line over 100k+ points draws in time proportional to the plot width while every spike stays visible.
|
||||
/// </summary>
|
||||
public static class MinMaxDecimator
|
||||
{
|
||||
/// <summary>Index written to the output where the line must break (a run without finite samples).</summary>
|
||||
public const int Gap = -1;
|
||||
|
||||
/// <summary>Output capacity needed for <paramref name="count"/> samples over <paramref name="columns"/> columns.</summary>
|
||||
public static int Capacity(int count, int columns) => Math.Max(0, Math.Min(count, 2 * Math.Max(1, columns)));
|
||||
|
||||
/// <summary>
|
||||
/// Writes ascending sample indices to draw into <paramref name="output"/> and returns how many were written.
|
||||
/// When the series has at most two samples per column every finite sample is kept; otherwise each column
|
||||
/// keeps the indices of its minimum and maximum. Non-finite samples are skipped and a run of them (or a
|
||||
/// column without any finite sample) becomes one <see cref="Gap"/> entry.
|
||||
/// </summary>
|
||||
public static int Decimate(ReadOnlySpan<double> values, int columns, Span<int> output)
|
||||
{
|
||||
columns = Math.Max(1, columns);
|
||||
var n = values.Length;
|
||||
if (output.Length < Capacity(n, columns))
|
||||
throw new ArgumentException("Output span is smaller than Capacity(count, columns).", nameof(output));
|
||||
|
||||
var written = 0;
|
||||
if (n <= 2 * columns)
|
||||
{
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
if (double.IsFinite(values[i])) output[written++] = i;
|
||||
else if (written > 0 && output[written - 1] != Gap) output[written++] = Gap;
|
||||
}
|
||||
return Trim(output, written);
|
||||
}
|
||||
|
||||
for (var c = 0; c < columns; c++)
|
||||
{
|
||||
var start = (int)((long)c * n / columns);
|
||||
var end = (int)((long)(c + 1) * n / columns);
|
||||
int minIndex = -1, maxIndex = -1;
|
||||
double min = double.PositiveInfinity, max = double.NegativeInfinity;
|
||||
for (var i = start; i < end; i++)
|
||||
{
|
||||
var v = values[i];
|
||||
if (!double.IsFinite(v)) continue;
|
||||
if (v < min)
|
||||
{
|
||||
min = v;
|
||||
minIndex = i;
|
||||
}
|
||||
if (v > max)
|
||||
{
|
||||
max = v;
|
||||
maxIndex = i;
|
||||
}
|
||||
}
|
||||
if (minIndex < 0)
|
||||
{
|
||||
if (written > 0 && output[written - 1] != Gap) output[written++] = Gap;
|
||||
continue;
|
||||
}
|
||||
if (minIndex == maxIndex)
|
||||
{
|
||||
output[written++] = minIndex;
|
||||
}
|
||||
else
|
||||
{
|
||||
output[written++] = Math.Min(minIndex, maxIndex);
|
||||
output[written++] = Math.Max(minIndex, maxIndex);
|
||||
}
|
||||
}
|
||||
return Trim(output, written);
|
||||
}
|
||||
|
||||
/// <summary>A trailing gap carries no information.</summary>
|
||||
private static int Trim(Span<int> output, int written) => written > 0 && output[written - 1] == Gap ? written - 1 : written;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>Evenly spaced axis ticks: <see cref="First"/>, <see cref="First"/> + <see cref="Step"/>, … up to <see cref="Last"/>.</summary>
|
||||
public readonly record struct AxisTicks(double First, double Last, double Step)
|
||||
{
|
||||
/// <summary>Number of ticks (0 when the scale is empty).</summary>
|
||||
public int Count => Step > 0 && Last >= First ? (int)Math.Round((Last - First) / Step) + 1 : 0;
|
||||
|
||||
/// <summary>Value of tick <paramref name="i"/>, computed from integer multiples of the step to limit drift.</summary>
|
||||
public double this[int i] => (Math.Round(First / Step) + i) * Step;
|
||||
}
|
||||
|
||||
/// <summary>"Nice" numbers for axes (1, 2, 5 × 10ⁿ), padded data ranges and tick placement.</summary>
|
||||
public static class NiceScale
|
||||
{
|
||||
/// <summary>
|
||||
/// Heckbert's nice number: the 1/2/5 × 10ⁿ value closest to <paramref name="value"/> when
|
||||
/// <paramref name="round"/>, otherwise the smallest one that is ≥ <paramref name="value"/>.
|
||||
/// </summary>
|
||||
public static double NiceNumber(double value, bool round)
|
||||
{
|
||||
if (!double.IsFinite(value) || value <= 0) return 1;
|
||||
var exponent = Math.Floor(Math.Log10(value));
|
||||
var magnitude = Math.Pow(10, exponent);
|
||||
var fraction = value / magnitude;
|
||||
double nice;
|
||||
if (round)
|
||||
nice = fraction < 1.5 ? 1 : fraction < 3 ? 2 : fraction < 7 ? 5 : 10;
|
||||
else
|
||||
nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
|
||||
return nice * magnitude;
|
||||
}
|
||||
|
||||
/// <summary>Nice tick step giving at most <paramref name="maxTicks"/> (≥ 2) ticks inside [min, max].</summary>
|
||||
public static double Step(double min, double max, int maxTicks)
|
||||
{
|
||||
var span = max - min;
|
||||
if (!double.IsFinite(span) || span <= 0) return 1;
|
||||
var intervals = Math.Max(2, maxTicks) - 1;
|
||||
var step = NiceNumber(NiceNumber(span, false) / intervals, true);
|
||||
// Rounding the step down can overshoot the budget (e.g. 1/7 → 0.1); climb the 1-2-5 ladder until it fits.
|
||||
while (span / step > intervals + 1e-9) step = NextNice(step);
|
||||
return step;
|
||||
}
|
||||
|
||||
/// <summary>Ticks inside [min, max] (none outside), for gridlines over a fixed data range.</summary>
|
||||
public static AxisTicks Inner(double min, double max, int maxTicks)
|
||||
{
|
||||
if (!double.IsFinite(min) || !double.IsFinite(max) || max <= min) return default;
|
||||
var step = Step(min, max, maxTicks);
|
||||
var first = Math.Ceiling(min / step - 1e-9) * step;
|
||||
var last = Math.Floor(max / step + 1e-9) * step;
|
||||
return last < first ? default : new AxisTicks(first, last, step);
|
||||
}
|
||||
|
||||
/// <summary>Range widened outward to whole steps, for axes that should start and end on a tick (e.g. bars from zero).</summary>
|
||||
public static AxisTicks Outer(double min, double max, int maxTicks)
|
||||
{
|
||||
if (!double.IsFinite(min) || !double.IsFinite(max)) return default;
|
||||
if (max <= min) (min, max) = Expand(min);
|
||||
var step = Step(min, max, maxTicks);
|
||||
return new AxisTicks(Math.Floor(min / step + 1e-9) * step, Math.Ceiling(max / step - 1e-9) * step, step);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Data range padded by <paramref name="fraction"/> of its span on both sides; a flat range is widened around
|
||||
/// its value so the line sits in the middle.
|
||||
/// </summary>
|
||||
public static (double Min, double Max) Pad(double min, double max, double fraction)
|
||||
{
|
||||
if (!double.IsFinite(min) || !double.IsFinite(max)) return (0, 1);
|
||||
if (max < min) (min, max) = (max, min);
|
||||
if (max == min) return Expand(min);
|
||||
var pad = (max - min) * Math.Max(0, fraction);
|
||||
return (min - pad, max + pad);
|
||||
}
|
||||
|
||||
/// <summary>The next value of the 1-2-5 ladder above <paramref name="step"/>.</summary>
|
||||
private static double NextNice(double step)
|
||||
{
|
||||
var magnitude = Math.Pow(10, Math.Floor(Math.Log10(step)));
|
||||
var fraction = step / magnitude;
|
||||
return (fraction < 1.5 ? 2 : fraction < 3.5 ? 5 : 10) * magnitude;
|
||||
}
|
||||
|
||||
private static (double Min, double Max) Expand(double v)
|
||||
{
|
||||
var half = v == 0 ? 1 : Math.Abs(v) * 0.1;
|
||||
return (v - half, v + half);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>Device-pixel alignment for drawn lines and edges (<c>scale</c> = device pixels per DIP).</summary>
|
||||
public static class PixelGrid
|
||||
{
|
||||
/// <summary>Rounds <paramref name="value"/> to the nearest device-pixel boundary.</summary>
|
||||
public static double Snap(double value, double scale)
|
||||
{
|
||||
if (!(scale > 0) || !double.IsFinite(value)) return value;
|
||||
return Math.Round(value * scale) / scale;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Position of the centre of a line <paramref name="thickness"/> DIPs wide drawn at <paramref name="value"/> so it
|
||||
/// covers whole device pixels: odd pixel widths sit on pixel centres, even ones on pixel boundaries.
|
||||
/// </summary>
|
||||
public static double SnapLine(double value, double thickness, double scale)
|
||||
{
|
||||
if (!(scale > 0) || !double.IsFinite(value)) return value;
|
||||
var pixels = Math.Max(1, Math.Round(thickness * scale));
|
||||
var device = value * scale;
|
||||
var snapped = pixels % 2 == 1 ? Math.Floor(device) + 0.5 : Math.Round(device);
|
||||
return snapped / scale;
|
||||
}
|
||||
|
||||
/// <summary>Line thickness in DIPs that renders as whole device pixels (at least one).</summary>
|
||||
public static double SnapThickness(double thickness, double scale)
|
||||
{
|
||||
if (!(scale > 0)) return thickness;
|
||||
return Math.Max(1, Math.Round(thickness * scale)) / scale;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// Drawing surface of <see cref="PreviewViewport"/> (its <c>PART_Surface</c>). The corrected image, the original
|
||||
/// (clipped left of the wipe) and the overlays are retained visuals in image coordinates sharing one
|
||||
/// <see cref="MatrixTransform"/>, so panning and zooming only update a matrix; overlays are rebuilt when the zoom
|
||||
/// changes (to keep strokes and arrowheads a constant on-screen size) or their data changes. The wipe divider
|
||||
/// and its label live in a screen-space layer on top.
|
||||
/// </summary>
|
||||
public sealed class PreviewSurface : DrawingElement
|
||||
{
|
||||
public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(
|
||||
nameof(CornerRadius), typeof(double), typeof(PreviewSurface), new PropertyMetadata(8.0, (d, _) => ((PreviewSurface)d).UpdateClip()));
|
||||
|
||||
private const double LabelSize = 11;
|
||||
|
||||
private readonly VisualCollection _layers;
|
||||
private readonly DrawingVisual _corrected = new();
|
||||
private readonly DrawingVisual _original = new();
|
||||
private readonly ContainerVisual _originalHost = new();
|
||||
private readonly DrawingVisual _overlay = new();
|
||||
private readonly DrawingVisual _chrome = new();
|
||||
private readonly MatrixTransform _view = new();
|
||||
private readonly RectangleGeometry _wipeClip = new();
|
||||
private Size _imageSize = Size.Empty;
|
||||
private double _overlayScale;
|
||||
private double _zoom;
|
||||
|
||||
public PreviewSurface()
|
||||
{
|
||||
_corrected.Transform = _view;
|
||||
_original.Transform = _view;
|
||||
_overlay.Transform = _view;
|
||||
_originalHost.Clip = _wipeClip;
|
||||
_originalHost.Children.Add(_original);
|
||||
_layers = new VisualCollection(this) { _corrected, _originalHost, _overlay, _chrome };
|
||||
}
|
||||
|
||||
/// <summary>Radius of the rounded clip of the whole surface.</summary>
|
||||
public double CornerRadius { get => (double)GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); }
|
||||
|
||||
/// <summary>Viewport whose properties drive the layers.</summary>
|
||||
internal PreviewViewport? Owner { get; set; }
|
||||
|
||||
// The base constructor sets an inherited property, which may enumerate children before _layers exists.
|
||||
protected override int VisualChildrenCount => _layers is null ? 0 : _layers.Count;
|
||||
|
||||
protected override Visual GetVisualChild(int index) => _layers[index];
|
||||
|
||||
/// <summary>Redraws both images over the image rectangle [0, size].</summary>
|
||||
internal void SetImages(ImageSource? corrected, ImageSource? original, Size imageSize)
|
||||
{
|
||||
_imageSize = imageSize;
|
||||
var rect = imageSize.IsEmpty ? Rect.Empty : new Rect(imageSize);
|
||||
using (var dc = _corrected.RenderOpen())
|
||||
if (corrected is not null && !rect.IsEmpty) dc.DrawImage(corrected, rect);
|
||||
using (var dc = _original.RenderOpen())
|
||||
if (original is not null && !rect.IsEmpty) dc.DrawImage(original, rect);
|
||||
RefreshOverlay();
|
||||
RefreshChrome();
|
||||
}
|
||||
|
||||
/// <summary>Applies the image-to-view transform; <paramref name="zoom"/> is device pixels per image pixel.</summary>
|
||||
internal void SetView(ViewTransform view, double zoom)
|
||||
{
|
||||
_view.Matrix = new Matrix(view.Scale, 0, 0, view.Scale, view.OffsetX, view.OffsetY);
|
||||
if (zoom != _zoom)
|
||||
{
|
||||
_zoom = zoom;
|
||||
// Raw pixels from 1:1 up; filtered when shrinking.
|
||||
var mode = zoom >= 1 ? BitmapScalingMode.NearestNeighbor : BitmapScalingMode.HighQuality;
|
||||
RenderOptions.SetBitmapScalingMode(_corrected, mode);
|
||||
RenderOptions.SetBitmapScalingMode(_original, mode);
|
||||
}
|
||||
if (view.Scale != _overlayScale) RefreshOverlay();
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds the overlays (crop mask, region boundary, motion vectors) in image coordinates.</summary>
|
||||
internal void RefreshOverlay()
|
||||
{
|
||||
_overlayScale = _view.Matrix.M11;
|
||||
using var dc = _overlay.RenderOpen();
|
||||
if (Owner is not { } owner || _imageSize.IsEmpty || !(_overlayScale > 0)) return;
|
||||
var unit = 1 / _overlayScale;
|
||||
if (owner.ShowCropMask) DrawCropMask(dc, owner, unit);
|
||||
if (owner.ShowRegions && owner.RegionBoundary is { Count: > 1 } boundary) DrawRegion(dc, boundary, unit);
|
||||
if (owner.ShowVectors && owner.MotionVectors is { Count: > 0 } vectors) DrawVectors(dc, vectors, owner.VectorScale, unit);
|
||||
}
|
||||
|
||||
/// <summary>Redraws the wipe divider and label.</summary>
|
||||
internal void RefreshChrome()
|
||||
{
|
||||
UpdateWipeClip();
|
||||
using var dc = _chrome.RenderOpen();
|
||||
if (Owner is not { } owner || !IsWipeVisible(owner)) return;
|
||||
var scale = PixelScale;
|
||||
var x = PixelGrid.Snap(owner.WipePosition * ActualWidth, scale);
|
||||
dc.DrawRectangle(GetBrush("Brush.Text"), null, new Rect(x - 1, 0, 2, ActualHeight));
|
||||
if (string.IsNullOrEmpty(owner.WipeLabel)) return;
|
||||
var label = CreateText(owner.WipeLabel, LabelSize, GetBrush("Brush.Text"));
|
||||
var pill = new Rect(x - label.Width / 2 - 8, 12, label.Width + 16, label.Height + 6);
|
||||
pill.X = Math.Clamp(pill.X, 4, Math.Max(4, ActualWidth - pill.Width - 4));
|
||||
dc.PushOpacity(0.85);
|
||||
dc.DrawRoundedRectangle(GetBrush("Brush.Chrome"), null, pill, 4, 4);
|
||||
dc.Pop();
|
||||
dc.DrawText(label, new Point(pill.X + 8, pill.Y + 3));
|
||||
}
|
||||
|
||||
protected override void OnRender(DrawingContext dc) => DrawHitArea(dc);
|
||||
|
||||
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
|
||||
{
|
||||
base.OnRenderSizeChanged(sizeInfo);
|
||||
UpdateClip();
|
||||
RefreshChrome();
|
||||
}
|
||||
|
||||
protected override void OnThemeChanged()
|
||||
{
|
||||
base.OnThemeChanged();
|
||||
RefreshOverlay();
|
||||
RefreshChrome();
|
||||
}
|
||||
|
||||
private static bool IsWipeVisible(PreviewViewport owner) => owner.IsCompareEnabled && owner.OriginalSource is not null;
|
||||
|
||||
private void UpdateClip() => Clip = new RectangleGeometry(new Rect(RenderSize), CornerRadius, CornerRadius);
|
||||
|
||||
private void UpdateWipeClip()
|
||||
{
|
||||
var visible = Owner is { } owner && IsWipeVisible(owner);
|
||||
_wipeClip.Rect = visible ? new Rect(0, 0, Math.Max(0, Owner!.WipePosition * ActualWidth), Math.Max(0, ActualHeight)) : Rect.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Everything outside the crop: dimmed with the scrim ("what I lose") or hidden ("how it will look").</summary>
|
||||
private void DrawCropMask(DrawingContext dc, PreviewViewport owner, double unit)
|
||||
{
|
||||
var image = new Rect(_imageSize);
|
||||
var n = owner.CropRect;
|
||||
var crop = Rect.Intersect(image, new Rect(n.X * image.Width, n.Y * image.Height, n.Width * image.Width, n.Height * image.Height));
|
||||
if (crop.IsEmpty) crop = new Rect(image.TopLeft, new Size(0, 0));
|
||||
var outside = new CombinedGeometry(GeometryCombineMode.Exclude, new RectangleGeometry(image), new RectangleGeometry(crop));
|
||||
outside.Freeze();
|
||||
var loss = owner.CropMaskMode == CropMaskMode.ShowLoss;
|
||||
dc.DrawGeometry(loss ? GetBrush("Brush.Scrim") : owner.Background ?? GetBrush("Brush.Preview"), null, outside);
|
||||
if (loss && !crop.IsEmpty) dc.DrawRectangle(null, CreatePen("Brush.TextMuted", unit), crop);
|
||||
}
|
||||
|
||||
private void DrawRegion(DrawingContext dc, IReadOnlyList<Point> boundary, double unit)
|
||||
{
|
||||
var geometry = new StreamGeometry();
|
||||
using (var ctx = geometry.Open())
|
||||
{
|
||||
ctx.BeginFigure(boundary[0], false, false);
|
||||
for (var i = 1; i < boundary.Count; i++) ctx.LineTo(boundary[i], true, true);
|
||||
}
|
||||
geometry.Freeze();
|
||||
dc.DrawGeometry(null, CreatePen("Brush.Region", 1.5 * unit), geometry);
|
||||
}
|
||||
|
||||
/// <summary>Arrows from each sample along its (scaled) displacement; heads stay 5 px on screen.</summary>
|
||||
private void DrawVectors(DrawingContext dc, IReadOnlyList<MotionVector> vectors, double gain, double unit)
|
||||
{
|
||||
var head = 5 * unit;
|
||||
var geometry = new StreamGeometry();
|
||||
using (var ctx = geometry.Open())
|
||||
{
|
||||
for (var i = 0; i < vectors.Count; i++)
|
||||
{
|
||||
var v = vectors[i];
|
||||
var dx = v.Dx * gain;
|
||||
var dy = v.Dy * gain;
|
||||
var length = Math.Sqrt(dx * dx + dy * dy);
|
||||
if (!(length >= unit)) continue;
|
||||
var start = new Point(v.X, v.Y);
|
||||
var end = new Point(v.X + dx, v.Y + dy);
|
||||
ctx.BeginFigure(start, false, false);
|
||||
ctx.LineTo(end, true, false);
|
||||
// Arrowhead: two strokes at ±25° from the reversed direction.
|
||||
var ux = dx / length;
|
||||
var uy = dy / length;
|
||||
const double cos = 0.906, sin = 0.423;
|
||||
var h = Math.Min(head, length * 0.6);
|
||||
ctx.BeginFigure(new Point(end.X - h * (ux * cos - uy * sin), end.Y - h * (uy * cos + ux * sin)), false, false);
|
||||
ctx.LineTo(end, true, true);
|
||||
ctx.LineTo(new Point(end.X - h * (ux * cos + uy * sin), end.Y - h * (uy * cos - ux * sin)), true, true);
|
||||
}
|
||||
}
|
||||
geometry.Freeze();
|
||||
dc.DrawGeometry(null, CreatePen("Brush.Accent", 1.25 * unit), geometry);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>How the preview scales the image.</summary>
|
||||
public enum PreviewZoomMode
|
||||
{
|
||||
/// <summary>The whole image fits the view, centred; follows resizes.</summary>
|
||||
Fit,
|
||||
|
||||
/// <summary>One image pixel per device pixel (raw pixels, no interpolation).</summary>
|
||||
Actual,
|
||||
|
||||
/// <summary>Set by the wheel or by <see cref="PreviewViewport.Zoom"/>.</summary>
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// <summary>What the crop mask shows outside the crop rectangle.</summary>
|
||||
public enum CropMaskMode
|
||||
{
|
||||
/// <summary>"What I lose": the outside is dimmed with the scrim.</summary>
|
||||
ShowLoss,
|
||||
|
||||
/// <summary>"How it will look": the outside is hidden.</summary>
|
||||
ShowResult,
|
||||
}
|
||||
|
||||
/// <summary>A motion-field sample in image pixels: origin (X, Y) and displacement (Dx, Dy).</summary>
|
||||
public readonly record struct MotionVector(float X, float Y, float Dx, float Dy);
|
||||
|
||||
/// <summary>
|
||||
/// Editor preview (BRIEF §12.3): the corrected image with an optional original shown left of a draggable wipe
|
||||
/// divider (label from <see cref="WipeLabel"/>), zoom to fit / 1:1 (raw pixels) / wheel zoom around the cursor,
|
||||
/// pan by dragging, and overlays in image coordinates: motion vectors (Accent arrows), region boundary (Region
|
||||
/// polyline) and a crop mask (normalised <see cref="CropRect"/>; dims or hides what the output loses). Tools go
|
||||
/// bottom-left (<see cref="ToolsContent"/>), the shot data pill bottom-right (<see cref="InfoText"/>). Images and
|
||||
/// overlays are retained visuals under one shared transform, so panning re-renders nothing. Double-click toggles
|
||||
/// Fit and 1:1; Ctrl+0 fits, Ctrl+1 shows 1:1.
|
||||
/// </summary>
|
||||
[TemplatePart(Name = PartSurface, Type = typeof(FrameworkElement))]
|
||||
public class PreviewViewport : Control
|
||||
{
|
||||
public const string PartSurface = "PART_Surface";
|
||||
|
||||
public static readonly RoutedCommand FitCommand = new(nameof(FitCommand), typeof(PreviewViewport), [new KeyGesture(Key.D0, ModifierKeys.Control)]);
|
||||
public static readonly RoutedCommand ActualSizeCommand = new(nameof(ActualSizeCommand), typeof(PreviewViewport), [new KeyGesture(Key.D1, ModifierKeys.Control)]);
|
||||
|
||||
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
|
||||
nameof(Source), typeof(ImageSource), typeof(PreviewViewport), new PropertyMetadata(null, OnImagesChanged));
|
||||
|
||||
public static readonly DependencyProperty OriginalSourceProperty = DependencyProperty.Register(
|
||||
nameof(OriginalSource), typeof(ImageSource), typeof(PreviewViewport), new PropertyMetadata(null, OnImagesChanged));
|
||||
|
||||
public static readonly DependencyProperty IsCompareEnabledProperty = DependencyProperty.Register(
|
||||
nameof(IsCompareEnabled), typeof(bool), typeof(PreviewViewport), new PropertyMetadata(false, OnChromeChanged));
|
||||
|
||||
public static readonly DependencyProperty WipePositionProperty = DependencyProperty.Register(
|
||||
nameof(WipePosition), typeof(double), typeof(PreviewViewport),
|
||||
new FrameworkPropertyMetadata(0.5, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnChromeChanged, CoerceUnit));
|
||||
|
||||
public static readonly DependencyProperty WipeLabelProperty = DependencyProperty.Register(
|
||||
nameof(WipeLabel), typeof(string), typeof(PreviewViewport), new PropertyMetadata(null, OnChromeChanged));
|
||||
|
||||
public static readonly DependencyProperty ZoomModeProperty = DependencyProperty.Register(
|
||||
nameof(ZoomMode), typeof(PreviewZoomMode), typeof(PreviewViewport),
|
||||
new FrameworkPropertyMetadata(PreviewZoomMode.Fit, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnZoomModeChanged));
|
||||
|
||||
public static readonly DependencyProperty ZoomProperty = DependencyProperty.Register(
|
||||
nameof(Zoom), typeof(double), typeof(PreviewViewport),
|
||||
new FrameworkPropertyMetadata(1.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnZoomChanged, CoerceZoom));
|
||||
|
||||
public static readonly DependencyProperty ShowVectorsProperty = DependencyProperty.Register(
|
||||
nameof(ShowVectors), typeof(bool), typeof(PreviewViewport), new PropertyMetadata(false, OnOverlayChanged));
|
||||
|
||||
public static readonly DependencyProperty MotionVectorsProperty = DependencyProperty.Register(
|
||||
nameof(MotionVectors), typeof(IReadOnlyList<MotionVector>), typeof(PreviewViewport), new PropertyMetadata(null, OnOverlayChanged));
|
||||
|
||||
public static readonly DependencyProperty VectorScaleProperty = DependencyProperty.Register(
|
||||
nameof(VectorScale), typeof(double), typeof(PreviewViewport), new PropertyMetadata(1.0, OnOverlayChanged));
|
||||
|
||||
public static readonly DependencyProperty ShowRegionsProperty = DependencyProperty.Register(
|
||||
nameof(ShowRegions), typeof(bool), typeof(PreviewViewport), new PropertyMetadata(false, OnOverlayChanged));
|
||||
|
||||
public static readonly DependencyProperty RegionBoundaryProperty = DependencyProperty.Register(
|
||||
nameof(RegionBoundary), typeof(IReadOnlyList<Point>), typeof(PreviewViewport), new PropertyMetadata(null, OnOverlayChanged));
|
||||
|
||||
public static readonly DependencyProperty ShowCropMaskProperty = DependencyProperty.Register(
|
||||
nameof(ShowCropMask), typeof(bool), typeof(PreviewViewport), new PropertyMetadata(false, OnOverlayChanged));
|
||||
|
||||
public static readonly DependencyProperty CropRectProperty = DependencyProperty.Register(
|
||||
nameof(CropRect), typeof(Rect), typeof(PreviewViewport), new PropertyMetadata(new Rect(0, 0, 1, 1), OnOverlayChanged));
|
||||
|
||||
public static readonly DependencyProperty CropMaskModeProperty = DependencyProperty.Register(
|
||||
nameof(CropMaskMode), typeof(CropMaskMode), typeof(PreviewViewport), new PropertyMetadata(CropMaskMode.ShowLoss, OnOverlayChanged));
|
||||
|
||||
public static readonly DependencyProperty InfoTextProperty = DependencyProperty.Register(nameof(InfoText), typeof(string), typeof(PreviewViewport));
|
||||
|
||||
public static readonly DependencyProperty ToolsContentProperty = DependencyProperty.Register(nameof(ToolsContent), typeof(object), typeof(PreviewViewport));
|
||||
|
||||
private const double MinZoom = 0.01;
|
||||
private const double MaxZoom = 32;
|
||||
private const double DividerGrip = 6;
|
||||
|
||||
private PreviewSurface? _surface;
|
||||
private ViewTransform _view = new(1, 0, 0);
|
||||
private Size _imageSize = Size.Empty;
|
||||
private bool _syncingZoom;
|
||||
private DragMode _drag;
|
||||
private Point _dragStart;
|
||||
private ViewTransform _dragOrigin;
|
||||
|
||||
static PreviewViewport()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(PreviewViewport), new FrameworkPropertyMetadata(typeof(PreviewViewport)));
|
||||
FocusableProperty.OverrideMetadata(typeof(PreviewViewport), new FrameworkPropertyMetadata(true));
|
||||
}
|
||||
|
||||
public PreviewViewport()
|
||||
{
|
||||
CommandBindings.Add(new CommandBinding(FitCommand, (_, _) => SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Fit)));
|
||||
CommandBindings.Add(new CommandBinding(ActualSizeCommand, (_, _) => SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Actual)));
|
||||
}
|
||||
|
||||
private enum DragMode
|
||||
{
|
||||
None,
|
||||
Pan,
|
||||
Wipe,
|
||||
}
|
||||
|
||||
/// <summary>Corrected image (the output look).</summary>
|
||||
public ImageSource? Source { get => (ImageSource?)GetValue(SourceProperty); set => SetValue(SourceProperty, value); }
|
||||
|
||||
/// <summary>Original image for the wipe compare; drawn over the same area as <see cref="Source"/>.</summary>
|
||||
public ImageSource? OriginalSource { get => (ImageSource?)GetValue(OriginalSourceProperty); set => SetValue(OriginalSourceProperty, value); }
|
||||
|
||||
/// <summary>Shows the original left of the wipe divider.</summary>
|
||||
public bool IsCompareEnabled { get => (bool)GetValue(IsCompareEnabledProperty); set => SetValue(IsCompareEnabledProperty, value); }
|
||||
|
||||
/// <summary>Divider position as a fraction of the view width (two-way).</summary>
|
||||
public double WipePosition { get => (double)GetValue(WipePositionProperty); set => SetValue(WipePositionProperty, value); }
|
||||
|
||||
/// <summary>Label centred on the divider ("original | corrected").</summary>
|
||||
public string? WipeLabel { get => (string?)GetValue(WipeLabelProperty); set => SetValue(WipeLabelProperty, value); }
|
||||
|
||||
public PreviewZoomMode ZoomMode { get => (PreviewZoomMode)GetValue(ZoomModeProperty); set => SetValue(ZoomModeProperty, value); }
|
||||
|
||||
/// <summary>Device pixels per image pixel (1 = 1:1). Setting it switches to <see cref="PreviewZoomMode.Custom"/>.</summary>
|
||||
public double Zoom { get => (double)GetValue(ZoomProperty); set => SetValue(ZoomProperty, value); }
|
||||
|
||||
public bool ShowVectors { get => (bool)GetValue(ShowVectorsProperty); set => SetValue(ShowVectorsProperty, value); }
|
||||
|
||||
/// <summary>Motion field in image pixels.</summary>
|
||||
public IReadOnlyList<MotionVector>? MotionVectors { get => (IReadOnlyList<MotionVector>?)GetValue(MotionVectorsProperty); set => SetValue(MotionVectorsProperty, value); }
|
||||
|
||||
/// <summary>Gain applied to vector lengths so sub-pixel motion stays visible.</summary>
|
||||
public double VectorScale { get => (double)GetValue(VectorScaleProperty); set => SetValue(VectorScaleProperty, value); }
|
||||
|
||||
public bool ShowRegions { get => (bool)GetValue(ShowRegionsProperty); set => SetValue(ShowRegionsProperty, value); }
|
||||
|
||||
/// <summary>Sky/landscape boundary as a polyline in image pixels.</summary>
|
||||
public IReadOnlyList<Point>? RegionBoundary { get => (IReadOnlyList<Point>?)GetValue(RegionBoundaryProperty); set => SetValue(RegionBoundaryProperty, value); }
|
||||
|
||||
public bool ShowCropMask { get => (bool)GetValue(ShowCropMaskProperty); set => SetValue(ShowCropMaskProperty, value); }
|
||||
|
||||
/// <summary>Output crop in normalised image coordinates (0…1).</summary>
|
||||
public Rect CropRect { get => (Rect)GetValue(CropRectProperty); set => SetValue(CropRectProperty, value); }
|
||||
|
||||
public CropMaskMode CropMaskMode { get => (CropMaskMode)GetValue(CropMaskModeProperty); set => SetValue(CropMaskModeProperty, value); }
|
||||
|
||||
/// <summary>Shot data shown in the bottom-right pill.</summary>
|
||||
public string? InfoText { get => (string?)GetValue(InfoTextProperty); set => SetValue(InfoTextProperty, value); }
|
||||
|
||||
/// <summary>Tool buttons shown bottom-left over the image.</summary>
|
||||
public object? ToolsContent { get => GetValue(ToolsContentProperty); set => SetValue(ToolsContentProperty, value); }
|
||||
|
||||
/// <summary>Current image-to-view transform in DIPs (for hit testing overlays from outside).</summary>
|
||||
public ViewTransform View => _view;
|
||||
|
||||
/// <summary>Size of <see cref="Source"/> in image pixels.</summary>
|
||||
public Size ImageSize => _imageSize;
|
||||
|
||||
private Size ViewSize => _surface?.RenderSize ?? Size.Empty;
|
||||
|
||||
private double PixelScale => VisualTreeHelper.GetDpi(this).DpiScaleX;
|
||||
|
||||
public override void OnApplyTemplate()
|
||||
{
|
||||
if (_surface is not null) _surface.SizeChanged -= OnSurfaceSizeChanged;
|
||||
base.OnApplyTemplate();
|
||||
_surface = GetTemplateChild(PartSurface) as PreviewSurface;
|
||||
if (_surface is null) return;
|
||||
_surface.Owner = this;
|
||||
_surface.SizeChanged += OnSurfaceSizeChanged;
|
||||
_surface.SetImages(Source, OriginalSource, _imageSize);
|
||||
ApplyZoomMode();
|
||||
}
|
||||
|
||||
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
|
||||
{
|
||||
base.OnMouseLeftButtonDown(e);
|
||||
if (e.Handled || _surface is null) return;
|
||||
Focus();
|
||||
var p = e.GetPosition(_surface);
|
||||
if (e.ClickCount == 2)
|
||||
{
|
||||
ToggleZoom(p);
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
_drag = IsNearDivider(p) ? DragMode.Wipe : DragMode.Pan;
|
||||
_dragStart = p;
|
||||
_dragOrigin = _view;
|
||||
if (!CaptureMouse()) _drag = DragMode.None;
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
protected override void OnMouseMove(MouseEventArgs e)
|
||||
{
|
||||
base.OnMouseMove(e);
|
||||
if (_drag == DragMode.None || _surface is null) return;
|
||||
var p = e.GetPosition(_surface);
|
||||
if (_drag == DragMode.Wipe)
|
||||
{
|
||||
var width = ViewSize.Width;
|
||||
if (width > 0) SetCurrentValue(WipePositionProperty, p.X / width);
|
||||
return;
|
||||
}
|
||||
UpdateView(ViewportMath.Clamp(ViewportMath.Pan(_dragOrigin, p.X - _dragStart.X, p.Y - _dragStart.Y),
|
||||
_imageSize.Width, _imageSize.Height, ViewSize.Width, ViewSize.Height));
|
||||
}
|
||||
|
||||
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
|
||||
{
|
||||
base.OnMouseLeftButtonUp(e);
|
||||
if (_drag != DragMode.None) ReleaseMouseCapture();
|
||||
}
|
||||
|
||||
protected override void OnLostMouseCapture(MouseEventArgs e)
|
||||
{
|
||||
base.OnLostMouseCapture(e);
|
||||
_drag = DragMode.None;
|
||||
}
|
||||
|
||||
protected override void OnMouseWheel(MouseWheelEventArgs e)
|
||||
{
|
||||
base.OnMouseWheel(e);
|
||||
if (e.Handled || _surface is null || _imageSize.IsEmpty) return;
|
||||
var p = e.GetPosition(_surface);
|
||||
var dpi = PixelScale;
|
||||
var scale = ViewportMath.WheelZoom(_view.Scale, e.Delta / (double)Mouse.MouseWheelDeltaForOneLine, MinZoom / dpi, MaxZoom / dpi);
|
||||
SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Custom);
|
||||
UpdateView(ViewportMath.Clamp(ViewportMath.ZoomAt(_view, scale, p.X, p.Y), _imageSize.Width, _imageSize.Height, ViewSize.Width, ViewSize.Height));
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
protected override void OnQueryCursor(QueryCursorEventArgs e)
|
||||
{
|
||||
base.OnQueryCursor(e);
|
||||
if (e.Handled || _surface is null || !ReferenceEquals(e.OriginalSource, _surface)) return;
|
||||
var p = e.GetPosition(_surface);
|
||||
if (_drag == DragMode.Wipe || IsNearDivider(p)) e.Cursor = Cursors.SizeWE;
|
||||
else if (IsPannable()) e.Cursor = Cursors.SizeAll;
|
||||
else return;
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
protected override void OnDpiChanged(DpiScale oldDpi, DpiScale newDpi)
|
||||
{
|
||||
base.OnDpiChanged(oldDpi, newDpi);
|
||||
ApplyZoomMode();
|
||||
}
|
||||
|
||||
private static object CoerceUnit(DependencyObject d, object value) => double.IsNaN((double)value) ? 0.5 : Math.Clamp((double)value, 0, 1);
|
||||
|
||||
private static object CoerceZoom(DependencyObject d, object value) =>
|
||||
double.IsFinite((double)value) ? Math.Clamp((double)value, MinZoom, MaxZoom) : 1.0;
|
||||
|
||||
private static void OnImagesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
var viewport = (PreviewViewport)d;
|
||||
var size = PixelSize(viewport.Source);
|
||||
var resized = size != viewport._imageSize;
|
||||
viewport._imageSize = size;
|
||||
viewport._surface?.SetImages(viewport.Source, viewport.OriginalSource, size);
|
||||
// Same-size frames (scrubbing) keep zoom and pan; a new size refits or re-clamps.
|
||||
if (resized) viewport.ApplyZoomMode();
|
||||
}
|
||||
|
||||
private static void OnChromeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PreviewViewport)d)._surface?.RefreshChrome();
|
||||
|
||||
private static void OnOverlayChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PreviewViewport)d)._surface?.RefreshOverlay();
|
||||
|
||||
private static void OnZoomModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PreviewViewport)d).ApplyZoomMode();
|
||||
|
||||
private static void OnZoomChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
var viewport = (PreviewViewport)d;
|
||||
if (viewport._syncingZoom || viewport._imageSize.IsEmpty) return;
|
||||
viewport.SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Custom);
|
||||
var size = viewport.ViewSize;
|
||||
var scale = (double)e.NewValue / viewport.PixelScale;
|
||||
viewport.UpdateView(ViewportMath.Clamp(ViewportMath.ZoomAt(viewport._view, scale, size.Width / 2, size.Height / 2),
|
||||
viewport._imageSize.Width, viewport._imageSize.Height, size.Width, size.Height));
|
||||
}
|
||||
|
||||
private static Size PixelSize(ImageSource? source) => source switch
|
||||
{
|
||||
null => Size.Empty,
|
||||
BitmapSource bitmap => new Size(bitmap.PixelWidth, bitmap.PixelHeight),
|
||||
_ => new Size(source.Width, source.Height),
|
||||
};
|
||||
|
||||
private void OnSurfaceSizeChanged(object sender, SizeChangedEventArgs e)
|
||||
{
|
||||
ApplyZoomMode();
|
||||
_surface?.RefreshChrome();
|
||||
}
|
||||
|
||||
private void ApplyZoomMode()
|
||||
{
|
||||
var view = ViewSize;
|
||||
if (_surface is null || _imageSize.IsEmpty || view.Width <= 0 || view.Height <= 0) return;
|
||||
var (w, h) = (_imageSize.Width, _imageSize.Height);
|
||||
switch (ZoomMode)
|
||||
{
|
||||
case PreviewZoomMode.Fit:
|
||||
UpdateView(ViewportMath.Centered(ViewportMath.FitScale(w, h, view.Width, view.Height), w, h, view.Width, view.Height));
|
||||
break;
|
||||
case PreviewZoomMode.Actual:
|
||||
var actual = 1 / PixelScale;
|
||||
var start = _view.Scale > 0 ? _view : ViewportMath.Centered(actual, w, h, view.Width, view.Height);
|
||||
UpdateView(ViewportMath.Clamp(ViewportMath.ZoomAt(start, actual, view.Width / 2, view.Height / 2), w, h, view.Width, view.Height));
|
||||
break;
|
||||
default:
|
||||
UpdateView(ViewportMath.Clamp(_view, w, h, view.Width, view.Height));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void ToggleZoom(Point at)
|
||||
{
|
||||
if (_imageSize.IsEmpty) return;
|
||||
if (ZoomMode == PreviewZoomMode.Actual)
|
||||
{
|
||||
SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Fit);
|
||||
return;
|
||||
}
|
||||
// 1:1 centred on the double-clicked point.
|
||||
var view = ViewSize;
|
||||
var zoomed = ViewportMath.ZoomAt(_view, 1 / PixelScale, at.X, at.Y);
|
||||
_view = ViewportMath.Pan(zoomed, view.Width / 2 - at.X, view.Height / 2 - at.Y);
|
||||
SetCurrentValue(ZoomModeProperty, PreviewZoomMode.Actual);
|
||||
}
|
||||
|
||||
private void UpdateView(ViewTransform view)
|
||||
{
|
||||
var dpi = PixelScale;
|
||||
if (ZoomMode == PreviewZoomMode.Actual) view = ViewportMath.SnapOffset(view, dpi);
|
||||
_view = view;
|
||||
_surface?.SetView(view, view.Scale * dpi);
|
||||
var zoom = view.Scale * dpi;
|
||||
if (zoom == Zoom) return;
|
||||
_syncingZoom = true;
|
||||
try
|
||||
{
|
||||
SetCurrentValue(ZoomProperty, zoom);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_syncingZoom = false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsNearDivider(Point p) =>
|
||||
IsCompareEnabled && OriginalSource is not null && Math.Abs(p.X - WipePosition * ViewSize.Width) <= DividerGrip;
|
||||
|
||||
private bool IsPannable()
|
||||
{
|
||||
var view = ViewSize;
|
||||
return !_imageSize.IsEmpty && (_imageSize.Width * _view.Scale > view.Width + 0.5 || _imageSize.Height * _view.Scale > view.Height + 0.5);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.Collections.Specialized;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using Titano.Ui.Controls;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>Where a segment sits in its group; decides which corners are rounded.</summary>
|
||||
public enum SegmentPosition
|
||||
{
|
||||
Only,
|
||||
First,
|
||||
Middle,
|
||||
Last,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Grouped buttons with one shared border and a single selected segment in Accent (Library toolbar view
|
||||
/// switcher: grid / list / timeline). A single-selection list: bind <see cref="Selector.SelectedIndex"/> or
|
||||
/// <see cref="Selector.SelectedValue"/> (with <see cref="Selector.SelectedValuePath"/> = Tag). Left/Right move the
|
||||
/// selection; the group is one tab stop.
|
||||
/// </summary>
|
||||
public class SegmentedControl : ListBox
|
||||
{
|
||||
static SegmentedControl()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(SegmentedControl), new FrameworkPropertyMetadata(typeof(SegmentedControl)));
|
||||
SelectionModeProperty.OverrideMetadata(typeof(SegmentedControl), new FrameworkPropertyMetadata(SelectionMode.Single));
|
||||
KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(SegmentedControl), new FrameworkPropertyMetadata(KeyboardNavigationMode.Once));
|
||||
}
|
||||
|
||||
protected override DependencyObject GetContainerForItemOverride() => new SegmentedItem();
|
||||
|
||||
protected override bool IsItemItsOwnContainerOverride(object item) => item is SegmentedItem;
|
||||
|
||||
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
|
||||
{
|
||||
base.PrepareContainerForItemOverride(element, item);
|
||||
if (element is SegmentedItem segment) segment.Position = PositionOf(ItemContainerGenerator.IndexFromContainer(element), Items.Count);
|
||||
}
|
||||
|
||||
protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
base.OnItemsChanged(e);
|
||||
for (var i = 0; i < Items.Count; i++)
|
||||
if (ItemContainerGenerator.ContainerFromIndex(i) is SegmentedItem segment) segment.Position = PositionOf(i, Items.Count);
|
||||
}
|
||||
|
||||
private static SegmentPosition PositionOf(int index, int count) =>
|
||||
count <= 1 ? SegmentPosition.Only : index <= 0 ? SegmentPosition.First : index >= count - 1 ? SegmentPosition.Last : SegmentPosition.Middle;
|
||||
}
|
||||
|
||||
/// <summary>One segment: an icon (<see cref="Glyph"/>) and/or content; give it a ToolTip and an automation name.</summary>
|
||||
public class SegmentedItem : ListBoxItem
|
||||
{
|
||||
public static readonly DependencyProperty GlyphProperty = DependencyProperty.Register(nameof(Glyph), typeof(IconData), typeof(SegmentedItem));
|
||||
|
||||
private static readonly DependencyPropertyKey PositionKey = DependencyProperty.RegisterReadOnly(
|
||||
nameof(Position), typeof(SegmentPosition), typeof(SegmentedItem), new PropertyMetadata(SegmentPosition.Only));
|
||||
|
||||
public static readonly DependencyProperty PositionProperty = PositionKey.DependencyProperty;
|
||||
|
||||
static SegmentedItem()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(SegmentedItem), new FrameworkPropertyMetadata(typeof(SegmentedItem)));
|
||||
}
|
||||
|
||||
public IconData? Glyph { get => (IconData?)GetValue(GlyphProperty); set => SetValue(GlyphProperty, value); }
|
||||
|
||||
/// <summary>Place in the group, maintained by <see cref="SegmentedControl"/>.</summary>
|
||||
public SegmentPosition Position { get => (SegmentPosition)GetValue(PositionProperty); internal set => SetValue(PositionKey, value); }
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
using System.Collections;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Ui.Controls;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>One entry of a card's status row: glyph in the status colour, optional text (a count) and tooltip.</summary>
|
||||
public sealed record CardStatus(StatusKind Kind, string? Text = null, string? ToolTip = null);
|
||||
|
||||
/// <summary>
|
||||
/// Library card (DESIGN §4 Cards): 236 px wide, 16:9 thumbnail with a count badge top-right and a selection check
|
||||
/// box top-left (shown on hover or when selected), title, secondary line and status glyph row. Selected = accent
|
||||
/// border with an AccentSelected glow. Moving the mouse across the thumbnail scrubs through the sequence: the
|
||||
/// horizontal position picks a frame of <see cref="ScrubSource"/>, which is loaded asynchronously; stale requests
|
||||
/// are cancelled and the last frame stays until the next one arrives.
|
||||
/// </summary>
|
||||
[TemplatePart(Name = PartThumbnail, Type = typeof(FrameworkElement))]
|
||||
public class SequenceCard : Control
|
||||
{
|
||||
public const string PartThumbnail = "PART_Thumbnail";
|
||||
|
||||
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register(nameof(Title), typeof(string), typeof(SequenceCard));
|
||||
public static readonly DependencyProperty SubtitleProperty = DependencyProperty.Register(nameof(Subtitle), typeof(string), typeof(SequenceCard));
|
||||
public static readonly DependencyProperty BadgeProperty = DependencyProperty.Register(nameof(Badge), typeof(string), typeof(SequenceCard));
|
||||
public static readonly DependencyProperty StatusesProperty = DependencyProperty.Register(nameof(Statuses), typeof(IEnumerable), typeof(SequenceCard));
|
||||
public static readonly DependencyProperty SelectToolTipProperty = DependencyProperty.Register(nameof(SelectToolTip), typeof(object), typeof(SequenceCard));
|
||||
public static readonly DependencyProperty ActionsContentProperty = DependencyProperty.Register(nameof(ActionsContent), typeof(object), typeof(SequenceCard));
|
||||
|
||||
public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register(
|
||||
nameof(IsSelected), typeof(bool), typeof(SequenceCard),
|
||||
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
|
||||
|
||||
public static readonly DependencyProperty ThumbnailProperty = DependencyProperty.Register(
|
||||
nameof(Thumbnail), typeof(ImageSource), typeof(SequenceCard), new PropertyMetadata(null, OnThumbnailChanged));
|
||||
|
||||
public static readonly DependencyProperty ScrubSourceProperty = DependencyProperty.Register(
|
||||
nameof(ScrubSource), typeof(IThumbnailSource), typeof(SequenceCard), new PropertyMetadata(null, OnScrubSourceChanged));
|
||||
|
||||
private static readonly DependencyPropertyKey DisplayedThumbnailKey = DependencyProperty.RegisterReadOnly(
|
||||
nameof(DisplayedThumbnail), typeof(ImageSource), typeof(SequenceCard), new PropertyMetadata(null));
|
||||
|
||||
private static readonly DependencyPropertyKey IsScrubbingKey = DependencyProperty.RegisterReadOnly(
|
||||
nameof(IsScrubbing), typeof(bool), typeof(SequenceCard), new PropertyMetadata(false));
|
||||
|
||||
private static readonly DependencyPropertyKey ScrubPositionKey = DependencyProperty.RegisterReadOnly(
|
||||
nameof(ScrubPosition), typeof(double), typeof(SequenceCard), new PropertyMetadata(0.0));
|
||||
|
||||
public static readonly DependencyProperty DisplayedThumbnailProperty = DisplayedThumbnailKey.DependencyProperty;
|
||||
public static readonly DependencyProperty IsScrubbingProperty = IsScrubbingKey.DependencyProperty;
|
||||
public static readonly DependencyProperty ScrubPositionProperty = ScrubPositionKey.DependencyProperty;
|
||||
|
||||
private FrameworkElement? _thumbnailPart;
|
||||
private CancellationTokenSource? _scrubCancellation;
|
||||
private int _scrubIndex = -1;
|
||||
|
||||
static SequenceCard()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(SequenceCard), new FrameworkPropertyMetadata(typeof(SequenceCard)));
|
||||
}
|
||||
|
||||
public SequenceCard()
|
||||
{
|
||||
DataContextChanged += (_, _) => StopScrub();
|
||||
}
|
||||
|
||||
/// <summary>User title or "{date} {camera}".</summary>
|
||||
public string? Title { get => (string?)GetValue(TitleProperty); set => SetValue(TitleProperty, value); }
|
||||
|
||||
/// <summary>Secondary line: count · camera · span.</summary>
|
||||
public string? Subtitle { get => (string?)GetValue(SubtitleProperty); set => SetValue(SubtitleProperty, value); }
|
||||
|
||||
/// <summary>Count badge text (top-right of the thumbnail); hidden when empty.</summary>
|
||||
public string? Badge { get => (string?)GetValue(BadgeProperty); set => SetValue(BadgeProperty, value); }
|
||||
|
||||
/// <summary><see cref="CardStatus"/> entries of the status row.</summary>
|
||||
public IEnumerable? Statuses { get => (IEnumerable?)GetValue(StatusesProperty); set => SetValue(StatusesProperty, value); }
|
||||
|
||||
/// <summary>Tooltip of the selection check box.</summary>
|
||||
public object? SelectToolTip { get => GetValue(SelectToolTipProperty); set => SetValue(SelectToolTipProperty, value); }
|
||||
|
||||
/// <summary>Quick actions shown bottom-right of the thumbnail on hover (Open, Analyse, Render, Sync).</summary>
|
||||
public object? ActionsContent { get => GetValue(ActionsContentProperty); set => SetValue(ActionsContentProperty, value); }
|
||||
|
||||
/// <summary>Selection state; bind two-way to the container's IsSelected so the check box toggles it.</summary>
|
||||
public bool IsSelected { get => (bool)GetValue(IsSelectedProperty); set => SetValue(IsSelectedProperty, value); }
|
||||
|
||||
/// <summary>Hero thumbnail; may arrive later (asynchronous loading), a placeholder shows until then.</summary>
|
||||
public ImageSource? Thumbnail { get => (ImageSource?)GetValue(ThumbnailProperty); set => SetValue(ThumbnailProperty, value); }
|
||||
|
||||
/// <summary>Frames for hover scrubbing; null disables scrubbing.</summary>
|
||||
public IThumbnailSource? ScrubSource { get => (IThumbnailSource?)GetValue(ScrubSourceProperty); set => SetValue(ScrubSourceProperty, value); }
|
||||
|
||||
/// <summary>Image on screen: the scrubbed frame while scrubbing, otherwise <see cref="Thumbnail"/>.</summary>
|
||||
public ImageSource? DisplayedThumbnail { get => (ImageSource?)GetValue(DisplayedThumbnailProperty); private set => SetValue(DisplayedThumbnailKey, value); }
|
||||
|
||||
/// <summary>True while the mouse scrubs over the thumbnail.</summary>
|
||||
public bool IsScrubbing { get => (bool)GetValue(IsScrubbingProperty); private set => SetValue(IsScrubbingKey, value); }
|
||||
|
||||
/// <summary>Scrubbed position 0…1 along the sequence (drives the progress hairline).</summary>
|
||||
public double ScrubPosition { get => (double)GetValue(ScrubPositionProperty); private set => SetValue(ScrubPositionKey, value); }
|
||||
|
||||
public override void OnApplyTemplate()
|
||||
{
|
||||
base.OnApplyTemplate();
|
||||
_thumbnailPart = GetTemplateChild(PartThumbnail) as FrameworkElement;
|
||||
}
|
||||
|
||||
protected override void OnMouseMove(MouseEventArgs e)
|
||||
{
|
||||
base.OnMouseMove(e);
|
||||
if (ScrubSource is not { Count: > 0 } source || _thumbnailPart is not { ActualWidth: > 0 } part)
|
||||
{
|
||||
StopScrub();
|
||||
return;
|
||||
}
|
||||
var p = e.GetPosition(part);
|
||||
if (p.X < 0 || p.Y < 0 || p.X >= part.ActualWidth || p.Y >= part.ActualHeight)
|
||||
{
|
||||
StopScrub();
|
||||
return;
|
||||
}
|
||||
var count = source.Count;
|
||||
var index = Math.Clamp((int)(p.X / part.ActualWidth * count), 0, count - 1);
|
||||
IsScrubbing = true;
|
||||
ScrubPosition = (index + 1.0) / count;
|
||||
if (index == _scrubIndex) return;
|
||||
_scrubIndex = index;
|
||||
var pixelWidth = (int)Math.Ceiling(part.ActualWidth * VisualTreeHelper.GetDpi(this).DpiScaleX);
|
||||
_ = LoadScrubFrameAsync(source, index, pixelWidth);
|
||||
}
|
||||
|
||||
protected override void OnMouseLeave(MouseEventArgs e)
|
||||
{
|
||||
base.OnMouseLeave(e);
|
||||
StopScrub();
|
||||
}
|
||||
|
||||
private static void OnThumbnailChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
var card = (SequenceCard)d;
|
||||
if (!card.IsScrubbing) card.DisplayedThumbnail = (ImageSource?)e.NewValue;
|
||||
}
|
||||
|
||||
private static void OnScrubSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((SequenceCard)d).StopScrub();
|
||||
|
||||
private async Task LoadScrubFrameAsync(IThumbnailSource source, int index, int pixelWidth)
|
||||
{
|
||||
_scrubCancellation?.Cancel();
|
||||
var cancellation = new CancellationTokenSource();
|
||||
_scrubCancellation = cancellation;
|
||||
try
|
||||
{
|
||||
// Continues on the UI thread: the result is applied only if this is still the frame under the mouse.
|
||||
var image = await source.GetAsync(index, pixelWidth, cancellation.Token);
|
||||
if (!cancellation.IsCancellationRequested && index == _scrubIndex && image is not null) DisplayedThumbnail = image;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("ui.card", $"Scrub frame {index} failed", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (ReferenceEquals(_scrubCancellation, cancellation)) _scrubCancellation = null;
|
||||
cancellation.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private void StopScrub()
|
||||
{
|
||||
_scrubCancellation?.Cancel();
|
||||
_scrubCancellation = null;
|
||||
_scrubIndex = -1;
|
||||
if (!IsScrubbing) return;
|
||||
IsScrubbing = false;
|
||||
ScrubPosition = 0;
|
||||
DisplayedThumbnail = Thumbnail;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="Legend"/>, plus a right-aligned
|
||||
/// <see cref="Summary"/>), 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
|
||||
/// <see cref="CurrentIndex"/>; 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
|
||||
/// <see cref="YMinimum"/>/<see cref="YMaximum"/> are set.
|
||||
/// </summary>
|
||||
public sealed class SeriesChart : DrawingElement
|
||||
{
|
||||
public static readonly DependencyProperty SeriesProperty = DependencyProperty.Register(
|
||||
nameof(Series), typeof(IReadOnlyList<ChartSeries>), typeof(SeriesChart), new PropertyMetadata(null, OnDataPropertyChanged));
|
||||
|
||||
public static readonly DependencyProperty MarkersProperty = DependencyProperty.Register(
|
||||
nameof(Markers), typeof(IReadOnlyList<TimelineMarker>), typeof(SeriesChart), new PropertyMetadata(null, OnDataPropertyChanged));
|
||||
|
||||
public static readonly DependencyProperty LegendProperty = DependencyProperty.Register(
|
||||
nameof(Legend), typeof(IReadOnlyList<ChartLegendItem>), 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<double, string>), typeof(SeriesChart), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
|
||||
|
||||
public static readonly DependencyProperty XLabelFormatterProperty = DependencyProperty.Register(
|
||||
nameof(XLabelFormatter), typeof(Func<double, string>), 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)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Lines to draw; replace the list (or use an observable collection) to update.</summary>
|
||||
public IReadOnlyList<ChartSeries>? Series { get => (IReadOnlyList<ChartSeries>?)GetValue(SeriesProperty); set => SetValue(SeriesProperty, value); }
|
||||
|
||||
/// <summary>Frame markers drawn as dashed vertical lines in the marker colour.</summary>
|
||||
public IReadOnlyList<TimelineMarker>? Markers { get => (IReadOnlyList<TimelineMarker>?)GetValue(MarkersProperty); set => SetValue(MarkersProperty, value); }
|
||||
|
||||
/// <summary>Explicit legend entries; null lists the titled series.</summary>
|
||||
public IReadOnlyList<ChartLegendItem>? Legend { get => (IReadOnlyList<ChartLegendItem>?)GetValue(LegendProperty); set => SetValue(LegendProperty, value); }
|
||||
|
||||
/// <summary>Right-aligned text of the legend row (e.g. "flicker −67 % · max step 0.21 EV").</summary>
|
||||
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); }
|
||||
|
||||
/// <summary>Playhead frame (two-way); −1 hides it.</summary>
|
||||
public int CurrentIndex { get => (int)GetValue(CurrentIndexProperty); set => SetValue(CurrentIndexProperty, value); }
|
||||
|
||||
/// <summary>Whether clicking or dragging sets <see cref="CurrentIndex"/>.</summary>
|
||||
public bool IsSeekEnabled { get => (bool)GetValue(IsSeekEnabledProperty); set => SetValue(IsSeekEnabledProperty, value); }
|
||||
|
||||
/// <summary>Fixed bottom of the Y axis; NaN = automatic.</summary>
|
||||
public double YMinimum { get => (double)GetValue(YMinimumProperty); set => SetValue(YMinimumProperty, value); }
|
||||
|
||||
/// <summary>Fixed top of the Y axis; NaN = automatic.</summary>
|
||||
public double YMaximum { get => (double)GetValue(YMaximumProperty); set => SetValue(YMaximumProperty, value); }
|
||||
|
||||
/// <summary>Fraction of the data span added above and below an automatic range.</summary>
|
||||
public double YPadding { get => (double)GetValue(YPaddingProperty); set => SetValue(YPaddingProperty, value); }
|
||||
|
||||
/// <summary>Culture-aware formatting of values (axis labels and readout).</summary>
|
||||
public Func<double, string>? YLabelFormatter { get => (Func<double, string>?)GetValue(YLabelFormatterProperty); set => SetValue(YLabelFormatterProperty, value); }
|
||||
|
||||
/// <summary>Formatting of frame indices (readout header and, when set, X axis labels).</summary>
|
||||
public Func<double, string>? XLabelFormatter { get => (Func<double, string>?)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);
|
||||
}
|
||||
|
||||
/// <summary>Draws the legend row and returns the plot top.</summary>
|
||||
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<ChartLegendItem> AutoLegend()
|
||||
{
|
||||
var items = new List<ChartLegendItem>();
|
||||
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<double, string> 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using System.Collections;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// Main action on the left, a ▾ part on the right that drops down a menu of choices (Editor: "Render · preset ▾").
|
||||
/// The main part executes <see cref="Command"/>; choosing a menu entry sets <see cref="SelectedItem"/> (checked in
|
||||
/// the menu) — bind <see cref="CommandParameter"/> to it to act on the chosen preset. The control's ToolTip
|
||||
/// describes the main action, <see cref="DropDownToolTip"/> the ▾ part. F4 or Alt+Down opens the menu.
|
||||
/// <see cref="IsPrimary"/> gives the accent look of the screen's primary button.
|
||||
/// </summary>
|
||||
public class SplitButton : Control
|
||||
{
|
||||
public static readonly DependencyProperty ContentProperty = DependencyProperty.Register(nameof(Content), typeof(object), typeof(SplitButton));
|
||||
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(SplitButton));
|
||||
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register(nameof(CommandParameter), typeof(object), typeof(SplitButton));
|
||||
public static readonly DependencyProperty CommandTargetProperty = DependencyProperty.Register(nameof(CommandTarget), typeof(IInputElement), typeof(SplitButton));
|
||||
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(nameof(ItemsSource), typeof(IEnumerable), typeof(SplitButton));
|
||||
public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register(nameof(ItemTemplate), typeof(DataTemplate), typeof(SplitButton));
|
||||
public static readonly DependencyProperty ItemContainerStyleProperty = DependencyProperty.Register(nameof(ItemContainerStyle), typeof(Style), typeof(SplitButton));
|
||||
public static readonly DependencyProperty DisplayMemberPathProperty = DependencyProperty.Register(nameof(DisplayMemberPath), typeof(string), typeof(SplitButton));
|
||||
public static readonly DependencyProperty DropDownToolTipProperty = DependencyProperty.Register(nameof(DropDownToolTip), typeof(object), typeof(SplitButton));
|
||||
public static readonly DependencyProperty IsPrimaryProperty = DependencyProperty.Register(nameof(IsPrimary), typeof(bool), typeof(SplitButton));
|
||||
|
||||
public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(
|
||||
nameof(SelectedItem), typeof(object), typeof(SplitButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
|
||||
|
||||
public static readonly DependencyProperty IsDropDownOpenProperty = DependencyProperty.Register(
|
||||
nameof(IsDropDownOpen), typeof(bool), typeof(SplitButton),
|
||||
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsDropDownOpenChanged));
|
||||
|
||||
private ContextMenu? _menu;
|
||||
|
||||
static SplitButton()
|
||||
{
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(SplitButton), new FrameworkPropertyMetadata(typeof(SplitButton)));
|
||||
FocusableProperty.OverrideMetadata(typeof(SplitButton), new FrameworkPropertyMetadata(false));
|
||||
}
|
||||
|
||||
/// <summary>Content of the main part (e.g. "Render · 4K 10-bit HEVC").</summary>
|
||||
public object? Content { get => GetValue(ContentProperty); set => SetValue(ContentProperty, value); }
|
||||
|
||||
public ICommand? Command { get => (ICommand?)GetValue(CommandProperty); set => SetValue(CommandProperty, value); }
|
||||
|
||||
public object? CommandParameter { get => GetValue(CommandParameterProperty); set => SetValue(CommandParameterProperty, value); }
|
||||
|
||||
public IInputElement? CommandTarget { get => (IInputElement?)GetValue(CommandTargetProperty); set => SetValue(CommandTargetProperty, value); }
|
||||
|
||||
/// <summary>Choices listed in the drop-down menu.</summary>
|
||||
public IEnumerable? ItemsSource { get => (IEnumerable?)GetValue(ItemsSourceProperty); set => SetValue(ItemsSourceProperty, value); }
|
||||
|
||||
public DataTemplate? ItemTemplate { get => (DataTemplate?)GetValue(ItemTemplateProperty); set => SetValue(ItemTemplateProperty, value); }
|
||||
|
||||
/// <summary>Style of the menu items (e.g. to bind a ToolTip per choice).</summary>
|
||||
public Style? ItemContainerStyle { get => (Style?)GetValue(ItemContainerStyleProperty); set => SetValue(ItemContainerStyleProperty, value); }
|
||||
|
||||
public string? DisplayMemberPath { get => (string?)GetValue(DisplayMemberPathProperty); set => SetValue(DisplayMemberPathProperty, value); }
|
||||
|
||||
/// <summary>The chosen entry (two-way).</summary>
|
||||
public object? SelectedItem { get => GetValue(SelectedItemProperty); set => SetValue(SelectedItemProperty, value); }
|
||||
|
||||
public bool IsDropDownOpen { get => (bool)GetValue(IsDropDownOpenProperty); set => SetValue(IsDropDownOpenProperty, value); }
|
||||
|
||||
/// <summary>Tooltip of the ▾ part.</summary>
|
||||
public object? DropDownToolTip { get => GetValue(DropDownToolTipProperty); set => SetValue(DropDownToolTipProperty, value); }
|
||||
|
||||
/// <summary>Accent fill (the one primary action of a screen).</summary>
|
||||
public bool IsPrimary { get => (bool)GetValue(IsPrimaryProperty); set => SetValue(IsPrimaryProperty, value); }
|
||||
|
||||
protected override void OnKeyDown(KeyEventArgs e)
|
||||
{
|
||||
base.OnKeyDown(e);
|
||||
if (e.Handled) return;
|
||||
var key = e.Key == Key.System ? e.SystemKey : e.Key;
|
||||
if (key == Key.F4 || (key == Key.Down && (Keyboard.Modifiers & ModifierKeys.Alt) != 0))
|
||||
{
|
||||
SetCurrentValue(IsDropDownOpenProperty, true);
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnIsDropDownOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
var button = (SplitButton)d;
|
||||
if ((bool)e.NewValue) button.EnsureMenu().IsOpen = true;
|
||||
else if (button._menu is { IsOpen: true } menu) menu.IsOpen = false;
|
||||
}
|
||||
|
||||
private ContextMenu EnsureMenu()
|
||||
{
|
||||
if (_menu is not null) return _menu;
|
||||
var menu = new ContextMenu { PlacementTarget = this, Placement = PlacementMode.Bottom, VerticalOffset = 4 };
|
||||
menu.SetBinding(ItemsControl.ItemsSourceProperty, new Binding(nameof(ItemsSource)) { Source = this });
|
||||
menu.SetBinding(ItemsControl.ItemTemplateProperty, new Binding(nameof(ItemTemplate)) { Source = this });
|
||||
menu.SetBinding(ItemsControl.ItemContainerStyleProperty, new Binding(nameof(ItemContainerStyle)) { Source = this });
|
||||
menu.SetBinding(ItemsControl.DisplayMemberPathProperty, new Binding(nameof(DisplayMemberPath)) { Source = this });
|
||||
menu.SetBinding(DataContextProperty, new Binding(nameof(DataContext)) { Source = this });
|
||||
menu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(OnMenuItemClick));
|
||||
menu.Opened += (_, _) => MarkSelected();
|
||||
menu.Closed += (_, _) => SetCurrentValue(IsDropDownOpenProperty, false);
|
||||
_menu = menu;
|
||||
return menu;
|
||||
}
|
||||
|
||||
private void OnMenuItemClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_menu is null || e.OriginalSource is not MenuItem container) return;
|
||||
var item = _menu.ItemContainerGenerator.ItemFromContainer(container);
|
||||
if (item != DependencyProperty.UnsetValue) SetCurrentValue(SelectedItemProperty, item);
|
||||
}
|
||||
|
||||
/// <summary>Checks the menu entry of the current choice.</summary>
|
||||
private void MarkSelected()
|
||||
{
|
||||
if (_menu is null) return;
|
||||
_menu.UpdateLayout();
|
||||
for (var i = 0; i < _menu.Items.Count; i++)
|
||||
if (_menu.ItemContainerGenerator.ContainerFromIndex(i) is MenuItem container)
|
||||
container.IsChecked = Equals(_menu.Items[i], SelectedItem);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="ItemActivatedEvent"/>.
|
||||
/// </summary>
|
||||
public sealed class StackedBar : DrawingElement
|
||||
{
|
||||
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
|
||||
nameof(Items), typeof(IReadOnlyList<ChartItem>), 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<double, string>), 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<Rect> _segments = [];
|
||||
private readonly List<Rect> _entries = [];
|
||||
private int _hover = -1;
|
||||
|
||||
/// <summary>Parts in display order (largest first reads best).</summary>
|
||||
public IReadOnlyList<ChartItem>? Items { get => (IReadOnlyList<ChartItem>?)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); }
|
||||
|
||||
/// <summary>Formats a share 0…1 for the legend (default: culture percent without decimals).</summary>
|
||||
public Func<double, string>? ShareFormatter { get => (Func<double, string>?)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<ChartItem> items)
|
||||
{
|
||||
var total = 0.0;
|
||||
for (var i = 0; i < items.Count; i++) total += Math.Max(0, items[i].Value);
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <summary>Rank fade 1 → 0.35 for items in the shared colour; items with their own brush stay opaque.</summary>
|
||||
private static double OpacityOf(int index, IReadOnlyList<ChartItem> 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);
|
||||
|
||||
/// <summary>Flows legend entries into lines of the given width; draws them when <paramref name="dc"/> is set. Returns the line count.</summary>
|
||||
private int LayoutLegend(IReadOnlyList<ChartItem> 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// Cells of a filmstrip: as many cells of about the target width as fit, each standing for a contiguous run of
|
||||
/// frames and showing the frame in the middle of its run; X positions map continuously to frames for seeking.
|
||||
/// </summary>
|
||||
public readonly struct StripLayout
|
||||
{
|
||||
public StripLayout(double width, double targetCellWidth, double gap, int frameCount)
|
||||
{
|
||||
Width = double.IsFinite(width) ? Math.Max(0, width) : 0;
|
||||
Gap = double.IsFinite(gap) ? Math.Max(0, gap) : 0;
|
||||
FrameCount = Math.Max(0, frameCount);
|
||||
var target = double.IsFinite(targetCellWidth) && targetCellWidth > 1 ? targetCellWidth : 1;
|
||||
CellCount = FrameCount == 0 || Width <= 0
|
||||
? 0
|
||||
: (int)Math.Min(FrameCount, Math.Max(1, Math.Floor((Width + Gap) / (target + Gap))));
|
||||
CellWidth = CellCount == 0 ? 0 : Math.Max(0, (Width - Gap * (CellCount - 1)) / CellCount);
|
||||
}
|
||||
|
||||
public double Width { get; }
|
||||
|
||||
public double Gap { get; }
|
||||
|
||||
public int FrameCount { get; }
|
||||
|
||||
public int CellCount { get; }
|
||||
|
||||
public double CellWidth { get; }
|
||||
|
||||
public double CellLeft(int cell) => cell * (CellWidth + Gap);
|
||||
|
||||
/// <summary>Cell whose run contains <paramref name="frame"/>.</summary>
|
||||
public int CellForFrame(int frame)
|
||||
{
|
||||
if (CellCount == 0) return -1;
|
||||
return (int)((long)Math.Clamp(frame, 0, FrameCount - 1) * CellCount / FrameCount);
|
||||
}
|
||||
|
||||
/// <summary>Frame shown by <paramref name="cell"/>: the middle of the frames that map to it.</summary>
|
||||
public int FrameForCell(int cell)
|
||||
{
|
||||
if (CellCount == 0) return -1;
|
||||
cell = Math.Clamp(cell, 0, CellCount - 1);
|
||||
var first = FirstFrame(cell);
|
||||
var last = FirstFrame(cell + 1) - 1;
|
||||
return first + (last - first) / 2;
|
||||
}
|
||||
|
||||
/// <summary>Frame under <paramref name="x"/> (continuous across cells and gaps), clamped to the sequence.</summary>
|
||||
public int FrameAt(double x)
|
||||
{
|
||||
if (FrameCount == 0 || Width <= 0) return -1;
|
||||
return (int)Math.Clamp(Math.Floor(x / Width * FrameCount), 0, FrameCount - 1);
|
||||
}
|
||||
|
||||
/// <summary>Centre X of <paramref name="frame"/> on the continuous frame axis.</summary>
|
||||
public double XForFrame(double frame) => FrameCount == 0 ? 0 : (frame + 0.5) / FrameCount * Width;
|
||||
|
||||
/// <summary>Smallest frame f with CellForFrame(f) = cell, i.e. ⌈cell · frames / cells⌉.</summary>
|
||||
private int FirstFrame(int cell) => (int)(((long)cell * FrameCount + CellCount - 1) / CellCount);
|
||||
}
|
||||
|
||||
/// <summary>A grid of square cells with gaps (heatmap): cell origins and hit testing that excludes the gaps.</summary>
|
||||
public readonly struct CellGridLayout
|
||||
{
|
||||
public CellGridLayout(double left, double top, int rows, int columns, double cellSize, double gap)
|
||||
{
|
||||
Left = left;
|
||||
Top = top;
|
||||
Rows = Math.Max(0, rows);
|
||||
Columns = Math.Max(0, columns);
|
||||
CellSize = Math.Max(0, cellSize);
|
||||
Gap = Math.Max(0, gap);
|
||||
}
|
||||
|
||||
public double Left { get; }
|
||||
|
||||
public double Top { get; }
|
||||
|
||||
public int Rows { get; }
|
||||
|
||||
public int Columns { get; }
|
||||
|
||||
public double CellSize { get; }
|
||||
|
||||
public double Gap { get; }
|
||||
|
||||
public double Pitch => CellSize + Gap;
|
||||
|
||||
public double Width => Columns == 0 ? 0 : Columns * Pitch - Gap;
|
||||
|
||||
public double Height => Rows == 0 ? 0 : Rows * Pitch - Gap;
|
||||
|
||||
public (double X, double Y) CellOrigin(int row, int column) => (Left + column * Pitch, Top + row * Pitch);
|
||||
|
||||
/// <summary>Largest square cell (≤ <paramref name="maxCell"/>) letting the grid fit in width × height.</summary>
|
||||
public static double FitCellSize(double width, double height, int rows, int columns, double gap, double maxCell)
|
||||
{
|
||||
if (rows <= 0 || columns <= 0) return 0;
|
||||
var byWidth = double.IsFinite(width) ? (width - gap * (columns - 1)) / columns : double.PositiveInfinity;
|
||||
var byHeight = double.IsFinite(height) ? (height - gap * (rows - 1)) / rows : double.PositiveInfinity;
|
||||
var size = Math.Min(Math.Min(byWidth, byHeight), maxCell);
|
||||
return double.IsFinite(size) ? Math.Max(0, size) : Math.Max(0, maxCell);
|
||||
}
|
||||
|
||||
/// <summary>Cell under (<paramref name="x"/>, <paramref name="y"/>); false over gaps and outside the grid.</summary>
|
||||
public bool TryHit(double x, double y, out int row, out int column)
|
||||
{
|
||||
row = column = -1;
|
||||
if (Rows == 0 || Columns == 0 || CellSize <= 0) return false;
|
||||
var dx = x - Left;
|
||||
var dy = y - Top;
|
||||
if (dx < 0 || dy < 0) return false;
|
||||
var c = (int)Math.Floor(dx / Pitch);
|
||||
var r = (int)Math.Floor(dy / Pitch);
|
||||
if (c >= Columns || r >= Rows) return false;
|
||||
if (dx - c * Pitch > CellSize || dy - r * Pitch > CellSize) return false;
|
||||
row = r;
|
||||
column = c;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// (<see cref="CurrentBand"/>, <see cref="CurrentSlot"/>) is outlined in Accent; clicking a slot makes it current
|
||||
/// and raises <see cref="SlotActivatedEvent"/>. Desired height = bands × <see cref="BandHeight"/>, so the control
|
||||
/// scrolls inside a ScrollViewer.
|
||||
/// </summary>
|
||||
public sealed class TimelineBands : DrawingElement
|
||||
{
|
||||
public static readonly DependencyProperty BandsProperty = DependencyProperty.Register(
|
||||
nameof(Bands), typeof(IReadOnlyList<ChartRow>), typeof(TimelineBands), new PropertyMetadata(null, OnDataPropertyChanged));
|
||||
|
||||
public static readonly DependencyProperty SlotLabelsProperty = DependencyProperty.Register(
|
||||
nameof(SlotLabels), typeof(IReadOnlyList<string>), 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<double, string>), 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);
|
||||
|
||||
/// <summary>One band per year: label + one value per slot.</summary>
|
||||
public IReadOnlyList<ChartRow>? Bands { get => (IReadOnlyList<ChartRow>?)GetValue(BandsProperty); set => SetValue(BandsProperty, value); }
|
||||
|
||||
/// <summary>Slot captions (culture-aware month initials); also fixes the slot count.</summary>
|
||||
public IReadOnlyList<string>? SlotLabels { get => (IReadOnlyList<string>?)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); }
|
||||
|
||||
/// <summary>Band of the current slot (two-way); −1 = none.</summary>
|
||||
public int CurrentBand { get => (int)GetValue(CurrentBandProperty); set => SetValue(CurrentBandProperty, value); }
|
||||
|
||||
/// <summary>Current slot inside <see cref="CurrentBand"/> (two-way); −1 = none.</summary>
|
||||
public int CurrentSlot { get => (int)GetValue(CurrentSlotProperty); set => SetValue(CurrentSlotProperty, value); }
|
||||
|
||||
/// <summary>Culture-aware value formatting for readouts.</summary>
|
||||
public Func<double, string>? ValueFormatter { get => (Func<double, string>?)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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>Uniform scale and translation from image pixels to view units: view = image × <see cref="Scale"/> + offset.</summary>
|
||||
public readonly record struct ViewTransform(double Scale, double OffsetX, double OffsetY)
|
||||
{
|
||||
public (double X, double Y) ToView(double x, double y) => (x * Scale + OffsetX, y * Scale + OffsetY);
|
||||
|
||||
public (double X, double Y) ToImage(double x, double y) => ((x - OffsetX) / Scale, (y - OffsetY) / Scale);
|
||||
}
|
||||
|
||||
/// <summary>Zoom and pan math of the preview: fit, zoom around a fixed point, panning limits and pixel alignment.</summary>
|
||||
public static class ViewportMath
|
||||
{
|
||||
/// <summary>Largest scale at which the whole image fits the view (0 when either is empty).</summary>
|
||||
public static double FitScale(double imageWidth, double imageHeight, double viewWidth, double viewHeight)
|
||||
{
|
||||
if (!(imageWidth > 0) || !(imageHeight > 0) || !(viewWidth > 0) || !(viewHeight > 0)) return 0;
|
||||
return Math.Min(viewWidth / imageWidth, viewHeight / imageHeight);
|
||||
}
|
||||
|
||||
/// <summary>The image at <paramref name="scale"/>, centred in the view.</summary>
|
||||
public static ViewTransform Centered(double scale, double imageWidth, double imageHeight, double viewWidth, double viewHeight) =>
|
||||
new(scale, (viewWidth - imageWidth * scale) / 2, (viewHeight - imageHeight * scale) / 2);
|
||||
|
||||
/// <summary>
|
||||
/// Changes the scale to <paramref name="scale"/> keeping the image point under (<paramref name="viewX"/>,
|
||||
/// <paramref name="viewY"/>) where it is.
|
||||
/// </summary>
|
||||
public static ViewTransform ZoomAt(ViewTransform t, double scale, double viewX, double viewY)
|
||||
{
|
||||
if (!(t.Scale > 0) || !(scale > 0)) return t;
|
||||
var k = scale / t.Scale;
|
||||
return new ViewTransform(scale, viewX - (viewX - t.OffsetX) * k, viewY - (viewY - t.OffsetY) * k);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the image covering the view on each axis where it is larger than the view, and centred on each axis
|
||||
/// where it is smaller, so panning can never lose the picture.
|
||||
/// </summary>
|
||||
public static ViewTransform Clamp(ViewTransform t, double imageWidth, double imageHeight, double viewWidth, double viewHeight) =>
|
||||
t with
|
||||
{
|
||||
OffsetX = ClampAxis(t.OffsetX, imageWidth * t.Scale, viewWidth),
|
||||
OffsetY = ClampAxis(t.OffsetY, imageHeight * t.Scale, viewHeight),
|
||||
};
|
||||
|
||||
/// <summary>Moves the offset by (<paramref name="dx"/>, <paramref name="dy"/>) view units.</summary>
|
||||
public static ViewTransform Pan(ViewTransform t, double dx, double dy) => t with { OffsetX = t.OffsetX + dx, OffsetY = t.OffsetY + dy };
|
||||
|
||||
/// <summary>Rounds the offset to whole device pixels (<paramref name="pixelsPerUnit"/> device pixels per view unit) so 1:1 shows raw pixels.</summary>
|
||||
public static ViewTransform SnapOffset(ViewTransform t, double pixelsPerUnit)
|
||||
{
|
||||
if (!(pixelsPerUnit > 0)) return t;
|
||||
return t with
|
||||
{
|
||||
OffsetX = Math.Round(t.OffsetX * pixelsPerUnit) / pixelsPerUnit,
|
||||
OffsetY = Math.Round(t.OffsetY * pixelsPerUnit) / pixelsPerUnit,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Next zoom level for a wheel movement of <paramref name="notches"/> (positive = in), by a factor of 1.25 per notch.</summary>
|
||||
public static double WheelZoom(double scale, double notches, double minScale, double maxScale) =>
|
||||
Math.Clamp(scale * Math.Pow(1.25, notches), minScale, maxScale);
|
||||
|
||||
private static double ClampAxis(double offset, double size, double view)
|
||||
{
|
||||
if (size <= view) return (view - size) / 2;
|
||||
return Math.Clamp(offset, view - size, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
using System.Collections.Specialized;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// Items host that wraps fixed-size items into rows and scrolls vertically by pixels (BRIEF §12.2: Library grid,
|
||||
/// 60 fps over 500k items). Only the rows in view plus one row above and below have containers; containers are
|
||||
/// recycled when the owner's <see cref="VirtualizingPanel.VirtualizationModeProperty"/> is Recycling. Index ↔ offset
|
||||
/// mapping is O(1) (<see cref="WrapLayout"/>). Arrow keys, PageUp/PageDown and Home/End move focus and selection
|
||||
/// in grid order (Ctrl moves focus only, Shift extends an Extended selection). Requires a ScrollViewer with
|
||||
/// <c>CanContentScroll="True"</c>; grouping is not supported.
|
||||
/// </summary>
|
||||
public sealed class VirtualizingWrapPanel : VirtualizingPanel, IScrollInfo
|
||||
{
|
||||
public static readonly DependencyProperty ItemWidthProperty = DependencyProperty.Register(
|
||||
nameof(ItemWidth), typeof(double), typeof(VirtualizingWrapPanel),
|
||||
new FrameworkPropertyMetadata(236.0, FrameworkPropertyMetadataOptions.AffectsMeasure), IsPositive);
|
||||
|
||||
public static readonly DependencyProperty ItemHeightProperty = DependencyProperty.Register(
|
||||
nameof(ItemHeight), typeof(double), typeof(VirtualizingWrapPanel),
|
||||
new FrameworkPropertyMetadata(208.0, FrameworkPropertyMetadataOptions.AffectsMeasure), IsPositive);
|
||||
|
||||
public static readonly DependencyProperty SpacingProperty = DependencyProperty.Register(
|
||||
nameof(Spacing), typeof(double), typeof(VirtualizingWrapPanel),
|
||||
new FrameworkPropertyMetadata(16.0, FrameworkPropertyMetadataOptions.AffectsMeasure), IsNonNegative);
|
||||
|
||||
public static readonly DependencyProperty JustifyProperty = DependencyProperty.Register(
|
||||
nameof(Justify), typeof(bool), typeof(VirtualizingWrapPanel),
|
||||
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsMeasure));
|
||||
|
||||
public static readonly DependencyProperty PaddingProperty = DependencyProperty.Register(
|
||||
nameof(Padding), typeof(Thickness), typeof(VirtualizingWrapPanel),
|
||||
new FrameworkPropertyMetadata(default(Thickness), FrameworkPropertyMetadataOptions.AffectsMeasure));
|
||||
|
||||
/// <summary>Rows realized beyond each edge of the viewport so the next row is ready before it scrolls in.</summary>
|
||||
private const int CacheRows = 1;
|
||||
|
||||
private WrapLayout _layout;
|
||||
private Thickness _padding;
|
||||
private Size _viewport;
|
||||
private Size _extent;
|
||||
private double _offset;
|
||||
private int _realizedFirst;
|
||||
private int _realizedLast = -1;
|
||||
private bool _generationDirty = true;
|
||||
private int _anchor = -1;
|
||||
private int _rangeAnchor = -1;
|
||||
private int _rangeEnd = -1;
|
||||
|
||||
/// <summary>Slot width of one item container (DESIGN §4: cards are 236 px).</summary>
|
||||
public double ItemWidth { get => (double)GetValue(ItemWidthProperty); set => SetValue(ItemWidthProperty, value); }
|
||||
|
||||
/// <summary>Slot height of one item container.</summary>
|
||||
public double ItemHeight { get => (double)GetValue(ItemHeightProperty); set => SetValue(ItemHeightProperty, value); }
|
||||
|
||||
/// <summary>Gap between columns and between rows.</summary>
|
||||
public double Spacing { get => (double)GetValue(SpacingProperty); set => SetValue(SpacingProperty, value); }
|
||||
|
||||
/// <summary>Spread leftover width over the column gaps so the grid spans the full width.</summary>
|
||||
public bool Justify { get => (bool)GetValue(JustifyProperty); set => SetValue(JustifyProperty, value); }
|
||||
|
||||
/// <summary>Space around the grid that scrolls with the items (unlike a ScrollViewer padding, which clips them).</summary>
|
||||
public Thickness Padding { get => (Thickness)GetValue(PaddingProperty); set => SetValue(PaddingProperty, value); }
|
||||
|
||||
public bool CanHorizontallyScroll { get; set; }
|
||||
|
||||
public bool CanVerticallyScroll { get; set; }
|
||||
|
||||
public double ExtentWidth => _extent.Width;
|
||||
|
||||
public double ExtentHeight => _extent.Height;
|
||||
|
||||
public double ViewportWidth => _viewport.Width;
|
||||
|
||||
public double ViewportHeight => _viewport.Height;
|
||||
|
||||
public double HorizontalOffset => 0;
|
||||
|
||||
public double VerticalOffset => _offset;
|
||||
|
||||
public ScrollViewer? ScrollOwner { get; set; }
|
||||
|
||||
/// <summary>Scroll distance of one line: a quarter row, at least 16 px.</summary>
|
||||
private double LineSize => Math.Max(16, _layout.RowPitch / 4);
|
||||
|
||||
public void LineUp() => SetVerticalOffset(_offset - LineSize);
|
||||
|
||||
public void LineDown() => SetVerticalOffset(_offset + LineSize);
|
||||
|
||||
public void PageUp() => SetVerticalOffset(_offset - _viewport.Height);
|
||||
|
||||
public void PageDown() => SetVerticalOffset(_offset + _viewport.Height);
|
||||
|
||||
public void MouseWheelUp() => SetVerticalOffset(_offset - WheelDistance());
|
||||
|
||||
public void MouseWheelDown() => SetVerticalOffset(_offset + WheelDistance());
|
||||
|
||||
public void LineLeft()
|
||||
{
|
||||
}
|
||||
|
||||
public void LineRight()
|
||||
{
|
||||
}
|
||||
|
||||
public void PageLeft()
|
||||
{
|
||||
}
|
||||
|
||||
public void PageRight()
|
||||
{
|
||||
}
|
||||
|
||||
public void MouseWheelLeft()
|
||||
{
|
||||
}
|
||||
|
||||
public void MouseWheelRight()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Only vertical scrolling exists: rows always fit the width.</summary>
|
||||
public void SetHorizontalOffset(double offset)
|
||||
{
|
||||
}
|
||||
|
||||
public void SetVerticalOffset(double offset)
|
||||
{
|
||||
offset = ClampOffset(offset);
|
||||
if (offset == _offset) return;
|
||||
_offset = offset;
|
||||
ScrollOwner?.InvalidateScrollInfo();
|
||||
InvalidateMeasure();
|
||||
}
|
||||
|
||||
public Rect MakeVisible(Visual visual, Rect rectangle)
|
||||
{
|
||||
if (rectangle.IsEmpty || visual is null || ReferenceEquals(visual, this) || !IsAncestorOf(visual)) return Rect.Empty;
|
||||
var bounds = visual.TransformToAncestor(this).TransformBounds(rectangle);
|
||||
var top = bounds.Top + _offset;
|
||||
SetVerticalOffset(WrapLayout.OffsetToReveal(top, bounds.Height, _offset, _viewport.Height));
|
||||
bounds.Y = top - _offset;
|
||||
return bounds;
|
||||
}
|
||||
|
||||
protected override void BringIndexIntoView(int index)
|
||||
{
|
||||
var owner = ItemsControl.GetItemsOwner(this);
|
||||
if (owner is null || index < 0 || index >= owner.Items.Count) return;
|
||||
if (_layout.Columns == 0) UpdateLayout();
|
||||
if (_layout.Columns == 0) return;
|
||||
SetVerticalOffset(WrapLayout.OffsetToReveal(_padding.Top + _layout.TopOf(index), _layout.ItemHeight, _offset, _viewport.Height));
|
||||
UpdateLayout();
|
||||
}
|
||||
|
||||
protected override Size MeasureOverride(Size availableSize)
|
||||
{
|
||||
var owner = ItemsControl.GetItemsOwner(this);
|
||||
var count = owner?.Items.Count ?? 0;
|
||||
var previous = _layout;
|
||||
var previousTop = _padding.Top;
|
||||
_padding = Padding;
|
||||
var horizontal = _padding.Left + _padding.Right;
|
||||
var vertical = _padding.Top + _padding.Bottom;
|
||||
_layout = new WrapLayout(count, Math.Max(0, availableSize.Width - horizontal), ItemWidth, ItemHeight, Spacing, Justify);
|
||||
KeepTopItemOnReflow(previous, previousTop);
|
||||
|
||||
var extent = new Size(_layout.ExtentWidth + horizontal, _layout.ExtentHeight + vertical);
|
||||
var viewportHeight = double.IsInfinity(availableSize.Height) ? extent.Height : availableSize.Height;
|
||||
var viewportWidth = double.IsInfinity(availableSize.Width) ? extent.Width : availableSize.Width;
|
||||
UpdateScrollInfo(new Size(viewportWidth, viewportHeight), new Size(Math.Max(viewportWidth, extent.Width), extent.Height));
|
||||
|
||||
if (owner is not null)
|
||||
{
|
||||
var (first, last) = _layout.VisibleRange(_offset - _padding.Top, viewportHeight, CacheRows);
|
||||
if (_generationDirty || first != _realizedFirst || last != _realizedLast)
|
||||
{
|
||||
CleanUp(owner, first, last);
|
||||
Realize(first, last);
|
||||
_realizedFirst = first;
|
||||
_realizedLast = last;
|
||||
_generationDirty = false;
|
||||
}
|
||||
var slot = new Size(ItemWidth, ItemHeight);
|
||||
var children = InternalChildren;
|
||||
for (var i = 0; i < children.Count; i++) children[i].Measure(slot);
|
||||
}
|
||||
return new Size(viewportWidth, viewportHeight);
|
||||
}
|
||||
|
||||
protected override Size ArrangeOverride(Size finalSize)
|
||||
{
|
||||
var generator = ItemContainerGenerator;
|
||||
var children = InternalChildren;
|
||||
if (generator is null) return finalSize;
|
||||
for (var i = 0; i < children.Count; i++)
|
||||
{
|
||||
var index = generator.IndexFromGeneratorPosition(new GeneratorPosition(i, 0));
|
||||
if (index < 0) continue;
|
||||
children[i].Arrange(new Rect(_padding.Left + _layout.LeftOf(index), _padding.Top + _layout.TopOf(index) - _offset, ItemWidth, ItemHeight));
|
||||
}
|
||||
return finalSize;
|
||||
}
|
||||
|
||||
protected override void OnItemsChanged(object sender, ItemsChangedEventArgs args)
|
||||
{
|
||||
base.OnItemsChanged(sender, args);
|
||||
switch (args.Action)
|
||||
{
|
||||
case NotifyCollectionChangedAction.Remove:
|
||||
case NotifyCollectionChangedAction.Replace:
|
||||
RemoveChildRange(args.Position, args.ItemUICount);
|
||||
break;
|
||||
case NotifyCollectionChangedAction.Move:
|
||||
RemoveChildRange(args.OldPosition, args.ItemUICount);
|
||||
break;
|
||||
}
|
||||
_generationDirty = true;
|
||||
_anchor = _rangeAnchor = _rangeEnd = -1;
|
||||
InvalidateMeasure();
|
||||
}
|
||||
|
||||
protected override void OnClearChildren()
|
||||
{
|
||||
base.OnClearChildren();
|
||||
_generationDirty = true;
|
||||
_realizedFirst = 0;
|
||||
_realizedLast = -1;
|
||||
}
|
||||
|
||||
/// <summary>Wheel scrolling proportional to the delta, so precision touchpads scroll smoothly.</summary>
|
||||
protected override void OnMouseWheel(MouseWheelEventArgs e)
|
||||
{
|
||||
base.OnMouseWheel(e);
|
||||
if (e.Handled || ScrollOwner is null) return;
|
||||
var before = _offset;
|
||||
SetVerticalOffset(_offset - e.Delta / (double)Mouse.MouseWheelDeltaForOneLine * WheelDistance());
|
||||
e.Handled = _offset != before;
|
||||
}
|
||||
|
||||
protected override void OnKeyDown(KeyEventArgs e)
|
||||
{
|
||||
base.OnKeyDown(e);
|
||||
if (e.Handled || (Keyboard.Modifiers & ModifierKeys.Alt) != 0) return;
|
||||
var step = StepFor(e.Key);
|
||||
var owner = ItemsControl.GetItemsOwner(this);
|
||||
if (step is null || owner is null || _layout.ItemCount == 0) return;
|
||||
var current = FocusedIndex(owner);
|
||||
if (current < 0) return;
|
||||
e.Handled = true;
|
||||
var target = _layout.Navigate(current, step.Value, _layout.PageRows(_viewport.Height));
|
||||
if (target != current) NavigateTo(owner, current, target);
|
||||
}
|
||||
|
||||
private static bool IsPositive(object value) => value is double d && double.IsFinite(d) && d > 0;
|
||||
|
||||
private static bool IsNonNegative(object value) => value is double d && double.IsFinite(d) && d >= 0;
|
||||
|
||||
private double WheelDistance()
|
||||
{
|
||||
var lines = SystemParameters.WheelScrollLines;
|
||||
return lines < 0 ? _viewport.Height : lines * LineSize;
|
||||
}
|
||||
|
||||
/// <summary>When the column count changes (resize), keeps the first visible item at the same height in the viewport.</summary>
|
||||
private void KeepTopItemOnReflow(WrapLayout previous, double previousTop)
|
||||
{
|
||||
if (previous.Columns == _layout.Columns || previous.ItemCount == 0 || _layout.ItemCount == 0) return;
|
||||
var (top, _) = previous.VisibleRange(_offset - previousTop, Math.Max(1, _viewport.Height));
|
||||
if (top < 0 || top >= _layout.ItemCount) return;
|
||||
var delta = _offset - (previousTop + previous.TopOf(top));
|
||||
_offset = _padding.Top + _layout.TopOf(top) + delta;
|
||||
}
|
||||
|
||||
private double ClampOffset(double offset) =>
|
||||
double.IsNaN(offset) ? 0 : Math.Clamp(offset, 0, Math.Max(0, _extent.Height - _viewport.Height));
|
||||
|
||||
private void UpdateScrollInfo(Size viewport, Size extent)
|
||||
{
|
||||
var changed = viewport != _viewport || extent != _extent;
|
||||
_viewport = viewport;
|
||||
_extent = extent;
|
||||
var clamped = ClampOffset(_offset);
|
||||
if (clamped != _offset)
|
||||
{
|
||||
_offset = clamped;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) ScrollOwner?.InvalidateScrollInfo();
|
||||
}
|
||||
|
||||
/// <summary>Recycles (or removes) containers outside [first, last]; a container holding keyboard focus is kept.</summary>
|
||||
private void CleanUp(ItemsControl owner, int first, int last)
|
||||
{
|
||||
var generator = ItemContainerGenerator;
|
||||
if (generator is null) return;
|
||||
var recycling = GetVirtualizationMode(owner) == VirtualizationMode.Recycling;
|
||||
var children = InternalChildren;
|
||||
for (var i = children.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var position = new GeneratorPosition(i, 0);
|
||||
var index = generator.IndexFromGeneratorPosition(position);
|
||||
if ((index >= first && index <= last) || children[i].IsKeyboardFocusWithin) continue;
|
||||
if (recycling) ((IRecyclingItemContainerGenerator)generator).Recycle(position, 1);
|
||||
else generator.Remove(position, 1);
|
||||
RemoveInternalChildRange(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Generates containers for [first, last], inserting them so children stay in item order.</summary>
|
||||
private void Realize(int first, int last)
|
||||
{
|
||||
var generator = ItemContainerGenerator;
|
||||
if (generator is null || last < first) return;
|
||||
var start = generator.GeneratorPositionFromIndex(first);
|
||||
var childIndex = start.Offset == 0 ? start.Index : start.Index + 1;
|
||||
using (generator.StartAt(start, GeneratorDirection.Forward, true))
|
||||
{
|
||||
for (var i = first; i <= last; i++, childIndex++)
|
||||
{
|
||||
if (generator.GenerateNext(out var newlyRealized) is not UIElement child) break;
|
||||
if (!newlyRealized) continue;
|
||||
if (childIndex >= InternalChildren.Count) AddInternalChild(child);
|
||||
else InsertInternalChild(childIndex, child);
|
||||
generator.PrepareItemContainer(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveChildRange(GeneratorPosition position, int uiCount)
|
||||
{
|
||||
if (uiCount <= 0) return;
|
||||
var index = position.Offset > 0 ? position.Index + 1 : position.Index;
|
||||
var children = InternalChildren;
|
||||
if (index < children.Count) RemoveInternalChildRange(index, Math.Min(uiCount, children.Count - index));
|
||||
}
|
||||
|
||||
private WrapStep? StepFor(Key key)
|
||||
{
|
||||
var rtl = FlowDirection == FlowDirection.RightToLeft;
|
||||
return key switch
|
||||
{
|
||||
Key.Left => rtl ? WrapStep.Right : WrapStep.Left,
|
||||
Key.Right => rtl ? WrapStep.Left : WrapStep.Right,
|
||||
Key.Up => WrapStep.Up,
|
||||
Key.Down => WrapStep.Down,
|
||||
Key.PageUp => WrapStep.PageUp,
|
||||
Key.PageDown => WrapStep.PageDown,
|
||||
Key.Home => WrapStep.First,
|
||||
Key.End => WrapStep.Last,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
private static int FocusedIndex(ItemsControl owner)
|
||||
{
|
||||
if (Keyboard.FocusedElement is not DependencyObject focused) return -1;
|
||||
var container = owner.ContainerFromElement(focused);
|
||||
return container is null ? -1 : owner.ItemContainerGenerator.IndexFromContainer(container);
|
||||
}
|
||||
|
||||
private void NavigateTo(ItemsControl owner, int from, int to)
|
||||
{
|
||||
BringIndexIntoView(to);
|
||||
if (owner.ItemContainerGenerator.ContainerFromIndex(to) is not UIElement container) return;
|
||||
container.Focus();
|
||||
if (owner is not Selector selector) return;
|
||||
|
||||
var modifiers = Keyboard.Modifiers;
|
||||
var mode = owner is ListBox listBox ? listBox.SelectionMode : SelectionMode.Single;
|
||||
if (mode == SelectionMode.Multiple || (mode == SelectionMode.Extended && (modifiers & ModifierKeys.Control) != 0)) return;
|
||||
if (mode == SelectionMode.Extended && (modifiers & ModifierKeys.Shift) != 0)
|
||||
{
|
||||
SelectRange((ListBox)owner, from, to);
|
||||
return;
|
||||
}
|
||||
selector.SelectedIndex = to;
|
||||
_anchor = to;
|
||||
_rangeAnchor = _rangeEnd = -1;
|
||||
}
|
||||
|
||||
/// <summary>Selects anchor…<paramref name="to"/>, touching only the items that enter or leave the previous range.</summary>
|
||||
private void SelectRange(ListBox listBox, int from, int to)
|
||||
{
|
||||
var items = listBox.Items;
|
||||
var anchor = _anchor >= 0 && _anchor < items.Count && listBox.SelectedItems.Contains(items[_anchor]) ? _anchor : from;
|
||||
_anchor = anchor;
|
||||
var newLow = Math.Min(anchor, to);
|
||||
var newHigh = Math.Max(anchor, to);
|
||||
if (_rangeAnchor != anchor || _rangeEnd < 0)
|
||||
{
|
||||
listBox.SelectedItems.Clear();
|
||||
for (var i = newLow; i <= newHigh; i++) listBox.SelectedItems.Add(items[i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
var oldLow = Math.Min(anchor, _rangeEnd);
|
||||
var oldHigh = Math.Max(anchor, _rangeEnd);
|
||||
for (var i = oldLow; i <= oldHigh; i++)
|
||||
if (i < newLow || i > newHigh) listBox.SelectedItems.Remove(items[i]);
|
||||
for (var i = newLow; i <= newHigh; i++)
|
||||
if (i < oldLow || i > oldHigh) listBox.SelectedItems.Add(items[i]);
|
||||
}
|
||||
_rangeAnchor = anchor;
|
||||
_rangeEnd = to;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>Keyboard steps inside a wrapped grid.</summary>
|
||||
public enum WrapStep
|
||||
{
|
||||
Left,
|
||||
Right,
|
||||
Up,
|
||||
Down,
|
||||
PageUp,
|
||||
PageDown,
|
||||
First,
|
||||
Last,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Geometry of a grid of fixed-size items wrapped into rows: O(1) mapping between item index, row, column and
|
||||
/// pixel offset, visible ranges, minimal scroll to reveal an item and keyboard navigation targets.
|
||||
/// </summary>
|
||||
public readonly struct WrapLayout
|
||||
{
|
||||
private const double Epsilon = 1e-9;
|
||||
|
||||
/// <param name="itemCount">Number of items.</param>
|
||||
/// <param name="viewportWidth">Width available for the rows; infinite puts every item on one row.</param>
|
||||
/// <param name="itemWidth">Slot width of one item.</param>
|
||||
/// <param name="itemHeight">Slot height of one item.</param>
|
||||
/// <param name="spacing">Gap between columns and between rows.</param>
|
||||
/// <param name="justify">Spread the leftover width over the column gaps so the grid spans the viewport.</param>
|
||||
public WrapLayout(int itemCount, double viewportWidth, double itemWidth, double itemHeight, double spacing, bool justify = false)
|
||||
{
|
||||
ItemCount = Math.Max(0, itemCount);
|
||||
ItemWidth = Positive(itemWidth);
|
||||
ItemHeight = Positive(itemHeight);
|
||||
Spacing = double.IsFinite(spacing) ? Math.Max(0, spacing) : 0;
|
||||
var finiteWidth = double.IsFinite(viewportWidth);
|
||||
Columns = finiteWidth ? ColumnsFor(viewportWidth, ItemWidth, Spacing) : Math.Max(1, ItemCount);
|
||||
Rows = ItemCount == 0 ? 0 : (ItemCount + Columns - 1) / Columns;
|
||||
RowPitch = ItemHeight + Spacing;
|
||||
ColumnPitch = justify && finiteWidth && Columns > 1
|
||||
? Math.Max(ItemWidth + Spacing, (viewportWidth - ItemWidth) / (Columns - 1))
|
||||
: ItemWidth + Spacing;
|
||||
}
|
||||
|
||||
public int ItemCount { get; }
|
||||
|
||||
public double ItemWidth { get; }
|
||||
|
||||
public double ItemHeight { get; }
|
||||
|
||||
public double Spacing { get; }
|
||||
|
||||
public int Columns { get; }
|
||||
|
||||
public int Rows { get; }
|
||||
|
||||
/// <summary>Distance between the tops of two consecutive rows.</summary>
|
||||
public double RowPitch { get; }
|
||||
|
||||
/// <summary>Distance between the left edges of two consecutive columns.</summary>
|
||||
public double ColumnPitch { get; }
|
||||
|
||||
/// <summary>Height of all rows, without a trailing gap.</summary>
|
||||
public double ExtentHeight => Rows == 0 ? 0 : Rows * RowPitch - Spacing;
|
||||
|
||||
/// <summary>Width spanned by the columns, without a trailing gap.</summary>
|
||||
public double ExtentWidth => ItemCount == 0 ? 0 : (Math.Min(Columns, ItemCount) - 1) * ColumnPitch + ItemWidth;
|
||||
|
||||
/// <summary>Columns that fit in <paramref name="width"/> (at least one).</summary>
|
||||
public static int ColumnsFor(double width, double itemWidth, double spacing)
|
||||
{
|
||||
if (!double.IsFinite(width) || width <= 0) return 1;
|
||||
var pitch = Positive(itemWidth) + Math.Max(0, spacing);
|
||||
return Math.Max(1, (int)Math.Floor((width + Math.Max(0, spacing)) / pitch + Epsilon));
|
||||
}
|
||||
|
||||
public int RowOf(int index) => index / Columns;
|
||||
|
||||
public int ColumnOf(int index) => index % Columns;
|
||||
|
||||
public double LeftOf(int index) => ColumnOf(index) * ColumnPitch;
|
||||
|
||||
public double TopOf(int index) => RowOf(index) * RowPitch;
|
||||
|
||||
/// <summary>Row whose slot band [top, top + pitch) contains <paramref name="y"/>, clamped to the rows.</summary>
|
||||
public int RowAt(double y)
|
||||
{
|
||||
if (Rows == 0) return -1;
|
||||
if (!(y > 0)) return 0;
|
||||
return (int)Math.Min(Rows - 1, Math.Floor(y / RowPitch));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// First and last item index whose slot intersects [offset, offset + viewportHeight), widened by
|
||||
/// <paramref name="cacheRows"/> rows on each side. Returns (0, −1) when nothing is visible.
|
||||
/// </summary>
|
||||
public (int First, int Last) VisibleRange(double offset, double viewportHeight, int cacheRows = 0)
|
||||
{
|
||||
if (Rows == 0 || !(viewportHeight > 0)) return (0, -1);
|
||||
if (double.IsInfinity(viewportHeight)) return (0, ItemCount - 1);
|
||||
// Row r occupies [r·pitch, r·pitch + itemHeight): visible when it starts before the bottom edge and ends after the top edge.
|
||||
var firstRow = (long)Math.Floor((offset - ItemHeight) / RowPitch + Epsilon) + 1;
|
||||
var lastRow = (long)Math.Ceiling((offset + viewportHeight) / RowPitch - Epsilon) - 1;
|
||||
firstRow = Math.Max(0, firstRow - Math.Max(0, cacheRows));
|
||||
lastRow = Math.Min(Rows - 1, lastRow + Math.Max(0, cacheRows));
|
||||
if (firstRow > lastRow) return (0, -1);
|
||||
var first = (int)(firstRow * Columns);
|
||||
var last = (int)Math.Min(ItemCount - 1, (lastRow + 1) * Columns - 1);
|
||||
return (first, last);
|
||||
}
|
||||
|
||||
/// <summary>Clamps a vertical offset to [0, extent − viewport].</summary>
|
||||
public double ClampOffset(double offset, double viewportHeight)
|
||||
{
|
||||
var max = Math.Max(0, ExtentHeight - Math.Max(0, viewportHeight));
|
||||
return double.IsNaN(offset) ? 0 : Math.Clamp(offset, 0, max);
|
||||
}
|
||||
|
||||
/// <summary>Smallest change of <paramref name="offset"/> that shows [top, top + height) fully; a band taller than the viewport is aligned to its top.</summary>
|
||||
public static double OffsetToReveal(double top, double height, double offset, double viewportHeight)
|
||||
{
|
||||
if (top < offset || height >= viewportHeight) return top;
|
||||
if (top + height > offset + viewportHeight) return top + height - viewportHeight;
|
||||
return offset;
|
||||
}
|
||||
|
||||
/// <summary>Clamped offset that shows item <paramref name="index"/> fully with the least scrolling.</summary>
|
||||
public double OffsetToReveal(int index, double offset, double viewportHeight)
|
||||
{
|
||||
if (index < 0 || index >= ItemCount) return ClampOffset(offset, viewportHeight);
|
||||
return ClampOffset(OffsetToReveal(TopOf(index), ItemHeight, offset, viewportHeight), viewportHeight);
|
||||
}
|
||||
|
||||
/// <summary>Whole rows that fit in the viewport (at least one): the PageUp/PageDown step.</summary>
|
||||
public int PageRows(double viewportHeight) =>
|
||||
double.IsFinite(viewportHeight) ? Math.Max(1, (int)Math.Floor((viewportHeight + Spacing) / RowPitch + Epsilon)) : Math.Max(1, Rows);
|
||||
|
||||
/// <summary>
|
||||
/// Target of a keyboard step from <paramref name="index"/>. Left/Right walk the reading order (wrapping across
|
||||
/// rows); Up/Down keep the column; Down from a row above a shorter last row lands on the last item; page steps
|
||||
/// move <paramref name="pageRows"/> rows in the same column. Returns −1 when there are no items.
|
||||
/// </summary>
|
||||
public int Navigate(int index, WrapStep step, int pageRows)
|
||||
{
|
||||
if (ItemCount == 0) return -1;
|
||||
index = Math.Clamp(index, 0, ItemCount - 1);
|
||||
var last = ItemCount - 1;
|
||||
var page = Math.Max(1, pageRows);
|
||||
switch (step)
|
||||
{
|
||||
case WrapStep.Left:
|
||||
return Math.Max(0, index - 1);
|
||||
case WrapStep.Right:
|
||||
return Math.Min(last, index + 1);
|
||||
case WrapStep.Up:
|
||||
return index >= Columns ? index - Columns : index;
|
||||
case WrapStep.Down:
|
||||
if (index + Columns <= last) return index + Columns;
|
||||
return RowOf(index) < Rows - 1 ? last : index;
|
||||
case WrapStep.PageUp:
|
||||
{
|
||||
var row = Math.Max(0, RowOf(index) - page);
|
||||
return row * Columns + ColumnOf(index);
|
||||
}
|
||||
case WrapStep.PageDown:
|
||||
{
|
||||
var row = Math.Min(Rows - 1, RowOf(index) + page);
|
||||
return Math.Min(last, row * Columns + ColumnOf(index));
|
||||
}
|
||||
case WrapStep.First:
|
||||
return 0;
|
||||
case WrapStep.Last:
|
||||
return last;
|
||||
default:
|
||||
return index;
|
||||
}
|
||||
}
|
||||
|
||||
private static double Positive(double v) => double.IsFinite(v) && v > 0 ? v : 1;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Tests.Visuals;
|
||||
|
||||
public sealed class CurveMathTests
|
||||
{
|
||||
private const double Gap = CurveMath.DefaultMinGap;
|
||||
|
||||
[Test]
|
||||
public void DraggedPointCannotPassItsNeighbours()
|
||||
{
|
||||
double[] xs = [0, 0.3, 0.6, 1];
|
||||
Assert.Approximately(0.6 - Gap, CurveMath.ConstrainX(xs, 1, 0.9, Gap, pinEnds: true), 1e-12);
|
||||
Assert.Approximately(0 + Gap, CurveMath.ConstrainX(xs, 1, -0.4, Gap, pinEnds: true), 1e-12);
|
||||
Assert.Approximately(0.45, CurveMath.ConstrainX(xs, 1, 0.45, Gap, pinEnds: true), 1e-12);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PinnedEndsStayAtZeroAndOne()
|
||||
{
|
||||
double[] xs = [0, 0.5, 1];
|
||||
Assert.Approximately(0, CurveMath.ConstrainX(xs, 0, 0.2, Gap, pinEnds: true), 0);
|
||||
Assert.Approximately(1, CurveMath.ConstrainX(xs, 2, 0.7, Gap, pinEnds: true), 0);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FreeEndsMoveInsideTheUnitInterval()
|
||||
{
|
||||
double[] xs = [0.1, 0.5, 0.9];
|
||||
Assert.Approximately(0, CurveMath.ConstrainX(xs, 0, -3, Gap, pinEnds: false), 0);
|
||||
Assert.Approximately(0.5 - Gap, CurveMath.ConstrainX(xs, 0, 0.8, Gap, pinEnds: false), 1e-12);
|
||||
Assert.Approximately(1, CurveMath.ConstrainX(xs, 2, 4, Gap, pinEnds: false), 0);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnySequenceOfDragsKeepsXStrictlyIncreasing()
|
||||
{
|
||||
var random = new Random(11);
|
||||
double[] xs = [0, 0.2, 0.4, 0.6, 0.8, 1];
|
||||
for (var step = 0; step < 10_000; step++)
|
||||
{
|
||||
var i = random.Next(xs.Length);
|
||||
xs[i] = CurveMath.ConstrainX(xs, i, random.NextDouble() * 1.4 - 0.2, Gap, pinEnds: true);
|
||||
for (var k = 1; k < xs.Length; k++) Assert.True(xs[k] - xs[k - 1] >= Gap - 1e-12, $"x[{k - 1}]={xs[k - 1]} x[{k}]={xs[k]}");
|
||||
Assert.Approximately(0, xs[0], 0);
|
||||
Assert.Approximately(1, xs[^1], 0);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertionKeepsOrderAndRespectsGapAndPins()
|
||||
{
|
||||
double[] xs = [0, 0.5, 1];
|
||||
Assert.Equal(1, CurveMath.InsertionIndex(xs, 0.25, Gap, pinEnds: true));
|
||||
Assert.Equal(2, CurveMath.InsertionIndex(xs, 0.75, Gap, pinEnds: true));
|
||||
Assert.Equal(-1, CurveMath.InsertionIndex(xs, 0.5 + Gap / 2, Gap, pinEnds: true));
|
||||
Assert.Equal(-1, CurveMath.InsertionIndex(xs, 1.2, Gap, pinEnds: false));
|
||||
|
||||
double[] free = [0.2, 0.6];
|
||||
Assert.Equal(0, CurveMath.InsertionIndex(free, 0.1, Gap, pinEnds: false));
|
||||
Assert.Equal(2, CurveMath.InsertionIndex(free, 0.9, Gap, pinEnds: false));
|
||||
Assert.Equal(-1, CurveMath.InsertionIndex(free, 0.1, Gap, pinEnds: true));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RemovalKeepsTwoPointsAndPinnedEnds()
|
||||
{
|
||||
Assert.False(CurveMath.CanRemove(2, 1, pinEnds: false));
|
||||
Assert.True(CurveMath.CanRemove(3, 0, pinEnds: false));
|
||||
Assert.False(CurveMath.CanRemove(3, 0, pinEnds: true));
|
||||
Assert.True(CurveMath.CanRemove(3, 1, pinEnds: true));
|
||||
Assert.False(CurveMath.CanRemove(3, 2, pinEnds: true));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HitTestPicksTheNearestPointWithinRadius()
|
||||
{
|
||||
double[] xs = [10, 50, 54];
|
||||
double[] ys = [10, 10, 10];
|
||||
Assert.Equal(2, CurveMath.HitTest(xs, ys, 53, 11, 6));
|
||||
Assert.Equal(1, CurveMath.HitTest(xs, ys, 51, 10, 6));
|
||||
Assert.Equal(-1, CurveMath.HitTest(xs, ys, 30, 10, 6));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Tests.Visuals;
|
||||
|
||||
public sealed class LruCacheTests
|
||||
{
|
||||
[Test]
|
||||
public void EvictsTheLeastRecentlyUsedEntry()
|
||||
{
|
||||
var cache = new LruCache<int, string>(2);
|
||||
cache.Set(1, "a");
|
||||
cache.Set(2, "b");
|
||||
Assert.True(cache.TryGet(1, out _));
|
||||
cache.Set(3, "c");
|
||||
Assert.False(cache.TryGet(2, out _));
|
||||
Assert.True(cache.TryGet(1, out var one));
|
||||
Assert.Equal("a", one);
|
||||
Assert.True(cache.TryGet(3, out _));
|
||||
Assert.Equal(2, cache.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReplacingAValueRefreshesItsRecency()
|
||||
{
|
||||
var cache = new LruCache<int, string>(2);
|
||||
cache.Set(1, "a");
|
||||
cache.Set(2, "b");
|
||||
cache.Set(1, "a2");
|
||||
cache.Set(3, "c");
|
||||
Assert.True(cache.TryGet(1, out var value));
|
||||
Assert.Equal("a2", value);
|
||||
Assert.False(cache.TryGet(2, out _));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ShrinkingCapacityEvictsOldestFirst()
|
||||
{
|
||||
var cache = new LruCache<int, int>(10);
|
||||
for (var i = 0; i < 10; i++) cache.Set(i, i);
|
||||
cache.Capacity = 3;
|
||||
Assert.Equal(3, cache.Count);
|
||||
for (var i = 0; i < 7; i++) Assert.False(cache.TryGet(i, out _));
|
||||
for (var i = 7; i < 10; i++) Assert.True(cache.TryGet(i, out _));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RemoveAndClear()
|
||||
{
|
||||
var cache = new LruCache<string, int>(4);
|
||||
cache.Set("x", 1);
|
||||
cache.Set("y", 2);
|
||||
Assert.True(cache.Remove("x"));
|
||||
Assert.False(cache.Remove("x"));
|
||||
cache.Clear();
|
||||
Assert.Equal(0, cache.Count);
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => _ = new LruCache<int, int>(0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Tests.Visuals;
|
||||
|
||||
public sealed class MinMaxDecimatorTests
|
||||
{
|
||||
[Test]
|
||||
public void ShortSeriesKeepsEverySample()
|
||||
{
|
||||
double[] values = [3, 1, 4, 1, 5];
|
||||
var output = new int[MinMaxDecimator.Capacity(values.Length, 10)];
|
||||
var n = MinMaxDecimator.Decimate(values, 10, output);
|
||||
Assert.SequenceEqual([0, 1, 2, 3, 4], output[..n]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LongSeriesKeepsAtMostTwoSamplesPerColumn()
|
||||
{
|
||||
var values = Noise(200_000, seed: 1);
|
||||
const int columns = 800;
|
||||
var output = new int[MinMaxDecimator.Capacity(values.Length, columns)];
|
||||
var n = MinMaxDecimator.Decimate(values, columns, output);
|
||||
Assert.LessOrEqual(n, 2 * columns);
|
||||
Assert.Monotonic(output[..n].Select(i => (double)i), strict: true);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryColumnPreservesItsMinimumAndMaximum()
|
||||
{
|
||||
var values = Noise(123_457, seed: 2);
|
||||
// Plant spikes that a naive stride sampler would miss.
|
||||
values[50_001] = 1000;
|
||||
values[99_999] = -1000;
|
||||
const int columns = 640;
|
||||
var output = new int[MinMaxDecimator.Capacity(values.Length, columns)];
|
||||
var n = MinMaxDecimator.Decimate(values, columns, output);
|
||||
var kept = output[..n];
|
||||
|
||||
for (var c = 0; c < columns; c++)
|
||||
{
|
||||
var start = (int)((long)c * values.Length / columns);
|
||||
var end = (int)((long)(c + 1) * values.Length / columns);
|
||||
double min = double.PositiveInfinity, max = double.NegativeInfinity;
|
||||
double keptMin = double.PositiveInfinity, keptMax = double.NegativeInfinity;
|
||||
for (var i = start; i < end; i++)
|
||||
{
|
||||
min = Math.Min(min, values[i]);
|
||||
max = Math.Max(max, values[i]);
|
||||
}
|
||||
foreach (var i in kept)
|
||||
{
|
||||
if (i < start || i >= end) continue;
|
||||
keptMin = Math.Min(keptMin, values[i]);
|
||||
keptMax = Math.Max(keptMax, values[i]);
|
||||
}
|
||||
Assert.Equal(min, keptMin, $"column {c} min");
|
||||
Assert.Equal(max, keptMax, $"column {c} max");
|
||||
}
|
||||
Assert.Contains(50_001, kept);
|
||||
Assert.Contains(99_999, kept);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NonFiniteRunsBecomeSingleGaps()
|
||||
{
|
||||
double[] values = [1, double.NaN, double.NaN, 2, double.PositiveInfinity, 3, double.NaN];
|
||||
var output = new int[values.Length];
|
||||
var n = MinMaxDecimator.Decimate(values, 100, output);
|
||||
Assert.SequenceEqual([0, MinMaxDecimator.Gap, 3, MinMaxDecimator.Gap, 5], output[..n]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmptyColumnsBreakTheLineInDecimatedMode()
|
||||
{
|
||||
var values = new double[1000];
|
||||
for (var i = 0; i < values.Length; i++) values[i] = i < 400 || i >= 600 ? i : double.NaN;
|
||||
var output = new int[MinMaxDecimator.Capacity(values.Length, 10)];
|
||||
var n = MinMaxDecimator.Decimate(values, 10, output);
|
||||
// Columns 4 and 5 (indices 400–599) hold no finite sample: exactly one gap between columns 3 and 6.
|
||||
Assert.SequenceEqual([0, 99, 100, 199, 200, 299, 300, 399, MinMaxDecimator.Gap, 600, 699, 700, 799, 800, 899, 900, 999], output[..n]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FlatColumnsEmitOneSample()
|
||||
{
|
||||
var values = Enumerable.Repeat(5.0, 1000).ToArray();
|
||||
var output = new int[MinMaxDecimator.Capacity(values.Length, 4)];
|
||||
var n = MinMaxDecimator.Decimate(values, 4, output);
|
||||
Assert.SequenceEqual([0, 250, 500, 750], output[..n]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UndersizedOutputIsRejected()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => MinMaxDecimator.Decimate(new double[100], 10, new int[5]));
|
||||
}
|
||||
|
||||
private static double[] Noise(int count, int seed)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var values = new double[count];
|
||||
for (var i = 0; i < count; i++) values[i] = Math.Sin(i * 0.001) + random.NextDouble() * 0.2;
|
||||
return values;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Tests.Visuals;
|
||||
|
||||
public sealed class NiceScaleTests
|
||||
{
|
||||
[Theory]
|
||||
[Case(0.6, true, 0.5)]
|
||||
[Case(1.2, true, 1.0)]
|
||||
[Case(2.9, true, 2.0)]
|
||||
[Case(3.1, true, 5.0)]
|
||||
[Case(7.5, true, 10.0)]
|
||||
[Case(1.2, false, 2.0)]
|
||||
[Case(4.0, false, 5.0)]
|
||||
[Case(5.0, false, 5.0)]
|
||||
[Case(1234.0, false, 2000.0)]
|
||||
[Case(0.025, true, 0.02)]
|
||||
public void NiceNumbersAreOneTwoOrFiveTimesAPowerOfTen(double value, bool round, double expected)
|
||||
{
|
||||
Assert.Approximately(expected, NiceScale.NiceNumber(value, round), expected * 1e-12);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InnerTicksStayInsideTheRangeOnNiceMultiples()
|
||||
{
|
||||
var ticks = NiceScale.Inner(0.13, 0.87, 5);
|
||||
Assert.Approximately(0.2, ticks.Step, 1e-12);
|
||||
Assert.Equal(4, ticks.Count);
|
||||
Assert.Approximately(0.2, ticks[0], 1e-12);
|
||||
Assert.Approximately(0.8, ticks[3], 1e-12);
|
||||
for (var i = 0; i < ticks.Count; i++) Assert.InRange(ticks[i], 0.13, 0.87);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OuterTicksEncloseTheRange()
|
||||
{
|
||||
var ticks = NiceScale.Outer(3, 1870, 5);
|
||||
Assert.Approximately(500, ticks.Step, 1e-9);
|
||||
Assert.Approximately(0, ticks.First, 1e-9);
|
||||
Assert.Approximately(2000, ticks.Last, 1e-9);
|
||||
Assert.Equal(5, ticks.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TickValuesDoNotDriftOverManySteps()
|
||||
{
|
||||
var ticks = NiceScale.Inner(-1e6, 1e6, 11);
|
||||
Assert.Approximately(200_000, ticks.Step, 1e-6);
|
||||
Assert.Approximately(0, ticks[5], 1e-6);
|
||||
Assert.Approximately(1e6, ticks[ticks.Count - 1], 1e-6);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TickCountNeverExceedsTheRequest()
|
||||
{
|
||||
var random = new Random(7);
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
var a = (random.NextDouble() - 0.5) * Math.Pow(10, random.Next(-3, 7));
|
||||
var b = a + random.NextDouble() * Math.Pow(10, random.Next(-3, 7)) + 1e-9;
|
||||
var max = random.Next(2, 12);
|
||||
var ticks = NiceScale.Inner(a, b, max);
|
||||
Assert.LessOrEqual(ticks.Count, max);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PadWidensBothSidesAndCentresFlatData()
|
||||
{
|
||||
var (min, max) = NiceScale.Pad(10, 20, 0.1);
|
||||
Assert.Approximately(9, min, 1e-12);
|
||||
Assert.Approximately(21, max, 1e-12);
|
||||
|
||||
var (flatMin, flatMax) = NiceScale.Pad(5, 5, 0.1);
|
||||
Assert.Approximately(5, (flatMin + flatMax) / 2, 1e-12);
|
||||
Assert.Greater(flatMax - flatMin, 0);
|
||||
|
||||
var (zeroMin, zeroMax) = NiceScale.Pad(0, 0, 0.1);
|
||||
Assert.Approximately(-1, zeroMin, 1e-12);
|
||||
Assert.Approximately(1, zeroMax, 1e-12);
|
||||
Assert.Equal((0.0, 1.0), NiceScale.Pad(double.NaN, 3, 0.1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DegenerateRangesGiveNoInnerTicks()
|
||||
{
|
||||
Assert.Equal(0, NiceScale.Inner(4, 4, 5).Count);
|
||||
Assert.Equal(0, NiceScale.Inner(double.NaN, 4, 5).Count);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Tests.Visuals;
|
||||
|
||||
public sealed class PixelGridTests
|
||||
{
|
||||
[Theory]
|
||||
[Case(1.0)]
|
||||
[Case(1.25)]
|
||||
[Case(1.5)]
|
||||
[Case(2.0)]
|
||||
public void HairlinesCoverWholeDevicePixels(double scale)
|
||||
{
|
||||
var thickness = PixelGrid.SnapThickness(1, scale);
|
||||
var devicePixels = thickness * scale;
|
||||
Assert.Approximately(Math.Round(devicePixels), devicePixels, 1e-9);
|
||||
for (var v = 0.0; v < 50; v += 0.37)
|
||||
{
|
||||
var centre = PixelGrid.SnapLine(v, thickness, scale) * scale;
|
||||
var left = centre - devicePixels / 2;
|
||||
Assert.Approximately(Math.Round(left), left, 1e-9, $"v={v}");
|
||||
Assert.LessOrEqual(Math.Abs(centre - v * scale), 1);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SnapRoundsToDevicePixelBoundaries()
|
||||
{
|
||||
Assert.Approximately(10, PixelGrid.Snap(10.2, 1), 1e-12);
|
||||
Assert.Approximately(10 + 2 / 3.0, PixelGrid.Snap(10.6, 1.5), 1e-12);
|
||||
Assert.Approximately(3.3, PixelGrid.Snap(3.3, 0), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Tests.Visuals;
|
||||
|
||||
public sealed class StripLayoutTests
|
||||
{
|
||||
[Test]
|
||||
public void CellsFillTheWidthExactly()
|
||||
{
|
||||
var strip = new StripLayout(898, 36, 2, 3600);
|
||||
Assert.Equal(23, strip.CellCount);
|
||||
Assert.Approximately(898, strip.CellLeft(strip.CellCount - 1) + strip.CellWidth, 1e-9);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ShortSequencesGetOneCellPerFrame()
|
||||
{
|
||||
var strip = new StripLayout(898, 36, 2, 5);
|
||||
Assert.Equal(5, strip.CellCount);
|
||||
for (var c = 0; c < 5; c++) Assert.Equal(c, strip.FrameForCell(c));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(3600, 23)]
|
||||
[Case(5, 4)]
|
||||
[Case(7, 7)]
|
||||
[Case(1001, 24)]
|
||||
[Case(24, 23)]
|
||||
public void EachCellShowsAFrameFromItsOwnRun(int frames, int cells)
|
||||
{
|
||||
var strip = new StripLayout(cells * 40 - 2, 38, 2, frames);
|
||||
Assert.Equal(Math.Min(cells, frames), strip.CellCount);
|
||||
var previous = -1;
|
||||
for (var c = 0; c < strip.CellCount; c++)
|
||||
{
|
||||
var frame = strip.FrameForCell(c);
|
||||
Assert.Equal(c, strip.CellForFrame(frame));
|
||||
Assert.Greater(frame, previous);
|
||||
previous = frame;
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SeekingMapsXToFramesContinuously()
|
||||
{
|
||||
var strip = new StripLayout(900, 36, 2, 3600);
|
||||
Assert.Equal(0, strip.FrameAt(-5));
|
||||
Assert.Equal(0, strip.FrameAt(0));
|
||||
Assert.Equal(1800, strip.FrameAt(450));
|
||||
Assert.Equal(3599, strip.FrameAt(900));
|
||||
Assert.Equal(3599, strip.FrameAt(5000));
|
||||
Assert.Equal(412, strip.FrameAt(strip.XForFrame(412)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmptyStripHasNoCells()
|
||||
{
|
||||
var strip = new StripLayout(900, 36, 2, 0);
|
||||
Assert.Equal(0, strip.CellCount);
|
||||
Assert.Equal(-1, strip.FrameAt(10));
|
||||
Assert.Equal(-1, strip.FrameForCell(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HeatmapHitTestExcludesGaps()
|
||||
{
|
||||
var grid = new CellGridLayout(30, 20, 8, 12, 16, 3);
|
||||
Assert.True(grid.TryHit(30 + 19 * 2 + 5, 20 + 19 * 7 + 15.5, out var row, out var column));
|
||||
Assert.Equal(7, row);
|
||||
Assert.Equal(2, column);
|
||||
Assert.False(grid.TryHit(30 + 16.5, 25, out _, out _));
|
||||
Assert.False(grid.TryHit(29, 25, out _, out _));
|
||||
Assert.False(grid.TryHit(30 + grid.Width + 1, 25, out _, out _));
|
||||
Assert.Approximately(12 * 19 - 3, grid.Width, 1e-12);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HeatmapCellsFitTheSmallerAxis()
|
||||
{
|
||||
Assert.Approximately(16, CellGridLayout.FitCellSize(500, 149, 8, 12, 3, 24), 1e-9);
|
||||
Assert.Approximately(24, CellGridLayout.FitCellSize(5000, 5000, 8, 12, 3, 24), 1e-9);
|
||||
Assert.Approximately((260 - 33) / 12.0, CellGridLayout.FitCellSize(260, double.PositiveInfinity, 8, 12, 3, 24), 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Tests.Visuals;
|
||||
|
||||
public sealed class ViewportMathTests
|
||||
{
|
||||
[Test]
|
||||
public void FitUsesTheLimitingAxisAndCentres()
|
||||
{
|
||||
// 8192×5464 into 900×430: height limits.
|
||||
var scale = ViewportMath.FitScale(8192, 5464, 900, 430);
|
||||
Assert.Approximately(430.0 / 5464, scale, 1e-12);
|
||||
var t = ViewportMath.Centered(scale, 8192, 5464, 900, 430);
|
||||
Assert.Approximately(0, t.OffsetY, 1e-9);
|
||||
Assert.Approximately((900 - 8192 * scale) / 2, t.OffsetX, 1e-9);
|
||||
Assert.Approximately(0, ViewportMath.FitScale(0, 100, 900, 430), 0);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ZoomAtKeepsThePointUnderTheCursorFixed()
|
||||
{
|
||||
var t = new ViewTransform(0.25, 37, -12);
|
||||
var (ix, iy) = t.ToImage(410, 220);
|
||||
var zoomed = ViewportMath.ZoomAt(t, 1.7, 410, 220);
|
||||
var (vx, vy) = zoomed.ToView(ix, iy);
|
||||
Assert.Within(410, 220, vx, vy, 1e-9);
|
||||
Assert.Approximately(1.7, zoomed.Scale, 0);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WheelZoomStepsGeometricallyAndClamps()
|
||||
{
|
||||
Assert.Approximately(1.25, ViewportMath.WheelZoom(1, 1, 0.01, 32), 1e-12);
|
||||
Assert.Approximately(1 / 1.5625, ViewportMath.WheelZoom(1, -2, 0.01, 32), 1e-12);
|
||||
Assert.Approximately(32, ViewportMath.WheelZoom(30, 3, 0.01, 32), 0);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ClampCentresSmallImagesAndCoversWithLargeOnes()
|
||||
{
|
||||
// Image 400×300 at scale 1 inside 900×430: centred on both axes whatever the offset.
|
||||
var small = ViewportMath.Clamp(new ViewTransform(1, -500, 999), 400, 300, 900, 430);
|
||||
Assert.Approximately(250, small.OffsetX, 1e-9);
|
||||
Assert.Approximately(65, small.OffsetY, 1e-9);
|
||||
|
||||
// Image 4000×3000 at scale 1: the view must stay covered.
|
||||
var large = ViewportMath.Clamp(new ViewTransform(1, 100, -5000), 4000, 3000, 900, 430);
|
||||
Assert.Approximately(0, large.OffsetX, 1e-9);
|
||||
Assert.Approximately(430 - 3000, large.OffsetY, 1e-9);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PanMovesAndRoundTripsThroughImageCoordinates()
|
||||
{
|
||||
var t = ViewportMath.Pan(new ViewTransform(2, 10, 20), -4, 6);
|
||||
Assert.Approximately(6, t.OffsetX, 0);
|
||||
Assert.Approximately(26, t.OffsetY, 0);
|
||||
var (x, y) = t.ToView(123.5, 77.25);
|
||||
var (ix, iy) = t.ToImage(x, y);
|
||||
Assert.Within(123.5, 77.25, ix, iy, 1e-12);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SnapOffsetAlignsToDevicePixels()
|
||||
{
|
||||
// 150 % DPI: 1.5 device pixels per DIP.
|
||||
var t = ViewportMath.SnapOffset(new ViewTransform(1, 10.4, -3.1), 1.5);
|
||||
Assert.Approximately(Math.Round(10.4 * 1.5), t.OffsetX * 1.5, 1e-9);
|
||||
Assert.Approximately(Math.Round(-3.1 * 1.5), t.OffsetY * 1.5, 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Threading;
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Theming;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Tests.Visuals;
|
||||
|
||||
/// <summary>
|
||||
/// Loads the real theme (Controls.xaml + Visuals.xaml) on an STA dispatcher and measures, arranges and renders
|
||||
/// every visual off screen in both themes: catches template, resource and layout errors that compile cleanly.
|
||||
/// </summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
public sealed class VisualsSmokeTests
|
||||
{
|
||||
[Test]
|
||||
public void ThemeProvidesVisualStyles() => WpfHost.Run(() =>
|
||||
{
|
||||
Assert.True(Application.Current.TryFindResource(typeof(SequenceCard)) is Style);
|
||||
Assert.True(Application.Current.TryFindResource(typeof(PreviewViewport)) is Style);
|
||||
Assert.True(Application.Current.TryFindResource("ListBox.Cards") is Style);
|
||||
Assert.True(Application.Current.TryFindResource("ListBoxItem.Card") is Style);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void EveryVisualRendersInBothThemes() => WpfHost.Run(() =>
|
||||
{
|
||||
foreach (var theme in new[] { AppTheme.Dark, AppTheme.Light })
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
foreach (var (name, element, width, height) in Samples())
|
||||
{
|
||||
var pixels = Painted(Render(element, width, height));
|
||||
Assert.Greater(pixels, 0, $"{name} drew nothing in {theme}");
|
||||
}
|
||||
}
|
||||
ThemeManager.Apply(AppTheme.Dark);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void CardFitsTheDefaultGridSlot() => WpfHost.Run(() =>
|
||||
{
|
||||
var card = SampleCard();
|
||||
card.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
|
||||
Assert.Approximately(236, card.DesiredSize.Width, 0.5);
|
||||
Assert.LessOrEqual(card.DesiredSize.Height, (double)VirtualizingWrapPanel.ItemHeightProperty.DefaultMetadata.DefaultValue + 0.5);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void WrapPanelVirtualizesHalfAMillionItems() => WpfHost.Run(() =>
|
||||
{
|
||||
var list = new ListBox
|
||||
{
|
||||
Style = (Style)Application.Current.FindResource("ListBox.Cards"),
|
||||
ItemsSource = Enumerable.Range(0, 500_000).ToArray(),
|
||||
};
|
||||
Render(list, 1300, 900);
|
||||
var panel = Assert.NotNull(FindChild<VirtualizingWrapPanel>(list));
|
||||
var columns = WrapLayout.ColumnsFor(1300 - 40, panel.ItemWidth, panel.Spacing);
|
||||
var rows = (int)Math.Ceiling(900 / (panel.ItemHeight + panel.Spacing)) + 3;
|
||||
Assert.LessOrEqual(panel.Children.Count, rows * columns);
|
||||
Assert.Approximately(100_000 * (panel.ItemHeight + panel.Spacing) - panel.Spacing + 16, panel.ExtentHeight, 1);
|
||||
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
for (var i = 0; i < 300; i++)
|
||||
{
|
||||
panel.SetVerticalOffset(panel.VerticalOffset + 37);
|
||||
list.UpdateLayout();
|
||||
}
|
||||
stopwatch.Stop();
|
||||
Assert.Less(stopwatch.Elapsed.TotalSeconds, 5, "300 scroll steps");
|
||||
Assert.LessOrEqual(panel.Children.Count, rows * columns);
|
||||
|
||||
panel.SetVerticalOffset(panel.ExtentHeight / 2);
|
||||
list.UpdateLayout();
|
||||
var first = (int)((ListBoxItem)panel.Children[0]).Content;
|
||||
Assert.InRange(first, 249_000, 251_000);
|
||||
|
||||
list.ScrollIntoView(400_000);
|
||||
list.UpdateLayout();
|
||||
Assert.NotNull(list.ItemContainerGenerator.ContainerFromIndex(400_000));
|
||||
Assert.LessOrEqual(panel.Children.Count, rows * columns);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void PreviewZoomModesMapToDevicePixels() => WpfHost.Run(() =>
|
||||
{
|
||||
var preview = new PreviewViewport { Source = Bitmap(2000, 1500) };
|
||||
Render(preview, 800, 450);
|
||||
var dpi = VisualTreeHelper.GetDpi(preview).DpiScaleX;
|
||||
Assert.Approximately(Math.Min(800 / 2000.0, 450 / 1500.0) * dpi, preview.Zoom, 1e-6);
|
||||
preview.ZoomMode = PreviewZoomMode.Actual;
|
||||
Assert.Approximately(1, preview.Zoom, 1e-9);
|
||||
preview.Zoom = 2;
|
||||
Assert.Equal(PreviewZoomMode.Custom, preview.ZoomMode);
|
||||
Assert.Approximately(2 / dpi, preview.View.Scale, 1e-9);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void SegmentsKnowTheirPosition() => WpfHost.Run(() =>
|
||||
{
|
||||
var control = SampleSegments();
|
||||
Render(control, 120, 32);
|
||||
Assert.Equal(SegmentPosition.First, ((SegmentedItem)control.Items[0]).Position);
|
||||
Assert.Equal(SegmentPosition.Middle, ((SegmentedItem)control.Items[1]).Position);
|
||||
Assert.Equal(SegmentPosition.Last, ((SegmentedItem)control.Items[2]).Position);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void FilmstripRequestsThumbnailsAsynchronously() => WpfHost.Run(() =>
|
||||
{
|
||||
var source = new FakeFrames(3600);
|
||||
var strip = new Filmstrip { Source = source, CurrentIndex = 412 };
|
||||
Render(strip, 900, 58);
|
||||
WpfHost.DoEvents();
|
||||
Assert.Greater(source.Requests, 0);
|
||||
Assert.Greater(source.LastPixelWidth, 0);
|
||||
Render(strip, 900, 58);
|
||||
Assert.Equal(412, strip.CurrentIndex);
|
||||
});
|
||||
|
||||
private static IEnumerable<(string Name, FrameworkElement Element, double Width, double Height)> Samples()
|
||||
{
|
||||
var n = 120_000;
|
||||
var measured = new double[n];
|
||||
var target = new double[n];
|
||||
var sky = new double[n];
|
||||
var random = new Random(3);
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
target[i] = 0.8 - i / (double)n * 0.6;
|
||||
measured[i] = target[i] + (random.NextDouble() - 0.5) * 0.05;
|
||||
sky[i] = i is > 500 and < 900 ? double.NaN : target[i] + 0.1;
|
||||
}
|
||||
var markers = new[] { new TimelineMarker(30_000, MarkerKind.ExposureStep, "-1 EV"), new TimelineMarker(70_000, MarkerKind.Keyframe) };
|
||||
yield return ("SeriesChart", new SeriesChart
|
||||
{
|
||||
Series =
|
||||
[
|
||||
new ChartSeries("measured", measured, "Brush.Sun") { Thickness = 1.4 },
|
||||
new ChartSeries("target", target, "Brush.Accent") { Thickness = 2.2 },
|
||||
new ChartSeries("sky", sky, "Brush.Region") { Dash = LineDash.Dashed },
|
||||
],
|
||||
Markers = markers,
|
||||
Summary = "summary",
|
||||
CurrentIndex = 1000,
|
||||
XLabelFormatter = v => v.ToString("N0"),
|
||||
}, 900, 200);
|
||||
|
||||
var items = new[] { new ChartItem("2019", 0.3), new ChartItem("2020", 0.5), new ChartItem("2021", 1.8, "1.8 TB") };
|
||||
yield return ("BarChart.Horizontal", new BarChart { Items = items, MinimumOpacity = 0.5 }, 300, 120);
|
||||
yield return ("BarChart.Vertical", new BarChart { Items = items, Orientation = Orientation.Vertical, ShowGrid = true }, 300, 160);
|
||||
yield return ("StackedBar", new StackedBar { Items = items }, 300, 60);
|
||||
|
||||
var months = new[] { "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" };
|
||||
var rows = Enumerable.Range(2019, 8).Select(y => new ChartRow(y.ToString(), Enumerable.Range(0, 12).Select(m => y == 2026 && m > 8 ? double.NaN : (double)(m * y % 97)).ToArray())).ToArray();
|
||||
yield return ("HeatmapStrip", new HeatmapStrip { Rows = rows, ColumnLabels = months }, 300, 220);
|
||||
yield return ("TimelineBands", new TimelineBands { Bands = rows, SlotLabels = months, CurrentBand = 1, CurrentSlot = 3 }, 600, 520);
|
||||
|
||||
yield return ("Filmstrip", new Filmstrip { Source = new FakeFrames(3600), Markers = markers, CurrentIndex = 500 }, 900, 58);
|
||||
yield return ("CurveEditor", new CurveEditor
|
||||
{
|
||||
Points = new ObservableCollection<Point> { new(0, 0), new(0.5, 0.3), new(1, 1) },
|
||||
Evaluator = x => x * x,
|
||||
Mode = CurveEditMode.TimeRemap,
|
||||
ShowDiagonal = true,
|
||||
PlayheadPosition = 0.4,
|
||||
SelectedIndex = 1,
|
||||
}, 400, 200);
|
||||
|
||||
yield return ("PreviewViewport", new PreviewViewport
|
||||
{
|
||||
Source = Bitmap(2000, 1500),
|
||||
OriginalSource = Bitmap(1000, 750),
|
||||
IsCompareEnabled = true,
|
||||
WipeLabel = "original | corrected",
|
||||
InfoText = "0413 / 3,600",
|
||||
ShowVectors = true,
|
||||
MotionVectors = [new MotionVector(100, 100, 3, -2), new MotionVector(900, 700, -1, 4)],
|
||||
VectorScale = 20,
|
||||
ShowRegions = true,
|
||||
RegionBoundary = [new Point(0, 800), new Point(1000, 760), new Point(2000, 820)],
|
||||
ShowCropMask = true,
|
||||
CropRect = new Rect(0.1, 0.1, 0.8, 0.8),
|
||||
}, 800, 450);
|
||||
|
||||
yield return ("SequenceCard", SampleCard(), 236, 208);
|
||||
yield return ("SegmentedControl", SampleSegments(), 120, 32);
|
||||
yield return ("SplitButton", new SplitButton { Content = "Render", ItemsSource = new[] { "4K", "1080p" }, IsPrimary = true }, 200, 32);
|
||||
}
|
||||
|
||||
private static SequenceCard SampleCard() => new()
|
||||
{
|
||||
Title = "Harbour sunset",
|
||||
Subtitle = "3,600 · Canon EOS R5 · 2 h 00 m",
|
||||
Badge = "3,600",
|
||||
Thumbnail = Bitmap(320, 180),
|
||||
IsSelected = true,
|
||||
Statuses = new[] { new CardStatus(StatusKind.Analysed, "a"), new CardStatus(StatusKind.Rendered, "2"), new CardStatus(StatusKind.Synced) },
|
||||
};
|
||||
|
||||
private static SegmentedControl SampleSegments()
|
||||
{
|
||||
var control = new SegmentedControl();
|
||||
foreach (var key in new[] { "Icon.ViewGrid", "Icon.ViewList", "Icon.ViewTimeline" })
|
||||
control.Items.Add(new SegmentedItem { Glyph = (IconData)Application.Current.FindResource(key), ToolTip = key });
|
||||
control.SelectedIndex = 0;
|
||||
return control;
|
||||
}
|
||||
|
||||
private static BitmapSource Bitmap(int width, int height)
|
||||
{
|
||||
var pixels = new byte[width * height * 4];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var i = (y * width + x) * 4;
|
||||
pixels[i] = (byte)(x * 255 / width);
|
||||
pixels[i + 1] = (byte)(y * 255 / height);
|
||||
pixels[i + 2] = 128;
|
||||
pixels[i + 3] = 255;
|
||||
}
|
||||
}
|
||||
var bitmap = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgra32, null, pixels, width * 4);
|
||||
bitmap.Freeze();
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
private static RenderTargetBitmap Render(FrameworkElement element, double width, double height)
|
||||
{
|
||||
element.Measure(new Size(width, height));
|
||||
element.Arrange(new Rect(0, 0, width, height));
|
||||
element.UpdateLayout();
|
||||
var bitmap = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32);
|
||||
bitmap.Render(element);
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
private static int Painted(BitmapSource bitmap)
|
||||
{
|
||||
var stride = bitmap.PixelWidth * 4;
|
||||
var pixels = new byte[stride * bitmap.PixelHeight];
|
||||
bitmap.CopyPixels(pixels, stride, 0);
|
||||
var count = 0;
|
||||
for (var i = 3; i < pixels.Length; i += 4)
|
||||
if (pixels[i] != 0) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
private static T? FindChild<T>(DependencyObject root)
|
||||
where T : DependencyObject
|
||||
{
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
|
||||
{
|
||||
var child = VisualTreeHelper.GetChild(root, i);
|
||||
if (child is T match) return match;
|
||||
if (FindChild<T>(child) is { } nested) return nested;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private sealed class FakeFrames(int count) : IThumbnailSource
|
||||
{
|
||||
private readonly BitmapSource _frame = Bitmap(64, 36);
|
||||
|
||||
public int Count => count;
|
||||
|
||||
public int Requests { get; private set; }
|
||||
|
||||
public int LastPixelWidth { get; private set; }
|
||||
|
||||
public ValueTask<ImageSource?> GetAsync(int index, int pixelWidth, CancellationToken cancellationToken)
|
||||
{
|
||||
Requests++;
|
||||
LastPixelWidth = pixelWidth;
|
||||
return ValueTask.FromResult<ImageSource?>(_frame);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One STA dispatcher with an Application and the Titano theme, shared by the WPF tests.</summary>
|
||||
private static class WpfHost
|
||||
{
|
||||
private static readonly Lazy<Dispatcher> Dispatcher = new(Start);
|
||||
|
||||
public static void Run(Action action) => Dispatcher.Value.Invoke(action);
|
||||
|
||||
/// <summary>Processes queued dispatcher work (async continuations) on the current dispatcher.</summary>
|
||||
public static void DoEvents()
|
||||
{
|
||||
var frame = new DispatcherFrame();
|
||||
System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, () => frame.Continue = false);
|
||||
System.Windows.Threading.Dispatcher.PushFrame(frame);
|
||||
}
|
||||
|
||||
private static Dispatcher Start()
|
||||
{
|
||||
Dispatcher? dispatcher = null;
|
||||
using var ready = new ManualResetEventSlim();
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
|
||||
ThemeManager.Initialize(app, AppTheme.Dark);
|
||||
dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
|
||||
ready.Set();
|
||||
System.Windows.Threading.Dispatcher.Run();
|
||||
});
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.IsBackground = true;
|
||||
thread.Start();
|
||||
ready.Wait();
|
||||
return dispatcher!;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Tests.Visuals;
|
||||
|
||||
public sealed class WrapLayoutTests
|
||||
{
|
||||
[Theory]
|
||||
[Case(0.0, 1)]
|
||||
[Case(235.0, 1)]
|
||||
[Case(236.0, 1)]
|
||||
[Case(487.0, 1)]
|
||||
[Case(488.0, 2)]
|
||||
[Case(1252.0, 5)]
|
||||
[Case(1255.0, 5)]
|
||||
public void ColumnsCountWholeItemsWithGapsBetween(double width, int expected)
|
||||
{
|
||||
// 236-px cards with 16-px gaps: n columns need n·236 + (n−1)·16 px.
|
||||
Assert.Equal(expected, WrapLayout.ColumnsFor(width, 236, 16));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RowsAndExtentLeaveNoTrailingGap()
|
||||
{
|
||||
var layout = new WrapLayout(11, 1252, 236, 208, 16);
|
||||
Assert.Equal(5, layout.Columns);
|
||||
Assert.Equal(3, layout.Rows);
|
||||
Assert.Approximately(3 * 224 - 16, layout.ExtentHeight, 1e-9);
|
||||
Assert.Approximately(5 * 236 + 4 * 16, layout.ExtentWidth, 1e-9);
|
||||
Assert.Approximately(0, new WrapLayout(0, 1252, 236, 208, 16).ExtentHeight, 1e-9);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IndexMapsToRowColumnAndPixelOrigin()
|
||||
{
|
||||
var layout = new WrapLayout(500_000, 1252, 236, 208, 16);
|
||||
Assert.Equal(1234, layout.RowOf(6172));
|
||||
Assert.Equal(2, layout.ColumnOf(6172));
|
||||
Assert.Approximately(2 * 252, layout.LeftOf(6172), 1e-9);
|
||||
Assert.Approximately(1234 * 224, layout.TopOf(6172), 1e-6);
|
||||
Assert.Equal(100_000, layout.Rows);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void VisibleRangeIsConstantTimeAndCoversPartialRows()
|
||||
{
|
||||
var layout = new WrapLayout(500_000, 1252, 236, 208, 16);
|
||||
// Offset in the middle of row 50 000's gap: row 50 000 has ended, row 50 001 starts at 50 001·224.
|
||||
var offset = 50_000 * 224.0 + 210;
|
||||
var (first, last) = layout.VisibleRange(offset, 600);
|
||||
Assert.Equal(50_001 * 5, first);
|
||||
// Bottom edge at offset + 600 = 50 000·224 + 810 → rows up to 50 003 (starts at +672) are visible.
|
||||
Assert.Equal(50_004 * 5 - 1, last);
|
||||
|
||||
var (cachedFirst, cachedLast) = layout.VisibleRange(offset, 600, cacheRows: 1);
|
||||
Assert.Equal(first - 5, cachedFirst);
|
||||
Assert.Equal(last + 5, cachedLast);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void VisibleRangeExcludesRowStartingAtBottomEdge()
|
||||
{
|
||||
var layout = new WrapLayout(100, 1252, 236, 208, 16);
|
||||
var (first, last) = layout.VisibleRange(0, 224);
|
||||
Assert.Equal(0, first);
|
||||
Assert.Equal(4, last);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void VisibleRangeClampsToLastPartialRow()
|
||||
{
|
||||
var layout = new WrapLayout(12, 1252, 236, 208, 16);
|
||||
var (first, last) = layout.VisibleRange(0, 10_000, cacheRows: 2);
|
||||
Assert.Equal(0, first);
|
||||
Assert.Equal(11, last);
|
||||
Assert.Equal((0, -1), new WrapLayout(0, 1252, 236, 208, 16).VisibleRange(0, 500));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OffsetToRevealScrollsTheLeastAmount()
|
||||
{
|
||||
var layout = new WrapLayout(100, 1252, 236, 208, 16);
|
||||
// Row 3 spans [672, 880): below a viewport [0, 600) → bottom-aligned.
|
||||
Assert.Approximately(880 - 600, layout.OffsetToReveal(15, 0, 600), 1e-9);
|
||||
// Already visible → unchanged.
|
||||
Assert.Approximately(300, layout.OffsetToReveal(15, 300, 600), 1e-9);
|
||||
// Above the viewport → top-aligned.
|
||||
Assert.Approximately(224, layout.OffsetToReveal(5, 1000, 600), 1e-9);
|
||||
// Taller than the viewport → top-aligned.
|
||||
Assert.Approximately(672, WrapLayout.OffsetToReveal(672, 208, 0, 100), 1e-9);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ClampOffsetKeepsViewportInsideExtent()
|
||||
{
|
||||
var layout = new WrapLayout(10, 1252, 236, 208, 16);
|
||||
Assert.Approximately(432 - 300, layout.ClampOffset(5000, 300), 1e-9);
|
||||
Assert.Approximately(0, layout.ClampOffset(-20, 300), 1e-9);
|
||||
Assert.Approximately(0, layout.ClampOffset(50, 1000), 1e-9);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JustifySpreadsLeftoverWidthOverGaps()
|
||||
{
|
||||
var layout = new WrapLayout(10, 1300, 236, 208, 16, justify: true);
|
||||
Assert.Equal(5, layout.Columns);
|
||||
Assert.Approximately(1300, layout.LeftOf(4) + 236, 1e-9);
|
||||
Assert.Approximately(1300, layout.ExtentWidth, 1e-9);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(7, WrapStep.Left, 6)]
|
||||
[Case(5, WrapStep.Left, 4)]
|
||||
[Case(0, WrapStep.Left, 0)]
|
||||
[Case(4, WrapStep.Right, 5)]
|
||||
[Case(11, WrapStep.Right, 11)]
|
||||
[Case(7, WrapStep.Up, 2)]
|
||||
[Case(2, WrapStep.Up, 2)]
|
||||
[Case(2, WrapStep.Down, 7)]
|
||||
[Case(9, WrapStep.Down, 11)]
|
||||
[Case(11, WrapStep.Down, 11)]
|
||||
[Case(7, WrapStep.First, 0)]
|
||||
[Case(7, WrapStep.Last, 11)]
|
||||
public void KeyboardStepsFollowReadingOrderAndColumns(int from, WrapStep step, int expected)
|
||||
{
|
||||
// 12 items in rows of 5: 0–4, 5–9, 10–11.
|
||||
var layout = new WrapLayout(12, 1252, 236, 208, 16);
|
||||
Assert.Equal(expected, layout.Navigate(from, step, pageRows: 2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PageStepsMoveWholeViewportRowsInTheSameColumn()
|
||||
{
|
||||
var layout = new WrapLayout(1000, 1252, 236, 208, 16);
|
||||
var pageRows = layout.PageRows(700);
|
||||
Assert.Equal(3, pageRows);
|
||||
Assert.Equal(2 + 3 * 5, layout.Navigate(2, WrapStep.PageDown, pageRows));
|
||||
Assert.Equal(2, layout.Navigate(2 + 3 * 5, WrapStep.PageUp, pageRows));
|
||||
Assert.Equal(3, layout.Navigate(8, WrapStep.PageUp, pageRows));
|
||||
// From row 198 a page down is clamped to the last row, same column.
|
||||
Assert.Equal(999, layout.Navigate(994, WrapStep.PageDown, pageRows));
|
||||
Assert.Equal(-1, new WrapLayout(0, 1252, 236, 208, 16).Navigate(0, WrapStep.Down, 1));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user