using System;
using System.Collections.Generic;
using Annulus;
using Azimuth;
using Glass;
namespace Clave.Glass
{
///
/// One chord of an action, shown as its keys with a button at the end that takes it out. Activating it captures
/// the next keys pressed in its place, and a Shift, Ctrl or Alt in it is a button that steps through which side
/// counts.
///
public class KeyBindingSlot : Button
{
///
/// The keys that take a focused slot's chord out.
///
public static readonly ChordSet RemoveChords =
ChordSet.Of(Chord.OnPressOrRepeat(KeyCode.Delete), Chord.OnPressOrRepeat(KeyCode.Backspace));
private readonly KeyBindingsEditor editor;
private readonly KeyBindings source;
private readonly KeyAction action;
private readonly KeyBindingsMaterial material;
private readonly List parts = new List();
private readonly List partSizes = new List();
// The label of each key, which is inside its button when the key has sides.
private readonly List keyLabels = new List();
private readonly ChordSet keyChords;
private readonly Label removeLabel;
private bool clashing;
private KeyCapture capture;
private KeyboardManager.CaptureScope captureScope;
///
/// Which of the action's chords this shows. Their count stands for one about to be added, which shows nothing
/// until a capture fills it.
///
public KeyBindingSlot(KeyBindingsEditor editor, KeyBindings source, KeyAction action, int index,
KeyBindingsMaterial material) : base(ButtonBehavior.Default)
{
this.editor = editor ?? throw new ArgumentNullException(nameof(editor));
this.source = source ?? throw new ArgumentNullException(nameof(source));
this.action = action ?? throw new ArgumentNullException(nameof(action));
if (index < 0 || index > source.ChordsOf(action).Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
this.material = material;
Index = index;
var chords = new ChordSetBuilder(Behavior.KeyChords);
chords.AddAll(RemoveChords);
keyChords = chords.Build();
OnActivate += (ButtonBase _, in KeyboardSnapshot held, KeyboardManager keys) => BeginCapture(held, keys);
RemoveButton = new Button(ButtonBehavior.Default) { ButtonMaterial = material.RemoveButton };
removeLabel = new Label(material.RemoveTextStyle ?? new TextMaterialStyle(),
material.TextOrEnglish.RemoveChord);
RemoveButton.CanvasChildren.Add(removeLabel);
RemoveButton.OnActivate += (ButtonBase _, in KeyboardSnapshot __, KeyboardManager ___) => RemoveChord();
CanvasChildren.Add(RemoveButton);
Show();
}
public int Index { get; }
///
/// Gets the chord shown, or null when the slot stands for one about to be added.
///
public Chord Chord
{
get
{
IReadOnlyList chords = source.ChordsOf(action);
return Index < chords.Count ? chords[Index] : null;
}
}
///
/// Gets the chord as keys, or null when it is no combo of keys, such as one with alternatives. Its keys are
/// shown one part each, and otherwise the chord is shown as one label.
///
public KeyCombo Combo { get; private set; }
public bool Capturing => capture != null;
///
/// Gets the button at the end of the slot that takes its chord out, hidden while there is no chord to take out
/// or a capture is on.
///
public Button RemoveButton { get; }
///
/// Gets or sets whether the chord clashes with another binding, which shows it in the clashing look.
///
public bool Clashing
{
get => clashing;
set
{
clashing = value;
ButtonMaterial = LookNow(Chord);
}
}
///
/// Gets the size the slot needs for what it shows now.
///
public Vector PreferredBoundsSize { get; private set; }
///
/// Gets what the slot shows, in order: the prompt while capturing, or else a label or a button per key with the
/// separators between them.
///
public IReadOnlyList Parts
{
get { return parts; }
}
///
/// Raised when a capture ends without keys, from .
///
public event Action CaptureCancelled;
///
/// Raised after the slot is shown again, which may have changed its size, such as when a capture starts and the
/// prompt replaces the keys.
///
public event Action Resized;
private static Label NewLabel(TextMaterialStyle style, string text)
{
return new Label(style ?? new TextMaterialStyle(), text);
}
///
/// Returns the side of the square remove button, which is a line of key text so it fits inside the slot.
///
public static Scalar RemoveSideFor(KeyBindingsMaterial material)
{
return (material.KeyTextStyle ?? new TextMaterialStyle()).SingleLineHeight;
}
///
/// Returns the size a slot in needs to show , and a remove
/// button after it when . It is never shorter than the look's own art.
///
public static Vector BoundsSizeFor(Vector content, bool removable, ButtonMaterial look,
KeyBindingsMaterial material)
{
Vector inside = content;
if (removable)
{
Scalar side = RemoveSideFor(material);
inside = new Vector(content.X + material.Spacing + side, Scalar.Max(content.Y, side));
}
Vector returnMe = look.BoundsSizeFor(inside);
return Vector.Max(returnMe, new Vector(0, look.PreferredSize(Constraints.Unbounded).Y));
}
// The size a part showing a key needs: its label, inside a button when it has sides.
private static Vector KeySizeFor(ComboKey key, Vector labelSize, KeyBindingsMaterial material)
{
return key.HasSides ? material.SidedKey.BoundsSizeFor(labelSize) : labelSize;
}
///
/// Returns the size of what a slot shows for : a part per key and the separators
/// between them.
///
public static Vector ContentSizeFor(KeyCombo combo, KeyLabeler labeler, KeyBindingsMaterial material)
{
if (combo == null)
{
throw new ArgumentNullException(nameof(combo));
}
Vector separator = NewLabel(material.KeyTextStyle, KeyLabeler.KeySeparator)
.PreferredSize(Constraints.Unbounded);
var sizes = new List();
for (int i = 0; i < combo.Keys.Count; ++i)
{
if (i > 0)
{
sizes.Add(separator);
}
Vector labelSize = NewLabel(material.KeyTextStyle, labeler.LabelOf(combo.Keys[i], combo.Space))
.PreferredSize(Constraints.Unbounded);
sizes.Add(KeySizeFor(combo.Keys[i], labelSize, material));
}
return StripLayout.SizeOf(sizes, 0);
}
///
/// Returns the size a slot needs to show in , such as the
/// capture prompt, with no remove button.
///
public static Vector BoundsSizeFor(string text, ButtonMaterial look, KeyBindingsMaterial material)
{
Vector content = NewLabel(material.KeyTextStyle, text).PreferredSize(Constraints.Unbounded);
return BoundsSizeFor(content, removable: false, look, material);
}
private void AddPart(Control part, Vector size)
{
parts.Add(part);
partSizes.Add(size);
CanvasChildren.Add(part);
}
private void AddLabel(string text)
{
Label label = NewLabel(material.KeyTextStyle, text);
AddPart(label, label.PreferredSize(Constraints.Unbounded));
}
private void StepSide(int keyIndex)
{
KeyCombo stepped = Combo.WithKey(keyIndex, Combo.Keys[keyIndex].NextSide());
editor.SetChord(source, action, Index, stepped.ToChord());
Show();
}
private void AddKey(int keyIndex, string text)
{
Label label = NewLabel(material.KeyTextStyle, text);
Vector labelSize = label.PreferredSize(Constraints.Unbounded);
keyLabels.Add(label);
if (!Combo.Keys[keyIndex].HasSides)
{
AddPart(label, labelSize);
return;
}
var button = new Button(ButtonBehavior.Default) { ButtonMaterial = material.SidedKey };
button.CanvasChildren.Add(label);
label.Bounds = Rect.FromPositionAndSize(Vector.Zero, labelSize);
button.OnActivate += (ButtonBase _, in KeyboardSnapshot __, KeyboardManager ___) => StepSide(keyIndex);
AddPart(button, KeySizeFor(Combo.Keys[keyIndex], labelSize, material));
}
// Whether the parts already there are the ones Combo needs, so only their text has to change. Stepping a side
// keeps the button that was activated, and with it the focus.
private bool PartsFit(KeyCombo combo, KeyCombo shown)
{
if (combo == null || shown == null || combo.Keys.Count != shown.Keys.Count || Capturing)
{
return false;
}
for (int i = 0; i < combo.Keys.Count; ++i)
{
if (combo.Keys[i].HasSides != shown.Keys[i].HasSides)
{
return false;
}
}
return parts.Count == 2 * combo.Keys.Count - 1;
}
private void Relabel(KeyLabeler labeler)
{
for (int i = 0; i < Combo.Keys.Count; ++i)
{
keyLabels[i].Text = labeler.LabelOf(Combo.Keys[i], Combo.Space);
Vector labelSize = keyLabels[i].PreferredSize(Constraints.Unbounded);
keyLabels[i].Bounds = Rect.FromPositionAndSize(Vector.Zero, labelSize);
partSizes[2 * i] = KeySizeFor(Combo.Keys[i], labelSize, material);
}
}
private void Rebuild(KeyLabeler labeler, Chord chord)
{
foreach (Control part in parts)
{
CanvasChildren.Remove(part);
}
parts.Clear();
partSizes.Clear();
keyLabels.Clear();
if (Capturing)
{
AddLabel(material.TextOrEnglish.CapturePrompt);
}
else if (Combo != null)
{
for (int i = 0; i < Combo.Keys.Count; ++i)
{
if (i > 0)
{
AddLabel(KeyLabeler.KeySeparator);
}
AddKey(i, labeler.LabelOf(Combo.Keys[i], Combo.Space));
}
}
else if (chord != null)
{
AddLabel(labeler.LabelOf(chord));
}
else
{
AddLabel(material.TextOrEnglish.AddChord);
}
}
private ButtonMaterial LookNow(Chord chord)
{
if (Capturing)
{
return material.CapturingBinding;
}
if (chord == null)
{
return material.EmptyBinding;
}
return clashing ? material.ClashingBinding : material.Binding;
}
private bool Removable => Chord != null && !Capturing;
///
/// Gives the slot , such as a cell wider or taller than it needs, with what it shows
/// at the left and the remove button at the right, each centred on the height.
///
public void Arrange(Rect bounds)
{
Bounds = bounds;
Rect inside = Rect.FromPositionAndSize(Vector.Zero, CanvasRect.Size);
Scalar side = RemoveSideFor(material);
Rect removeColumn = inside.NewCol(side, HorizontalJustification.Right, shortfall: Shortfall.UseWhatIsLeft);
removeColumn.Center(new Vector(removeColumn.Width, side), Shortfall.UseWhatIsLeft);
RemoveButton.Bounds = removeColumn;
removeLabel.Bounds = Rect.FromPositionAndSize(Vector.Zero, RemoveButton.CanvasRect.Size);
RemoveButton.Visible = Removable;
StripLayout.Arrange(parts, partSizes, Rect.FromPositionAndSize(Vector.Zero, CanvasRect.Size), 0);
}
///
/// Shows the chord the slot stands for now, the prompt while capturing, or the add text when it stands for a
/// chord about to be added, and sizes the slot to fit. Keeps the slot's position.
///
public void Show()
{
KeyLabeler labeler = source.Keys.KeyLabels;
Chord chord = Chord;
KeyCombo combo = null;
if (chord != null && !Capturing)
{
KeyCombo.TryFrom(chord, out combo);
}
KeyCombo shown = Combo;
Combo = combo;
if (PartsFit(combo, shown))
{
Relabel(labeler);
}
else
{
Rebuild(labeler, chord);
}
ButtonMaterial = LookNow(chord);
Vector content = StripLayout.SizeOf(partSizes, 0);
PreferredBoundsSize = BoundsSizeFor(content, Removable, ButtonMaterial, material);
Arrange(Bounds.WithSize(PreferredBoundsSize));
Resized?.Invoke(this);
}
private void EndCapture()
{
captureScope.Dispose();
capture = null;
}
private void FeedCapture(KeyboardSnapshot keyboard)
{
if (!capture.Feed(keyboard))
{
return;
}
KeyCombo captured = capture.ToCombo(action.Kind);
EndCapture();
editor.SetChord(source, action, Index, captured.ToChord());
Show();
}
///
/// Sends every key to this slot until the keys pressed together are all let go of, and binds them in place of
/// the chord shown. Keys already down are left out until released.
///
/// If a capture is already on.
public void BeginCapture(in KeyboardSnapshot held, KeyboardManager keys)
{
if (keys == null)
{
throw new ArgumentNullException(nameof(keys));
}
if (Capturing)
{
throw new InvalidOperationException("This slot is already capturing keys.");
}
// Begun before the capture is kept, so a manager already capturing for something else leaves it alone.
KeyboardManager.CaptureScope scope = keys.BeginCapture(FeedCapture);
capture = new KeyCapture(KeySpace.Physical, held[KeySpace.Physical].Held);
captureScope = scope;
Show();
}
///
/// Ends a capture without binding anything. Does nothing when the slot isn't capturing.
///
public void CancelCapture()
{
if (!Capturing)
{
return;
}
EndCapture();
Show();
CaptureCancelled?.Invoke(this);
}
///
/// Takes the chord shown out of the action. Does nothing for a slot standing for a chord about to be added.
///
public void RemoveChord()
{
if (Chord != null)
{
editor.RemoveChord(source, action, Index);
}
}
public override ChordSet KeyChords => keyChords;
public override bool KeyDown(in KeyboardSnapshot keyboard, KeyboardManager keys)
{
// Delete and Backspace can still be bound, since a capture takes them before any control hears them.
if (Enabled && Chord != null && keys.ShouldFireAny(RemoveChords, this, keyboard))
{
RemoveChord();
return true;
}
return base.KeyDown(keyboard, keys);
}
}
}