input.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. This file contains utilities for handling input from the user and registering specific keys to specific functions,
  16. based on https://github.com/bchao1/bullet
  17. """
  18. from .keymap import KEYMAP, get_character
  19. def mark(key: str):
  20. """
  21. Mark the function with the key code so it can be handled in the register
  22. """
  23. def decorator(func):
  24. handle = getattr(func, "handle_key", [])
  25. handle += [key]
  26. func.handle_key = handle
  27. return func
  28. return decorator
  29. def mark_multiple(*keys: list[str]):
  30. """
  31. Mark the function with the key codes so it can be handled in the register
  32. """
  33. def decorator(func):
  34. handle = getattr(func, "handle_key", [])
  35. handle += keys
  36. func.handle_key = handle
  37. return func
  38. return decorator
  39. class KeyHandler(type):
  40. """
  41. Metaclass that adds the key handlers to the class
  42. """
  43. def __new__(cls, name, bases, attrs):
  44. new_cls = super().__new__(cls, name, bases, attrs)
  45. if not hasattr(new_cls, "key_handler"):
  46. new_cls.key_handler = {}
  47. new_cls.handle_input = KeyHandler.handle_input
  48. for value in attrs.values():
  49. handled_keys = getattr(value, "handle_key", [])
  50. for key in handled_keys:
  51. new_cls.key_handler[key] = value
  52. return new_cls
  53. @staticmethod
  54. def handle_input(cls):
  55. "Finds and returns the selected character if it exists in the handler"
  56. char = get_character()
  57. if char != KEYMAP["undefined"]:
  58. char = ord(char)
  59. handler = cls.key_handler.get(char)
  60. if handler:
  61. cls.current_selection = char
  62. return handler(cls)
  63. else:
  64. return None
  65. def register(cls):
  66. """Adds KeyHandler metaclass to the class"""
  67. return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy())