ShortcutController.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.ObjectModel;
  3. using System.Linq;
  4. using System.Windows.Input;
  5. namespace PixiEditor.Models.Controllers.Shortcuts
  6. {
  7. public class ShortcutController
  8. {
  9. public ShortcutController(params ShortcutGroup[] shortcutGroups)
  10. {
  11. ShortcutGroups = new ObservableCollection<ShortcutGroup>(shortcutGroups);
  12. }
  13. public static bool BlockShortcutExecution { get; set; }
  14. public ObservableCollection<ShortcutGroup> ShortcutGroups { get; init; }
  15. public Shortcut LastShortcut { get; private set; }
  16. public const Key MoveViewportToolTransientChangeKey = Key.Space;
  17. public Shortcut GetToolShortcut<T>()
  18. {
  19. return GetToolShortcut(typeof(T));
  20. }
  21. public Shortcut GetToolShortcut(Type type)
  22. {
  23. return ShortcutGroups.SelectMany(x => x.Shortcuts).ToList().Where(i => i.CommandParameter is Type nextType && nextType == type).SingleOrDefault();
  24. }
  25. public Key GetToolShortcutKey<T>()
  26. {
  27. return GetToolShortcutKey(typeof(T));
  28. }
  29. public Key GetToolShortcutKey(Type type)
  30. {
  31. var sh = GetToolShortcut(type);
  32. return sh != null ? sh.ShortcutKey : Key.None;
  33. }
  34. public void KeyPressed(Key key, ModifierKeys modifiers)
  35. {
  36. if (!BlockShortcutExecution)
  37. {
  38. Shortcut[] shortcuts = ShortcutGroups.SelectMany(x => x.Shortcuts).ToList().FindAll(x => x.ShortcutKey == key).ToArray();
  39. if (shortcuts.Length < 1)
  40. {
  41. return;
  42. }
  43. shortcuts = shortcuts.OrderByDescending(x => x.Modifier).ToArray();
  44. for (int i = 0; i < shortcuts.Length; i++)
  45. {
  46. if (modifiers.HasFlag(shortcuts[i].Modifier))
  47. {
  48. shortcuts[i].Execute();
  49. LastShortcut = shortcuts[i];
  50. break;
  51. }
  52. }
  53. }
  54. }
  55. }
  56. }