KeyHandler.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package me.hammerle.snuviengine.api;
  2. import java.util.HashMap;
  3. public final class KeyHandler
  4. {
  5. private final static HashMap<Integer, KeyBinding> BINDINGS = new HashMap<>();
  6. private static KeyBinding rebind = null;
  7. public static KeyBinding register(int key) throws KeyDuplicateException
  8. {
  9. KeyBinding binding = new KeyBinding(key);
  10. if(BINDINGS.putIfAbsent(key, binding) != null)
  11. {
  12. throw new KeyDuplicateException("the key '" + key + "' has already been registered");
  13. }
  14. return binding;
  15. }
  16. public static void rebind(KeyBinding binding)
  17. {
  18. rebind = binding;
  19. if(binding != null)
  20. {
  21. binding.setIsRebinding(true);
  22. }
  23. }
  24. public static void rebind(KeyBinding binding, int key)
  25. {
  26. if(BINDINGS.containsKey(key))
  27. {
  28. return;
  29. }
  30. BINDINGS.remove(binding.getKey());
  31. binding.setKey(key);
  32. BINDINGS.put(key, binding);
  33. }
  34. protected static void onKeyDownEvent(int key)
  35. {
  36. if(rebind != null)
  37. {
  38. rebind.setIsRebinding(false);
  39. rebind(rebind, key);
  40. rebind = null;
  41. return;
  42. }
  43. KeyBinding binding = BINDINGS.get(key);
  44. if(binding != null)
  45. {
  46. binding.onKeyDownEvent();
  47. }
  48. }
  49. protected static void onKeyUpEvent(int key)
  50. {
  51. KeyBinding binding = BINDINGS.get(key);
  52. if(binding != null)
  53. {
  54. binding.onKeyUpEvent();
  55. }
  56. }
  57. protected static void tick()
  58. {
  59. BINDINGS.values().forEach(binding -> binding.tick());
  60. }
  61. }