load.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # Copyright © 2024 Noah Vogt <noah@noahvogt.com>
  2. # This program is free software: you can redistribute it and/or modify
  3. # it under the terms of the GNU General Public License as published by
  4. # the Free Software Foundation, either version 3 of the License, or
  5. # (at your option) any later version.
  6. # This program is distributed in the hope that it will be useful,
  7. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. # GNU General Public License for more details.
  10. # You should have received a copy of the GNU General Public License
  11. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  12. from dataclasses import dataclass
  13. import yaml
  14. from util import CustomException
  15. from .classes import Config
  16. from .validate import is_valid_hexcolor
  17. def get_state_from_id(states: list, state_id: int) -> dict:
  18. for state in states:
  19. possible_id = state.get("id", None)
  20. if isinstance(possible_id, int):
  21. if possible_id == state_id:
  22. return state
  23. return {}
  24. def get_state_id_from_exit_code(states: list, exit_code: int) -> int:
  25. found_state_id = False
  26. for found_states in states:
  27. if found_states["id"] == exit_code:
  28. found_state_id = True
  29. break
  30. if not found_state_id:
  31. exit_code = 1
  32. return exit_code
  33. @dataclass
  34. class ConfigLoader:
  35. config_path: str
  36. def __post_init__(self) -> None:
  37. self.buttons = []
  38. self.columns = 0
  39. self.rows = 0
  40. self.padding = 0
  41. self.spacing = 0
  42. self.borderless = False
  43. def get_config(self) -> Config | str:
  44. try:
  45. with open(self.config_path, "r", encoding="utf-8") as config_reader:
  46. yaml_config = yaml.safe_load(config_reader)
  47. self.columns = yaml_config.get("columns")
  48. self.rows = yaml_config.get("rows")
  49. self.buttons = yaml_config.get("buttons")
  50. self.padding = yaml_config.get("padding", 5)
  51. self.spacing = yaml_config.get("spacing", 5)
  52. self.borderless = yaml_config.get("borderless", False)
  53. return self.__interpret_config()
  54. except (FileNotFoundError, PermissionError, IOError) as error:
  55. return f"Error: Could not access config file at {self.config_path}. Reason: {error}"
  56. except (yaml.YAMLError, CustomException) as error:
  57. return f"Error parsing config file. Reason: {error}"
  58. def __interpret_config(self) -> Config:
  59. self.__validate_dimensions()
  60. self.__validate_buttons()
  61. self.__validate_styling()
  62. return Config(
  63. self.columns,
  64. self.rows,
  65. self.buttons,
  66. self.spacing,
  67. self.padding,
  68. self.borderless,
  69. )
  70. def __validate_buttons(self) -> None:
  71. if not isinstance(self.buttons, list):
  72. raise CustomException(
  73. "invalid button config. needs to be a list of dicts."
  74. )
  75. for button in self.buttons:
  76. if not isinstance(button, dict):
  77. raise CustomException(
  78. "invalid button config. needs to be a list of dicts."
  79. )
  80. if (
  81. not isinstance(dimensions := button.get("position", ""), list)
  82. or (not isinstance(dimensions[0], int))
  83. or (not isinstance(dimensions[1], int))
  84. or (0 > dimensions[0] or dimensions[0] > self.rows - 1)
  85. or (0 > dimensions[1] or dimensions[1] > self.columns - 1)
  86. ):
  87. raise CustomException(
  88. f"invalid 'position' subentry: '{dimensions}'"
  89. )
  90. btn_dims = f"button ({dimensions[0]}, {dimensions[1]})"
  91. if not isinstance(states := button.get("states", ""), list):
  92. raise CustomException(
  93. f"invalid {btn_dims} 'states' subentry: '{states}'"
  94. )
  95. if len(states) == 0:
  96. raise CustomException(
  97. f"invalid {btn_dims} 'states' subentry: list cannot be empty"
  98. )
  99. defined_state_ids = set()
  100. for state in states:
  101. if not (
  102. isinstance(state, dict)
  103. or isinstance(state.get("id", None), int)
  104. or isinstance(state.get("cmd", None), str)
  105. or isinstance(state.get("txt", None), str)
  106. ):
  107. raise CustomException(
  108. f"invalid {btn_dims}: invalid state detected"
  109. )
  110. defined_state_ids.add(state.get("id", None))
  111. if not isinstance(
  112. bg_color := state.get("bg_color", "cccccc"), str
  113. ) or not is_valid_hexcolor(bg_color):
  114. raise CustomException(
  115. f"invalid {btn_dims} 'bg_color' subentry: '{bg_color}'"
  116. )
  117. if not isinstance(
  118. fg_color := state.get("fg_color", "ffffff"), str
  119. ) or not is_valid_hexcolor(fg_color):
  120. raise CustomException(
  121. f"invalid {btn_dims} 'fg_color' subentry: '{fg_color}'"
  122. )
  123. print(defined_state_ids)
  124. # TODO: add const or rethink needed state id's
  125. if not 0 in defined_state_ids:
  126. raise CustomException(f"invalid {btn_dims}: missing state id 0")
  127. def __validate_dimensions(self) -> None:
  128. for dimension in (self.columns, self.rows):
  129. if not isinstance(dimension, int) or (dimension <= 0):
  130. raise CustomException(f"invalid dimension: {dimension}")
  131. def __validate_styling(self) -> None:
  132. for styling in (self.spacing, self.padding):
  133. if not isinstance(styling, int) or (styling <= 0):
  134. raise CustomException(f"invalid styling: {styling}")
  135. if not isinstance(self.borderless, bool):
  136. raise CustomException("invalid borderless value, should be boolean")