using System.IO;
using System.Text;
using Amphora;
using Annulus;
using Azimuth;
using Clave;
using Clave.Glass;
using Prism;
namespace Glass.Testbed.TestCases.Controls
{
///
/// A square moved by keys a player can rebind, beside the bindings screen. The bindings are saved whenever they
/// change and loaded the next time the case is built.
///
public class KeyBindingsTestCase : TestCase
{
private const string SettingsFileName = "key-bindings.lua";
private const int PlayAreaSize = 240;
private const int SquareSize = 24;
private const int SquareSpeed = 160;
private const int PanelHeight = 360;
private static readonly Material SquareLook = new SolidColorMaterial { Color = Color.FromArgb(255, 214, 110) };
private static readonly Material GlowLook = new SolidColorMaterial { Color = Color.FromArgb(255, 255, 255) };
private static ButtonMaterial FlatButton(Color nominal, Color hover, Color pressed)
{
return new ButtonMaterial(new SolidColorMaterial { Color = nominal })
{
HoverMaterial = new SolidColorMaterial { Color = hover },
PressedMaterial = new SolidColorMaterial { Color = pressed },
HoverPressedMaterial = new SolidColorMaterial { Color = pressed },
DisabledMaterial = new SolidColorMaterial { Color = Colors.Gray },
};
}
private static readonly ScrollViewMaterial PanelLook = new ScrollViewMaterial
{
Background = UiPacksheetMaterials.Panel,
Canvas = Material.Invisible,
HorizontalScrollBar = UiPacksheetMaterials.HorizontalScrollBar,
VerticalScrollBar = UiPacksheetMaterials.VerticalScrollBar,
};
// Quiet until the pointer is on it, so a column of them doesn't pull the eye.
private static readonly ButtonMaterial RemoveLook = FlatButton(Color.FromArgb(0, 0, 0, 0),
Color.FromArgb(235, 150, 140), Color.FromArgb(215, 110, 100));
private static readonly TextMaterialStyle RemoveText = Widgets.CloseButtonLabelStyle with
{
TintColor = Color.FromArgb(140, 140, 140),
};
private static readonly ButtonMaterial ClashingField = new ButtonMaterial(UiPacksheetMaterials.TextField with
{
TintColor = Color.FromArgb(255, 205, 150),
});
private readonly World world;
private readonly KeyAction left = new KeyAction("left", "Move left", KeyStateKind.Held,
Chord.Hold(KeyCode.A), Chord.Hold(KeyCode.ArrowLeft));
private readonly KeyAction right = new KeyAction("right", "Move right", KeyStateKind.Held,
Chord.Hold(KeyCode.D), Chord.Hold(KeyCode.ArrowRight));
private readonly KeyAction up = new KeyAction("up", "Move up", KeyStateKind.Held,
Chord.Hold(KeyCode.W), Chord.Hold(KeyCode.ArrowUp));
private readonly KeyAction down = new KeyAction("down", "Move down", KeyStateKind.Held,
Chord.Hold(KeyCode.S), Chord.Hold(KeyCode.ArrowDown));
private readonly KeyAction glow = new KeyAction("glow", "Glow", KeyStateKind.Held, Chord.Hold(KeyCode.Space));
private KeyBindings bindings;
private KeyBindingsEditor editor;
private KeyBindingsScreen screen;
private ScrollView bindingsPanel;
private KeyBindingsCommands commands;
private Panel square;
private Vector squarePosition = new Vector((PlayAreaSize - SquareSize) / 2, (PlayAreaSize - SquareSize) / 2);
public KeyBindingsTestCase(World world)
{
this.world = world;
}
private KeyboardManager Keys => world.uiWorld.screen.KeyboardManager;
private static KeyBindingsMaterial Look()
{
TextMaterialStyle keyText = Widgets.MenuLabelStyle with { HorizontalMargin = 4, VerticalMargin = 2 };
return new KeyBindingsMaterial
{
ActionTextStyle = Widgets.MenuLabelStyle,
KeyTextStyle = keyText,
ClashTextStyle = Widgets.MenuLabelStyle with { TintColor = Color.FromArgb(170, 80, 20) },
ButtonTextStyle = keyText,
RemoveTextStyle = RemoveText,
Binding = UiPacksheetMaterials.TextField,
CapturingBinding = UiPacksheetMaterials.YellowFlatPanel,
ClashingBinding = ClashingField,
SidedKey = FlatButton(Color.FromArgb(190, 215, 245), Color.FromArgb(160, 190, 230),
Color.FromArgb(130, 165, 215)),
RemoveButton = RemoveLook,
// Faint at rest, so the add cell after each action's bindings doesn't read as one more binding.
EmptyBinding = FlatButton(Color.FromArgb(28, 0, 0, 0), Color.FromArgb(56, 0, 0, 0),
Color.FromArgb(84, 0, 0, 0)),
CommandButton = Widgets.ListItemButton,
Spacing = Margin,
};
}
private string SettingsPath => world.SettingsFiles.Combine(world.SettingsDirectory, SettingsFileName);
private void LoadBindings()
{
if (world.SettingsFiles == null)
{
return;
}
StatusOr opened = world.SettingsFiles.OpenRead(SettingsPath);
if (!opened.TryGetValue(out Stream stream))
{
return;
}
string text;
using (stream)
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
text = reader.ReadToEnd();
}
if (SavedKeyBindings.TryFromText(text, out SavedKeyBindings saved))
{
editor.Load(saved);
}
}
// A failure is dropped, since a case that can't save still works for this run.
private void SaveBindings()
{
if (world.SettingsFiles == null)
{
return;
}
world.SettingsFiles.CreateDirectory(world.SettingsDirectory);
StatusOr opened = world.SettingsFiles.OpenWrite(SettingsPath);
if (!opened.TryGetValue(out Stream stream))
{
return;
}
using (stream)
using (var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)))
{
writer.Write(editor.Save().ToText());
}
}
protected override void Populate()
{
AddCaption("Click a binding, then press the keys for it. Click a Ctrl, Shift or Alt to pick its side.");
bindings = new KeyBindings("testbed.square", Keys, left, right, up, down, glow);
editor = new KeyBindingsEditor(bindings);
LoadBindings();
bindings.Rebound += _ => SaveBindings();
KeyBindingsMaterial look = Look();
screen = new KeyBindingsScreen(editor, look) { DebugName = "key bindings" };
commands = new KeyBindingsCommands(editor, look) { DebugName = "key bindings commands" };
bindingsPanel = new ScrollView
{
DebugName = "key bindings panel",
ScrollsHorizontally = false,
ScrollsVertically = true,
ScrollViewMaterial = PanelLook,
};
bindingsPanel.CanvasChildren.Add(screen);
var playArea = new Panel
{
DebugName = "play area",
Material = new SolidColorMaterial { Color = Color.FromArgb(30, 60, 70) },
};
square = new Panel { DebugName = "square", Material = SquareLook };
playArea.CanvasChildren.Add(square);
// The commands go under the panel, where scrolling the bindings can't take them out of view.
Rect row = ContentAggregator.NewRow(PanelHeight + Margin + commands.Size.Y);
Rect playColumn = row.NewCol(PlayAreaSize, margin: Gutter);
playArea.Bounds = playColumn.NewRow(PlayAreaSize);
Rect panelRect = row.NewRow(PanelHeight, margin: Margin);
bindingsPanel.Bounds = panelRect.WithSize(new Vector(0, PanelHeight));
commands.Bounds = row.WithSize(commands.Size);
Add(playArea);
Add(bindingsPanel);
Add(commands);
PlaceSquare();
screen.Resized += _ => FitPanel();
FitPanel();
}
// The panel is as wide as the screen and its padding need, and scrolls when the screen grows past its height.
private void FitPanel()
{
var padding = new Rect.BorderSize(Margin);
Vector content = Rect.FromPositionAndSize(Vector.Zero, screen.Size).Expand(padding).Size;
screen.Bounds = Rect.FromPositionAndSize(Vector.Zero, content).Erode(padding);
bindingsPanel.ContentSize = content;
Vector size = bindingsPanel.ScrollViewMaterial.BoundsSizeFor(content, ScrollAxes.Vertical);
bindingsPanel.Bounds = bindingsPanel.Bounds.WithSize(new Vector(size.X, PanelHeight));
}
private void PlaceSquare()
{
square.Bounds = Rect.FromPositionAndSize(squarePosition, new Vector(SquareSize, SquareSize));
}
protected override void Teardown()
{
// A capture left on would take every key from the case shown next.
screen.CancelCapture();
}
public override void Update(Duration elapsed)
{
KeyboardSnapshot held = Keys.Held;
Vector heading = Vector.Zero;
if (bindings.ShouldFire(left, held))
{
heading += new Vector(-1, 0);
}
if (bindings.ShouldFire(right, held))
{
heading += new Vector(1, 0);
}
if (bindings.ShouldFire(up, held))
{
heading += new Vector(0, -1);
}
if (bindings.ShouldFire(down, held))
{
heading += new Vector(0, 1);
}
Scalar step = SquareSpeed * elapsed.TotalSeconds;
Vector moved = squarePosition + heading * step;
Scalar limit = PlayAreaSize - SquareSize;
squarePosition = new Vector(Scalar.Clamp(moved.X, 0, limit), Scalar.Clamp(moved.Y, 0, limit));
PlaceSquare();
square.Material = bindings.ShouldFire(glow, held) ? GlowLook : SquareLook;
}
}
}