using System;
using System.Collections.Generic;
using Amphora;
using Azimuth;
namespace Prism.Glass
{
///
/// A function being edited: its points, what it does between them, and which point is selected. The points are
/// kept in order of X, so moving one past another changes its index. X is held to 0 through 1 and Y is any finite
/// value.
///
public class FunctionModel
{
private struct Point
{
public double X;
public double Y;
}
private readonly List points = new List();
private FunctionMode mode;
private int selectedIndex;
///
/// Gets the function as edited so far. It is replaced by a new one each time the model changes.
///
public PointFunction Function { get; private set; }
///
/// Raised with the new function each time a point is added, removed or moved, or the mode changes. It comes
/// before when an edit does both.
///
public event Action Changed;
///
/// Raised with the new index when the selected point is a different one, or has moved to a different index.
///
public event Action SelectionChanged;
///
/// Makes a model of the function, with its first point selected.
///
/// The function is null.
/// The function isn't made of points.
public FunctionModel(IScalarFunction function)
{
Fill(function);
}
private static FunctionMode ModeOf(IScalarFunction function)
{
if (function == null)
{
throw new ArgumentNullException(nameof(function));
}
if (function is MonotoneSpline)
{
return FunctionMode.Smooth;
}
if (function is PiecewiseStep)
{
return FunctionMode.Step;
}
if (function is PiecewiseLinear)
{
return FunctionMode.Linear;
}
throw new ArgumentException("Only a function made of points can be edited.", nameof(function));
}
private void Fill(IScalarFunction function)
{
FunctionMode newMode = ModeOf(function);
var source = (PointFunction)function;
mode = newMode;
Function = source;
selectedIndex = 0;
points.Clear();
for (int i = 0; i < source.PointCount; ++i)
{
points.Add(new Point { X = source.GetX(i).Value, Y = source.GetY(i).Value });
}
}
///
/// Replaces everything the model holds with another function's points and mode, and selects the first point.
/// is raised, then , even when the function looks the same
/// as before.
///
/// The function is null.
/// The function isn't made of points.
public void Load(IScalarFunction function)
{
Fill(function);
Changed?.Invoke(Function);
SelectionChanged?.Invoke(selectedIndex);
}
public int PointCount => points.Count;
///
/// Gets the index of the selected point.
///
public int SelectedIndex => selectedIndex;
///
/// Gets what the function does between its points. changes it.
///
public FunctionMode Mode => mode;
///
/// Gets or sets what is done with each function an edit would make, before the model takes it. A failed status
/// turns the edit down and changes nothing. Loading a function doesn't ask.
///
public Func Apply { get; set; }
private static StatusOr TryBuild(FunctionMode mode, List points)
{
var knots = new (Scalar X, Scalar Y)[points.Count];
for (int i = 0; i < knots.Length; ++i)
{
knots[i] = (points[i].X, points[i].Y);
}
switch (mode)
{
case FunctionMode.Smooth:
// A rise too big for any slope to hold has no smooth line through it.
try
{
return new MonotoneSpline(knots);
}
catch (ArgumentException)
{
return FunctionFailures.SmoothSpansTooMuchY.Fail();
}
case FunctionMode.Step:
return new PiecewiseStep(knots);
default:
return new PiecewiseLinear(knots);
}
}
// The function an edit would make, if the mode can build it and what is applying it takes it.
private StatusOr Build(FunctionMode mode, List points)
{
StatusOr built = TryBuild(mode, points);
if (!built.IsOk)
{
return built;
}
Status applied = Apply == null ? Status.Ok : Apply(built.Value);
if (!applied.IsOk)
{
return applied;
}
return built;
}
private void Replace(PointFunction function, List edited)
{
points.Clear();
points.AddRange(edited);
Function = function;
Changed?.Invoke(Function);
}
///
/// Changes what the function does between its points. It is refused, changing nothing, when the points can't
/// be joined that way, which is so for a smooth line through a rise too big for any slope, and then the status
/// is . It is refused with 's status when
/// that turns the function down.
///
/// The mode isn't a defined one.
public Status SetMode(FunctionMode value)
{
if (!Enum.IsDefined(typeof(FunctionMode), value))
{
throw new ArgumentOutOfRangeException(nameof(value), value, "Not a function mode.");
}
if (value == mode)
{
return Status.Ok;
}
StatusOr built = Build(value, points);
if (!built.IsOk)
{
return built.Status;
}
mode = value;
Replace(built.Value, new List(points));
return Status.Ok;
}
private void CheckIndex(int index)
{
if (index < 0 || index >= points.Count)
{
throw new ArgumentOutOfRangeException(nameof(index), index, "Not a point of this function.");
}
}
private static double ClampToUnit(Scalar x)
{
double returnMe = x.Value;
if (double.IsNaN(returnMe))
{
throw new ArgumentOutOfRangeException(nameof(x), x, "X must be a number.");
}
if (returnMe < 0)
{
returnMe = 0;
}
else if (returnMe > 1)
{
returnMe = 1;
}
return returnMe;
}
private static double Finite(Scalar y)
{
if (Scalar.IsNaN(y) || Scalar.IsInfinity(y))
{
throw new ArgumentOutOfRangeException(nameof(y), y, "Y must be finite.");
}
return y.Value;
}
// After the points that share its X, so it is the later value at a jump.
private static int InsertAfterEquals(List list, Point point)
{
int returnMe = 0;
while (returnMe < list.Count && list[returnMe].X <= point.X)
{
++returnMe;
}
list.Insert(returnMe, point);
return returnMe;
}
///
/// Returns where a point is along the function, from 0 to 1. The points are in order of X.
///
/// The index is not a point.
public Scalar GetX(int index)
{
CheckIndex(index);
return points[index].X;
}
///
/// Returns the function's value at a point.
///
/// The index is not a point.
public Scalar GetY(int index)
{
CheckIndex(index);
return points[index].Y;
}
///
/// Selects a point. Selecting the one already selected changes nothing.
///
/// The index is not a point.
public void Select(int index)
{
CheckIndex(index);
if (index != selectedIndex)
{
selectedIndex = index;
SelectionChanged?.Invoke(selectedIndex);
}
}
///
/// Adds a point here, with X held to 0 through 1. It goes after any point with the same X, and is selected.
/// Returns its index, or and changes nothing when the mode
/// can't have a point there. 's status comes back instead when that turns the function
/// down.
///
/// The X is not a number, or the Y is not finite.
public StatusOr AddPoint(Scalar x, Scalar y)
{
var added = new Point { X = ClampToUnit(x), Y = Finite(y) };
var edited = new List(points);
int index = InsertAfterEquals(edited, added);
StatusOr built = Build(mode, edited);
if (!built.IsOk)
{
return built.Status;
}
selectedIndex = index;
Replace(built.Value, edited);
SelectionChanged?.Invoke(selectedIndex);
return index;
}
///
/// Removes a point. The last point stays, since a function needs one. The selection stays on the point it was
/// on, or on the one that takes the removed point's place if that was it. Changes nothing, and returns , for the last point. It returns when the mode can't join the points that are left. 's status comes back instead when that turns the function down.
///
/// The index is not a point.
public Status RemovePoint(int index)
{
CheckIndex(index);
if (points.Count == 1)
{
return FunctionFailures.NeedsAPoint.Fail();
}
var edited = new List(points);
edited.RemoveAt(index);
StatusOr built = Build(mode, edited);
if (!built.IsOk)
{
return built.Status;
}
bool selectionMoved = index <= selectedIndex;
if (index < selectedIndex)
{
--selectedIndex;
}
else if (index == selectedIndex)
{
selectedIndex = Math.Min(selectedIndex, edited.Count - 1);
}
Replace(built.Value, edited);
if (selectionMoved)
{
SelectionChanged?.Invoke(selectedIndex);
}
return Status.Ok;
}
///
/// Moves a point here, with X held to 0 through 1, after any point with the same X. The selection stays on the
/// point it was on. Returns the point's new index, which differs when it passes another. When the mode can't
/// have it there nothing changes, and the result is . 's status comes back instead when that turns the function down.
///
///
/// The index is not a point, the X is not a number, or the Y is not finite.
///
public StatusOr MovePoint(int index, Scalar x, Scalar y)
{
CheckIndex(index);
var moved = new Point { X = ClampToUnit(x), Y = Finite(y) };
if (points[index].X == moved.X && points[index].Y == moved.Y)
{
return index;
}
var edited = new List(points);
edited.RemoveAt(index);
int returnMe = InsertAfterEquals(edited, moved);
StatusOr built = Build(mode, edited);
if (!built.IsOk)
{
return built.Status;
}
int selectedBefore = selectedIndex;
if (selectedIndex == index)
{
selectedIndex = returnMe;
}
else if (index < selectedIndex && selectedIndex <= returnMe)
{
--selectedIndex;
}
else if (returnMe <= selectedIndex && selectedIndex < index)
{
++selectedIndex;
}
Replace(built.Value, edited);
if (selectedIndex != selectedBefore)
{
SelectionChanged?.Invoke(selectedIndex);
}
return returnMe;
}
}
}