ShortcutController.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using PixiEditor.Models.Tools;
  2. using PixiEditor.Models.Tools.Tools;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Collections.ObjectModel;
  6. using System.Linq;
  7. using System.Windows.Documents;
  8. using System.Windows.Input;
  9. namespace PixiEditor.Models.Controllers.Shortcuts
  10. {
  11. public class ShortcutController
  12. {
  13. public ShortcutController(params ShortcutGroup[] shortcutGroups)
  14. {
  15. ShortcutGroups = new ObservableCollection<ShortcutGroup>(shortcutGroups);
  16. }
  17. public static bool ShortcutExecutionBlocked => _shortcutExecutionBlockers.Count > 0;
  18. private static List<string> _shortcutExecutionBlockers = new List<string>();
  19. public ObservableCollection<ShortcutGroup> ShortcutGroups { get; init; }
  20. public Shortcut LastShortcut { get; private set; }
  21. public Dictionary<Key, Tool> TransientShortcuts { get; set; } = new Dictionary<Key, Tool>();
  22. public static void BlockShortcutExection(string blocker)
  23. {
  24. if (_shortcutExecutionBlockers.Contains(blocker)) return;
  25. _shortcutExecutionBlockers.Add(blocker);
  26. }
  27. public static void UnblockShortcutExecution(string blocker)
  28. {
  29. if (!_shortcutExecutionBlockers.Contains(blocker)) return;
  30. _shortcutExecutionBlockers.Remove(blocker);
  31. }
  32. public static void UnblockShortcutExecutionAll()
  33. {
  34. _shortcutExecutionBlockers.Clear();
  35. }
  36. public Shortcut GetToolShortcut<T>()
  37. {
  38. return GetToolShortcut(typeof(T));
  39. }
  40. public Shortcut GetToolShortcut(Type type)
  41. {
  42. return ShortcutGroups.SelectMany(x => x.Shortcuts).ToList().Where(i => i.CommandParameter is Type nextType && nextType == type).SingleOrDefault();
  43. }
  44. public Key GetToolShortcutKey<T>()
  45. {
  46. return GetToolShortcutKey(typeof(T));
  47. }
  48. public Key GetToolShortcutKey(Type type)
  49. {
  50. var sh = GetToolShortcut(type);
  51. return sh != null ? sh.ShortcutKey : Key.None;
  52. }
  53. public void KeyPressed(Key key, ModifierKeys modifiers)
  54. {
  55. if (!ShortcutExecutionBlocked)
  56. {
  57. Shortcut[] shortcuts = ShortcutGroups.SelectMany(x => x.Shortcuts).ToList().FindAll(x => x.ShortcutKey == key).ToArray();
  58. if (shortcuts.Length < 1)
  59. {
  60. return;
  61. }
  62. shortcuts = shortcuts.OrderByDescending(x => x.Modifier).ToArray();
  63. for (int i = 0; i < shortcuts.Length; i++)
  64. {
  65. if (modifiers.HasFlag(shortcuts[i].Modifier))
  66. {
  67. shortcuts[i].Execute();
  68. LastShortcut = shortcuts[i];
  69. break;
  70. }
  71. }
  72. }
  73. }
  74. }
  75. }