using Amphora;
using Annulus;
using Azimuth;
using Clave;
using Glass;
using System;
namespace Prism.Glass
{
///
/// A bar showing a gradient, with a marker under it for each stop. Pressing a marker selects its stop and dragging
/// moves it. Pressing the bar adds a stop there, which then follows the drag. Every part edits the model it is
/// given, and follows it.
///
public class GradientEditor : Panel
{
private static readonly ChordSet DefaultRemoveStopChords = BuildRemoveStopChords();
// Press rather than repeat, so holding the key can't take every stop.
private static ChordSet BuildRemoveStopChords()
{
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 MaxStops stops and the markers past its count hide.
private readonly PickSurface[] markers;
private readonly TintedOverlay[] markerOverlays;
private readonly TintedOverlay[] selectedOverlays;
private readonly byte[] pixels;
private readonly int barPixels;
private readonly Action upload;
private GradientEditorMaterial editorMaterial;
// Where the markers sit, which is under the bar.
private Rect markerRow;
// The stop a drag is moving, or -1 for none, and how far its offset is from the pointer's.
private int draggedStop = -1;
private double grabOffset;
// The press itself has already put the stop where it is, so the pick that comes with it moves nothing.
private bool pressPending;
private ChordSet removeStopChords = DefaultRemoveStopChords;
///
/// Gets the gradient being edited.
///
public GradientModel Model { get; }
///
/// Raised with why, when the model refuses an edit. A drag raises it for each move that is refused.
///
public event Action OnRefused;
///
/// Gets how many stops the editor has room for.
///
public int MaxStops => markers.Length;
///
/// Gets the panel behind the bar.
///
public Panel BarBackdrop { get; } = new Panel { AbsorbsMouse = false };
///
/// Gets the bar, which adds a stop where it is pressed.
///
public PickSurface Bar { get; } = new PickSurface();
///
/// Gets the button that removes the selected stop.
///
public Button RemoveButton { get; }
///
/// Gets or sets the chords that remove the selected stop while the editor has focus, which a press of a marker
/// or the bar gives it. The last stop stays, as it does for the button.
///
/// The value is null.
public ChordSet RemoveStopChords
{
get => removeStopChords;
set => removeStopChords = value ?? throw new ArgumentNullException(nameof(value));
}
///
/// Gets the marker of the stop at an index. It is hidden when the model has no stop there.
///
public PickSurface MarkerAt(int index)
{
return markers[index];
}
///
/// Makes an editor for a gradient. It has no look until it is given an .
///
/// How many stops the editor has room for, which the model may not already pass.
///
/// How many pixels wide the bar's texture is. The editor fills a buffer of them with the gradient and hands it
/// to each time the gradient changes, always the same buffer.
///
/// Puts the buffer's RGBA pixels into the bar's texture.
public GradientEditor(
GradientModel model, int maxStops, int barPixels, Action upload, ButtonBehavior removeBehavior)
{
Model = model ?? throw new ArgumentNullException(nameof(model));
this.upload = upload ?? throw new ArgumentNullException(nameof(upload));
if (maxStops < model.StopCount)
{
throw new ArgumentOutOfRangeException(
nameof(maxStops), maxStops, "The editor needs room for every stop the model has.");
}
if (barPixels < 2)
{
throw new ArgumentOutOfRangeException(nameof(barPixels), barPixels, "A bar needs at least 2 pixels.");
}
this.barPixels = barPixels;
pixels = new byte[Rgba.ByteCount(barPixels, 1)];
RemoveButton = new Button(removeBehavior);
markers = new PickSurface[maxStops];
markerOverlays = new TintedOverlay[maxStops];
selectedOverlays = new TintedOverlay[maxStops];
CanvasChildren.Add(BarBackdrop);
CanvasChildren.Add(Bar);
for (int i = 0; i < maxStops; ++i)
{
int index = i;
markers[i] = new PickSurface();
markers[i].OnPressed += fraction => PressMarker(index, fraction);
markers[i].OnPicked += fraction => Drag(markers[index], fraction);
CanvasChildren.Add(markers[i]);
}
CanvasChildren.Add(RemoveButton);
Bar.OnPressed += PressBar;
Bar.OnPicked += fraction => Drag(Bar, fraction);
RemoveButton.OnActivate += (ButtonBase _, in KeyboardSnapshot held, KeyboardManager keys) =>
RemoveSelected();
model.Changed += _ => Refresh();
model.SelectionChanged += _ => ShowMarkers();
Focusable = true;
FocusOnClick = true;
ApplyMaterials();
Layout();
Refresh();
}
///
/// Gets or sets the look of the parts, which also sizes the editor to them.
///
public GradientEditorMaterial 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;
}
// The overlay is shown even with no art, which it then draws as nothing, so ShowMarkers never meets a null.
private static TintedOverlay Overlay(Material art)
{
return new TintedOverlay { ChildMaterial = art };
}
// Where a pick on a surface is along the bar, as a fraction of its width. A marker's pick is across itself.
private double BarFractionOf(PickSurface surface, double fractionAcross)
{
if (ReferenceEquals(surface, Bar) || !(Bar.Bounds.Width > 0))
{
return fractionAcross;
}
Rect bounds = surface.Bounds;
return (bounds.Left + fractionAcross * bounds.Width - Bar.Bounds.Left) / Bar.Bounds.Width;
}
private void PressMarker(int index, Vector fraction)
{
Model.Select(index);
draggedStop = index;
grabOffset = Model.GetOffset(index) - BarFractionOf(markers[index], fraction.X);
pressPending = true;
}
private void RemoveSelected()
{
Status removed = Model.RemoveStop(Model.SelectedIndex);
if (!removed.IsOk)
{
OnRefused?.Invoke(removed);
}
}
private void PressBar(Vector fraction)
{
pressPending = true;
grabOffset = 0;
if (Model.StopCount >= markers.Length)
{
draggedStop = -1;
OnRefused?.Invoke(GradientFailures.TooManyStops.Fail(
$"This editor can show at most {markers.Length} stops."));
return;
}
StatusOr added = Model.AddStop(fraction.X);
if (added.IsOk)
{
draggedStop = added.Value;
}
else
{
draggedStop = -1;
OnRefused?.Invoke(added.Status);
}
}
private void Drag(PickSurface surface, Vector fraction)
{
if (pressPending)
{
pressPending = false;
return;
}
if (draggedStop >= 0)
{
StatusOr moved = Model.MoveStop(draggedStop, BarFractionOf(surface, fraction.X) + grabOffset);
// A stop the model can't have there stays where it was, and the drag goes on.
if (moved.IsOk)
{
draggedStop = moved.Value;
}
else
{
OnRefused?.Invoke(moved.Status);
}
}
}
private void ApplyMaterials()
{
Material = editorMaterial.Background;
Show(BarBackdrop, editorMaterial.BarBackdrop);
Show(Bar, editorMaterial.Bar);
for (int i = 0; i < markers.Length; ++i)
{
markerOverlays[i] = Overlay(editorMaterial.Marker);
selectedOverlays[i] = editorMaterial.SelectedMarker == null
? markerOverlays[i]
: Overlay(editorMaterial.SelectedMarker);
}
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 buttonSize = RemoveButton.Visible
? editorMaterial.RemoveButton.Value.PreferredSize(Constraints.Unbounded)
: Vector.Zero;
// The first and last stops sit at the ends of the bar, so their markers overhang it by half a marker.
Scalar overhang = markerSize.X / 2;
Scalar barWidth = SizeOf(editorMaterial.Bar).X;
var across = new RectAggregator(Vector.Zero);
across.NewCol(overhang);
across.NewCol(barWidth);
across.NewCol(overhang);
var down = new RectAggregator(new Vector(0, spacing));
down.NewRow(editorMaterial.BarHeight);
if (editorMaterial.Marker != null)
{
down.NewRow(markerSize.Y);
}
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 barRow = remainder.NewRow(editorMaterial.BarHeight, VerticalJustification.Top, spacing, tooSmall);
barRow.NewCol(overhang, HorizontalJustification.Left, 0, tooSmall);
Bar.Bounds = barRow.NewCol(barWidth, HorizontalJustification.Left, 0, tooSmall);
BarBackdrop.Bounds = Bar.Bounds;
if (editorMaterial.Marker != null)
{
markerRow = remainder.NewRow(markerSize.Y, VerticalJustification.Top, spacing, 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 stop's marker is drawn as the look says, and every marker takes its stop's color.
private void ShowMarkers()
{
Vector markerSize = SizeOf(editorMaterial.Marker);
for (int i = 0; i < markers.Length; ++i)
{
bool shown = i < Model.StopCount && editorMaterial.Marker != null;
markers[i].Visible = shown;
if (!shown)
{
continue;
}
bool selected = i == Model.SelectedIndex;
TintedOverlay overlay = selected ? selectedOverlays[i] : markerOverlays[i];
overlay.Tint = Color.FromArgb(byte.MaxValue, Model.GetColor(i).ToColor());
markers[i].Material = overlay;
Scalar center = Bar.Bounds.Left + Model.GetOffset(i) * Bar.Bounds.Width;
// lint-ignore: carve The stop's offset decides where the marker sits along the row.
markers[i].Bounds = Rect.FromPositionAndSize(
new Vector(center - markerSize.X / 2, markerRow.Top), markerSize);
}
RemoveButton.Enabled = Model.StopCount > 1;
}
///
/// Draws the model's gradient into the bar's texture and puts the markers where the stops are.
///
private void Refresh()
{
ColorStrips.FillGradient(pixels, barPixels, Model.Gradient);
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 => removeStopChords;
// The key is claimed even with one stop left, so a press meant for the editor never reaches a shortcut.
public override bool KeyDown(in KeyboardSnapshot keyboard, KeyboardManager keys)
{
if (!keys.ShouldFireAny(removeStopChords, this, keyboard))
{
return false;
}
RemoveSelected();
return true;
}
}
}