using System;
using System.Collections.Generic;
using Glass;
namespace Clave.Glass
{
///
/// Changes the bindings of any number of sources the way a bindings screen does, with undo, and saves and loads
/// them without knowing what the sources are.
///
public class KeyBindingsEditor
{
private struct Change
{
public KeyBindings Source;
public KeyAction Action;
public Chord[] Before;
}
private readonly KeyBindings[] sources;
private readonly List undo = new List();
// What a load found for sources and actions that aren't here, so the next save still holds it.
private readonly Dictionary>> unplugged =
new Dictionary>>();
// The chords in unplugged that follow their action's kind.
private readonly Dictionary>> unpluggedFollowing =
new Dictionary>>();
/// If two sources share an id.
public KeyBindingsEditor(params KeyBindings[] sources)
{
if (sources == null)
{
throw new ArgumentNullException(nameof(sources));
}
var ids = new HashSet();
foreach (KeyBindings source in sources)
{
if (source == null)
{
throw new ArgumentNullException(nameof(sources));
}
if (!ids.Add(source.Id))
{
throw new ArgumentException($"Two sources have the id {source.Id}.", nameof(sources));
}
}
this.sources = (KeyBindings[])sources.Clone();
}
public IReadOnlyList Sources
{
get { return sources; }
}
public bool CanUndo => undo.Count > 0;
private void RequireSource(KeyBindings source)
{
if (Array.IndexOf(sources, source) < 0)
{
throw new ArgumentException("That source isn't one this editor changes.", nameof(source));
}
}
private static Chord[] CopyOf(IReadOnlyList chords)
{
var returnMe = new Chord[chords.Count];
for (int i = 0; i < returnMe.Length; ++i)
{
returnMe[i] = chords[i];
}
return returnMe;
}
private void Rebind(KeyBindings source, KeyAction action, Chord[] chords)
{
// On the undo list before the bind, so a screen redrawn as the bind tells it already sees it can undo.
var change = new Change { Source = source, Action = action, Before = CopyOf(source.ChordsOf(action)) };
undo.Add(new[] { change });
try
{
source.Bind(action, chords);
}
catch
{
undo.RemoveAt(undo.Count - 1);
throw;
}
}
///
/// Binds in place of the chord at of the action, or adds it
/// after the others when the index is their count.
///
public void SetChord(KeyBindings source, KeyAction action, int index, Chord chord)
{
RequireSource(source);
if (chord == null)
{
throw new ArgumentNullException(nameof(chord));
}
IReadOnlyList chords = source.ChordsOf(action);
if (index < 0 || index > chords.Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
var after = new List(chords);
if (index == chords.Count)
{
after.Add(chord);
}
else
{
after[index] = chord;
}
Rebind(source, action, after.ToArray());
}
public void RemoveChord(KeyBindings source, KeyAction action, int index)
{
RequireSource(source);
IReadOnlyList chords = source.ChordsOf(action);
if (index < 0 || index >= chords.Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
var after = new List(chords);
after.RemoveAt(index);
Rebind(source, action, after.ToArray());
}
///
/// Puts every action back to its defaults, as one change to undo. Does nothing when they all are already.
///
public void ResetToDefaults()
{
var changes = new List();
foreach (KeyBindings source in sources)
{
foreach (KeyAction action in source.Actions)
{
if (!source.IsDefault(action))
{
Chord[] before = CopyOf(source.ChordsOf(action));
changes.Add(new Change { Source = source, Action = action, Before = before });
}
}
}
if (changes.Count == 0)
{
return;
}
// On the undo list first, as in Rebind. A default fails to bind only if the app made its chord a shortcut
// of its own while it was out, which is the app's mistake to fix.
undo.Add(changes.ToArray());
foreach (Change change in changes)
{
change.Source.Bind(change.Action, change.Action.Defaults);
}
}
///
/// Takes back the latest change that hasn't been taken back.
///
/// If there is nothing to undo.
public void Undo()
{
if (undo.Count == 0)
{
throw new InvalidOperationException("There is nothing to undo.");
}
Change[] changes = undo[undo.Count - 1];
undo.RemoveAt(undo.Count - 1);
for (int i = changes.Length - 1; i >= 0; --i)
{
changes[i].Source.Bind(changes[i].Action, changes[i].Before);
}
}
///
/// Returns what , bound or about to be bound to , competes
/// with: chords that fire on the same keys, and chords that take the keys from it, such as Tab moving focus.
/// Chords it takes the keys from aren't listed, since Ctrl+W taking W is what a player expects. Nor are chords
/// that take the keys from a fallback, which by design gets a key only when nothing else wants it.
///
public List ClashesOf(KeyBindings source, KeyAction action, Chord chord)
{
RequireSource(source);
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
var returnMe = new List();
foreach (ChordConflict conflict in source.Keys.ConflictsOf(chord, source.Priority, action.Context))
{
if (conflict.Kind == ChordConflictKind.Hides || source.ActionOf(conflict.Other) == action)
{
continue;
}
if (conflict.Kind == ChordConflictKind.HiddenBy && source.Priority == KeyPriority.Fallback)
{
continue;
}
var clash = new KeyClash(conflict.Kind, source.Keys.NameOf(conflict.Other));
if (!returnMe.Contains(clash))
{
returnMe.Add(clash);
}
}
return returnMe;
}
private static void Keep(Dictionary>> into,
string sourceId, string actionId, List items)
{
if (!into.TryGetValue(sourceId, out Dictionary> actions))
{
actions = new Dictionary>();
into.Add(sourceId, actions);
}
actions[actionId] = items;
}
// A default keeps its exact chord, since the app made it and may not mean it to follow the kind.
private static bool IsDefaultChord(KeyAction action, Chord chord)
{
foreach (Chord candidate in action.Defaults)
{
if (candidate.Formula.Equals(chord.Formula))
{
return true;
}
}
return false;
}
// A chord a player captured has its action's kind. One of another kind, such as a tap of Alt on an action of
// presses, is deliberate and stays as it is.
private static bool FollowsKind(KeyAction action, Chord chord)
{
return !IsDefaultChord(action, chord) && KeyCombo.TryFrom(chord, out KeyCombo combo)
&& combo.Kind == action.Kind;
}
///
/// Returns the actions that differ from their defaults, with what the last load found for sources and actions
/// that aren't here.
///
public SavedKeyBindings Save()
{
var returnMe = new SavedKeyBindings();
foreach (KeyValuePair>> source in unplugged)
{
foreach (KeyValuePair> action in source.Value)
{
Keep(returnMe.Sources, source.Key, action.Key, new List(action.Value));
var following = new List(unpluggedFollowing[source.Key][action.Key]);
Keep(returnMe.FollowsKind, source.Key, action.Key, following);
}
}
foreach (KeyBindings source in sources)
{
foreach (KeyAction action in source.Actions)
{
if (source.IsDefault(action))
{
continue;
}
var chords = new List(source.ChordsOf(action));
var following = new List();
foreach (Chord chord in chords)
{
if (FollowsKind(action, chord))
{
following.Add(chord);
}
}
Keep(returnMe.Sources, source.Id, action.Id, chords);
Keep(returnMe.FollowsKind, source.Id, action.Id, following);
}
}
return returnMe;
}
private static bool HasAction(KeyBindings source, string id)
{
foreach (KeyAction action in source.Actions)
{
if (action.Id == id)
{
return true;
}
}
return false;
}
private static List Present(List chords)
{
var returnMe = new List();
if (chords != null)
{
foreach (Chord chord in chords)
{
if (chord != null)
{
returnMe.Add(chord);
}
}
}
return returnMe;
}
private static List Following(SavedKeyBindings saved, string sourceId, string actionId,
List chords)
{
var returnMe = new List();
foreach (Chord chord in chords)
{
if (saved.Follows(sourceId, actionId, chord))
{
returnMe.Add(chord);
}
}
return returnMe;
}
private static Chord[] WithKindOf(SavedKeyBindings saved, KeyBindings source, KeyAction action,
List chords)
{
var returnMe = new Chord[chords.Count];
for (int i = 0; i < returnMe.Length; ++i)
{
returnMe[i] = chords[i];
if (saved.Follows(source.Id, action.Id, chords[i]) && KeyCombo.TryFrom(chords[i], out KeyCombo combo))
{
returnMe[i] = combo.WithKind(action.Kind).ToChord();
}
}
return returnMe;
}
///
/// Binds each action to what holds for it, or to its defaults when it holds nothing,
/// and forgets what there was to undo. A chord that didn't load is left out.
///
public void Load(SavedKeyBindings saved)
{
if (saved == null)
{
throw new ArgumentNullException(nameof(saved));
}
undo.Clear();
unplugged.Clear();
unpluggedFollowing.Clear();
var everySource = saved.Sources ?? new Dictionary>>();
foreach (KeyValuePair>> source in everySource)
{
if (source.Value == null)
{
continue;
}
KeyBindings plugged = Array.Find(sources, candidate => candidate.Id == source.Key);
foreach (KeyValuePair> action in source.Value)
{
if (plugged == null || !HasAction(plugged, action.Key))
{
List kept = Present(action.Value);
Keep(unplugged, source.Key, action.Key, kept);
Keep(unpluggedFollowing, source.Key, action.Key,
Following(saved, source.Key, action.Key, kept));
}
}
}
foreach (KeyBindings source in sources)
{
everySource.TryGetValue(source.Id, out Dictionary> actions);
foreach (KeyAction action in source.Actions)
{
if (actions != null && actions.TryGetValue(action.Id, out List chords))
{
source.Bind(action, WithKindOf(saved, source, action, Present(chords)));
}
else
{
source.Bind(action, action.Defaults);
}
}
}
}
}
}