diff --git a/Source/Directory.Build.props b/Source/Directory.Build.props index 1f55fde..69caaa0 100644 --- a/Source/Directory.Build.props +++ b/Source/Directory.Build.props @@ -1,6 +1,6 @@ - 12.0.2 + 12.1.4 2.2.0 \ 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..7c870b2 --- /dev/null +++ b/Source/OxyPlot.Avalonia.Tests/OxyPlot.Avalonia.Tests.csproj @@ -0,0 +1,46 @@ + + + + + net10.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().First(c => c.Name != "Overlays"); + } + + /// + /// A model with axes 0..10 for both coordinates: panning and zooming are tested on it. + /// + public static PlotModel ModelWithAxes() + { + var model = new PlotModel(); + model.Axes.Add(new CoreAxes.LinearAxis { Position = CoreAxes.AxisPosition.Bottom, Minimum = 0, Maximum = 10 }); + model.Axes.Add(new CoreAxes.LinearAxis { Position = CoreAxes.AxisPosition.Left, Minimum = 0, Maximum = 10 }); + return model; + } +} diff --git a/Source/OxyPlot.Avalonia.Tests/xunit.runner.json b/Source/OxyPlot.Avalonia.Tests/xunit.runner.json new file mode 100644 index 0000000..4a9ef02 --- /dev/null +++ b/Source/OxyPlot.Avalonia.Tests/xunit.runner.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json", + "diagnosticMessages": true, + "showLiveOutput": true, + "methodDisplay": "method" +} diff --git a/Source/OxyPlot.Avalonia.sln b/Source/OxyPlot.Avalonia.sln index 0ce89c5..791e5f6 100644 --- a/Source/OxyPlot.Avalonia.sln +++ b/Source/OxyPlot.Avalonia.sln @@ -33,6 +33,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Directory.Build.props = Directory.Build.props EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OxyPlot.Avalonia.Tests", "OxyPlot.Avalonia.Tests\OxyPlot.Avalonia.Tests.csproj", "{E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -103,6 +105,18 @@ Global {E4993D0B-C4C6-47CE-A55E-19EFB28EC034}.Release|x64.Build.0 = Release|Any CPU {E4993D0B-C4C6-47CE-A55E-19EFB28EC034}.Release|x86.ActiveCfg = Release|Any CPU {E4993D0B-C4C6-47CE-A55E-19EFB28EC034}.Release|x86.Build.0 = Release|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Debug|x64.ActiveCfg = Debug|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Debug|x64.Build.0 = Debug|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Debug|x86.ActiveCfg = Debug|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Debug|x86.Build.0 = Debug|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Release|Any CPU.Build.0 = Release|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Release|x64.ActiveCfg = Release|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Release|x64.Build.0 = Release|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Release|x86.ActiveCfg = Release|Any CPU + {E4CA5C30-A4BD-4D70-8857-BCB31A18ADE7}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Source/OxyPlot.Avalonia/Annotations/ArrowAnnotation.cs b/Source/OxyPlot.Avalonia/Annotations/ArrowAnnotation.cs index fbd441f..a1f8259 100644 --- a/Source/OxyPlot.Avalonia/Annotations/ArrowAnnotation.cs +++ b/Source/OxyPlot.Avalonia/Annotations/ArrowAnnotation.cs @@ -74,7 +74,6 @@ public class ArrowAnnotation : TextualAnnotation static ArrowAnnotation() { TextColorProperty.OverrideDefaultValue(MoreColors.Automatic); - TextColorProperty.Changed.AddClassHandler(AppearanceChanged); ArrowDirectionProperty.Changed.AddClassHandler(DataChanged); ColorProperty.Changed.AddClassHandler(AppearanceChanged); diff --git a/Source/OxyPlot.Avalonia/Annotations/EllipseAnnotation.cs b/Source/OxyPlot.Avalonia/Annotations/EllipseAnnotation.cs index 1250aae..7d34eb3 100644 --- a/Source/OxyPlot.Avalonia/Annotations/EllipseAnnotation.cs +++ b/Source/OxyPlot.Avalonia/Annotations/EllipseAnnotation.cs @@ -32,7 +32,6 @@ public class EllipseAnnotation : ShapeAnnotation static EllipseAnnotation() { TextColorProperty.OverrideDefaultValue(MoreColors.Automatic); - TextColorProperty.Changed.AddClassHandler(AppearanceChanged); XProperty.Changed.AddClassHandler(DataChanged); YProperty.Changed.AddClassHandler(DataChanged); diff --git a/Source/OxyPlot.Avalonia/Annotations/FunctionAnnotation.cs b/Source/OxyPlot.Avalonia/Annotations/FunctionAnnotation.cs index c22a010..660b2d5 100644 --- a/Source/OxyPlot.Avalonia/Annotations/FunctionAnnotation.cs +++ b/Source/OxyPlot.Avalonia/Annotations/FunctionAnnotation.cs @@ -33,7 +33,7 @@ public class FunctionAnnotation : PathAnnotation /// /// Identifies the dependency property. /// - public static readonly StyledProperty ResolutionProperty = AvaloniaProperty.Register(nameof(Resolution), 400); + public static readonly StyledProperty ResolutionProperty = AvaloniaProperty.Register(nameof(Resolution), 400, validate: ValidateResolution); /// /// Initializes static members of the class. @@ -41,13 +41,12 @@ public class FunctionAnnotation : PathAnnotation static FunctionAnnotation() { TextColorProperty.OverrideDefaultValue(MoreColors.Automatic); - TextColorProperty.Changed.AddClassHandler(AppearanceChanged); TextHorizontalAlignmentProperty.OverrideDefaultValue(HorizontalAlignment.Right); - TextHorizontalAlignmentProperty.Changed.AddClassHandler(AppearanceChanged); TextVerticalAlignmentProperty.OverrideDefaultValue(VerticalAlignment.Top); - TextVerticalAlignmentProperty.Changed.AddClassHandler(AppearanceChanged); TypeProperty.Changed.AddClassHandler(DataChanged); + EquationProperty.Changed.AddClassHandler(DataChanged); + ResolutionProperty.Changed.AddClassHandler(DataChanged); } /// @@ -58,6 +57,17 @@ public FunctionAnnotation() InternalAnnotation = new Annotations.FunctionAnnotation(); } + /// + /// Validates the number of points of the function. The core divides the range by this number and steps + /// to the bound: with zero or a negative value the loop never ends. + /// + /// The number of points. + /// true if the value is valid. + private static bool ValidateResolution(int value) + { + return value >= 1; + } + /// /// Gets or sets the equation. /// diff --git a/Source/OxyPlot.Avalonia/Annotations/LineAnnotation.cs b/Source/OxyPlot.Avalonia/Annotations/LineAnnotation.cs index 8fbe274..7dab3aa 100644 --- a/Source/OxyPlot.Avalonia/Annotations/LineAnnotation.cs +++ b/Source/OxyPlot.Avalonia/Annotations/LineAnnotation.cs @@ -70,11 +70,8 @@ public class LineAnnotation : PathAnnotation static LineAnnotation() { TextColorProperty.OverrideDefaultValue(MoreColors.Automatic); - TextColorProperty.Changed.AddClassHandler(AppearanceChanged); TextHorizontalAlignmentProperty.OverrideDefaultValue(HorizontalAlignment.Right); - TextHorizontalAlignmentProperty.Changed.AddClassHandler(AppearanceChanged); TextVerticalAlignmentProperty.OverrideDefaultValue(VerticalAlignment.Top); - TextVerticalAlignmentProperty.Changed.AddClassHandler(AppearanceChanged); TypeProperty.Changed.AddClassHandler(DataChanged); InterceptProperty.Changed.AddClassHandler(DataChanged); diff --git a/Source/OxyPlot.Avalonia/Annotations/PointAnnotation.cs b/Source/OxyPlot.Avalonia/Annotations/PointAnnotation.cs index d3750e5..890e870 100644 --- a/Source/OxyPlot.Avalonia/Annotations/PointAnnotation.cs +++ b/Source/OxyPlot.Avalonia/Annotations/PointAnnotation.cs @@ -49,9 +49,7 @@ public class PointAnnotation : ShapeAnnotation static PointAnnotation() { TextColorProperty.OverrideDefaultValue(MoreColors.Automatic); - TextColorProperty.Changed.AddClassHandler(AppearanceChanged); TextVerticalAlignmentProperty.OverrideDefaultValue(VerticalAlignment.Top); - TextVerticalAlignmentProperty.Changed.AddClassHandler(AppearanceChanged); XProperty.Changed.AddClassHandler(DataChanged); YProperty.Changed.AddClassHandler(DataChanged); diff --git a/Source/OxyPlot.Avalonia/Annotations/PolygonAnnotation.cs b/Source/OxyPlot.Avalonia/Annotations/PolygonAnnotation.cs index 7482425..419b1b6 100644 --- a/Source/OxyPlot.Avalonia/Annotations/PolygonAnnotation.cs +++ b/Source/OxyPlot.Avalonia/Annotations/PolygonAnnotation.cs @@ -31,7 +31,7 @@ public class PolygonAnnotation : ShapeAnnotation /// /// Identifies the dependency property. /// - public static readonly StyledProperty> PointsProperty = AvaloniaProperty.Register>(nameof(Points), new List()); + public static readonly StyledProperty> PointsProperty = AvaloniaProperty.Register>(nameof(Points)); /// /// Initializes static members of the class. @@ -39,7 +39,6 @@ public class PolygonAnnotation : ShapeAnnotation static PolygonAnnotation() { TextColorProperty.OverrideDefaultValue(MoreColors.Automatic); - TextColorProperty.Changed.AddClassHandler(AppearanceChanged); LineJoinProperty.Changed.AddClassHandler(AppearanceChanged); LineStyleProperty.Changed.AddClassHandler(AppearanceChanged); @@ -52,6 +51,9 @@ static PolygonAnnotation() public PolygonAnnotation() { InternalAnnotation = new Annotations.PolygonAnnotation(); + + // Every instance has its own list of points, otherwise points leak between annotations + SetCurrentValue(PointsProperty, new List()); } /// @@ -121,7 +123,10 @@ public override void SynchronizeProperties() base.SynchronizeProperties(); var a = (Annotations.PolygonAnnotation)InternalAnnotation; a.Points.Clear(); - a.Points.AddRange(Points); + if (Points != null) + { + a.Points.AddRange(Points); + } a.LineStyle = LineStyle; a.LineJoin = LineJoin; diff --git a/Source/OxyPlot.Avalonia/Annotations/PolylineAnnotation.cs b/Source/OxyPlot.Avalonia/Annotations/PolylineAnnotation.cs index 33772d0..7a5ef07 100644 --- a/Source/OxyPlot.Avalonia/Annotations/PolylineAnnotation.cs +++ b/Source/OxyPlot.Avalonia/Annotations/PolylineAnnotation.cs @@ -32,7 +32,7 @@ public class PolylineAnnotation : PathAnnotation /// /// Identifies the dependency property. /// - public static readonly StyledProperty> PointsProperty = AvaloniaProperty.Register>(nameof(Points), new List()); + public static readonly StyledProperty> PointsProperty = AvaloniaProperty.Register>(nameof(Points)); /// /// Initializes static members of the class. @@ -40,13 +40,11 @@ public class PolylineAnnotation : PathAnnotation static PolylineAnnotation() { TextColorProperty.OverrideDefaultValue(MoreColors.Automatic); - TextColorProperty.Changed.AddClassHandler(AppearanceChanged); TextHorizontalAlignmentProperty.OverrideDefaultValue(HorizontalAlignment.Right); - TextHorizontalAlignmentProperty.Changed.AddClassHandler(AppearanceChanged); TextVerticalAlignmentProperty.OverrideDefaultValue(VerticalAlignment.Top); - TextVerticalAlignmentProperty.Changed.AddClassHandler(AppearanceChanged); InterpolationAlgorithmProperty.Changed.AddClassHandler(DataChanged); + MinimumSegmentLengthProperty.Changed.AddClassHandler(DataChanged); PointsProperty.Changed.AddClassHandler(DataChanged); } @@ -56,6 +54,9 @@ static PolylineAnnotation() public PolylineAnnotation() { this.InternalAnnotation = new Annotations.PolylineAnnotation(); + + // Every instance has its own list of points, otherwise points leak between annotations + SetCurrentValue(PointsProperty, new List()); } /// @@ -116,7 +117,11 @@ public override void SynchronizeProperties() var a = (Annotations.PolylineAnnotation)this.InternalAnnotation; a.Points.Clear(); - a.Points.AddRange(this.Points); + if (this.Points != null) + { + a.Points.AddRange(this.Points); + } + a.InterpolationAlgorithm = this.InterpolationAlgorithm; a.MinimumSegmentLength = this.MinimumSegmentLength; } diff --git a/Source/OxyPlot.Avalonia/Annotations/RectangleAnnotation.cs b/Source/OxyPlot.Avalonia/Annotations/RectangleAnnotation.cs index 6c9f0a1..a450a86 100644 --- a/Source/OxyPlot.Avalonia/Annotations/RectangleAnnotation.cs +++ b/Source/OxyPlot.Avalonia/Annotations/RectangleAnnotation.cs @@ -19,22 +19,22 @@ public class RectangleAnnotation : ShapeAnnotation /// /// Identifies the dependency property. /// - public static readonly StyledProperty MaximumXProperty = AvaloniaProperty.Register(nameof(MaximumX), double.MaxValue); + public static readonly StyledProperty MaximumXProperty = AvaloniaProperty.Register(nameof(MaximumX), double.PositiveInfinity); /// /// Identifies the dependency property. /// - public static readonly StyledProperty MaximumYProperty = AvaloniaProperty.Register(nameof(MaximumY), double.MaxValue); + public static readonly StyledProperty MaximumYProperty = AvaloniaProperty.Register(nameof(MaximumY), double.PositiveInfinity); /// /// Identifies the dependency property. /// - public static readonly StyledProperty MinimumXProperty = AvaloniaProperty.Register(nameof(MinimumX), double.MinValue); + public static readonly StyledProperty MinimumXProperty = AvaloniaProperty.Register(nameof(MinimumX), double.NegativeInfinity); /// /// Identifies the dependency property. /// - public static readonly StyledProperty MinimumYProperty = AvaloniaProperty.Register(nameof(MinimumY), double.MinValue); + public static readonly StyledProperty MinimumYProperty = AvaloniaProperty.Register(nameof(MinimumY), double.NegativeInfinity); /// /// Initializes static members of the class. @@ -42,7 +42,6 @@ public class RectangleAnnotation : ShapeAnnotation static RectangleAnnotation() { TextColorProperty.OverrideDefaultValue(MoreColors.Automatic); - TextColorProperty.Changed.AddClassHandler(AppearanceChanged); MaximumXProperty.Changed.AddClassHandler(DataChanged); MaximumYProperty.Changed.AddClassHandler(DataChanged); @@ -140,10 +139,13 @@ public override void SynchronizeProperties() base.SynchronizeProperties(); var a = (Annotations.RectangleAnnotation)InternalAnnotation; - a.MinimumX = MinimumX; - a.MaximumX = MaximumX; - a.MinimumY = MinimumY; - a.MaximumY = MaximumY; + // OxyPlot core 2.2.0 treats a bound as open only when it is infinite or NaN. + // The previous defaults double.MinValue/MaxValue are converted to infinity, + // otherwise the rectangle ends up in infinite screen coordinates. + a.MinimumX = MinimumX <= double.MinValue ? double.NegativeInfinity : MinimumX; + a.MaximumX = MaximumX >= double.MaxValue ? double.PositiveInfinity : MaximumX; + a.MinimumY = MinimumY <= double.MinValue ? double.NegativeInfinity : MinimumY; + a.MaximumY = MaximumY >= double.MaxValue ? double.PositiveInfinity : MaximumY; } } } \ No newline at end of file diff --git a/Source/OxyPlot.Avalonia/Annotations/TextAnnotation.cs b/Source/OxyPlot.Avalonia/Annotations/TextAnnotation.cs index 7f19a3e..762bdd5 100644 --- a/Source/OxyPlot.Avalonia/Annotations/TextAnnotation.cs +++ b/Source/OxyPlot.Avalonia/Annotations/TextAnnotation.cs @@ -50,11 +50,8 @@ public class TextAnnotation : TextualAnnotation static TextAnnotation() { TextColorProperty.OverrideDefaultValue(MoreColors.Automatic); - TextColorProperty.Changed.AddClassHandler(AppearanceChanged); TextHorizontalAlignmentProperty.OverrideDefaultValue(HorizontalAlignment.Right); - TextHorizontalAlignmentProperty.Changed.AddClassHandler(AppearanceChanged); TextVerticalAlignmentProperty.OverrideDefaultValue(VerticalAlignment.Top); - TextVerticalAlignmentProperty.Changed.AddClassHandler(AppearanceChanged); BackgroundProperty.Changed.AddClassHandler(AppearanceChanged); OffsetProperty.Changed.AddClassHandler(AppearanceChanged); @@ -168,11 +165,9 @@ public override void SynchronizeProperties() { base.SynchronizeProperties(); var a = (Annotations.TextAnnotation)InternalAnnotation; - a.TextHorizontalAlignment = HorizontalAlignment.ToHorizontalAlignment(); a.Background = Background.ToOxyColor(); a.Offset = Offset.ToScreenVector(); - a.TextVerticalAlignment = VerticalAlignment.ToVerticalAlignment(); a.Padding = Padding.ToOxyThickness(); a.Stroke = Stroke.ToOxyColor(); diff --git a/Source/OxyPlot.Avalonia/Axes/AngleAxis.cs b/Source/OxyPlot.Avalonia/Axes/AngleAxis.cs index b81521c..1d60858 100644 --- a/Source/OxyPlot.Avalonia/Axes/AngleAxis.cs +++ b/Source/OxyPlot.Avalonia/Axes/AngleAxis.cs @@ -35,14 +35,13 @@ static AngleAxis() { MajorGridlineStyleProperty.OverrideMetadata(typeof(AngleAxis), new StyledPropertyMetadata(LineStyle.Solid)); MinorGridlineStyleProperty.OverrideMetadata(typeof(AngleAxis), new StyledPropertyMetadata(LineStyle.Solid)); - PositionProperty.OverrideMetadata(typeof(AngleAxis), new StyledPropertyMetadata(AxisPosition.None)); + // Same as in the core: with None the axis does not reserve margins and the angle labels are clipped + PositionProperty.OverrideMetadata(typeof(AngleAxis), new StyledPropertyMetadata(AxisPosition.All)); TickStyleProperty.OverrideMetadata(typeof(AngleAxis), new StyledPropertyMetadata(TickStyle.None)); IsPanEnabledProperty.OverrideMetadata(typeof(AngleAxis), new StyledPropertyMetadata(false)); IsZoomEnabledProperty.OverrideMetadata(typeof(AngleAxis), new StyledPropertyMetadata(false)); StartAngleProperty.Changed.AddClassHandler(AppearanceChanged); EndAngleProperty.Changed.AddClassHandler(AppearanceChanged); - PositionProperty.Changed.AddClassHandler(AppearanceChanged); - TickStyleProperty.Changed.AddClassHandler(AppearanceChanged); } /// @@ -50,9 +49,9 @@ static AngleAxis() /// public AngleAxis() { + // The gridline styles are set by OverrideMetadata above. An assignment here would become a local + // value and would override the style setters. InternalAxis = new Axes.AngleAxis(); - MajorGridlineStyle = LineStyle.Solid; - MinorGridlineStyle = LineStyle.Solid; } /// diff --git a/Source/OxyPlot.Avalonia/Axes/Axis.cs b/Source/OxyPlot.Avalonia/Axes/Axis.cs index a2c595a..8da437e 100644 --- a/Source/OxyPlot.Avalonia/Axes/Axis.cs +++ b/Source/OxyPlot.Avalonia/Axes/Axis.cs @@ -93,7 +93,7 @@ public abstract class Axis : Control /// /// Identifies the dependency property. /// - public static readonly StyledProperty ExtraGridlinesProperty = AvaloniaProperty.Register("ExtraGridLines", null); + public static readonly StyledProperty ExtraGridlinesProperty = AvaloniaProperty.Register(nameof(ExtraGridlines), null); /// /// Identifies the dependency property. @@ -589,7 +589,7 @@ public double ExtraGridlineThickness } /// - /// Gets or sets ExtraGridLines. + /// Gets or sets ExtraGridlines. /// public double[] ExtraGridlines { @@ -1548,7 +1548,7 @@ protected virtual void SynchronizeProperties() a.MinimumPadding = MinimumPadding; a.MaximumPadding = MaximumPadding; a.MinimumMargin = MinimumMargin; - a.MaximumMargin = MinimumMargin; + a.MaximumMargin = MaximumMargin; a.MinimumDataMargin = MinimumDataMargin; a.MaximumDataMargin = MaximumDataMargin; a.Position = Position; @@ -1599,6 +1599,8 @@ static Axis() FontWeightProperty.Changed.AddClassHandler(AppearanceChanged); IntervalLengthProperty.Changed.AddClassHandler(AppearanceChanged); IsAxisVisibleProperty.Changed.AddClassHandler(AppearanceChanged); + IsPanEnabledProperty.Changed.AddClassHandler(AppearanceChanged); + IsZoomEnabledProperty.Changed.AddClassHandler(AppearanceChanged); KeyProperty.Changed.AddClassHandler(DataChanged); LabelFormatterProperty.Changed.AddClassHandler(AppearanceChanged); LayerProperty.Changed.AddClassHandler(AppearanceChanged); diff --git a/Source/OxyPlot.Avalonia/Axes/CategoryAxis.cs b/Source/OxyPlot.Avalonia/Axes/CategoryAxis.cs index 1cca98d..71c63d2 100644 --- a/Source/OxyPlot.Avalonia/Axes/CategoryAxis.cs +++ b/Source/OxyPlot.Avalonia/Axes/CategoryAxis.cs @@ -42,7 +42,7 @@ public class CategoryAxis : LinearAxis /// /// Identifies the dependency property. /// - public static readonly StyledProperty> LabelsProperty = AvaloniaProperty.Register>(nameof(Labels), new List()); + public static readonly StyledProperty> LabelsProperty = AvaloniaProperty.Register>(nameof(Labels)); /// /// Initializes static members of the class. @@ -53,6 +53,7 @@ static CategoryAxis() MinimumPaddingProperty.OverrideMetadata(typeof(CategoryAxis), new StyledPropertyMetadata(0.0)); MaximumPaddingProperty.OverrideMetadata(typeof(CategoryAxis), new StyledPropertyMetadata(0.0)); MajorStepProperty.OverrideMetadata(typeof(CategoryAxis), new StyledPropertyMetadata(1.0)); + GapWidthProperty.Changed.AddClassHandler(DataChanged); IsTickCenteredProperty.Changed.AddClassHandler(DataChanged); ItemsProperty.Changed.AddClassHandler(DataChanged); LabelFieldProperty.Changed.AddClassHandler(DataChanged); @@ -69,6 +70,9 @@ static CategoryAxis() public CategoryAxis() { InternalAxis = new Axes.CategoryAxis(); + + // The list is created per instance: the default value in Avalonia is shared by all axes. + SetCurrentValue(LabelsProperty, new List()); } /// diff --git a/Source/OxyPlot.Avalonia/Axes/DateTimeAxis.cs b/Source/OxyPlot.Avalonia/Axes/DateTimeAxis.cs index d635017..fc1b115 100644 --- a/Source/OxyPlot.Avalonia/Axes/DateTimeAxis.cs +++ b/Source/OxyPlot.Avalonia/Axes/DateTimeAxis.cs @@ -56,10 +56,12 @@ public class DateTimeAxis : Axis static DateTimeAxis() { PositionProperty.OverrideDefaultValue(AxisPosition.Bottom); - PositionProperty.Changed.AddClassHandler(AppearanceChanged); CalendarWeekRuleProperty.Changed.AddClassHandler(DataChanged); FirstDayOfWeekProperty.Changed.AddClassHandler(DataChanged); MinorIntervalTypeProperty.Changed.AddClassHandler(DataChanged); + IntervalTypeProperty.Changed.AddClassHandler(DataChanged); + FirstDateTimeProperty.Changed.AddClassHandler(DataChanged); + LastDateTimeProperty.Changed.AddClassHandler(DataChanged); } /// diff --git a/Source/OxyPlot.Avalonia/Axes/LinearAxis.cs b/Source/OxyPlot.Avalonia/Axes/LinearAxis.cs index 7dcfbdf..43fb1cf 100644 --- a/Source/OxyPlot.Avalonia/Axes/LinearAxis.cs +++ b/Source/OxyPlot.Avalonia/Axes/LinearAxis.cs @@ -31,6 +31,16 @@ public class LinearAxis : Axis /// public static readonly StyledProperty FractionUnitSymbolProperty = AvaloniaProperty.Register(nameof(FractionUnitSymbol)); + /// + /// Initializes static members of the class. + /// + static LinearAxis() + { + FormatAsFractionsProperty.Changed.AddClassHandler(AppearanceChanged); + FractionUnitProperty.Changed.AddClassHandler(AppearanceChanged); + FractionUnitSymbolProperty.Changed.AddClassHandler(AppearanceChanged); + } + /// /// Initializes a new instance of the class. /// diff --git a/Source/OxyPlot.Avalonia/Axes/LinearColorAxis.cs b/Source/OxyPlot.Avalonia/Axes/LinearColorAxis.cs index 2ff5afe..b1b2c12 100644 --- a/Source/OxyPlot.Avalonia/Axes/LinearColorAxis.cs +++ b/Source/OxyPlot.Avalonia/Axes/LinearColorAxis.cs @@ -7,7 +7,6 @@ // // -------------------------------------------------------------------------------------------------------------------- -using System.Diagnostics.Contracts; using Avalonia; namespace OxyPlot.Avalonia @@ -44,13 +43,21 @@ public class LinearColorAxis : Axis /// public static readonly StyledProperty PaletteSizeProperty = AvaloniaProperty.Register(nameof(PaletteSize), 20, validate: ValidatePaletteSize); + /// + /// The default palette of the core. It is returned when there are no gradient stops. + /// + private readonly OxyPalette defaultPalette; + /// /// Initializes a new instance of the class. /// public LinearColorAxis() { InternalAxis = new Axes.LinearColorAxis(); - GradientStops = new List(); + defaultPalette = ((Axes.LinearColorAxis)InternalAxis).Palette; + + // The value is set as the current one so that it does not override style setters. + SetCurrentValue(GradientStopsProperty, new List()); } /// @@ -136,13 +143,25 @@ public override Axes.Axis CreateModel() protected override void SynchronizeProperties() { base.SynchronizeProperties(); - var axis = InternalAxis as Axes.LinearColorAxis; - Contract.Requires(axis != null); - if (GradientStops != null) + if (InternalAxis is not Axes.LinearColorAxis axis) { - axis.Palette = GradientStops.Count > 2 - ? Interpolate(GradientStops.ToList(), PaletteSize) - : new OxyPalette(); + throw new InvalidOperationException("The internal axis must be of type LinearColorAxis."); + } + + if (GradientStops != null && GradientStops.Count >= 2) + { + axis.Palette = Interpolate(GradientStops.ToList(), PaletteSize); + } + else if (GradientStops != null && GradientStops.Count == 1) + { + // A single stop: a palette of one color, but of the requested size. + axis.Palette = new OxyPalette( + Enumerable.Repeat(GradientStops[0].Color.ToOxyColor(), Math.Max(1, PaletteSize)).ToList()); + } + else + { + // No stops: return the palette of the core, otherwise the map would become monochrome. + axis.Palette = defaultPalette; } axis.HighColor = HighColor.ToOxyColor(); @@ -168,26 +187,39 @@ private static OxyPalette Interpolate(List stops, int paletteSize) Debug.Assert(stops.Count >= 2, "Can't interpolate less than 2 gradient stops."); Debug.Assert(paletteSize > 0, "Palette size must be non-zero positive number."); - var palette = new List(); stops.Sort((x1, x2) => x1.Offset.CompareTo(x2.Offset)); - var palettePositions = stops[0].Offset; - var step = (double)stops.Count / paletteSize; + var first = stops[0].Offset; + var last = stops[stops.Count - 1].Offset; + var range = last - first; + + // All stops are at one point or a single color is needed: there is nothing to interpolate, + // but the requested palette size must still be honored. + if (range <= 0 || paletteSize < 2) + { + return new OxyPalette( + Enumerable.Repeat(stops[0].Color.ToOxyColor(), Math.Max(1, paletteSize)).ToList()); + } + + var palette = new List(paletteSize); + var segment = 0; - for (int i = 0; i < stops.Count - 1; i++) + for (int i = 0; i < paletteSize; i++) { - var start = stops[i]; - var end = stops[i + 1]; + var position = first + (range * i / (paletteSize - 1)); - while (palettePositions <= end.Offset) + while (segment < stops.Count - 2 && position > stops[segment + 1].Offset) { - palette.Add( - OxyColor.Interpolate( - start.Color.ToOxyColor(), - end.Color.ToOxyColor(), - (palettePositions - start.Offset) / (end.Offset - start.Offset))); - palettePositions += step; + segment++; } + + var start = stops[segment]; + var end = stops[segment + 1]; + var span = end.Offset - start.Offset; + // Stops with the same offset: take the start color, no division by zero. + var t = span > 0 ? (position - start.Offset) / span : 0.0; + + palette.Add(OxyColor.Interpolate(start.Color.ToOxyColor(), end.Color.ToOxyColor(), t)); } return new OxyPalette(palette); diff --git a/Source/OxyPlot.Avalonia/Axes/LogarithmicAxis.cs b/Source/OxyPlot.Avalonia/Axes/LogarithmicAxis.cs index bff3605..27a2e8b 100644 --- a/Source/OxyPlot.Avalonia/Axes/LogarithmicAxis.cs +++ b/Source/OxyPlot.Avalonia/Axes/LogarithmicAxis.cs @@ -20,7 +20,7 @@ public class LogarithmicAxis : Axis /// Identifies the dependency property. /// /// The logarithmic base. - public static readonly StyledProperty BaseProperty = AvaloniaProperty.Register(nameof(Base), 10.0); + public static readonly StyledProperty BaseProperty = AvaloniaProperty.Register(nameof(Base), 10.0, validate: ValidateBase); /// /// Identifies the dependency property. @@ -33,7 +33,6 @@ public class LogarithmicAxis : Axis public LogarithmicAxis() { InternalAxis = new Axes.LogarithmicAxis(); - FilterMinValue = 0; } /// @@ -89,8 +88,22 @@ protected override void SynchronizeProperties() a.PowerPadding = PowerPadding; } + /// + /// Validates the logarithm base. With a base that is not greater than one or is not a number + /// the core cannot compute the axis ticks and rendering hangs. + /// + /// The base. + /// true if the value is valid. + private static bool ValidateBase(double value) + { + return double.IsFinite(value) && value > 1; + } + static LogarithmicAxis() { + // A default value instead of an assignment in the constructor: a local value would override styles + FilterMinValueProperty.OverrideDefaultValue(0.0); + BaseProperty.Changed.AddClassHandler(DataChanged); PowerPaddingProperty.Changed.AddClassHandler(DataChanged); } diff --git a/Source/OxyPlot.Avalonia/Axes/MagnitudeAxis.cs b/Source/OxyPlot.Avalonia/Axes/MagnitudeAxis.cs index 5a428ca..de0ef92 100644 --- a/Source/OxyPlot.Avalonia/Axes/MagnitudeAxis.cs +++ b/Source/OxyPlot.Avalonia/Axes/MagnitudeAxis.cs @@ -25,7 +25,6 @@ static MagnitudeAxis() MajorGridlineStyleProperty.OverrideDefaultValue(LineStyle.Solid); MinorGridlineStyleProperty.OverrideDefaultValue(LineStyle.Solid); PositionProperty.OverrideDefaultValue(AxisPosition.None); - PositionProperty.Changed.AddClassHandler(AppearanceChanged); IsPanEnabledProperty.OverrideDefaultValue(false); IsZoomEnabledProperty.OverrideDefaultValue(false); } diff --git a/Source/OxyPlot.Avalonia/CanvasRenderContext.cs b/Source/OxyPlot.Avalonia/CanvasRenderContext.cs index 17762c3..d9ac737 100644 --- a/Source/OxyPlot.Avalonia/CanvasRenderContext.cs +++ b/Source/OxyPlot.Avalonia/CanvasRenderContext.cs @@ -102,6 +102,11 @@ public override void DrawEllipse(OxyRect rect, double thickness, EdgeRenderingMode edgeRenderingMode) { + if (!IsFinite(rect)) + { + return; + } + var path = CreateAndAdd(); SetStroke(path, stroke, thickness, edgeRenderingMode); if (!fill.IsUndefined()) @@ -136,6 +141,11 @@ private void DrawEllipsesByStreamGeometry( foreach (var rect in rects) { + if (!IsFinite(rect)) + { + continue; + } + if (path == null) { path = CreateAndAdd(); @@ -220,6 +230,12 @@ public override void DrawLine( double[] dashArray, LineJoin lineJoin) { + points = FiniteOnly(points); + if (points.Count == 0) + { + return; + } + if (thickness < BalancedLineDrawingThicknessLimit) { DrawLineBalanced(points, stroke, thickness, edgeRenderingMode, dashArray, lineJoin); @@ -260,6 +276,11 @@ private void DrawLineSegmentsByStreamGeometry( for (int i = 0; i + 1 < points.Count; i += 2) { + if (!IsFinite(points[i]) || !IsFinite(points[i + 1])) + { + continue; + } + if (streamGeometry == null) { streamGeometry = new StreamGeometry(); @@ -325,6 +346,11 @@ public override void DrawLineSegments( for (int i = 0; i + 1 < points.Count; i += 2) { + if (!IsFinite(points[i]) || !IsFinite(points[i + 1])) + { + continue; + } + if (path == null) { path = CreateAndAdd(); @@ -365,6 +391,11 @@ public override void DrawPolygon( double[] dashArray, LineJoin lineJoin) { + if (!IsFinite(points)) + { + return; + } + var e = CreateAndAdd(); SetStroke(e, stroke, thickness, edgeRenderingMode, lineJoin, dashArray, 0); @@ -410,6 +441,11 @@ private void DrawPolygonsByStreamGeometry( foreach (var polygon in polygons) { + if (!IsFinite(polygon)) + { + continue; + } + if (path == null) { path = CreateAndAdd(); @@ -498,6 +534,11 @@ public override void DrawPolygons( foreach (var polygon in polygons) { + if (!IsFinite(polygon)) + { + continue; + } + if (path == null) { path = CreateAndAdd(); @@ -563,6 +604,11 @@ public override void DrawRectangle(OxyRect rect, double thickness, EdgeRenderingMode edgeRenderingMode) { + if (!IsFinite(rect)) + { + return; + } + var path = CreateAndAdd(); SetStroke(path, stroke, thickness, edgeRenderingMode); if (!fill.IsUndefined()) @@ -615,6 +661,11 @@ public override void DrawText( VerticalAlignment valign, OxySize? maxSize) { + if (!IsFinite(p)) + { + return; + } + var tb = CreateAndAdd(); tb.Text = text; tb.Foreground = GetCachedBrush(fill); @@ -638,7 +689,9 @@ public override void DrawText( if (maxSize != null || halign != HorizontalAlignment.Left || valign != VerticalAlignment.Top) { - tb.Measure(new Size(1000, 1000)); + // Measure without a limit: the hard-coded 1000x1000 clipped long labels. + // The required truncation is done by the block below according to maxSize. + tb.Measure(Size.Infinity); var size = tb.DesiredSize; if (maxSize != null) { @@ -730,7 +783,8 @@ public override OxySize MeasureText(string text, tb.FontWeight = GetFontWeight(fontWeight); } - tb.Measure(new Size(1000, 1000)); + // Measure without a limit: the hard-coded 1000x1000 understated the size of long labels. + tb.Measure(Size.Infinity); return new OxySize(tb.DesiredSize.Width, tb.DesiredSize.Height); } @@ -771,25 +825,33 @@ public override void DrawImage( double opacity, bool interpolate) { - if (destWidth <= 0 || destHeight <= 0 || srcWidth <= 0 || srcHeight <= 0) + if (!(destWidth > 0) || !(destHeight > 0) || !(srcWidth > 0) || !(srcHeight > 0) + || !double.IsFinite(destX) || !double.IsFinite(destY) + || !double.IsFinite(destWidth) || !double.IsFinite(destHeight)) { return; } - var image = CreateAndAdd(destX, destY); - var bitmapChain = GetImageSource(source); - - // ReSharper disable CompareOfFloatsByEqualityOperator - if (srcX == 0 && srcY == 0 && srcWidth == bitmapChain.PixelSize.Width && srcHeight == bitmapChain.PixelSize.Height) - // ReSharper restore CompareOfFloatsByEqualityOperator + var bitmap = GetImageSource(source); + if (bitmap == null) { - // do not crop + return; } - else + + // The part of the source is cropped by whole pixels within the bitmap. Clip is not suitable here: + // it is specified in the coordinates of the element, not of the source, and overrides the clipping to the plot area. + var left = Math.Max(0, (int)Math.Floor(srcX)); + var top = Math.Max(0, (int)Math.Floor(srcY)); + var right = Math.Min(bitmap.PixelSize.Width, (int)Math.Ceiling(srcX + srcWidth)); + var bottom = Math.Min(bitmap.PixelSize.Height, (int)Math.Ceiling(srcY + srcHeight)); + if (right <= left || bottom <= top) { - image.Clip = new RectangleGeometry(new Rect(srcX, srcY, srcWidth, srcHeight)); + return; } + var image = CreateAndAdd(destX, destY); + var isWholeBitmap = left == 0 && top == 0 && right == bitmap.PixelSize.Width && bottom == bitmap.PixelSize.Height; + image.Opacity = opacity; image.Width = destWidth; image.Height = destHeight; @@ -800,7 +862,9 @@ public override void DrawImage( Canvas.SetTop(image, destY); //// alternative: image.RenderTransform = new TranslateTransform(destX, destY); - image.Source = bitmapChain; + image.Source = isWholeBitmap + ? bitmap + : new CroppedBitmap(bitmap, new PixelRect(left, top, right - left, bottom - top)); if (interpolate) { @@ -1024,9 +1088,13 @@ private void DrawLineBalanced(IList points, OxyColor stroke, double double lineLength = 0; var dashPatternLength = (dashArray != null) ? dashArray.Sum() : 0; var last = new Point(); + + // The anti-aliasing mode does not depend on the point index, while the check walks the whole list, + // so it is computed once before the loop. Inside the loop it gave quadratic complexity. + var aliased = !this.ShouldUseAntiAliasingForLine(edgeRenderingMode, points); + for (int i = 0; i < n; i++) { - bool aliased = !this.ShouldUseAntiAliasingForLine(edgeRenderingMode, points); var p = aliased ? ToPixelAlignedPoint(points[i]) : ToPoint(points[i]); pc.Add(p); @@ -1105,6 +1173,58 @@ private static Rect ToRect(OxyRect r) return new Rect(r.Left, r.Top, r.Width, r.Height); } + // A shape with NaN or infinite coordinates breaks the whole Canvas layout pass + // (InvalidOperationException from Measure), not just itself. The core produces such + // coordinates for annotations that are not fully configured, so these shapes are not drawn. + + /// + /// Checks that all coordinates of the rectangle are finite. + /// + /// The rectangle. + /// true if the shape can be drawn. + private static bool IsFinite(OxyRect r) + { + return double.IsFinite(r.Left) && double.IsFinite(r.Top) && double.IsFinite(r.Width) && double.IsFinite(r.Height); + } + + /// + /// Checks that both coordinates of the point are finite. + /// + /// The point. + /// true if the point can be drawn. + private static bool IsFinite(ScreenPoint p) + { + return double.IsFinite(p.X) && double.IsFinite(p.Y); + } + + /// + /// Checks that the coordinates of all points are finite. + /// + /// The points. + /// true if the shape can be drawn. + private static bool IsFinite(IList points) + { + for (var i = 0; i < points.Count; i++) + { + if (!IsFinite(points[i])) + { + return false; + } + } + + return true; + } + + /// + /// Removes points with non-finite coordinates from a line. If there are none, returns the same list. + /// + /// The points of the line. + /// The points with finite coordinates. + private static IList FiniteOnly(IList points) + { + return IsFinite(points) ? points : points.Where(IsFinite).ToList(); + } + /// /// Converts an to a pixel aligned . /// diff --git a/Source/OxyPlot.Avalonia/Legends/Legend.Properties.cs b/Source/OxyPlot.Avalonia/Legends/Legend.Properties.cs index 188bab8..3c94003 100644 --- a/Source/OxyPlot.Avalonia/Legends/Legend.Properties.cs +++ b/Source/OxyPlot.Avalonia/Legends/Legend.Properties.cs @@ -49,7 +49,7 @@ public partial class Legend : Control /// /// Identifies the dependency property. /// - public static readonly StyledProperty LegendFontSizeProperty = AvaloniaProperty.Register(nameof(LegendFontSize), 12.0); + public static readonly StyledProperty LegendFontSizeProperty = AvaloniaProperty.Register(nameof(LegendFontSize), double.NaN); /// /// Identifies the dependency property. @@ -154,7 +154,7 @@ public partial class Legend : Control /// /// Identifies the dependency property. /// - public static readonly StyledProperty LegendTitleFontSizeProperty = AvaloniaProperty.Register(nameof(LegendTitleFontSize), 12.0); + public static readonly StyledProperty LegendTitleFontSizeProperty = AvaloniaProperty.Register(nameof(LegendTitleFontSize), double.NaN); /// /// Identifies the dependency property. diff --git a/Source/OxyPlot.Avalonia/Plot.Properties.cs b/Source/OxyPlot.Avalonia/Plot.Properties.cs index 9d900cf..cec7f79 100644 --- a/Source/OxyPlot.Avalonia/Plot.Properties.cs +++ b/Source/OxyPlot.Avalonia/Plot.Properties.cs @@ -95,7 +95,7 @@ public partial class Plot /// /// Identifies the dependency property. /// - public static readonly StyledProperty PlotAreaBackgroundProperty = AvaloniaProperty.Register(nameof(PlotAreaBackground), null); + public static readonly StyledProperty PlotAreaBackgroundProperty = AvaloniaProperty.Register(nameof(PlotAreaBackground), null); /// /// Identifies the dependency property. @@ -140,7 +140,7 @@ public partial class Plot /// /// Identifies the dependency property. /// - public static readonly StyledProperty TitleAlignmentProperty = AvaloniaProperty.Register(nameof(TitleHorizontalAlignment), TitleHorizontalAlignment.CenteredWithinPlotArea); + public static readonly StyledProperty TitleHorizontalAlignmentProperty = AvaloniaProperty.Register(nameof(TitleHorizontalAlignment), TitleHorizontalAlignment.CenteredWithinPlotArea); /// /// Identifies the dependency property. @@ -204,7 +204,7 @@ static Plot() SubtitleFontWeightProperty.Changed.AddClassHandler(AppearanceChanged); SubtitleProperty.Changed.AddClassHandler(AppearanceChanged); TextColorProperty.Changed.AddClassHandler(AppearanceChanged); - TitleAlignmentProperty.Changed.AddClassHandler(AppearanceChanged); + TitleHorizontalAlignmentProperty.Changed.AddClassHandler(AppearanceChanged); TitleFontProperty.Changed.AddClassHandler(AppearanceChanged); TitleFontSizeProperty.Changed.AddClassHandler(AppearanceChanged); TitleFontWeightProperty.Changed.AddClassHandler(AppearanceChanged); @@ -426,7 +426,7 @@ public Color SubtitleColor /// Gets or sets the background brush of the Plot area. /// /// The brush. - public Brush PlotAreaBackground + public IBrush PlotAreaBackground { get { @@ -640,12 +640,12 @@ public TitleHorizontalAlignment TitleHorizontalAlignment { get { - return GetValue(TitleAlignmentProperty); + return GetValue(TitleHorizontalAlignmentProperty); } set { - SetValue(TitleAlignmentProperty, value); + SetValue(TitleHorizontalAlignmentProperty, value); } } diff --git a/Source/OxyPlot.Avalonia/Plot.cs b/Source/OxyPlot.Avalonia/Plot.cs index abab5a3..595292c 100644 --- a/Source/OxyPlot.Avalonia/Plot.cs +++ b/Source/OxyPlot.Avalonia/Plot.cs @@ -14,6 +14,7 @@ namespace OxyPlot.Avalonia using global::Avalonia.Controls; using global::Avalonia.LogicalTree; using global::Avalonia.VisualTree; + using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; @@ -93,15 +94,16 @@ public override IPlotController ActualController /// Updates the model. If Model==null, an internal model will be created. The ActualModel.Update will be called (updates all series data). /// /// if set to true , all data collections will be updated. - protected new void UpdateModel(bool updateData = true) + protected override void UpdateModel(bool updateData = true) { + // The method is virtual, so InvalidatePlot also ends up here (including from InvalidateFlag + // and from the axes): without synchronization, in-place edits of the wrappers would not reach the model. SynchronizeProperties(); SynchronizeSeries(); SynchronizeAxes(); SynchronizeAnnotations(); SynchronizeLegends(); - // TODO: does this achieve anything? we always call InvalidatePlot after UpdateModel base.UpdateModel(updateData); } @@ -110,22 +112,19 @@ public override IPlotController ActualController /// protected void OnAppearanceChanged() { - UpdateModel(false); InvalidatePlot(false); } void IPlot.ElementAppearanceChanged(object element) { // TODO: determine type of element to perform a more fine-grained update - this.UpdateModel(false); - base.InvalidatePlot(false); + InvalidatePlot(false); } void IPlot.ElementDataChanged(object element) { // TODO: determine type of element to perform a more fine-grained update - this.UpdateModel(true); - base.InvalidatePlot(true); + InvalidatePlot(true); } @@ -175,6 +174,19 @@ private void OnSeriesChanged(object sender, NotifyCollectionChangedEventArgs e) /// The instance containing the event data. private void SyncLogicalTree(NotifyCollectionChangedEventArgs e) { + // Reset (which is Clear) does not provide OldItems, while Move and Replace send + // the same element in both NewItems and OldItems. In these cases the per-item logic + // below leaves garbage in the tree, clears the parent or fails on re-adding, + // so the tree is rebuilt completely. + if (e.Action == NotifyCollectionChangedAction.Reset + || e.Action == NotifyCollectionChangedAction.Move + || e.Action == NotifyCollectionChangedAction.Replace) + { + RebuildTreeChildren(); + OnElementsChanged(); + return; + } + // In order to get DataContext and binding to work with the series, axes and annotations // we add the items to the logical tree if (e.NewItems != null) @@ -201,7 +213,70 @@ private void SyncLogicalTree(NotifyCollectionChangedEventArgs e) } } - this.OnAppearanceChanged(); + OnElementsChanged(); + } + + /// + /// Updates the model after the set of series, axes, annotations or legends has changed. + /// This is a data update: the core loads the series points and computes the axis ranges + /// only during it, otherwise an added series stays empty and the axes have no range. + /// + private void OnElementsChanged() + { + InvalidatePlot(true); + } + + /// + /// Brings the logical and visual trees in line with the collections of the plot. + /// Elements of the control template are not touched: they are also in the visual tree, + /// and removing them would break rendering permanently. + /// + private void RebuildTreeChildren() + { + var expected = new HashSet( + series.Cast().Concat(axes).Concat(annotations).Concat(legends)); + + foreach (var child in LogicalChildren.ToArray()) + { + if (IsPlotPart(child) && !expected.Contains(child)) + { + (child as ISetLogicalParent)?.SetParent(null); + LogicalChildren.Remove(child); + } + } + + foreach (var child in VisualChildren.ToArray()) + { + if (IsPlotPart(child) && !expected.Contains(child)) + { + VisualChildren.Remove(child); + } + } + + foreach (var item in expected) + { + if (item is ILogical logical && !LogicalChildren.Contains(logical)) + { + (item as ISetLogicalParent)?.SetParent(this); + LogicalChildren.Add(logical); + } + + if (item is Visual visual && !VisualChildren.Contains(visual)) + { + VisualChildren.Add(visual); + } + } + } + + /// + /// Determines whether a tree element belongs to the collections of the plot, + /// and not to the control template. + /// + /// The tree element. + /// true if this is a series, an axis, an annotation or a legend. + private static bool IsPlotPart(object child) + { + return child is Series || child is Axis || child is Annotation || child is Legend; } /// @@ -229,6 +304,7 @@ private void SynchronizeProperties() m.TitleFontSize = TitleFontSize; m.TitleFontWeight = (int)TitleFontWeight; m.TitleToolTip = TitleToolTip; + m.TitleHorizontalAlignment = TitleHorizontalAlignment; m.Subtitle = Subtitle; m.SubtitleColor = SubtitleColor.ToOxyColor(); diff --git a/Source/OxyPlot.Avalonia/PlotBase.Events.cs b/Source/OxyPlot.Avalonia/PlotBase.Events.cs index 3443a61..0d53e27 100644 --- a/Source/OxyPlot.Avalonia/PlotBase.Events.cs +++ b/Source/OxyPlot.Avalonia/PlotBase.Events.cs @@ -12,7 +12,6 @@ namespace OxyPlot.Avalonia { using global::Avalonia.Input; - using System; using System.Collections.Generic; using System.Linq; @@ -57,6 +56,16 @@ protected override void OnPointerWheelChanged(PointerWheelEventArgs e) /// private SortedDictionary TouchPositions { get; } = new SortedDictionary(); + /// + /// The last known position of the pointer. + /// + private ScreenPoint lastPointerPosition; + + /// + /// Indicates that the capture is released by itself, not by the system. + /// + private bool isReleasingPointer; + /// /// Invoked when an unhandled MouseDown attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event. /// @@ -72,6 +81,12 @@ protected override void OnPointerPressed(PointerPressedEventArgs e) Focus(); e.Pointer.Capture(this); + // The press point is remembered for any pointer: it decides whether the context menu is shown. + mouseDownPoint = e.GetPosition(this).ToScreenPoint(); + mouseDownPointerType = e.Pointer.Type; + hasMouseDownPoint = true; + lastPointerPosition = mouseDownPoint; + if (e.Pointer.Type == PointerType.Touch) { var position = e.GetPosition(this).ToScreenPoint(); @@ -93,9 +108,6 @@ protected override void OnPointerPressed(PointerPressedEventArgs e) } else { - // store the mouse down point, check it when mouse button is released to determine if the context menu should be shown - mouseDownPoint = e.GetPosition(this).ToScreenPoint(); - e.Handled = ActualController.HandleMouseDown(this, e.ToMouseDownEventArgs(this)); } } @@ -112,6 +124,8 @@ protected override void OnPointerMoved(PointerEventArgs e) return; } + lastPointerPosition = e.GetPosition(this).ToScreenPoint(); + if (e.Pointer.Type == PointerType.Touch) { var point = e.GetPosition(this).ToScreenPoint(); @@ -135,13 +149,30 @@ protected override void OnPointerMoved(PointerEventArgs e) /// The that contains the event data. The event data reports that the mouse button was released. protected override void OnPointerReleased(PointerReleasedEventArgs e) { + // The state is remembered before the base method: it raises ContextRequested + // and copies its Handled here. Otherwise, when a context menu is set, + // the controller would not receive the release and the manipulator would stay active. + var handledBefore = e.Handled; base.OnPointerReleased(e); - if (e.Handled) + + // The capture is always released, even if the event has already been marked as handled. + // Otherwise the pointer stays captured after a right click and panning gets stuck. + // Releasing the capture synchronously raises PointerCaptureLost: the flag distinguishes it from a loss of + // capture by the system, otherwise the manipulator would be completed twice. + isReleasingPointer = true; + try { - return; + e.Pointer.Capture(null); + } + finally + { + isReleasingPointer = false; } - e.Pointer.Capture(null); + if (handledBefore) + { + return; + } if (e.Pointer.Type == PointerType.Touch) { @@ -165,24 +196,70 @@ protected override void OnPointerReleased(PointerReleasedEventArgs e) else { e.Handled = ActualController.HandleMouseUp(this, e.ToMouseReleasedEventArgs(this)); + } + } - // Open the context menu - var p = e.GetPosition(this).ToScreenPoint(); - var d = p.DistanceTo(mouseDownPoint); + /// + /// Completes the action started by a press if the pointer capture is lost without a release: + /// the window lost activation, the system cancelled the touch, etc. Otherwise the manipulator of the controller + /// stays active and the plot is panned by plain mouse movement, and the touch stays forever + /// in , so the following gestures do not start. + /// + /// The event data. + protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) + { + base.OnPointerCaptureLost(e); + if (isReleasingPointer) + { + return; + } - if (ContextMenu != null) + if (e.Pointer.Type == PointerType.Touch) + { + if (TouchPositions.TryGetValue(e.Pointer.Id, out var position)) { - if (Math.Abs(d) < 1e-8 && e.InitialPressMouseButton == MouseButton.Right) + TouchPositions.Remove(e.Pointer.Id); + if (TouchPositions.Count == 0) { - ContextMenu.DataContext = DataContext; - ContextMenu.IsVisible = true; - } - else - { - ContextMenu.IsVisible = false; + ActualController.HandleTouchCompleted(this, new OxyTouchEventArgs + { + Position = position, + DeltaTranslation = new ScreenVector(0, 0), + DeltaScale = new ScreenVector(1, 1), + }); } } } + else + { + ActualController.HandleMouseUp(this, new OxyMouseEventArgs { Position = lastPointerPosition }); + } + } + + /// + /// Prepares the context menu for display. The menu is opened by Avalonia itself on the + /// event, so it does not need to be opened manually. + /// If the pointer was moved after the button was pressed (a zoom rectangle was drawn), the menu is not shown. + /// + /// The event source. + /// The event data. + private void OnPlotContextRequested(object sender, ContextRequestedEventArgs e) + { + // The menu is suppressed only for the mouse: for touch and pen it is opened by a long press, + // and the press point is irrelevant to that. + if (hasMouseDownPoint && mouseDownPointerType == PointerType.Mouse + && e.TryGetPosition(this, out var position) + && position.ToScreenPoint().DistanceTo(mouseDownPoint) > 1e-8) + { + // A handled event suppresses opening of the menu. + e.Handled = true; + return; + } + + if (ContextMenu != null) + { + ContextMenu.DataContext = DataContext; + } } /// diff --git a/Source/OxyPlot.Avalonia/PlotBase.Export.cs b/Source/OxyPlot.Avalonia/PlotBase.Export.cs index a41f100..6859ec7 100644 --- a/Source/OxyPlot.Avalonia/PlotBase.Export.cs +++ b/Source/OxyPlot.Avalonia/PlotBase.Export.cs @@ -10,6 +10,7 @@ namespace OxyPlot.Avalonia { using global::Avalonia.Media.Imaging; + using System; using System.IO; /// @@ -23,7 +24,7 @@ public partial class PlotBase /// Stream to which to write the bitmap. public void SaveBitmap(Stream stream) { - SaveBitmap(stream, -1, -1, ActualModel.Background); + SaveBitmap(stream, -1, -1, GetModelForExport().Background); } /// @@ -35,6 +36,8 @@ public void SaveBitmap(Stream stream) /// The background. public void SaveBitmap(Stream stream, int width, int height, OxyColor background) { + var model = GetModelForExport(); + if (width <= 0) { width = (int)Bounds.Width; @@ -45,12 +48,25 @@ public void SaveBitmap(Stream stream, int width, int height, OxyColor background height = (int)Bounds.Height; } + CheckExportSize(width, height); + if (!background.IsVisible()) { background = Background.ToOxyColor(); } - PngExporter.Export(ActualModel, stream, width, height, background); + try + { + lock (model.SyncRoot) + { + PngExporter.Export(model, stream, width, height, background); + } + } + finally + { + // The export recalculated the live model for its own size, so it is restored to the size of the control + InvalidatePlot(false); + } } /// @@ -59,8 +75,49 @@ public void SaveBitmap(Stream stream, int width, int height, OxyColor background /// A bitmap. public Bitmap ToBitmap() { - var background = ActualModel.Background.IsVisible() ? ActualModel.Background : Background.ToOxyColor(); - return PngExporter.ExportToBitmap(ActualModel, (int)Bounds.Width, (int)Bounds.Height, background); + var model = GetModelForExport(); + var width = (int)Bounds.Width; + var height = (int)Bounds.Height; + CheckExportSize(width, height); + + var background = model.Background.IsVisible() ? model.Background : Background.ToOxyColor(); + try + { + lock (model.SyncRoot) + { + return PngExporter.ExportToBitmap(model, width, height, background); + } + } + finally + { + // The export recalculated the live model for its own size, so it is restored to the size of the control + InvalidatePlot(false); + } + } + + /// + /// Gets the model for export. + /// + /// The current model. + /// There is no model. + private PlotModel GetModelForExport() + { + return ActualModel ?? throw new InvalidOperationException("Cannot export a plot without a model: the Model property is not set."); + } + + /// + /// Validates the bitmap size for export. + /// + /// The width. + /// The height. + /// The size is less than one pixel. + private static void CheckExportSize(int width, int height) + { + if (width < 1 || height < 1) + { + throw new InvalidOperationException( + "The control has not been laid out yet or is hidden, so its size is zero. Specify the width and height explicitly in SaveBitmap."); + } } } } diff --git a/Source/OxyPlot.Avalonia/PlotBase.Properties.cs b/Source/OxyPlot.Avalonia/PlotBase.Properties.cs index 92dd5a8..d2b62d3 100644 --- a/Source/OxyPlot.Avalonia/PlotBase.Properties.cs +++ b/Source/OxyPlot.Avalonia/PlotBase.Properties.cs @@ -55,6 +55,11 @@ public partial class PlotBase static PlotBase() { + // Without this the control does not take focus, and the keyboard commands of the plot do not work. + FocusableProperty.OverrideDefaultValue(true); + + // The plot must not be part of the Tab order, it takes focus only by a click. + IsTabStopProperty.OverrideDefaultValue(false); } /// diff --git a/Source/OxyPlot.Avalonia/PlotBase.cs b/Source/OxyPlot.Avalonia/PlotBase.cs index f9f348e..f2c6335 100644 --- a/Source/OxyPlot.Avalonia/PlotBase.cs +++ b/Source/OxyPlot.Avalonia/PlotBase.cs @@ -75,24 +75,24 @@ public abstract partial class PlotBase : TemplatedControl, IPlotView private ScreenPoint mouseDownPoint; /// - /// The overlays. + /// Indicates that the press point has been filled in at least once. /// - private Canvas overlays; + private bool hasMouseDownPoint; /// - /// The zoom control. + /// The type of the pointer that made the last press. /// - private ContentControl zoomControl; + private PointerType mouseDownPointerType; /// - /// The is visible to user cache. + /// The overlays. /// - private bool isVisibleToUserCache; + private Canvas overlays; /// - /// The cached parent. + /// The zoom control. /// - private Control containerCache; + private ContentControl zoomControl; /// /// Initializes a new instance of the class. @@ -101,8 +101,9 @@ protected PlotBase() { DisconnectCanvasWhileUpdating = true; trackerDefinitions = new ObservableCollection(); - + this.GetObservable(BoundsProperty).Subscribe(new AnonymousObserver(OnSizeChanged)); + AddHandler(ContextRequestedEvent, OnPlotContextRequested); } /// @@ -366,9 +367,20 @@ public void ShowZoomRectangle(OxyRect r) /// The text. public async void SetClipboardText(string text) { - if (TopLevel.GetTopLevel(this) is { Clipboard: { } clipboard }) + // The method is declared as void in IPlotView, so there is nobody to catch an exception from here. + // Without try/catch an unavailable or busy clipboard would crash the whole application. + try { - await clipboard.SetTextAsync(text).ConfigureAwait(true); + if (TopLevel.GetTopLevel(this) is { Clipboard: { } clipboard }) + { + await clipboard.SetTextAsync(text).ConfigureAwait(true); + } + } + catch (Exception ex) + { + global::Avalonia.Logging.Logger + .TryGet(global::Avalonia.Logging.LogEventLevel.Warning, global::Avalonia.Logging.LogArea.Control) + ?.Log(this, "Failed to write text to the clipboard: {0}", ex.Message); } } @@ -395,9 +407,22 @@ protected override Size ArrangeOverride(Size finalSize) /// Updates the model. /// /// The update Data. - protected void UpdateModel(bool updateData = true) + protected virtual void UpdateModel(bool updateData = true) { - if (Width <= 0 || Height <= 0 || ActualModel == null) + if (ActualModel == null) + { + // The model was removed: the old plot is erased by UpdateVisuals, but it is only called by + // the layout pass triggered by the isPlotInvalidated flag. Without the flag the picture would stay on the screen. + isUpdateRequired = 0; + if (Interlocked.CompareExchange(ref isPlotInvalidated, 1, 0) == 0) + { + BeginInvoke(InvalidateArrange); + } + + return; + } + + if (Width <= 0 || Height <= 0) { isUpdateRequired = 0; return; @@ -551,15 +576,17 @@ private void UpdateVisuals() /// Invokes the specified action on the dispatcher, if necessary. /// /// The action. - private static void BeginInvoke(Action action) + private void BeginInvoke(Action action) { - if (Dispatcher.UIThread.CheckAccess()) + // The dispatcher of the control, not Dispatcher.UIThread: in Avalonia 12 a control can live + // in a window on another UI thread, and then the main thread has no access to it. + if (CheckAccess()) { action?.Invoke(); } else { - Dispatcher.UIThread.InvokeAsync(action, DispatcherPriority.Loaded); + Dispatcher.InvokeAsync(action, DispatcherPriority.Loaded); } } } diff --git a/Source/OxyPlot.Avalonia/PngExporter.cs b/Source/OxyPlot.Avalonia/PngExporter.cs index e8696a0..d991261 100644 --- a/Source/OxyPlot.Avalonia/PngExporter.cs +++ b/Source/OxyPlot.Avalonia/PngExporter.cs @@ -75,7 +75,7 @@ public static void Export(IPlotModel model, Stream stream, int width, int height /// The height. /// The background. /// The resolution (dpi). - /// A bitmap. + /// A bitmap. The caller must dispose it. public static Bitmap ExportToBitmap( IPlotModel model, int width, @@ -94,15 +94,21 @@ public static Bitmap ExportToBitmap( /// The output stream. public void Export(IPlotModel model, Stream stream) { - var bmp = ExportToBitmap(model); - bmp.Save(stream); + // The bitmap holds a native surface, so it is disposed right after writing. + using var bmp = ExportToBitmap(model); + bmp.Save(stream, PngBitmapEncoderOptions.Default); } /// /// Exports the specified plot model to a bitmap. /// /// The model to export. - /// A bitmap. + /// A bitmap. The caller must dispose it. + /// + /// The model is updated and rendered for the export size. If it is shown in a control, + /// it must be redrawn after the export (InvalidatePlot), otherwise the tracker and zooming + /// work with the geometry of the export. The SaveBitmap and ToBitmap methods of the control do this themselves. + /// public Bitmap ExportToBitmap(IPlotModel model) { var scale = 96d / Resolution; diff --git a/Source/OxyPlot.Avalonia/Series/AreaSeries.cs b/Source/OxyPlot.Avalonia/Series/AreaSeries.cs index 9064411..cfaa019 100644 --- a/Source/OxyPlot.Avalonia/Series/AreaSeries.cs +++ b/Source/OxyPlot.Avalonia/Series/AreaSeries.cs @@ -21,7 +21,7 @@ public class AreaSeries : LineSeries /// /// Identifies the dependency property. /// - public static readonly StyledProperty Color2Property = AvaloniaProperty.Register(nameof(Color2), MoreColors.Automatic); + public static readonly StyledProperty Color2Property = AvaloniaProperty.Register(nameof(Color2), MoreColors.Automatic); /// /// Identifies the dependency property. diff --git a/Source/OxyPlot.Avalonia/Series/BarSeries/BarSeriesBase.cs b/Source/OxyPlot.Avalonia/Series/BarSeries/BarSeriesBase.cs index 6440597..ace86d3 100644 --- a/Source/OxyPlot.Avalonia/Series/BarSeries/BarSeriesBase.cs +++ b/Source/OxyPlot.Avalonia/Series/BarSeries/BarSeriesBase.cs @@ -85,19 +85,20 @@ public class BarSeriesBase : CategorizedSeries static BarSeriesBase() { TrackerFormatStringProperty.OverrideMetadata(typeof(BarSeriesBase), new StyledPropertyMetadata(OxyPlot.Series.BarSeries.DefaultTrackerFormatString)); - BaseValueProperty.Changed.AddClassHandler(AppearanceChanged); + // BaseValue, IsStacked and StackGroup change the range of values, which the core + // recalculates only when the data is updated + BaseValueProperty.Changed.AddClassHandler(DataChanged); ColorFieldProperty.Changed.AddClassHandler(DataChanged); FillColorProperty.Changed.AddClassHandler(AppearanceChanged); - IsStackedProperty.Changed.AddClassHandler(AppearanceChanged); + IsStackedProperty.Changed.AddClassHandler(DataChanged); LabelFormatStringProperty.Changed.AddClassHandler(AppearanceChanged); LabelMarginProperty.Changed.AddClassHandler(AppearanceChanged); LabelPlacementProperty.Changed.AddClassHandler(AppearanceChanged); NegativeFillColorProperty.Changed.AddClassHandler(AppearanceChanged); - StackGroupProperty.Changed.AddClassHandler(AppearanceChanged); + StackGroupProperty.Changed.AddClassHandler(DataChanged); StrokeColorProperty.Changed.AddClassHandler(AppearanceChanged); StrokeThicknessProperty.Changed.AddClassHandler(AppearanceChanged); ValueFieldProperty.Changed.AddClassHandler(DataChanged); - TrackerFormatStringProperty.Changed.AddClassHandler(AppearanceChanged); } /// diff --git a/Source/OxyPlot.Avalonia/Series/BarSeries/BarSeriesBase{T}.cs b/Source/OxyPlot.Avalonia/Series/BarSeries/BarSeriesBase{T}.cs index 96391e3..6e578c6 100644 --- a/Source/OxyPlot.Avalonia/Series/BarSeries/BarSeriesBase{T}.cs +++ b/Source/OxyPlot.Avalonia/Series/BarSeries/BarSeriesBase{T}.cs @@ -23,13 +23,15 @@ public class BarSeriesBase : BarSeriesBase protected override void SynchronizeProperties(OxyPlot.Series.Series series) { base.SynchronizeProperties(series); - if (Items != null) + var s = (OxyPlot.Series.BarSeriesBase)series; + s.Items.Clear(); + + // Items can contain foreign objects if ItemsSource is set together with ValueField or ColorField + foreach (var item in Items) { - var s = (OxyPlot.Series.BarSeriesBase)series; - s.Items.Clear(); - foreach (T item in Items) + if (item is T typed) { - s.Items.Add(item); + s.Items.Add(typed); } } } diff --git a/Source/OxyPlot.Avalonia/Series/BarSeries/LinearBarSeries.cs b/Source/OxyPlot.Avalonia/Series/BarSeries/LinearBarSeries.cs index ae0fa10..999cddb 100644 --- a/Source/OxyPlot.Avalonia/Series/BarSeries/LinearBarSeries.cs +++ b/Source/OxyPlot.Avalonia/Series/BarSeries/LinearBarSeries.cs @@ -21,7 +21,7 @@ public class LinearBarSeries : DataPointSeries /// /// Identifies the dependency property. /// - public static readonly StyledProperty BarWidthProperty = AvaloniaProperty.Register(nameof(BarWidth), 1.0); + public static readonly StyledProperty BarWidthProperty = AvaloniaProperty.Register(nameof(BarWidth), 5.0); /// /// Identifies the dependency property. @@ -36,7 +36,7 @@ public class LinearBarSeries : DataPointSeries /// /// Identifies the dependency property. /// - public static readonly StyledProperty StrokeThicknessProperty = AvaloniaProperty.Register(nameof(StrokeThickness), 1.0); + public static readonly StyledProperty StrokeThicknessProperty = AvaloniaProperty.Register(nameof(StrokeThickness), 0.0); /// /// Identifies the dependency property. diff --git a/Source/OxyPlot.Avalonia/Series/BoxPlotSeries.cs b/Source/OxyPlot.Avalonia/Series/BoxPlotSeries.cs index 4882dbf..fb691e1 100644 --- a/Source/OxyPlot.Avalonia/Series/BoxPlotSeries.cs +++ b/Source/OxyPlot.Avalonia/Series/BoxPlotSeries.cs @@ -12,7 +12,6 @@ namespace OxyPlot.Avalonia { using global::Avalonia.Media; - using System.Linq; /// /// This is a Avalonia wrapper of OxyPlot.BoxPlotSeries @@ -103,7 +102,6 @@ static BoxPlotSeries() StrokeProperty.Changed.AddClassHandler(AppearanceChanged); StrokeThicknessProperty.Changed.AddClassHandler(AppearanceChanged); WhiskerWidthProperty.Changed.AddClassHandler(AppearanceChanged); - TrackerFormatStringProperty.Changed.AddClassHandler(AppearanceChanged); } /// @@ -262,24 +260,28 @@ protected override void SynchronizeProperties(OxyPlot.Series.Series series) base.SynchronizeProperties(series); var s = (OxyPlot.Series.BoxPlotSeries)series; + s.BoxWidth = BoxWidth; s.Fill = Fill.ToOxyColor(); s.LineStyle = LineStyle; s.MedianPointSize = MedianPointSize; + s.MedianThickness = MedianThickness; s.OutlierSize = OutlierSize; s.OutlierType = OutlierType; - s.OutlierOutline = (OutlierOutline ?? Enumerable.Empty()).Select(point => point.ToScreenPoint()).ToArray(); + s.OutlierOutline = OutlierOutline.ToScreenPointArray(); s.ShowBox = ShowBox; s.ShowMedianAsDot = ShowMedianAsDot; s.Stroke = Stroke.ToOxyColor(); s.StrokeThickness = StrokeThickness; s.WhiskerWidth = WhiskerWidth; - if (Items != null) + s.Items.Clear(); + + // Items can contain foreign objects if ItemsSource is set + foreach (var item in Items) { - s.Items.Clear(); - foreach (var item in Items) + if (item is OxyPlot.Series.BoxPlotItem boxItem) { - s.Items.Add((OxyPlot.Series.BoxPlotItem)item); + s.Items.Add(boxItem); } } } diff --git a/Source/OxyPlot.Avalonia/Series/DataPointSeries.cs b/Source/OxyPlot.Avalonia/Series/DataPointSeries.cs index b18f665..8ea9eec 100644 --- a/Source/OxyPlot.Avalonia/Series/DataPointSeries.cs +++ b/Source/OxyPlot.Avalonia/Series/DataPointSeries.cs @@ -123,6 +123,7 @@ static DataPointSeries() CanTrackerInterpolatePointsProperty.Changed.AddClassHandler(AppearanceChanged); DataFieldXProperty.Changed.AddClassHandler(DataChanged); DataFieldYProperty.Changed.AddClassHandler(DataChanged); + MappingProperty.Changed.AddClassHandler(DataChanged); } } } \ No newline at end of file diff --git a/Source/OxyPlot.Avalonia/Series/HeatMapSeries.cs b/Source/OxyPlot.Avalonia/Series/HeatMapSeries.cs index 6e752ee..ea68fb2 100644 --- a/Source/OxyPlot.Avalonia/Series/HeatMapSeries.cs +++ b/Source/OxyPlot.Avalonia/Series/HeatMapSeries.cs @@ -11,8 +11,6 @@ namespace OxyPlot.Avalonia { - using global::Avalonia.Media; - /// /// HeatMapSeries Avalonia wrapper /// @@ -48,16 +46,6 @@ public class HeatMapSeries : XYAxisSeries /// public static readonly StyledProperty ColorAxisKeyProperty = AvaloniaProperty.Register(nameof(ColorAxisKey), default); - /// - /// Identifies this dependency property. - /// - public static readonly StyledProperty LowColorProperty = AvaloniaProperty.Register(nameof(LowColor), default); - - /// - /// Identifies this dependency property. - /// - public static readonly StyledProperty HighColorProperty = AvaloniaProperty.Register(nameof(HighColor), default); - /// /// Initializes static members of the class. /// @@ -65,11 +53,14 @@ static HeatMapSeries() { TrackerFormatStringProperty.OverrideMetadata(typeof(HeatMapSeries), new StyledPropertyMetadata(OxyPlot.Series.HeatMapSeries.DefaultTrackerFormatString)); DataProperty.Changed.AddClassHandler(DataChanged); - X0Property.Changed.AddClassHandler(AppearanceChanged); - X1Property.Changed.AddClassHandler(AppearanceChanged); - Y0Property.Changed.AddClassHandler(AppearanceChanged); - Y1Property.Changed.AddClassHandler(AppearanceChanged); - TrackerFormatStringProperty.Changed.AddClassHandler(AppearanceChanged); + + // The core computes the series bounds in UpdateMaxMin, that is, only when the data is updated: + // otherwise the axes are not rescaled to the new coordinates. + X0Property.Changed.AddClassHandler(DataChanged); + X1Property.Changed.AddClassHandler(DataChanged); + Y0Property.Changed.AddClassHandler(DataChanged); + Y1Property.Changed.AddClassHandler(DataChanged); + ColorAxisKeyProperty.Changed.AddClassHandler(AppearanceChanged); } /// @@ -81,38 +72,6 @@ public HeatMapSeries() InternalSeries = new OxyPlot.Series.HeatMapSeries { Data = Data }; } - /// - /// Gets or sets LowColor - /// - public Color LowColor - { - get - { - return GetValue(LowColorProperty); - } - - set - { - SetValue(LowColorProperty, value); - } - } - - /// - /// Gets or sets HighColor - /// - public Color HighColor - { - get - { - return GetValue(LowColorProperty); - } - - set - { - SetValue(LowColorProperty, value); - } - } - /// /// Gets or sets ColorAxisKey property. /// @@ -237,6 +196,7 @@ protected override void SynchronizeProperties(OxyPlot.Series.Series series) s.X1 = X1; s.Y0 = Y0; s.Y1 = Y1; + s.ColorAxisKey = ColorAxisKey; } } } \ No newline at end of file diff --git a/Source/OxyPlot.Avalonia/Series/LineSeries.cs b/Source/OxyPlot.Avalonia/Series/LineSeries.cs index 93d436d..1443295 100644 --- a/Source/OxyPlot.Avalonia/Series/LineSeries.cs +++ b/Source/OxyPlot.Avalonia/Series/LineSeries.cs @@ -15,7 +15,6 @@ namespace OxyPlot.Avalonia using OxyPlot.Series; using System; using System.Collections.Generic; - using System.Linq; /// /// This is a Avalonia wrapper of OxyPlot.LineSeries @@ -144,7 +143,12 @@ static LineSeries() MarkerTypeProperty.Changed.AddClassHandler(AppearanceChanged); MinimumSegmentLengthProperty.Changed.AddClassHandler(AppearanceChanged); StrokeThicknessProperty.Changed.AddClassHandler(AppearanceChanged); - CanTrackerInterpolatePointsProperty.Changed.AddClassHandler(AppearanceChanged); + LabelFormatStringProperty.Changed.AddClassHandler(AppearanceChanged); + LabelMarginProperty.Changed.AddClassHandler(AppearanceChanged); + LineLegendPositionProperty.Changed.AddClassHandler(AppearanceChanged); + + // The core recalculates the smoothed points only when the data is updated + InterpolationAlgorithmProperty.Changed.AddClassHandler(DataChanged); } /// @@ -497,7 +501,7 @@ protected override void SynchronizeProperties(OxyPlot.Series.Series series) s.Dashes = Dashes; s.LineJoin = LineJoin; s.MarkerFill = MarkerFill.ToOxyColor(); - s.MarkerOutline = (MarkerOutline ?? Enumerable.Empty()).Select(point => point.ToScreenPoint()).ToArray(); + s.MarkerOutline = MarkerOutline.ToScreenPointArray(); s.MinimumSegmentLength = MinimumSegmentLength; s.LabelFormatString = LabelFormatString; s.LabelMargin = LabelMargin; diff --git a/Source/OxyPlot.Avalonia/Series/PieSeries.cs b/Source/OxyPlot.Avalonia/Series/PieSeries.cs index 0974308..4674afa 100644 --- a/Source/OxyPlot.Avalonia/Series/PieSeries.cs +++ b/Source/OxyPlot.Avalonia/Series/PieSeries.cs @@ -154,11 +154,11 @@ static PieSeries() TickRadialLengthProperty.Changed.AddClassHandler(AppearanceChanged); TickHorizontalLengthProperty.Changed.AddClassHandler(AppearanceChanged); TickLabelDistanceProperty.Changed.AddClassHandler(AppearanceChanged); + ExplodedDistanceProperty.Changed.AddClassHandler(AppearanceChanged); LabelFieldProperty.Changed.AddClassHandler(DataChanged); ValueFieldProperty.Changed.AddClassHandler(DataChanged); ColorFieldProperty.Changed.AddClassHandler(DataChanged); IsExplodedFieldProperty.Changed.AddClassHandler(DataChanged); - TrackerFormatStringProperty.Changed.AddClassHandler(AppearanceChanged); } /// diff --git a/Source/OxyPlot.Avalonia/Series/ScatterSeries{T}.cs b/Source/OxyPlot.Avalonia/Series/ScatterSeries{T}.cs index 981a1be..757f53c 100644 --- a/Source/OxyPlot.Avalonia/Series/ScatterSeries{T}.cs +++ b/Source/OxyPlot.Avalonia/Series/ScatterSeries{T}.cs @@ -54,7 +54,7 @@ public abstract class ScatterSeries : XYAxisSeries where T : ScatterPoint /// /// Identifies the dependency property. /// - public static readonly StyledProperty> MappingProperty = AvaloniaProperty.Register, Func>(nameof(Mapping), null); + public static readonly StyledProperty> MappingProperty = AvaloniaProperty.Register, Func>(nameof(Mapping), null); /// /// Identifies the dependency property. @@ -86,6 +86,11 @@ public abstract class ScatterSeries : XYAxisSeries where T : ScatterPoint /// public static readonly StyledProperty MarkerTypeProperty = AvaloniaProperty.Register, MarkerType>(nameof(MarkerType), MarkerType.Square); + /// + /// Identifies the dependency property. + /// + public static readonly StyledProperty ColorAxisKeyProperty = AvaloniaProperty.Register, string>(nameof(ColorAxisKey), null); + /// /// Initializes a new instance of the class. /// @@ -197,7 +202,7 @@ public Func Mapping { get { - return (Func)GetValue(MappingProperty); + return GetValue(MappingProperty); } set @@ -306,7 +311,18 @@ public MarkerType MarkerType /// Gets or sets the color axis key. /// /// The color axis key. - public string ColorAxisKey { get; set; } + public string ColorAxisKey + { + get + { + return GetValue(ColorAxisKeyProperty); + } + + set + { + SetValue(ColorAxisKeyProperty, value); + } + } /// /// Creates the internal series. @@ -358,6 +374,7 @@ static ScatterSeries() MarkerStrokeProperty.Changed.AddClassHandler>(AppearanceChanged); MarkerStrokeThicknessProperty.Changed.AddClassHandler>(AppearanceChanged); MarkerTypeProperty.Changed.AddClassHandler>(AppearanceChanged); + ColorAxisKeyProperty.Changed.AddClassHandler>(AppearanceChanged); } } } \ No newline at end of file diff --git a/Source/OxyPlot.Avalonia/Series/Series.cs b/Source/OxyPlot.Avalonia/Series/Series.cs index 8f95b98..3f4091a 100644 --- a/Source/OxyPlot.Avalonia/Series/Series.cs +++ b/Source/OxyPlot.Avalonia/Series/Series.cs @@ -64,8 +64,12 @@ public abstract class Series : ItemsControl /// static Series() { - IsVisibleProperty.Changed.AddClassHandler(AppearanceChanged); + // The core loads the data and computes the axis ranges only for visible series and only + // when the data is updated. Therefore showing and hiding a series is a data change. + IsVisibleProperty.Changed.AddClassHandler(DataChanged); BackgroundProperty.Changed.AddClassHandler(AppearanceChanged); + ForegroundProperty.Changed.AddClassHandler(AppearanceChanged); + FontFamilyProperty.Changed.AddClassHandler(AppearanceChanged); ColorProperty.Changed.AddClassHandler(AppearanceChanged); TitleProperty.Changed.AddClassHandler(AppearanceChanged); RenderInLegendProperty.Changed.AddClassHandler(AppearanceChanged); @@ -258,8 +262,12 @@ protected virtual void SynchronizeProperties(OxyPlot.Series.Series s) s.TrackerKey = TrackerKey; s.TrackerFormatString = TrackerFormatString; s.IsVisible = IsVisible; - s.Font = FontFamily.ToString(); - s.TextColor = Foreground.ToOxyColor(); + + // Foreground and FontFamily are inherited from the window and the theme. They are copied only if + // they are set on the series itself, otherwise the labels follow Plot.TextColor and Plot.DefaultFont, + // like those of the axes, and do not turn white on a white background in a dark theme. + s.Font = IsSet(FontFamilyProperty) ? FontFamily.ToString() : null; + s.TextColor = IsSet(ForegroundProperty) ? Foreground.ToOxyColor() : OxyColors.Automatic; s.EdgeRenderingMode = EdgeRenderingMode; } diff --git a/Source/OxyPlot.Avalonia/Series/ThreeColorLineSeries.cs b/Source/OxyPlot.Avalonia/Series/ThreeColorLineSeries.cs index a6ef45f..dfbb529 100644 --- a/Source/OxyPlot.Avalonia/Series/ThreeColorLineSeries.cs +++ b/Source/OxyPlot.Avalonia/Series/ThreeColorLineSeries.cs @@ -164,6 +164,8 @@ protected override void SynchronizeProperties(OxyPlot.Series.Series series) s.ColorLo = ColorLo.ToOxyColor(); s.LimitHi = LimitHi; s.ColorHi = ColorHi.ToOxyColor(); + s.LineStyleLo = LineStyleLo; + s.LineStyleHi = LineStyleHi; } static ThreeColorLineSeries() diff --git a/Source/OxyPlot.Avalonia/Series/TwoColorAreaSeries.cs b/Source/OxyPlot.Avalonia/Series/TwoColorAreaSeries.cs index 5c0223c..3132ef1 100644 --- a/Source/OxyPlot.Avalonia/Series/TwoColorAreaSeries.cs +++ b/Source/OxyPlot.Avalonia/Series/TwoColorAreaSeries.cs @@ -24,11 +24,6 @@ public class TwoColorAreaSeries : AreaSeries /// public static readonly StyledProperty Dashes2Property = AvaloniaProperty.Register(nameof(Dashes2)); - /// - /// Identifies the dependency property. - /// - public static readonly StyledProperty FillProperty = AvaloniaProperty.Register(nameof(Fill), MoreColors.Automatic); - /// /// Identifies the dependency property. /// @@ -77,22 +72,6 @@ public double[] Dashes2 } } - /// - /// Gets or sets Fill above the limit line. - /// - public Color Fill - { - get - { - return GetValue(FillProperty); - } - - set - { - SetValue(FillProperty, value); - } - } - /// /// Gets or sets Fill below the limit line. /// @@ -181,7 +160,6 @@ protected override void SynchronizeProperties(OxyPlot.Series.Series series) { base.SynchronizeProperties(series); var s = (OxyPlot.Series.TwoColorAreaSeries)series; - s.Fill = Fill.ToOxyColor(); s.Fill2 = Fill2.ToOxyColor(); s.MarkerFill2 = MarkerFill2.ToOxyColor(); s.MarkerStroke2 = MarkerStroke2.ToOxyColor(); @@ -192,11 +170,11 @@ protected override void SynchronizeProperties(OxyPlot.Series.Series series) static TwoColorAreaSeries() { - FillProperty.Changed.AddClassHandler(AppearanceChanged); Fill2Property.Changed.AddClassHandler(AppearanceChanged); MarkerFill2Property.Changed.AddClassHandler(AppearanceChanged); MarkerStroke2Property.Changed.AddClassHandler(AppearanceChanged); - LimitProperty.Changed.AddClassHandler(AppearanceChanged); + // The core splits the points into the parts above and below the limit in UpdateData, not while rendering + LimitProperty.Changed.AddClassHandler(DataChanged); Dashes2Property.Changed.AddClassHandler(AppearanceChanged); LineStyle2Property.Changed.AddClassHandler(AppearanceChanged); } diff --git a/Source/OxyPlot.Avalonia/Series/TwoColorLineSeries.cs b/Source/OxyPlot.Avalonia/Series/TwoColorLineSeries.cs index 6e23e57..5685c7b 100644 --- a/Source/OxyPlot.Avalonia/Series/TwoColorLineSeries.cs +++ b/Source/OxyPlot.Avalonia/Series/TwoColorLineSeries.cs @@ -99,6 +99,7 @@ protected override void SynchronizeProperties(OxyPlot.Series.Series series) var s = (OxyPlot.Series.TwoColorLineSeries)series; s.Limit = Limit; s.Color2 = Color2.ToOxyColor(); + s.LineStyle2 = LineStyle2; } static TwoColorLineSeries() diff --git a/Source/OxyPlot.Avalonia/Series/XYAxisSeries.cs b/Source/OxyPlot.Avalonia/Series/XYAxisSeries.cs index 269429e..d1aa95c 100644 --- a/Source/OxyPlot.Avalonia/Series/XYAxisSeries.cs +++ b/Source/OxyPlot.Avalonia/Series/XYAxisSeries.cs @@ -34,7 +34,6 @@ static XYAxisSeries() TrackerFormatStringProperty.OverrideMetadata(typeof(XYAxisSeries), new StyledPropertyMetadata(OxyPlot.Series.XYAxisSeries.DefaultTrackerFormatString)); XAxisKeyProperty.Changed.AddClassHandler(AppearanceChanged); YAxisKeyProperty.Changed.AddClassHandler(AppearanceChanged); - TrackerFormatStringProperty.Changed.AddClassHandler(AppearanceChanged); } /// diff --git a/Source/OxyPlot.Avalonia/Themes/Default.axaml b/Source/OxyPlot.Avalonia/Themes/Default.axaml index 6b5dcf4..f0f6a33 100644 --- a/Source/OxyPlot.Avalonia/Themes/Default.axaml +++ b/Source/OxyPlot.Avalonia/Themes/Default.axaml @@ -5,7 +5,9 @@ xmlns:local="http://oxyplot.org/avalonia" xmlns:oxy="clr-namespace:OxyPlot;assembly=OxyPlot"> - - -