diff --git a/README.md b/README.md
index 73ec877..9565c7a 100644
--- a/README.md
+++ b/README.md
@@ -8,6 +8,8 @@
dotnet add package OxyPlot.Avalonia
```
+The package targets Avalonia 12 and requires .NET 8 or later.
+
### Usage
To use the library, add the following to your `App.xaml`:
@@ -23,7 +25,7 @@ To use the library, add the following to your `App.xaml`:
-
+
diff --git a/Source/Directory.Build.props b/Source/Directory.Build.props
index 3f15db6..69caaa0 100644
--- a/Source/Directory.Build.props
+++ b/Source/Directory.Build.props
@@ -1,6 +1,6 @@
- 11.0.0
- 2.1.2
+ 12.1.4
+ 2.2.0
\ No newline at end of file
diff --git a/Source/Examples/Avalonia/AvaloniaExamples/App.axaml.cs b/Source/Examples/Avalonia/AvaloniaExamples/App.axaml.cs
index 3d40e69..edbb4c7 100644
--- a/Source/Examples/Avalonia/AvaloniaExamples/App.axaml.cs
+++ b/Source/Examples/Avalonia/AvaloniaExamples/App.axaml.cs
@@ -38,11 +38,5 @@ static void Main(string[] args)
.StartWithClassicDesktopLifetime(args);
}
- public static void AttachDevTools(Window window)
- {
-#if DEBUG
- DevToolsExtensions.AttachDevTools(window);
-#endif
- }
}
}
diff --git a/Source/Examples/Avalonia/AvaloniaExamples/AvaloniaExamples.csproj b/Source/Examples/Avalonia/AvaloniaExamples/AvaloniaExamples.csproj
index 3540b23..58627f7 100644
--- a/Source/Examples/Avalonia/AvaloniaExamples/AvaloniaExamples.csproj
+++ b/Source/Examples/Avalonia/AvaloniaExamples/AvaloniaExamples.csproj
@@ -2,6 +2,7 @@
net8.0
WinExe
+ false
@@ -11,6 +12,5 @@
-
\ No newline at end of file
diff --git a/Source/Examples/Avalonia/AvaloniaExamples/Examples/AnimationsDemo/MainWindow.axaml.cs b/Source/Examples/Avalonia/AvaloniaExamples/Examples/AnimationsDemo/MainWindow.axaml.cs
index 5add1fc..c0b1fd7 100644
--- a/Source/Examples/Avalonia/AvaloniaExamples/Examples/AnimationsDemo/MainWindow.axaml.cs
+++ b/Source/Examples/Avalonia/AvaloniaExamples/Examples/AnimationsDemo/MainWindow.axaml.cs
@@ -22,7 +22,6 @@ public partial class MainWindow : Avalonia.Controls.Window
public MainWindow()
{
this.InitializeComponent();
- App.AttachDevTools(this);
}
private void InitializeComponent()
diff --git a/Source/Examples/Avalonia/AvaloniaExamples/Examples/BarSeriesDemo/MainWindow.axaml.cs b/Source/Examples/Avalonia/AvaloniaExamples/Examples/BarSeriesDemo/MainWindow.axaml.cs
index e7b290a..4fdaeb6 100644
--- a/Source/Examples/Avalonia/AvaloniaExamples/Examples/BarSeriesDemo/MainWindow.axaml.cs
+++ b/Source/Examples/Avalonia/AvaloniaExamples/Examples/BarSeriesDemo/MainWindow.axaml.cs
@@ -51,7 +51,6 @@ public MainWindow()
this.InitializeComponent();
- App.AttachDevTools(this);
}
private void InitializeComponent()
diff --git a/Source/Examples/Avalonia/AvaloniaExamples/Examples/DataTemplateDemo/PlotViewDataTemplateWindow.axaml.cs b/Source/Examples/Avalonia/AvaloniaExamples/Examples/DataTemplateDemo/PlotViewDataTemplateWindow.axaml.cs
index 75e9beb..dfaccca 100644
--- a/Source/Examples/Avalonia/AvaloniaExamples/Examples/DataTemplateDemo/PlotViewDataTemplateWindow.axaml.cs
+++ b/Source/Examples/Avalonia/AvaloniaExamples/Examples/DataTemplateDemo/PlotViewDataTemplateWindow.axaml.cs
@@ -43,7 +43,6 @@ public PlotViewDataTemplateWindow()
private void InitializeComponent()
{
Avalonia.Markup.Xaml.AvaloniaXamlLoader.Load(this);
- App.AttachDevTools(this);
}
private static Random r = new Random(13);
diff --git a/Source/Examples/Avalonia/AvaloniaExamples/Examples/UserControlDemo/MainWindow.axaml.cs b/Source/Examples/Avalonia/AvaloniaExamples/Examples/UserControlDemo/MainWindow.axaml.cs
index 8bca701..d085f83 100644
--- a/Source/Examples/Avalonia/AvaloniaExamples/Examples/UserControlDemo/MainWindow.axaml.cs
+++ b/Source/Examples/Avalonia/AvaloniaExamples/Examples/UserControlDemo/MainWindow.axaml.cs
@@ -23,7 +23,6 @@ public MainWindow()
{
this.InitializeComponent();
this.DataContext = new { Model1 = new ViewModel { Title = "Plot1" }, Model2 = new ViewModel { Title = "Plot2" } };
- App.AttachDevTools(this);
}
private void InitializeComponent()
diff --git a/Source/Examples/Avalonia/AvaloniaExamples/Examples/UserControlDemo/MainWindow2.axaml.cs b/Source/Examples/Avalonia/AvaloniaExamples/Examples/UserControlDemo/MainWindow2.axaml.cs
index a166c1e..9d5123c 100644
--- a/Source/Examples/Avalonia/AvaloniaExamples/Examples/UserControlDemo/MainWindow2.axaml.cs
+++ b/Source/Examples/Avalonia/AvaloniaExamples/Examples/UserControlDemo/MainWindow2.axaml.cs
@@ -24,7 +24,6 @@ public MainWindow2()
{
this.InitializeComponent();
this.DataContext = new { Models = new List { new ViewModel { Title = "Plot1" }, new ViewModel { Title = "Plot2" } } };
- App.AttachDevTools(this);
}
private void InitializeComponent()
diff --git a/Source/Examples/Avalonia/AvaloniaExamples/MainWindow.axaml.cs b/Source/Examples/Avalonia/AvaloniaExamples/MainWindow.axaml.cs
index 74b48dc..75fedd6 100644
--- a/Source/Examples/Avalonia/AvaloniaExamples/MainWindow.axaml.cs
+++ b/Source/Examples/Avalonia/AvaloniaExamples/MainWindow.axaml.cs
@@ -19,7 +19,6 @@ namespace AvaloniaExamples
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
- using Avalonia.Diagnostics;
using Avalonia.Interactivity;
///
@@ -35,7 +34,6 @@ public MainWindow()
InitializeComponent();
ListBox.ItemsSource = this.Examples = this.GetExamples(this.GetType().Assembly).OrderBy(e => e.Title).ToArray();
this.DataContext = this;
- DevToolsExtensions.AttachDevTools(this);
}
private void InitializeComponent()
diff --git a/Source/Examples/Avalonia/ExampleBrowser/ExampleBrowser.csproj b/Source/Examples/Avalonia/ExampleBrowser/ExampleBrowser.csproj
index 90ea5f9..ca3cce2 100644
--- a/Source/Examples/Avalonia/ExampleBrowser/ExampleBrowser.csproj
+++ b/Source/Examples/Avalonia/ExampleBrowser/ExampleBrowser.csproj
@@ -2,11 +2,11 @@
WinExe
net8.0
+ false
-
diff --git a/Source/Examples/Avalonia/ExampleBrowser/MainWindow.axaml.cs b/Source/Examples/Avalonia/ExampleBrowser/MainWindow.axaml.cs
index 671653a..c8a0e51 100644
--- a/Source/Examples/Avalonia/ExampleBrowser/MainWindow.axaml.cs
+++ b/Source/Examples/Avalonia/ExampleBrowser/MainWindow.axaml.cs
@@ -9,9 +9,6 @@ public partial class MainWindow : Window
public MainWindow()
{
InitializeComponent();
-#if DEBUG
- this.AttachDevTools();
-#endif
}
private void InitializeComponent()
diff --git a/Source/Examples/Avalonia/MemoryTest/App.axaml.cs b/Source/Examples/Avalonia/MemoryTest/App.axaml.cs
index 361180d..7dc3cef 100644
--- a/Source/Examples/Avalonia/MemoryTest/App.axaml.cs
+++ b/Source/Examples/Avalonia/MemoryTest/App.axaml.cs
@@ -39,11 +39,5 @@ static void Main(string[] args)
.StartWithClassicDesktopLifetime(args);
}
- public static void AttachDevTools(Window window)
- {
-#if DEBUG
- DevToolsExtensions.AttachDevTools(window);
-#endif
- }
}
}
diff --git a/Source/Examples/Avalonia/MemoryTest/MainWindow.axaml.cs b/Source/Examples/Avalonia/MemoryTest/MainWindow.axaml.cs
index 6c19274..a46d688 100644
--- a/Source/Examples/Avalonia/MemoryTest/MainWindow.axaml.cs
+++ b/Source/Examples/Avalonia/MemoryTest/MainWindow.axaml.cs
@@ -8,7 +8,6 @@ public partial class MainWindow : Window
public MainWindow()
{
this.InitializeComponent();
- App.AttachDevTools(this);
}
private void InitializeComponent()
diff --git a/Source/Examples/Avalonia/MemoryTest/MemoryTest.csproj b/Source/Examples/Avalonia/MemoryTest/MemoryTest.csproj
index c13c26a..2f64e36 100644
--- a/Source/Examples/Avalonia/MemoryTest/MemoryTest.csproj
+++ b/Source/Examples/Avalonia/MemoryTest/MemoryTest.csproj
@@ -2,12 +2,12 @@
net8.0
Exe
+ false
-
\ No newline at end of file
diff --git a/Source/Examples/Avalonia/MemoryTest/Window1.axaml.cs b/Source/Examples/Avalonia/MemoryTest/Window1.axaml.cs
index b04f0db..0722c51 100644
--- a/Source/Examples/Avalonia/MemoryTest/Window1.axaml.cs
+++ b/Source/Examples/Avalonia/MemoryTest/Window1.axaml.cs
@@ -18,7 +18,6 @@ public Window1()
InitializeComponent();
- App.AttachDevTools(this);
}
private void InitializeComponent()
diff --git a/Source/Examples/Avalonia/MemoryTest/Window2.axaml.cs b/Source/Examples/Avalonia/MemoryTest/Window2.axaml.cs
index 71745e0..9382e75 100644
--- a/Source/Examples/Avalonia/MemoryTest/Window2.axaml.cs
+++ b/Source/Examples/Avalonia/MemoryTest/Window2.axaml.cs
@@ -22,7 +22,6 @@ public Window2()
}
InitializeComponent();
- App.AttachDevTools(this);
DataContext = Plots;
}
diff --git a/Source/Examples/Avalonia/SimpleDemo/MainWindow.axaml.cs b/Source/Examples/Avalonia/SimpleDemo/MainWindow.axaml.cs
index 44352a2..ef55e84 100644
--- a/Source/Examples/Avalonia/SimpleDemo/MainWindow.axaml.cs
+++ b/Source/Examples/Avalonia/SimpleDemo/MainWindow.axaml.cs
@@ -9,7 +9,6 @@
using Avalonia;
using Avalonia.Controls;
-using Avalonia.Diagnostics;
using Avalonia.Markup.Xaml;
namespace SimpleDemo
@@ -25,7 +24,6 @@ public partial class MainWindow : Window
public MainWindow()
{
InitializeComponent();
- this.AttachDevTools();
}
private void InitializeComponent()
diff --git a/Source/Examples/Avalonia/SimpleDemo/SimpleDemo.csproj b/Source/Examples/Avalonia/SimpleDemo/SimpleDemo.csproj
index e84ede3..168bcf8 100644
--- a/Source/Examples/Avalonia/SimpleDemo/SimpleDemo.csproj
+++ b/Source/Examples/Avalonia/SimpleDemo/SimpleDemo.csproj
@@ -2,6 +2,7 @@
net8.0
Exe
+ false
@@ -9,6 +10,5 @@
-
\ No newline at end of file
diff --git a/Source/OxyPlot.Avalonia.Tests/AnnotationTests.cs b/Source/OxyPlot.Avalonia.Tests/AnnotationTests.cs
new file mode 100644
index 0000000..4dc9772
--- /dev/null
+++ b/Source/OxyPlot.Avalonia.Tests/AnnotationTests.cs
@@ -0,0 +1,168 @@
+using Avalonia.Headless.XUnit;
+using Avalonia.Media;
+using OxyPlot;
+using OxyPlot.Avalonia;
+using AvaloniaHorizontalAlignment = Avalonia.Layout.HorizontalAlignment;
+using AvaloniaVerticalAlignment = Avalonia.Layout.VerticalAlignment;
+using CoreAnnotations = OxyPlot.Annotations;
+using CoreAxes = OxyPlot.Axes;
+using ShapePath = Avalonia.Controls.Shapes.Path;
+
+namespace OxyPlot.Avalonia.Tests;
+
+///
+/// Tests of the annotation controls: default values, copying to the core and rendering without failures.
+///
+public class AnnotationTests
+{
+ [AvaloniaFact]
+ public void RectangleAnnotation_HorizontalBand_DrawsAcrossPlotArea()
+ {
+ var plot = PlotWithAxes();
+ plot.Annotations.Add(new RectangleAnnotation { MinimumY = 4, MaximumY = 6 });
+
+ // Show used to throw InvalidOperationException from Measure: the rectangle went to infinity
+ var window = Ui.Show(plot);
+
+ var plotArea = plot.ActualModel.PlotArea;
+ var band = Assert.Single(
+ Ui.PlotCanvas(plot).Children.OfType(),
+ p => p.Fill != null && p.Data is RectangleGeometry);
+ var rect = ((RectangleGeometry)band.Data!).Rect;
+ Assert.Equal(plotArea.Width, rect.Width, 3);
+ Assert.True(rect.Height > 0 && rect.Height < plotArea.Height);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void RectangleAnnotation_Defaults_AreInfiniteAsInCore()
+ {
+ var annotation = new RectangleAnnotation();
+
+ Assert.Equal(double.NegativeInfinity, annotation.MinimumX);
+ Assert.Equal(double.PositiveInfinity, annotation.MaximumX);
+ Assert.Equal(double.NegativeInfinity, annotation.MinimumY);
+ Assert.Equal(double.PositiveInfinity, annotation.MaximumY);
+ }
+
+ [AvaloniaFact]
+ public void RectangleAnnotation_LegacyMinMaxValues_BecomeInfiniteInModel()
+ {
+ // the previous values double.MinValue/MaxValue still mean "no bound"
+ var annotation = new RectangleAnnotation
+ {
+ MinimumX = double.MinValue,
+ MaximumX = double.MaxValue,
+ MinimumY = 1,
+ MaximumY = 2,
+ };
+
+ var model = Assert.IsType(annotation.CreateModel());
+
+ Assert.Equal(double.NegativeInfinity, model.MinimumX);
+ Assert.Equal(double.PositiveInfinity, model.MaximumX);
+ Assert.Equal(1, model.MinimumY);
+ Assert.Equal(2, model.MaximumY);
+ }
+
+ [AvaloniaFact]
+ public void EllipseAnnotation_WithoutSize_DoesNotBreakLayout()
+ {
+ var plot = PlotWithAxes();
+ plot.Annotations.Add(new EllipseAnnotation { X = 5, Y = 5 });
+
+ var window = Ui.Show(plot);
+
+ Assert.True(plot.ActualModel.PlotArea.Width > 0);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void TextAnnotation_WithoutPosition_DoesNotBreakLayout()
+ {
+ var plot = PlotWithAxes();
+ plot.Annotations.Add(new TextAnnotation { Text = "label" });
+
+ var window = Ui.Show(plot);
+
+ Assert.True(plot.ActualModel.PlotArea.Width > 0);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotView_CoreEllipseAnnotationWithoutSize_DoesNotBreakLayout()
+ {
+ // the core itself builds an ellipse with a NaN size, so the protection is needed in the render context
+ var model = Ui.ModelWithAxes();
+ model.Annotations.Add(new CoreAnnotations.EllipseAnnotation { X = 5, Y = 5 });
+ var view = new PlotView { Model = model };
+
+ var window = Ui.Show(view);
+
+ Assert.True(model.PlotArea.Width > 0);
+ window.Close();
+ }
+
+ [AvaloniaTheory]
+ [InlineData(0)]
+ [InlineData(-1)]
+ public void FunctionAnnotation_NonPositiveResolution_Throws(int value)
+ {
+ // the core divides the range by Resolution and steps to the bound: the loop would never end
+ Assert.Throws(() => new FunctionAnnotation { Resolution = value });
+ }
+
+ [AvaloniaFact]
+ public void PolygonAnnotation_TwoInstances_HaveSeparatePointLists()
+ {
+ var first = new PolygonAnnotation();
+ var second = new PolygonAnnotation();
+
+ first.Points.Add(new DataPoint(1, 1));
+
+ Assert.NotSame(first.Points, second.Points);
+ Assert.Empty(second.Points);
+ }
+
+ [AvaloniaFact]
+ public void PolylineAnnotation_TwoInstances_HaveSeparatePointLists()
+ {
+ var first = new PolylineAnnotation();
+ var second = new PolylineAnnotation();
+
+ first.Points.Add(new DataPoint(1, 1));
+
+ Assert.NotSame(first.Points, second.Points);
+ Assert.Empty(second.Points);
+ }
+
+ [AvaloniaFact]
+ public void TextAnnotation_TextAlignment_ReachesModelInsteadOfLayoutAlignment()
+ {
+ // the layout alignment of the control must not replace the text alignment
+ var annotation = new TextAnnotation
+ {
+ Text = "label",
+ TextHorizontalAlignment = AvaloniaHorizontalAlignment.Left,
+ TextVerticalAlignment = AvaloniaVerticalAlignment.Bottom,
+ HorizontalAlignment = AvaloniaHorizontalAlignment.Right,
+ VerticalAlignment = AvaloniaVerticalAlignment.Top,
+ };
+
+ var model = Assert.IsType(annotation.CreateModel());
+
+ Assert.Equal(HorizontalAlignment.Left, model.TextHorizontalAlignment);
+ Assert.Equal(VerticalAlignment.Bottom, model.TextVerticalAlignment);
+ }
+
+ ///
+ /// A plot with linear axes 0..10 on which the annotations get screen coordinates.
+ ///
+ private static Plot PlotWithAxes()
+ {
+ var plot = new Plot();
+ plot.Axes.Add(new LinearAxis { Position = CoreAxes.AxisPosition.Bottom, Minimum = 0, Maximum = 10 });
+ plot.Axes.Add(new LinearAxis { Position = CoreAxes.AxisPosition.Left, Minimum = 0, Maximum = 10 });
+ return plot;
+ }
+}
diff --git a/Source/OxyPlot.Avalonia.Tests/AxisTests.cs b/Source/OxyPlot.Avalonia.Tests/AxisTests.cs
new file mode 100644
index 0000000..9452c8b
--- /dev/null
+++ b/Source/OxyPlot.Avalonia.Tests/AxisTests.cs
@@ -0,0 +1,188 @@
+using Avalonia;
+using Avalonia.Headless.XUnit;
+using Avalonia.Media;
+using Avalonia.Styling;
+using OxyPlot;
+using OxyPlot.Avalonia;
+using CoreAxes = OxyPlot.Axes;
+
+namespace OxyPlot.Avalonia.Tests;
+
+///
+/// Tests of the axis controls: default values, value validation and copying to the axes of the core.
+///
+public class AxisTests
+{
+ [AvaloniaFact]
+ public void AngleAxis_Default_PositionAllAsInCore()
+ {
+ var axis = new AngleAxis();
+
+ // with None the axis does not reserve margins and the angle labels are clipped
+ Assert.Equal(new CoreAxes.AngleAxis().Position, axis.CreateModel().Position);
+ Assert.Equal(CoreAxes.AxisPosition.All, axis.Position);
+ }
+
+ [AvaloniaFact]
+ public void AngleAxis_Default_SolidGridlines()
+ {
+ var axis = new AngleAxis();
+
+ Assert.Equal(LineStyle.Solid, axis.MajorGridlineStyle);
+ Assert.Equal(LineStyle.Solid, axis.MinorGridlineStyle);
+ }
+
+ [AvaloniaFact]
+ public void AngleAxis_StyleSetter_OverridesGridlineStyle()
+ {
+ var angle = new AngleAxis();
+ var plot = new Plot { PlotType = PlotType.Polar };
+ plot.Styles.Add(new Style(x => x.OfType())
+ {
+ Setters = { new Setter(Axis.MajorGridlineStyleProperty, LineStyle.Dot) },
+ });
+ plot.Axes.Add(angle);
+ plot.Axes.Add(new MagnitudeAxis());
+
+ var window = Ui.Show(plot);
+
+ // the value from the constructor was a local one and overrode the style
+ Assert.Equal(LineStyle.Dot, angle.MajorGridlineStyle);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void LogarithmicAxis_Default_FilterMinValueZero()
+ {
+ Assert.Equal(0.0, new LogarithmicAxis().FilterMinValue);
+ }
+
+ [AvaloniaFact]
+ public void LogarithmicAxis_StyleSetter_OverridesFilterMinValue()
+ {
+ var axis = new LogarithmicAxis { Position = CoreAxes.AxisPosition.Left };
+ var plot = new Plot();
+ plot.Styles.Add(new Style(x => x.OfType())
+ {
+ Setters = { new Setter(Axis.FilterMinValueProperty, -5.0) },
+ });
+ plot.Axes.Add(axis);
+
+ var window = Ui.Show(plot);
+
+ Assert.Equal(-5.0, axis.FilterMinValue);
+ window.Close();
+ }
+
+ [AvaloniaTheory]
+ [InlineData(1.0)]
+ [InlineData(0.0)]
+ [InlineData(-2.0)]
+ [InlineData(double.NaN)]
+ [InlineData(double.PositiveInfinity)]
+ public void LogarithmicAxis_InvalidBase_Throws(double value)
+ {
+ // with such a base the core cannot compute the ticks and rendering hangs
+ Assert.Throws(() => new LogarithmicAxis { Base = value });
+ }
+
+ [AvaloniaFact]
+ public void LogarithmicAxis_BaseTwo_ReachesModel()
+ {
+ var model = Assert.IsType(new LogarithmicAxis { Base = 2 }.CreateModel());
+
+ Assert.Equal(2, model.Base);
+ }
+
+ [AvaloniaFact]
+ public void Axis_MarginsAndExtraGridlines_ReachModel()
+ {
+ var axis = new LinearAxis { MinimumMargin = 3, MaximumMargin = 7, ExtraGridlines = new[] { 1.0, 2.0 } };
+
+ var model = axis.CreateModel();
+
+ // MaximumMargin used to receive the value of MinimumMargin
+ Assert.Equal(3, model.MinimumMargin);
+ Assert.Equal(7, model.MaximumMargin);
+ Assert.Equal(new[] { 1.0, 2.0 }, model.ExtraGridlines);
+
+ // the name of the Avalonia property matches the name of the CLR property, otherwise the attribute in markup is not found
+ Assert.Same(Axis.ExtraGridlinesProperty, AvaloniaPropertyRegistry.Instance.FindRegistered(axis, nameof(Axis.ExtraGridlines)));
+ }
+
+ [AvaloniaFact]
+ public void LinearColorAxis_TwoStops_InterpolatesRequestedPaletteSize()
+ {
+ var axis = new LinearColorAxis { PaletteSize = 5 };
+ axis.GradientStops.Add(new GradientStop(Colors.Black, 0));
+ axis.GradientStops.Add(new GradientStop(Colors.White, 1));
+
+ var palette = ((CoreAxes.LinearColorAxis)axis.CreateModel()).Palette.Colors;
+
+ Assert.Equal(5, palette.Count);
+ Assert.Equal(OxyColors.Black, palette[0]);
+ Assert.Equal(OxyColors.White, palette[4]);
+ }
+
+ [AvaloniaFact]
+ public void LinearColorAxis_PaletteSizeOne_GivesSingleColor()
+ {
+ var axis = new LinearColorAxis { PaletteSize = 1 };
+ axis.GradientStops.Add(new GradientStop(Colors.Black, 0));
+ axis.GradientStops.Add(new GradientStop(Colors.White, 1));
+
+ var palette = ((CoreAxes.LinearColorAxis)axis.CreateModel()).Palette.Colors;
+
+ Assert.Single(palette);
+ }
+
+ [AvaloniaFact]
+ public void LinearColorAxis_StopsAtSameOffset_KeepsPaletteSize()
+ {
+ var axis = new LinearColorAxis { PaletteSize = 4 };
+ axis.GradientStops.Add(new GradientStop(Colors.Red, 0.5));
+ axis.GradientStops.Add(new GradientStop(Colors.Blue, 0.5));
+
+ var palette = ((CoreAxes.LinearColorAxis)axis.CreateModel()).Palette.Colors;
+
+ Assert.Equal(4, palette.Count);
+ }
+
+ [AvaloniaFact]
+ public void LinearColorAxis_OneStop_GivesPaletteOfThatColor()
+ {
+ var axis = new LinearColorAxis { PaletteSize = 3 };
+ axis.GradientStops.Add(new GradientStop(Colors.Red, 0.2));
+
+ var palette = ((CoreAxes.LinearColorAxis)axis.CreateModel()).Palette.Colors;
+
+ Assert.Equal(3, palette.Count);
+ Assert.All(palette, c => Assert.Equal(OxyColors.Red, c));
+ }
+
+ [AvaloniaFact]
+ public void LinearColorAxis_NoStops_KeepsCorePalette()
+ {
+ var palette = ((CoreAxes.LinearColorAxis)new LinearColorAxis().CreateModel()).Palette.Colors;
+
+ Assert.Equal(new CoreAxes.LinearColorAxis().Palette.Colors, palette);
+ }
+
+ [AvaloniaFact]
+ public void LinearColorAxis_PaletteSizeZero_Throws()
+ {
+ Assert.Throws(() => new LinearColorAxis { PaletteSize = 0 });
+ }
+
+ [AvaloniaFact]
+ public void CategoryAxis_TwoInstances_HaveSeparateLabelLists()
+ {
+ var first = new CategoryAxis();
+ var second = new CategoryAxis();
+
+ first.Labels.Add("a");
+
+ Assert.NotSame(first.Labels, second.Labels);
+ Assert.Empty(second.Labels);
+ }
+}
diff --git a/Source/OxyPlot.Avalonia.Tests/ExportTests.cs b/Source/OxyPlot.Avalonia.Tests/ExportTests.cs
new file mode 100644
index 0000000..d6da516
--- /dev/null
+++ b/Source/OxyPlot.Avalonia.Tests/ExportTests.cs
@@ -0,0 +1,72 @@
+using Avalonia.Headless.XUnit;
+using OxyPlot;
+using OxyPlot.Avalonia;
+using CoreSeries = OxyPlot.Series;
+
+namespace OxyPlot.Avalonia.Tests;
+
+///
+/// Tests of the plot export to PNG.
+///
+public class ExportTests
+{
+ [AvaloniaFact]
+ public void PngExporter_Export_WritesPngOfRequestedSize()
+ {
+ var model = new PlotModel();
+ model.Series.Add(new CoreSeries.FunctionSeries(Math.Sin, 0, 10, 0.1));
+ using var stream = new MemoryStream();
+
+ PngExporter.Export(model, stream, 200, 100, OxyColors.White);
+
+ var bytes = stream.ToArray();
+ Assert.Equal(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, bytes.Take(8));
+
+ // the width and the height are in the IHDR header, big-endian
+ Assert.Equal(200, ReadBigEndian(bytes, 16));
+ Assert.Equal(100, ReadBigEndian(bytes, 20));
+ }
+
+ [AvaloniaFact]
+ public void PlotView_SaveBitmapOfOtherSize_RestoresScreenLayout()
+ {
+ var model = new PlotModel();
+ model.Series.Add(new CoreSeries.FunctionSeries(Math.Sin, 0, 10, 0.1));
+ var view = new PlotView { Model = model };
+ var window = Ui.Show(view);
+ var plotArea = model.PlotArea;
+ using var stream = new MemoryStream();
+
+ view.SaveBitmap(stream, 800, 600, OxyColors.White);
+ Ui.Flush();
+
+ // the export recalculates the live model for its own size, and the control restores it to its own
+ Assert.True(stream.Length > 0);
+ Assert.Equal(plotArea, model.PlotArea);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotView_SaveBitmapWithoutModel_ThrowsInvalidOperation()
+ {
+ var view = new PlotView();
+ using var stream = new MemoryStream();
+
+ Assert.Throws(() => view.SaveBitmap(stream));
+ Assert.Throws(() => view.ToBitmap());
+ }
+
+ [AvaloniaFact]
+ public void PlotView_ToBitmapBeforeLayout_ThrowsInvalidOperation()
+ {
+ var view = new PlotView { Model = new PlotModel() };
+
+ // the control has not been laid out yet, its size is zero
+ Assert.Throws(() => view.ToBitmap());
+ }
+
+ private static int ReadBigEndian(byte[] bytes, int offset)
+ {
+ return (bytes[offset] << 24) | (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3];
+ }
+}
diff --git a/Source/OxyPlot.Avalonia.Tests/InputTests.cs b/Source/OxyPlot.Avalonia.Tests/InputTests.cs
new file mode 100644
index 0000000..8eb85eb
--- /dev/null
+++ b/Source/OxyPlot.Avalonia.Tests/InputTests.cs
@@ -0,0 +1,185 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Headless;
+using Avalonia.Headless.XUnit;
+using Avalonia.Input;
+using Avalonia.Interactivity;
+using OxyPlot;
+using OxyPlot.Avalonia;
+
+namespace OxyPlot.Avalonia.Tests;
+
+///
+/// Input tests: the wheel, the right button with a context menu, the loss of the pointer capture.
+///
+public class InputTests
+{
+ private static readonly Point Center = new(200, 150);
+
+ [AvaloniaTheory]
+ [InlineData(0.25)]
+ [InlineData(-0.25)]
+ [InlineData(1.0)]
+ public void PlotView_WheelDelta_ZoomsAxis(double delta)
+ {
+ // a touchpad gives a fractional step: rounding before the multiplication turned it into zero
+ var model = Ui.ModelWithAxes();
+ var view = new PlotView { Model = model };
+ var window = Ui.Show(view);
+ var range = model.Axes[0].ActualMaximum - model.Axes[0].ActualMinimum;
+
+ window.MouseWheel(Center, new Vector(0, delta));
+ Ui.Flush();
+
+ var newRange = model.Axes[0].ActualMaximum - model.Axes[0].ActualMinimum;
+ if (delta > 0)
+ {
+ Assert.True(newRange < range);
+ }
+ else
+ {
+ Assert.True(newRange > range);
+ }
+
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotView_RightClickWithContextMenu_CompletesControllerAndReleasesCapture()
+ {
+ var controller = new CountingController();
+ var view = new PlotView { Model = Ui.ModelWithAxes(), Controller = controller, ContextMenu = new ContextMenu() };
+ var pointer = TrackPointer(view);
+ var window = Ui.Show(view);
+
+ window.MouseDown(Center, MouseButton.Right);
+ window.MouseUp(Center, MouseButton.Right);
+ Ui.Flush();
+
+ // the context menu marks the release as handled, but the controller still receives it
+ Assert.Equal(1, controller.MouseUps);
+ Assert.Null(pointer().Captured);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotView_RightDragThenRelease_SuppressesContextMenu()
+ {
+ var view = new PlotView { Model = Ui.ModelWithAxes(), ContextMenu = new ContextMenu() };
+ bool? handled = null;
+ view.AddHandler(Control.ContextRequestedEvent, (_, e) => handled = e.Handled, RoutingStrategies.Bubble, handledEventsToo: true);
+ var window = Ui.Show(view);
+
+ window.MouseDown(Center, MouseButton.Right);
+ window.MouseMove(Center + new Point(50, 20), RawInputModifiers.RightMouseButton);
+ window.MouseUp(Center + new Point(50, 20), MouseButton.Right);
+ Ui.Flush();
+
+ // the menu is not shown after panning with the right button
+ Assert.True(handled);
+ Assert.False(view.ContextMenu.IsOpen);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotView_RightClickWithoutDrag_AllowsContextMenu()
+ {
+ // without a menu of its own nobody else handles the event, so the decision of the plot itself is visible
+ var view = new PlotView { Model = Ui.ModelWithAxes() };
+ bool? handled = null;
+ view.AddHandler(Control.ContextRequestedEvent, (_, e) => handled = e.Handled, RoutingStrategies.Bubble, handledEventsToo: true);
+ var window = Ui.Show(view);
+
+ window.MouseDown(Center, MouseButton.Right);
+ window.MouseUp(Center, MouseButton.Right);
+ Ui.Flush();
+
+ Assert.False(handled);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotView_CaptureLostWhilePanning_StopsPanning()
+ {
+ var model = Ui.ModelWithAxes();
+ var view = new PlotView { Model = model };
+ var pointer = TrackPointer(view);
+ var window = Ui.Show(view);
+
+ window.MouseDown(Center, MouseButton.Right);
+ window.MouseMove(Center + new Point(50, 0), RawInputModifiers.RightMouseButton);
+ Ui.Flush();
+
+ // the system released the capture and the control never received the button release
+ pointer().Capture(null);
+ var minimum = model.Axes[0].ActualMinimum;
+ window.MouseMove(Center + new Point(100, 0));
+ Ui.Flush();
+
+ Assert.Equal(minimum, model.Axes[0].ActualMinimum);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotView_TouchCaptureLost_NextTouchStartsGesture()
+ {
+ var controller = new CountingController();
+ var view = new PlotView { Model = Ui.ModelWithAxes(), Controller = controller };
+ var pointer = TrackPointer(view);
+ var window = Ui.Show(view);
+
+ window.TouchBegin(Center);
+ Ui.Flush();
+ pointer().Capture(null);
+ Ui.Flush();
+
+ // the touch is completed and not left hanging in the list of active ones
+ Assert.Equal(1, controller.TouchCompletions);
+
+ window.TouchBegin(Center + new Point(-50, -50));
+ Ui.Flush();
+
+ Assert.Equal(2, controller.TouchStarts);
+ window.Close();
+ }
+
+ ///
+ /// Remembers the pointer of the last press on the control.
+ ///
+ private static Func TrackPointer(Control control)
+ {
+ IPointer? pointer = null;
+ control.AddHandler(InputElement.PointerPressedEvent, (_, e) => pointer = e.Pointer, RoutingStrategies.Bubble, handledEventsToo: true);
+ return () => pointer ?? throw new InvalidOperationException("The control was not pressed.");
+ }
+
+ ///
+ /// A controller that counts the calls that matter for the tests.
+ ///
+ private sealed class CountingController : PlotController
+ {
+ public int MouseUps { get; private set; }
+
+ public int TouchStarts { get; private set; }
+
+ public int TouchCompletions { get; private set; }
+
+ public override bool HandleMouseUp(IView view, OxyMouseEventArgs args)
+ {
+ MouseUps++;
+ return base.HandleMouseUp(view, args);
+ }
+
+ public override bool HandleTouchStarted(IView view, OxyTouchEventArgs args)
+ {
+ TouchStarts++;
+ return base.HandleTouchStarted(view, args);
+ }
+
+ public override bool HandleTouchCompleted(IView view, OxyTouchEventArgs args)
+ {
+ TouchCompletions++;
+ return base.HandleTouchCompleted(view, args);
+ }
+ }
+}
diff --git a/Source/OxyPlot.Avalonia.Tests/OxyPlot.Avalonia.Tests.csproj b/Source/OxyPlot.Avalonia.Tests/OxyPlot.Avalonia.Tests.csproj
new file mode 100644
index 0000000..a35733a
--- /dev/null
+++ b/Source/OxyPlot.Avalonia.Tests/OxyPlot.Avalonia.Tests.csproj
@@ -0,0 +1,46 @@
+
+
+
+
+ net8.0
+
+ OxyPlot.Tests.Avalonia
+ Exe
+ latest
+ enable
+ enable
+ false
+ true
+ false
+
+
+
+
+
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Source/OxyPlot.Avalonia.Tests/PlotTests.cs b/Source/OxyPlot.Avalonia.Tests/PlotTests.cs
new file mode 100644
index 0000000..51af964
--- /dev/null
+++ b/Source/OxyPlot.Avalonia.Tests/PlotTests.cs
@@ -0,0 +1,341 @@
+using System.Collections.ObjectModel;
+using Avalonia.Controls;
+using Avalonia.Controls.Shapes;
+using Avalonia.Headless.XUnit;
+using Avalonia.LogicalTree;
+using Avalonia.Media;
+using Avalonia.VisualTree;
+using OxyPlot;
+using OxyPlot.Avalonia;
+using CoreAnnotations = OxyPlot.Annotations;
+using CoreAxes = OxyPlot.Axes;
+using CoreSeries = OxyPlot.Series;
+
+namespace OxyPlot.Avalonia.Tests;
+
+///
+/// Tests that plots are built and rendered under Avalonia 12.
+///
+public class PlotTests
+{
+ [AvaloniaFact]
+ public void PlotView_WithModel_RendersPlotArea()
+ {
+ var model = new PlotModel { Title = "Plot" };
+ model.Series.Add(new CoreSeries.FunctionSeries(Math.Sin, 0, 10, 0.1));
+ var view = new PlotView { Model = model };
+
+ var window = Ui.Show(view);
+
+ // the plot area is computed while the model is rendered: so the template is applied and the model is drawn
+ Assert.Same(model, view.ActualModel);
+ Assert.True(model.PlotArea.Width > 0);
+
+ // the canvas contains the title and the line of the function, not just the computed area
+ Assert.Contains(view.GetVisualDescendants().OfType(), t => t.Text == "Plot");
+ Assert.Contains(view.GetVisualDescendants().OfType(), p => p.Points.Count > 10);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Plot_WithLineSeries_BuildsModelFromItemsSource()
+ {
+ var points = new[] { new DataPoint(0, 0), new DataPoint(1, 1), new DataPoint(2, 4) };
+ var plot = new Plot();
+ plot.Series.Add(new LineSeries { ItemsSource = points });
+
+ var window = Ui.Show(plot);
+
+ // the series control copies its properties to the series of the OxyPlot model
+ var series = Assert.Single(plot.ActualModel.Series);
+ Assert.Equal(points, Assert.IsType(series).ItemsSource.Cast());
+ Assert.True(plot.ActualModel.PlotArea.Width > 0);
+ Assert.Contains(Ui.PlotCanvas(plot).Children.OfType(), p => p.Points.Count == points.Length);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Plot_AddSeriesAfterAxes_LoadsDataAndRangesAxes()
+ {
+ // the axes are added before the series: the first model update ran without data,
+ // and adding a series must load its points, not just redraw
+ var plot = new Plot();
+ plot.Axes.Add(new LinearAxis { Position = CoreAxes.AxisPosition.Bottom });
+ plot.Axes.Add(new LinearAxis { Position = CoreAxes.AxisPosition.Left });
+ var window = Ui.Show(plot);
+
+ plot.Series.Add(new LineSeries { ItemsSource = new[] { new DataPoint(0, 0), new DataPoint(10, 100), new DataPoint(20, 50) } });
+ Ui.Flush();
+
+ var series = Assert.IsAssignableFrom(Assert.Single(plot.ActualModel.Series));
+ Assert.Equal(100, series.MaxY);
+ Assert.True(plot.ActualModel.Axes[0].ActualMaximum >= 20);
+ Assert.True(plot.ActualModel.Axes[1].ActualMaximum >= 100);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Plot_ShowHiddenSeries_LoadsItsData()
+ {
+ var visible = new LineSeries { ItemsSource = new[] { new DataPoint(0, 0), new DataPoint(1, 4) } };
+ var hidden = new LineSeries { ItemsSource = new[] { new DataPoint(0, 0), new DataPoint(1, 30) }, IsVisible = false };
+ var plot = new Plot();
+ plot.Series.Add(visible);
+ plot.Series.Add(hidden);
+ var window = Ui.Show(plot);
+
+ hidden.IsVisible = true;
+ Ui.Flush();
+
+ // the core loads the data of visible series only, and only when the data is updated
+ Assert.Equal(30, ((CoreSeries.XYAxisSeries)hidden.InternalSeries).MaxY);
+ Assert.True(plot.ActualModel.DefaultYAxis.ActualMaximum >= 30);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Plot_HideSeries_ShrinksAxisRange()
+ {
+ var small = new LineSeries { ItemsSource = new[] { new DataPoint(0, 0), new DataPoint(1, 4) } };
+ var large = new LineSeries { ItemsSource = new[] { new DataPoint(0, 0), new DataPoint(1, 300) } };
+ var plot = new Plot();
+ plot.Axes.Add(new LinearAxis { Position = CoreAxes.AxisPosition.Bottom });
+ plot.Axes.Add(new LinearAxis { Position = CoreAxes.AxisPosition.Left });
+ plot.Series.Add(small);
+ plot.Series.Add(large);
+ var window = Ui.Show(plot);
+ Assert.True(plot.ActualModel.Axes[1].ActualMaximum >= 300);
+
+ large.IsVisible = false;
+ Ui.Flush();
+
+ Assert.True(plot.ActualModel.Axes[1].ActualMaximum < 10);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotView_SetModelNull_ClearsCanvas()
+ {
+ var model = new PlotModel();
+ model.Series.Add(new CoreSeries.FunctionSeries(Math.Sin, 0, 10, 0.1));
+ var view = new PlotView { Model = model };
+ var window = Ui.Show(view);
+ var canvas = Ui.PlotCanvas(view);
+ Assert.NotEmpty(canvas.Children);
+
+ view.Model = null;
+ Ui.Flush();
+
+ // without a model the old picture must not stay on the screen
+ Assert.Empty(canvas.Children);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Plot_TitleHorizontalAlignment_ReachesModel()
+ {
+ var plot = new Plot { Title = "Title", TitleHorizontalAlignment = TitleHorizontalAlignment.CenteredWithinView };
+ var window = Ui.Show(plot);
+
+ Assert.Equal(TitleHorizontalAlignment.CenteredWithinView, plot.ActualModel.TitleHorizontalAlignment);
+
+ plot.TitleHorizontalAlignment = TitleHorizontalAlignment.CenteredWithinPlotArea;
+ Ui.Flush();
+
+ Assert.Equal(TitleHorizontalAlignment.CenteredWithinPlotArea, plot.ActualModel.TitleHorizontalAlignment);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Plot_PlotAreaBackgroundFromImmutableBrush_ReachesModel()
+ {
+ // Brushes.* give immutable brushes: a property of type Brush did not accept them, so the test would not even compile
+ var plot = new Plot { PlotAreaBackground = Brushes.LightGray };
+ var window = Ui.Show(plot);
+
+ Assert.Equal(OxyColors.LightGray, plot.ActualModel.PlotAreaBackground);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Plot_InvalidateFlagChanged_SynchronizesWrappers()
+ {
+ var polygon = new PolygonAnnotation();
+ var plot = new Plot();
+ plot.Annotations.Add(polygon);
+ var window = Ui.Show(plot);
+
+ // the list of points is changed in place, without notifications: the model is updated only by an explicit invalidation
+ polygon.Points.Add(new DataPoint(0, 0));
+ polygon.Points.Add(new DataPoint(1, 0));
+ polygon.Points.Add(new DataPoint(1, 1));
+ plot.InvalidateFlag++;
+ Ui.Flush();
+
+ var annotation = Assert.IsType(Assert.Single(plot.ActualModel.Annotations));
+ Assert.Equal(3, annotation.Points.Count);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Plot_ClearSeries_DetachesSeriesFromTrees()
+ {
+ var plot = new Plot();
+ var window = Ui.Show(plot);
+ var series = new LineSeries();
+ plot.Series.Add(series);
+ Ui.Flush();
+
+ plot.Series.Clear();
+ Ui.Flush();
+
+ Assert.Null(series.Parent);
+ Assert.DoesNotContain(series, plot.GetLogicalChildren());
+ Assert.DoesNotContain(series, plot.GetVisualChildren());
+ Assert.Empty(plot.ActualModel.Series);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Plot_ClearAndAddSameSeries_DoesNotThrow()
+ {
+ // Clear() used to leave the series in the visual tree, and adding it again failed.
+ // The window is shown before adding: applying the template clears the visual children itself and would hide the error
+ var plot = new Plot();
+ var window = Ui.Show(plot);
+ var series = new LineSeries();
+ plot.Series.Add(series);
+ Ui.Flush();
+
+ plot.Series.Clear();
+ plot.Series.Add(series);
+ Ui.Flush();
+
+ Assert.Same(plot, series.Parent);
+ Assert.Single(plot.ActualModel.Series);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Plot_MoveSeries_KeepsParentAndOrder()
+ {
+ var first = new LineSeries { Title = "a" };
+ var second = new LineSeries { Title = "b" };
+ var plot = new Plot();
+ plot.Series.Add(first);
+ plot.Series.Add(second);
+ var window = Ui.Show(plot);
+
+ ((ObservableCollection)plot.Series).Move(0, 1);
+ Ui.Flush();
+
+ Assert.Same(plot, first.Parent);
+ Assert.Single(plot.GetLogicalChildren(), c => ReferenceEquals(c, first));
+ Assert.Equal("b", plot.ActualModel.Series[0].Title);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Plot_ReplaceSeriesWithSameInstance_KeepsParent()
+ {
+ var series = new LineSeries();
+ var plot = new Plot();
+ plot.Series.Add(series);
+ var window = Ui.Show(plot);
+
+ plot.Series[0] = plot.Series[0];
+ Ui.Flush();
+
+ Assert.Same(plot, series.Parent);
+ Assert.Single(plot.GetLogicalChildren(), c => ReferenceEquals(c, series));
+ Assert.Single(plot.ActualModel.Series);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotViewSubclass_Shown_GetsTemplateAndRenders()
+ {
+ var model = new PlotModel();
+ model.Series.Add(new CoreSeries.FunctionSeries(Math.Sin, 0, 10, 0.1));
+ var view = new DerivedPlotView { Model = model };
+
+ var window = Ui.Show(view);
+
+ Assert.NotNull(view.Template);
+ Assert.True(model.PlotArea.Width > 0);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotSubclass_Shown_GetsTemplateAndRenders()
+ {
+ var plot = new DerivedPlot();
+ plot.Series.Add(new LineSeries { ItemsSource = new[] { new DataPoint(0, 0), new DataPoint(1, 1) } });
+
+ var window = Ui.Show(plot);
+
+ Assert.NotNull(plot.Template);
+ Assert.True(plot.ActualModel.PlotArea.Width > 0);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotView_ShowZoomRectangle_DrawsVisibleBorder()
+ {
+ var view = new PlotView { Model = Ui.ModelWithAxes() };
+ var window = Ui.Show(view);
+
+ view.ShowZoomRectangle(new OxyRect(10, 10, 100, 50));
+ Ui.Flush();
+
+ // the stroke thickness of a Rectangle in Avalonia is 0 by default, and the border is not visible
+ var rectangle = Assert.Single(view.GetVisualDescendants().OfType());
+ Assert.True(rectangle.StrokeThickness > 0);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PlotView_InvalidatePlotFromBackgroundThread_UpdatesModel()
+ {
+ var series = new CoreSeries.LineSeries();
+ var model = new PlotModel();
+ model.Series.Add(series);
+ var view = new PlotView { Model = model };
+ var window = Ui.Show(view);
+
+ series.Points.Add(new DataPoint(0, 0));
+ series.Points.Add(new DataPoint(1, 50));
+ var thread = new Thread(() => view.InvalidatePlot(true));
+ thread.Start();
+ thread.Join();
+ Ui.Flush();
+
+ // a call from a foreign thread goes to the dispatcher of the control and updates the data there
+ Assert.Equal(50, series.MaxY);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Legend_DefaultFontSizes_FollowPlotDefaultFontSize()
+ {
+ var legend = new Legend().CreateModel();
+
+ // NaN in the core means "same as the DefaultFontSize of the plot", the number 12 broke that
+ Assert.True(double.IsNaN(legend.LegendFontSize));
+ Assert.True(double.IsNaN(legend.LegendTitleFontSize));
+ }
+
+ ///
+ /// A descendant of PlotView: styles with an exact type selector did not find it.
+ ///
+ private sealed class DerivedPlotView : PlotView
+ {
+ }
+
+ ///
+ /// A descendant of Plot: styles with an exact type selector did not find it.
+ ///
+ private sealed class DerivedPlot : Plot
+ {
+ }
+}
diff --git a/Source/OxyPlot.Avalonia.Tests/RenderContextTests.cs b/Source/OxyPlot.Avalonia.Tests/RenderContextTests.cs
new file mode 100644
index 0000000..b36572e
--- /dev/null
+++ b/Source/OxyPlot.Avalonia.Tests/RenderContextTests.cs
@@ -0,0 +1,117 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.Shapes;
+using Avalonia.Headless.XUnit;
+using Avalonia.Media;
+using Avalonia.Media.Imaging;
+using OxyPlot;
+using OxyPlot.Avalonia;
+using Image = Avalonia.Controls.Image;
+
+namespace OxyPlot.Avalonia.Tests;
+
+///
+/// Tests of the render context on an Avalonia canvas.
+///
+public class RenderContextTests
+{
+ [AvaloniaFact]
+ public void MeasureText_LongText_IsNotLimitedTo1000()
+ {
+ var context = new CanvasRenderContext(new Canvas());
+
+ var size = context.MeasureText(new string('W', 500), "Arial", 20, 400);
+
+ // with the 1000x1000 limit the width came out as exactly 1000
+ Assert.True(size.Width > 1000);
+ }
+
+ [AvaloniaFact]
+ public void DrawText_LongCenteredText_IsShiftedByHalfOfFullWidth()
+ {
+ var canvas = new Canvas();
+ var context = new CanvasRenderContext(canvas);
+
+ context.DrawText(new ScreenPoint(0, 0), new string('W', 500), OxyColors.Black, "Arial", 20, 400, 0, HorizontalAlignment.Center, VerticalAlignment.Top, null);
+
+ var text = Assert.IsType(Assert.Single(canvas.Children));
+ Assert.True(text.RenderTransform!.Value.M31 < -1000);
+ }
+
+ [AvaloniaFact]
+ public void DrawImage_SourcePart_CropsSourceAndKeepsClip()
+ {
+ var canvas = new Canvas();
+ var context = new CanvasRenderContext(canvas);
+ context.PushClip(new OxyRect(0, 0, 50, 50));
+
+ context.DrawImage(CreateImage(), 1, 1, 2, 2, 10, 10, 20, 20, 1, false);
+
+ var image = Assert.IsType(Assert.Single(canvas.Children));
+ var cropped = Assert.IsType(image.Source);
+ Assert.Equal(new PixelRect(1, 1, 2, 2), cropped.SourceRect);
+
+ // the clipping to the plot area is translated to the coordinates of the element and is not overridden by the source area
+ var clip = Assert.IsType(image.Clip);
+ Assert.Equal(new Rect(-10, -10, 50, 50), clip.Rect);
+ }
+
+ [AvaloniaFact]
+ public void DrawImage_WholeSource_UsesBitmapAsIs()
+ {
+ var canvas = new Canvas();
+ var context = new CanvasRenderContext(canvas);
+
+ context.DrawImage(CreateImage(), 0, 0, 4, 4, 10, 10, 20, 20, 1, false);
+
+ var image = Assert.IsType(Assert.Single(canvas.Children));
+ Assert.IsAssignableFrom(image.Source);
+ }
+
+ [AvaloniaFact]
+ public void DrawShapes_NonFiniteGeometry_IsSkipped()
+ {
+ var canvas = new Canvas();
+ var context = new CanvasRenderContext(canvas);
+
+ context.DrawRectangle(new OxyRect(double.NegativeInfinity, 0, double.PositiveInfinity, 10), OxyColors.Red, OxyColors.Black, 1, EdgeRenderingMode.Automatic);
+ context.DrawEllipse(new OxyRect(0, 0, double.NaN, double.NaN), OxyColors.Red, OxyColors.Black, 1, EdgeRenderingMode.Automatic);
+ context.DrawPolygon(new[] { new ScreenPoint(0, 0), new ScreenPoint(double.NaN, 1), new ScreenPoint(1, 1) }, OxyColors.Red, OxyColors.Black, 1, EdgeRenderingMode.Automatic, null, LineJoin.Miter);
+ context.DrawLineSegments(new[] { new ScreenPoint(0, 0), new ScreenPoint(double.NaN, 1) }, OxyColors.Black, 1, EdgeRenderingMode.Automatic, null, LineJoin.Miter);
+ context.DrawText(new ScreenPoint(double.NaN, 0), "x", OxyColors.Black, null, 12, 400, 0, HorizontalAlignment.Left, VerticalAlignment.Top, null);
+
+ // a shape with NaN or infinity would break the layout pass of the canvas
+ Assert.Empty(canvas.Children);
+ }
+
+ [AvaloniaFact]
+ public void DrawLine_NonFinitePoint_IsDroppedFromLine()
+ {
+ var canvas = new Canvas();
+ var context = new CanvasRenderContext(canvas);
+
+ context.DrawLine(new[] { new ScreenPoint(0, 0), new ScreenPoint(double.NaN, double.NaN), new ScreenPoint(10, 10) }, OxyColors.Black, 1, EdgeRenderingMode.Automatic, null, LineJoin.Miter);
+ var window = Ui.Show(canvas);
+
+ var line = Assert.IsType(Assert.Single(canvas.Children));
+ Assert.Equal(2, line.Points.Count);
+ window.Close();
+ }
+
+ ///
+ /// A 4x4 picture in the PNG format.
+ ///
+ private static OxyImage CreateImage()
+ {
+ var pixels = new OxyColor[4, 4];
+ for (var x = 0; x < 4; x++)
+ {
+ for (var y = 0; y < 4; y++)
+ {
+ pixels[x, y] = (x + y) % 2 == 0 ? OxyColors.Black : OxyColors.White;
+ }
+ }
+
+ return OxyImage.Create(pixels, ImageFormat.Png);
+ }
+}
diff --git a/Source/OxyPlot.Avalonia.Tests/SeriesTests.cs b/Source/OxyPlot.Avalonia.Tests/SeriesTests.cs
new file mode 100644
index 0000000..b2f0db3
--- /dev/null
+++ b/Source/OxyPlot.Avalonia.Tests/SeriesTests.cs
@@ -0,0 +1,234 @@
+using System.Reflection;
+using Avalonia.Headless.XUnit;
+using Avalonia.Media;
+using Avalonia.Styling;
+using OxyPlot;
+using OxyPlot.Avalonia;
+using CoreAxes = OxyPlot.Axes;
+using CoreSeries = OxyPlot.Series;
+
+namespace OxyPlot.Avalonia.Tests;
+
+///
+/// Tests of the series controls: copying the properties to the series of the core and the reaction of the plot to their changes.
+///
+public class SeriesTests
+{
+ private static readonly DataPoint[] Points = { new(0, 0), new(1, 1), new(2, 4) };
+
+ [AvaloniaFact]
+ public void TwoColorLineSeries_LineStyle2_ReachesModel()
+ {
+ var series = new TwoColorLineSeries { LineStyle2 = LineStyle.Dash };
+
+ var model = Assert.IsType(series.CreateModel());
+
+ Assert.Equal(LineStyle.Dash, model.LineStyle2);
+ }
+
+ [AvaloniaFact]
+ public void ThreeColorLineSeries_LineStylesLoAndHi_ReachModel()
+ {
+ var series = new ThreeColorLineSeries { LineStyleLo = LineStyle.Dash, LineStyleHi = LineStyle.Dot };
+
+ var model = Assert.IsType(series.CreateModel());
+
+ Assert.Equal(LineStyle.Dash, model.LineStyleLo);
+ Assert.Equal(LineStyle.Dot, model.LineStyleHi);
+ }
+
+ [AvaloniaFact]
+ public void LineSeries_ChangeLabelAndInterpolationAfterShow_ReachesModel()
+ {
+ var series = new LineSeries { ItemsSource = Points };
+ var plot = new Plot();
+ plot.Series.Add(series);
+ var window = Ui.Show(plot);
+
+ series.LabelFormatString = "{1}";
+ series.LabelMargin = 10;
+ series.LineLegendPosition = CoreSeries.LineLegendPosition.End;
+ series.InterpolationAlgorithm = InterpolationAlgorithms.CanonicalSpline;
+ Ui.Flush();
+
+ var model = (CoreSeries.LineSeries)series.InternalSeries;
+ Assert.Equal("{1}", model.LabelFormatString);
+ Assert.Equal(10, model.LabelMargin);
+ Assert.Equal(CoreSeries.LineLegendPosition.End, model.LineLegendPosition);
+ Assert.Same(InterpolationAlgorithms.CanonicalSpline, model.InterpolationAlgorithm);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void DataPointSeries_ChangeMappingAfterShow_ReloadsData()
+ {
+ var samples = new[] { new Sample(0, 1), new Sample(1, 2) };
+ var series = new LineSeries { ItemsSource = samples, Mapping = o => new DataPoint(((Sample)o).X, ((Sample)o).Y) };
+ var plot = new Plot();
+ plot.Series.Add(series);
+ var window = Ui.Show(plot);
+ Assert.Equal(2, ((CoreSeries.XYAxisSeries)series.InternalSeries).MaxY);
+
+ series.Mapping = o => new DataPoint(((Sample)o).X, ((Sample)o).Y * 10);
+ Ui.Flush();
+
+ Assert.Equal(20, ((CoreSeries.XYAxisSeries)series.InternalSeries).MaxY);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void TwoColorAreaSeries_ChangeLimitAfterShow_SplitsPointsByNewLimit()
+ {
+ var series = new TwoColorAreaSeries
+ {
+ ItemsSource = new[] { new DataPoint(0, -1), new DataPoint(1, 1), new DataPoint(2, -1) },
+ Limit = 0,
+ };
+ var plot = new Plot();
+ plot.Series.Add(series);
+ var window = Ui.Show(plot);
+
+ series.Limit = 0.5;
+ Ui.Flush();
+
+ // the core inserts the points of intersection with the limit while splitting in UpdateData
+ var above = (List)typeof(CoreSeries.TwoColorAreaSeries)
+ .GetField("abovePoints", BindingFlags.Instance | BindingFlags.NonPublic)!
+ .GetValue(series.InternalSeries)!;
+ Assert.Contains(above, p => Math.Abs(p.Y - 0.5) < 1e-9);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void BarSeries_SetIsStackedAfterShow_RangesValueAxisBySum()
+ {
+ var first = new BarSeries { ItemsSource = new[] { new CoreSeries.BarItem(3), new CoreSeries.BarItem(5) } };
+ var second = new BarSeries { ItemsSource = new[] { new CoreSeries.BarItem(4), new CoreSeries.BarItem(6) } };
+ var plot = new Plot();
+ plot.Axes.Add(new CategoryAxis { Position = CoreAxes.AxisPosition.Left });
+ plot.Axes.Add(new LinearAxis { Position = CoreAxes.AxisPosition.Bottom });
+ plot.Series.Add(first);
+ plot.Series.Add(second);
+ var window = Ui.Show(plot);
+ Assert.True(plot.ActualModel.Axes[1].ActualMaximum < 11);
+
+ first.IsStacked = true;
+ second.IsStacked = true;
+ Ui.Flush();
+
+ // the stack sum 5 + 6 is computed in UpdateMaxMin, that is, only when the data is updated
+ Assert.True(plot.ActualModel.Axes[1].ActualMaximum >= 11);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void PieSeries_ChangeExplodedDistanceAfterShow_ReachesModel()
+ {
+ var series = new PieSeries();
+ var plot = new Plot();
+ plot.Series.Add(series);
+ var window = Ui.Show(plot);
+
+ series.ExplodedDistance = 0.3;
+ Ui.Flush();
+
+ Assert.Equal(0.3, ((CoreSeries.PieSeries)series.InternalSeries).ExplodedDistance);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void HeatMapSeries_ChangeX1AfterShow_RangesXAxis()
+ {
+ var series = new HeatMapSeries
+ {
+ Data = new double[,] { { 1, 2 }, { 3, 4 } },
+ X0 = 0,
+ X1 = 1,
+ Y0 = 0,
+ Y1 = 1,
+ ColorAxisKey = "c",
+ };
+ var plot = new Plot();
+ plot.Axes.Add(new LinearAxis { Position = CoreAxes.AxisPosition.Bottom });
+ plot.Axes.Add(new LinearAxis { Position = CoreAxes.AxisPosition.Left });
+ plot.Axes.Add(new LinearColorAxis { Position = CoreAxes.AxisPosition.Right, Key = "c" });
+ plot.Series.Add(series);
+ var window = Ui.Show(plot);
+
+ series.X1 = 10;
+ Ui.Flush();
+
+ Assert.True(((CoreSeries.XYAxisSeries)series.InternalSeries).MaxX >= 10);
+ Assert.True(plot.ActualModel.Axes[0].ActualMaximum >= 10);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void LinearBarSeries_Defaults_MatchCore()
+ {
+ var model = Assert.IsType(new LinearBarSeries().CreateModel());
+ var core = new CoreSeries.LinearBarSeries();
+
+ Assert.Equal(core.BarWidth, model.BarWidth);
+ Assert.Equal(core.StrokeThickness, model.StrokeThickness);
+ }
+
+ [AvaloniaFact]
+ public void ScatterSeries_ChangeColorAxisKeyAfterShow_ReachesModel()
+ {
+ var series = new ScatterSeries();
+ var plot = new Plot();
+ plot.Series.Add(series);
+ var window = Ui.Show(plot);
+
+ series.ColorAxisKey = "c";
+ Ui.Flush();
+
+ Assert.Equal("c", ((CoreSeries.ScatterSeries)series.InternalSeries).ColorAxisKey);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Series_InheritedForegroundAndFont_DoNotReachModel()
+ {
+ // in a dark theme the window passes a white Foreground down to the series, while the plot background is white
+ var series = new LineSeries { ItemsSource = Points, LabelFormatString = "{1}" };
+ var plot = new Plot();
+ plot.Series.Add(series);
+ var window = Ui.Show(plot, ThemeVariant.Dark);
+
+ Assert.Equal(OxyColors.Automatic, series.InternalSeries.TextColor);
+ Assert.Null(series.InternalSeries.Font);
+
+ series.Foreground = Brushes.Red;
+ Ui.Flush();
+
+ Assert.Equal(OxyColors.Red, series.InternalSeries.TextColor);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void BarSeries_ForeignItemsInItemsSource_AreSkipped()
+ {
+ var series = new BarSeries { ItemsSource = new object[] { new CoreSeries.BarItem(1), "foreign object" } };
+
+ var model = Assert.IsType(series.CreateModel());
+
+ Assert.Single(model.Items);
+ }
+
+ [AvaloniaFact]
+ public void BoxPlotSeries_ForeignItemsInItemsSource_AreSkipped()
+ {
+ var series = new BoxPlotSeries { ItemsSource = new object[] { new CoreSeries.BoxPlotItem(0, 1, 2, 3, 4, 5), "foreign object" } };
+
+ var model = Assert.IsType(series.CreateModel());
+
+ Assert.Single(model.Items);
+ }
+
+ ///
+ /// A data item that the series converts to a point through Mapping.
+ ///
+ private sealed record Sample(double X, double Y);
+}
diff --git a/Source/OxyPlot.Avalonia.Tests/TestAppBuilder.cs b/Source/OxyPlot.Avalonia.Tests/TestAppBuilder.cs
new file mode 100644
index 0000000..b9abf4e
--- /dev/null
+++ b/Source/OxyPlot.Avalonia.Tests/TestAppBuilder.cs
@@ -0,0 +1,40 @@
+using Avalonia;
+using Avalonia.Headless;
+using Avalonia.Markup.Xaml.Styling;
+using Avalonia.Themes.Simple;
+using OxyPlot.Avalonia.Tests;
+
+[assembly: AvaloniaTestApplication(typeof(TestAppBuilder))]
+
+// The application and the dispatcher are created once per assembly, so a foreign thread cannot occupy the
+// dispatcher between the tests. The price of the mode: the tests do not leave application styles and resources behind.
+[assembly: AvaloniaTestIsolation(AvaloniaTestIsolationLevel.PerAssembly)]
+
+namespace OxyPlot.Avalonia.Tests;
+
+///
+/// The entry point of the headless Avalonia application for the plot tests.
+///
+public class TestAppBuilder
+{
+ // Render with Skia instead of the headless stub: otherwise the PNG export writes an empty stream
+ public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure()
+ .UseSkia()
+ .UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false });
+}
+
+///
+/// The application for the tests: the simple Avalonia theme and the plot styles, like those of the consumers of the package.
+/// Without the plot styles neither Plot nor PlotView gets a template and nothing is drawn.
+///
+public class TestApp : Application
+{
+ public override void Initialize()
+ {
+ Styles.Add(new SimpleTheme());
+ Styles.Add(new StyleInclude(new Uri("avares://OxyPlot.Tests.Avalonia/"))
+ {
+ Source = new Uri("avares://OxyPlot.Avalonia/Themes/Default.axaml"),
+ });
+ }
+}
diff --git a/Source/OxyPlot.Avalonia.Tests/TrackerTests.cs b/Source/OxyPlot.Avalonia.Tests/TrackerTests.cs
new file mode 100644
index 0000000..2a3b9da
--- /dev/null
+++ b/Source/OxyPlot.Avalonia.Tests/TrackerTests.cs
@@ -0,0 +1,97 @@
+using Avalonia;
+using Avalonia.Collections;
+using Avalonia.Controls;
+using Avalonia.Controls.Shapes;
+using Avalonia.Headless.XUnit;
+using Avalonia.Media;
+using Avalonia.Styling;
+using Avalonia.VisualTree;
+using OxyPlot;
+using OxyPlot.Avalonia;
+using CoreSeries = OxyPlot.Series;
+using ShapePath = Avalonia.Controls.Shapes.Path;
+
+namespace OxyPlot.Avalonia.Tests;
+
+///
+/// Tracker tests: the template from the theme, the bindings and the shape of the border.
+///
+public class TrackerTests
+{
+ [AvaloniaFact]
+ public void PlotView_ShowTrackerInDarkTheme_TextIsBlackAndBound()
+ {
+ var model = new PlotModel();
+ model.Series.Add(new CoreSeries.FunctionSeries(Math.Sin, 0, 10, 0.1));
+ var view = new PlotView { Model = model };
+ var window = Ui.Show(view, ThemeVariant.Dark);
+
+ view.ShowTracker(new TrackerHitResult { Text = "value", Position = new ScreenPoint(50, 60), PlotModel = model });
+ Ui.Flush();
+
+ var tracker = Assert.Single(view.GetVisualDescendants().OfType());
+ Assert.Equal(new ScreenPoint(50, 60), tracker.Position);
+ Assert.Equal(model.PlotArea, tracker.LineExtents);
+
+ // the tracker background is always light: in a dark theme the inherited white text is not readable on it
+ var text = Assert.Single(tracker.GetVisualDescendants().OfType(), t => t.Text == "value");
+ Assert.Equal(Colors.Black, Assert.IsAssignableFrom(text.Foreground).Color);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void TrackerControl_LineDashArray_ReachesBothLines()
+ {
+ var tracker = new TrackerControl { LineDashArray = new AvaloniaList { 2, 1 } };
+ var window = Ui.Show(tracker);
+
+ var lines = tracker.GetVisualDescendants().OfType()
+ .Where(l => l.Name is "PART_HorizontalLine" or "PART_VerticalLine")
+ .ToList();
+
+ Assert.Equal(2, lines.Count);
+ Assert.All(lines, l => Assert.Equal(new[] { 2.0, 1.0 }, l.StrokeDashArray!));
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void TrackerControl_CornerRadiusWithoutPointer_RoundsBorder()
+ {
+ var tracker = new TrackerControl
+ {
+ ShowPointer = false,
+ CornerRadius = 6,
+ Content = new TextBlock { Text = "value", Margin = new Thickness(7) },
+ };
+ var canvas = new Canvas();
+ canvas.Children.Add(tracker);
+ var window = Ui.Show(canvas);
+
+ tracker.Position = new ScreenPoint(100, 100);
+ Ui.Flush();
+
+ var path = Assert.Single(tracker.GetVisualDescendants().OfType(), p => p.Name == "PART_Path");
+ var geometry = Assert.IsType(path.Data);
+ Assert.Equal(6, geometry.RadiusX);
+ Assert.Equal(6, geometry.RadiusY);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void TrackerControlSubclass_Shown_GetsTemplate()
+ {
+ var tracker = new DerivedTrackerControl();
+
+ var window = Ui.Show(tracker);
+
+ Assert.NotNull(tracker.Template);
+ window.Close();
+ }
+
+ ///
+ /// A descendant of the tracker: styles with an exact type selector did not find it.
+ ///
+ private sealed class DerivedTrackerControl : TrackerControl
+ {
+ }
+}
diff --git a/Source/OxyPlot.Avalonia.Tests/Ui.cs b/Source/OxyPlot.Avalonia.Tests/Ui.cs
new file mode 100644
index 0000000..5f61ea4
--- /dev/null
+++ b/Source/OxyPlot.Avalonia.Tests/Ui.cs
@@ -0,0 +1,58 @@
+using Avalonia.Controls;
+using Avalonia.Styling;
+using Avalonia.Threading;
+using Avalonia.VisualTree;
+using OxyPlot;
+using OxyPlot.Avalonia;
+using CoreAxes = OxyPlot.Axes;
+
+namespace OxyPlot.Avalonia.Tests;
+
+///
+/// Common actions of the tests: showing a control in a window of the headless application and running the deferred work.
+///
+internal static class Ui
+{
+ ///
+ /// Shows a control in a window and runs the deferred work of the dispatcher (the model update and rendering)
+ ///
+ public static Window Show(Control content, ThemeVariant? theme = null)
+ {
+ var window = new Window { Width = 400, Height = 300, Content = content };
+ if (theme != null)
+ {
+ window.RequestedThemeVariant = theme;
+ }
+
+ window.Show();
+ Flush();
+ return window;
+ }
+
+ ///
+ /// Runs the accumulated dispatcher work: the deferred model updates and the layout.
+ ///
+ public static void Flush()
+ {
+ Dispatcher.UIThread.RunJobs();
+ }
+
+ ///
+ /// The canvas on which the control renders the model (the first canvas of the template, not the tracker layer).
+ ///
+ public static Canvas PlotCanvas(PlotBase plot)
+ {
+ return plot.GetVisualDescendants().OfType