using Azimuth;
using Clave;
using Glass;
using System;
namespace Prism.Glass
{
///
/// A panel that reports where the pointer presses and drags across it, as fractions of its width and height.
///
public class PickSurface : Panel
{
private bool dragging;
public PickSurface()
{
// It decides which presses and moves are its own, so the panel's claim of the rest would override that.
AbsorbsMouse = false;
}
///
/// Raised with the pointer's place, as gives it, on a left press and on each move of
/// the drag that follows.
///
public event Action OnPicked;
///
/// Raised with the pointer's place on a left press only, just before hears of it.
///
public event Action OnPressed;
///
/// Raised when a drag ends, by the left button coming up or by .
///
public event Action OnDragEnded;
///
/// Returns where a point in the parent's canvas space lies on this surface, as fractions across and down. The
/// top left is (0, 0) and the bottom right (1, 1), and a point past the surface lies outside that range.
///
public Vector FractionAt(Vector parentPoint)
{
Vector size = CanvasRect.Size;
if (!(size.X > 0) || !(size.Y > 0))
{
return Vector.Zero;
}
Vector point = ToCanvas(parentPoint);
return new Vector(point.X / size.X, point.Y / size.Y);
}
public override bool MouseDown(
in MouseState state, MouseButtonFlags button, in KeyboardSnapshot held, KeyboardManager keys)
{
if (!Enabled || button != MouseButtonFlags.Left)
{
return base.MouseDown(state, button, held, keys);
}
base.MouseDown(state, button, held, keys);
dragging = true;
Vector fraction = FractionAt(state.Position);
OnPressed?.Invoke(fraction);
OnPicked?.Invoke(fraction);
return true;
}
public override bool MouseMove(in MouseState state, in KeyboardSnapshot held, KeyboardManager keys)
{
if (!dragging)
{
return base.MouseMove(state, held, keys);
}
base.MouseMove(state, held, keys);
OnPicked?.Invoke(FractionAt(state.Position));
return true;
}
public override bool MouseUp(
in MouseState state, MouseButtonFlags button, in KeyboardSnapshot held, KeyboardManager keys)
{
if (!dragging || button != MouseButtonFlags.Left)
{
return base.MouseUp(state, button, held, keys);
}
dragging = false;
base.MouseUp(state, button, held, keys);
OnDragEnded?.Invoke();
return true;
}
public override void CancelMouseInput()
{
bool wasDragging = dragging;
dragging = false;
base.CancelMouseInput();
if (wasDragging)
{
OnDragEnded?.Invoke();
}
}
}
}