using Amphora;
using Annulus;
using Azimuth;
using Clave;
using Glass;
using System;
namespace Prism.Glass
{
///
/// A plot of a function, with a marker on each of its points. Pressing a marker selects its point and dragging
/// moves it. Pressing the plot adds a point there, which then follows the drag. Every part edits the model it is
/// given, and follows it.
///
public class FunctionEditor : Panel
{
private static readonly ChordSet DefaultRemovePointChords = BuildRemovePointChords();
// Press rather than repeat, so holding the key can't take every point.
private static ChordSet BuildRemovePointChords()
{
var returnMe = new ChordSetBuilder();
returnMe.Add(Chord.OnPress(KeyCode.Delete));
return returnMe.Build();
}
// The controls are made up front, so a model has room for MaxPoints points and the markers past its count hide.
private readonly PickSurface[] markers;
private readonly byte[] pixels;
private readonly int plotWidth;
private readonly int plotHeight;
private readonly PlotColors colors;
private readonly Action upload;
private FunctionEditorMaterial editorMaterial;
// The values the plot spans up its height. They hold still during a drag, so the plot doesn't slide under the
// pointer, and fit the function again when it ends.
private Interval range = new Interval(0, 1);
private bool dragging;
// The point a drag is moving, or -1 for none, and how far it is from the pointer along X and in value.
private int draggedPoint = -1;
private double grabX;
private double grabValue;
// The press itself has already put the point where it is, so the pick that comes with it moves nothing.
private bool pressPending;
private ChordSet removePointChords = DefaultRemovePointChords;
///
/// Raised with why, when the model refuses a point that was added, dragged or removed here. A drag raises it
/// for each move that is refused.
///
public event Action OnRefused;
///
/// Gets the function being edited.
///
public FunctionModel Model { get; }
///
/// Gets how many points the editor has room for.
///
public int MaxPoints => markers.Length;
///
/// Gets the plot, which adds a point where it is pressed.
///
public PickSurface Plot { get; } = new PickSurface();
///
/// Gets the button that removes the selected point.
///
public Button RemoveButton { get; }
///
/// Gets or sets the chords that remove the selected point while the editor has focus, which a press of a marker
/// or the plot gives it. The last point stays, as it does for the button.
///
/// The value is null.
public ChordSet RemovePointChords
{
get => removePointChords;
set => removePointChords = value ?? throw new ArgumentNullException(nameof(value));
}
///
/// Gets the marker of the point at an index. It is hidden when the model has no point there.
///
public PickSurface MarkerAt(int index)
{
return markers[index];
}
///
/// Makes an editor for a function. It has no look until it is given an .
///
///
/// How many points the editor has room for, which the model may not already pass.
///
/// How many pixels wide the plot's texture is.
/// How many pixels tall the plot's texture is.
/// The colors the plot is drawn in.
///
/// Puts the plot's RGBA pixels into its texture. The editor draws into one buffer and hands it over each time
/// the function changes, always the same buffer.
///
public FunctionEditor(
FunctionModel model, int maxPoints, int plotWidth, int plotHeight, PlotColors colors,
Action upload, ButtonBehavior removeBehavior)
{
Model = model ?? throw new ArgumentNullException(nameof(model));
this.upload = upload ?? throw new ArgumentNullException(nameof(upload));
if (maxPoints < model.PointCount)
{
throw new ArgumentOutOfRangeException(
nameof(maxPoints), maxPoints, "The editor needs room for every point the model has.");
}
if (plotWidth < 2)
{
throw new ArgumentOutOfRangeException(nameof(plotWidth), plotWidth, "A plot needs at least 2 pixels.");
}
if (plotHeight < 1)
{
throw new ArgumentOutOfRangeException(
nameof(plotHeight), plotHeight, "A plot needs at least 1 pixel.");
}
this.plotWidth = plotWidth;
this.plotHeight = plotHeight;
this.colors = colors;
pixels = new byte[Rgba.ByteCount(plotWidth, plotHeight)];
RemoveButton = new Button(removeBehavior);
markers = new PickSurface[maxPoints];
CanvasChildren.Add(Plot);
for (int i = 0; i < maxPoints; ++i)
{
int index = i;
markers[i] = new PickSurface();
markers[i].OnPressed += fraction => PressMarker(index, fraction);
markers[i].OnPicked += fraction => Drag(markers[index], fraction);
markers[i].OnDragEnded += EndDrag;
CanvasChildren.Add(markers[i]);
}
CanvasChildren.Add(RemoveButton);
Plot.OnPressed += PressPlot;
Plot.OnPicked += fraction => Drag(Plot, fraction);
Plot.OnDragEnded += EndDrag;
RemoveButton.OnActivate += (ButtonBase _, in KeyboardSnapshot held, KeyboardManager keys) =>
RemoveSelected();
model.Changed += _ => Followed();
model.SelectionChanged += _ => ShowMarkers();
Focusable = true;
FocusOnClick = true;
FitRange();
ApplyMaterials();
Layout();
Refresh();
}
///
/// Gets or sets the look of the parts, which also sizes the editor to them.
///
public FunctionEditorMaterial EditorMaterial
{
get => editorMaterial;
set
{
editorMaterial = value;
ApplyMaterials();
Layout();
Refresh();
}
}
private static Vector SizeOf(Material material)
{
return material?.PreferredSize(Constraints.Unbounded) ?? Vector.Zero;
}
// A part with no art is hidden, since a panel with no material has nothing to draw.
private static void Show(Panel part, Material material)
{
part.Visible = material != null;
part.Material = material;
}
// Fits the range to the function, and returns whether that moved it. It spans 0 to 1 at least.
private bool FitRange()
{
Scalar low = Scalar.Min(0, Model.Function.MinY);
Scalar high = Scalar.Max(1, Model.Function.MaxY);
bool returnMe = low.Value != range.Min.Value || high.Value != range.Max.Value;
range = new Interval(low, high);
return returnMe;
}
private double ValueAt(double fractionDown)
{
return range.Max.Value - fractionDown * (range.Max.Value - range.Min.Value);
}
private double HeldToRange(double value)
{
if (value < range.Min.Value)
{
return range.Min.Value;
}
return value > range.Max.Value ? range.Max.Value : value;
}
// Where a pick on a surface is on the plot, as fractions across and down it. A marker's pick is across itself.
private Vector PlotFractionOf(PickSurface surface, Vector fractionOnSurface)
{
Rect plot = Plot.Bounds;
if (ReferenceEquals(surface, Plot) || !(plot.Width > 0) || !(plot.Height > 0))
{
return fractionOnSurface;
}
Rect bounds = surface.Bounds;
return new Vector(
(bounds.Left + fractionOnSurface.X * bounds.Width - plot.Left) / plot.Width,
(bounds.Top + fractionOnSurface.Y * bounds.Height - plot.Top) / plot.Height);
}
private void PressMarker(int index, Vector fraction)
{
Vector at = PlotFractionOf(markers[index], fraction);
Model.Select(index);
dragging = true;
draggedPoint = index;
grabX = Model.GetX(index).Value - at.X;
grabValue = Model.GetY(index).Value - ValueAt(at.Y);
pressPending = true;
}
private void RemoveSelected()
{
Status removed = Model.RemovePoint(Model.SelectedIndex);
if (!removed.IsOk)
{
OnRefused?.Invoke(removed);
}
}
private void PressPlot(Vector fraction)
{
dragging = true;
pressPending = true;
grabX = 0;
grabValue = 0;
if (Model.PointCount >= markers.Length)
{
draggedPoint = -1;
OnRefused?.Invoke(FunctionFailures.TooManyPoints.Fail(
$"This editor can show at most {markers.Length} points."));
return;
}
StatusOr added = Model.AddPoint(fraction.X, HeldToRange(ValueAt(fraction.Y)));
if (added.IsOk)
{
draggedPoint = added.Value;
}
else
{
draggedPoint = -1;
OnRefused?.Invoke(added.Status);
}
}
private void Drag(PickSurface surface, Vector fraction)
{
if (pressPending)
{
pressPending = false;
return;
}
if (draggedPoint >= 0)
{
Vector at = PlotFractionOf(surface, fraction);
StatusOr moved = Model.MovePoint(
draggedPoint, at.X + grabX, HeldToRange(ValueAt(at.Y) + grabValue));
// A point the mode can't have there stays where it was, and the drag goes on.
if (moved.IsOk)
{
draggedPoint = moved.Value;
}
else
{
OnRefused?.Invoke(moved.Status);
}
}
}
private void EndDrag()
{
dragging = false;
draggedPoint = -1;
pressPending = false;
if (FitRange())
{
Refresh();
}
}
// The model's edits refit the range, except the ones a drag makes.
private void Followed()
{
if (!dragging)
{
FitRange();
}
Refresh();
}
private void ApplyMaterials()
{
Material = editorMaterial.Background;
Show(Plot, editorMaterial.Plot);
RemoveButton.Visible = editorMaterial.RemoveButton.HasValue;
if (editorMaterial.RemoveButton.HasValue)
{
RemoveButton.ButtonMaterial = editorMaterial.RemoveButton.Value;
}
}
///
/// Sizes the editor to its parts and puts them in place. Setting does this too.
///
public void Layout()
{
Scalar spacing = editorMaterial.Spacing;
Vector markerSize = SizeOf(editorMaterial.Marker);
Vector plotSize = SizeOf(editorMaterial.Plot);
Vector buttonSize = RemoveButton.Visible
? editorMaterial.RemoveButton.Value.PreferredSize(Constraints.Unbounded)
: Vector.Zero;
// A point on an edge has its marker overhang the plot by half a marker, so the row has room for that.
Scalar overhangX = markerSize.X / 2;
Scalar overhangY = markerSize.Y / 2;
var plotDown = new RectAggregator(Vector.Zero);
plotDown.NewRow(overhangY);
plotDown.NewRow(plotSize.Y);
plotDown.NewRow(overhangY);
Scalar plotRowHeight = plotDown.Rect.Height;
var across = new RectAggregator(Vector.Zero);
across.NewCol(overhangX);
across.NewCol(plotSize.X);
across.NewCol(overhangX);
var down = new RectAggregator(new Vector(0, spacing));
down.NewRow(plotRowHeight);
if (RemoveButton.Visible)
{
down.NewRow(buttonSize.Y);
}
var inside = new Vector(Scalar.Max(across.Rect.Width, buttonSize.X), down.Rect.Height);
Vector boundsSize = inside;
if (Material != null)
{
boundsSize = Material.BoundsSizeFor(inside);
}
Bounds = Bounds.WithSize(boundsSize);
Rect remainder = CanvasRect;
const Shortfall tooSmall = Shortfall.UseWhatIsLeft;
Rect plotRow = remainder.NewRow(plotRowHeight, VerticalJustification.Top, spacing, tooSmall);
plotRow.NewCol(overhangX, HorizontalJustification.Left, 0, tooSmall);
plotRow.NewRow(overhangY, VerticalJustification.Top, 0, tooSmall);
Rect plotCell = plotRow.NewCol(plotSize.X, HorizontalJustification.Left, 0, tooSmall);
Plot.Bounds = plotCell.NewRow(plotSize.Y, VerticalJustification.Top, 0, tooSmall);
if (RemoveButton.Visible)
{
Rect buttonRow = remainder.NewRow(buttonSize.Y, VerticalJustification.Top, spacing, tooSmall);
RemoveButton.Bounds = buttonRow.NewCol(buttonSize.X, HorizontalJustification.Left, 0, tooSmall);
}
}
// The selected point's marker is drawn as the look says, and every marker is centered on its point.
private void ShowMarkers()
{
Vector markerSize = SizeOf(editorMaterial.Marker);
Rect plot = Plot.Bounds;
Scalar span = range.Max - range.Min;
for (int i = 0; i < markers.Length; ++i)
{
bool shown = i < Model.PointCount && editorMaterial.Marker != null;
markers[i].Visible = shown;
if (!shown)
{
continue;
}
bool selected = i == Model.SelectedIndex;
markers[i].Material = selected ? editorMaterial.SelectedMarker ?? editorMaterial.Marker
: editorMaterial.Marker;
Scalar centerX = plot.Left + Model.GetX(i) * plot.Width;
Scalar centerY = plot.Top + (range.Max - Model.GetY(i)) / span * plot.Height;
markers[i].Bounds = Rect.FromPositionAndSize(
new Vector(centerX - markerSize.X / 2, centerY - markerSize.Y / 2), markerSize);
}
RemoveButton.Enabled = Model.PointCount > 1;
}
///
/// Draws the model's function into the plot's texture and puts the markers where the points are.
///
private void Refresh()
{
FunctionPlotter.Draw(pixels, plotWidth, plotHeight, Model.Function, range, colors);
upload(pixels);
ShowMarkers();
}
// Nothing here moves with the keyboard, so Tab has no use for it. A press still focuses it.
public override bool IsTabStop => false;
public override ChordSet KeyChords => removePointChords;
// The key is claimed even with one point left, so a press meant for the editor never reaches a shortcut.
public override bool KeyDown(in KeyboardSnapshot keyboard, KeyboardManager keys)
{
if (!keys.ShouldFireAny(removePointChords, this, keyboard))
{
return false;
}
RemoveSelected();
return true;
}
}
}