CommandCollection.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using PixiEditor.Models.DataHolders;
  2. using System.Collections;
  3. using System.Diagnostics;
  4. using System.Windows.Input;
  5. using OneOf.Types;
  6. namespace PixiEditor.Models.Commands
  7. {
  8. [DebuggerDisplay("Count = {Count}")]
  9. public class CommandCollection : ICollection<Command>
  10. {
  11. private readonly Dictionary<string, Command> _commandInternalNames;
  12. private readonly OneToManyDictionary<KeyCombination, Command> _commandShortcuts;
  13. public int Count => _commandInternalNames.Count;
  14. public bool IsReadOnly => false;
  15. public Command this[string name] => _commandInternalNames[name];
  16. public IEnumerable<Command> this[KeyCombination shortcut] => _commandShortcuts[shortcut];
  17. public CommandCollection()
  18. {
  19. _commandInternalNames = new();
  20. _commandShortcuts = new();
  21. }
  22. public void Add(Command item)
  23. {
  24. _commandInternalNames.Add(item.InternalName, item);
  25. _commandShortcuts.Add(item.Shortcut, item);
  26. }
  27. public void Clear()
  28. {
  29. _commandInternalNames.Clear();
  30. _commandShortcuts.Clear();
  31. }
  32. public void ClearShortcuts() => _commandShortcuts.Clear();
  33. public bool Contains(Command item) => _commandInternalNames.ContainsKey(item.InternalName);
  34. public void CopyTo(Command[] array, int arrayIndex) => _commandInternalNames.Values.CopyTo(array, arrayIndex);
  35. public IEnumerator<Command> GetEnumerator() => _commandInternalNames.Values.GetEnumerator();
  36. public bool Remove(Command item)
  37. {
  38. bool anyRemoved = false;
  39. anyRemoved |= _commandInternalNames.Remove(item.InternalName);
  40. anyRemoved |= _commandShortcuts.Remove(item);
  41. return anyRemoved;
  42. }
  43. public void AddShortcut(Command command, KeyCombination shortcut)
  44. {
  45. _commandShortcuts.Remove(KeyCombination.None, command);
  46. _commandShortcuts.Add(shortcut, command);
  47. }
  48. public void RemoveShortcut(Command command, KeyCombination shortcut)
  49. {
  50. _commandShortcuts.Remove(shortcut, command);
  51. _commandShortcuts.Add(KeyCombination.None, command);
  52. }
  53. public void ClearShortcut(KeyCombination shortcut)
  54. {
  55. if (shortcut is { Key: Key.None, Modifiers: ModifierKeys.None })
  56. return;
  57. _commandShortcuts.AddRange(KeyCombination.None, _commandShortcuts[shortcut]);
  58. _commandShortcuts.Clear(shortcut);
  59. }
  60. public IEnumerable<KeyValuePair<KeyCombination, IEnumerable<Command>>> GetShortcuts() =>
  61. _commandShortcuts;
  62. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  63. }
  64. }