load.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. from .const import (
  18. DEFAULT_BUTTON_BG_COLOR,
  19. DEFAULT_BUTTON_FG_COLOR,
  20. DEFAULT_STATE_ID,
  21. ERROR_SINK_STATE_ID,
  22. )
  23. from .state import get_state_ids
  24. @dataclass
  25. class ConfigLoader:
  26. config_path: str
  27. def __post_init__(self) -> None:
  28. self.buttons = []
  29. self.columns = 0
  30. self.rows = 0
  31. self.padding = 0
  32. self.spacing = 0
  33. self.borderless = False
  34. def get_config(self) -> Config | str:
  35. try:
  36. with open(self.config_path, "r", encoding="utf-8") as config_reader:
  37. yaml_config = yaml.safe_load(config_reader)
  38. self.columns = yaml_config.get("columns")
  39. self.rows = yaml_config.get("rows")
  40. self.buttons = yaml_config.get("buttons")
  41. self.padding = yaml_config.get("padding", 5)
  42. self.spacing = yaml_config.get("spacing", 5)
  43. self.borderless = yaml_config.get("borderless", False)
  44. return self.__interpret_config()
  45. except (FileNotFoundError, PermissionError, IOError) as error:
  46. return f"Error: Could not access config file at {self.config_path}. Reason: {error}"
  47. except (yaml.YAMLError, CustomException) as error:
  48. return f"Error parsing config file. Reason: {error}"
  49. def __interpret_config(self) -> Config:
  50. self.__validate_dimensions()
  51. self.__validate_buttons()
  52. self.__validate_styling()
  53. return Config(
  54. self.columns,
  55. self.rows,
  56. self.buttons,
  57. self.spacing,
  58. self.padding,
  59. self.borderless,
  60. )
  61. def __validate_buttons(self) -> None:
  62. if not isinstance(self.buttons, list):
  63. raise CustomException(
  64. "invalid button config. needs to be a list of dicts."
  65. )
  66. buttons_that_affect_others = set()
  67. button_grid = {}
  68. for button in self.buttons:
  69. if not isinstance(button, dict):
  70. raise CustomException(
  71. "invalid button config. needs to be a list of dicts."
  72. )
  73. dimensions = button.get("position", "")
  74. if not self.is_valid_dimension(dimensions):
  75. raise CustomException(
  76. f"invalid 'position' subentry: '{dimensions}'"
  77. )
  78. btn_dims = f"button ({dimensions[0]}, {dimensions[1]})"
  79. if not isinstance(states := button.get("states", ""), list):
  80. raise CustomException(
  81. f"invalid {btn_dims} 'states' subentry: '{states}'"
  82. )
  83. if len(states) == 0:
  84. raise CustomException(
  85. f"invalid {btn_dims} 'states' subentry: list cannot be empty"
  86. )
  87. if not isinstance(button.get("autostart", False), bool):
  88. raise CustomException(
  89. f"invalid {btn_dims} 'autostart' entry: must be boolean"
  90. )
  91. defined_state_ids = set()
  92. to_follow_up_state_ids = set()
  93. for state in states:
  94. if not (
  95. isinstance(state, dict)
  96. and isinstance(state_id := state.get("id", None), int)
  97. ):
  98. raise CustomException(
  99. f"invalid {btn_dims}: invalid state id detected"
  100. )
  101. state_id = state.get("id", None)
  102. if isinstance(state_id, int):
  103. if state_id in defined_state_ids:
  104. raise CustomException(
  105. f"invalid {btn_dims}: tried to define state "
  106. + f"'{state_id}' twice"
  107. )
  108. defined_state_ids.add(state_id)
  109. for string in ("cmd", "txt"):
  110. if not isinstance(state.get(string, ""), str):
  111. raise CustomException(
  112. f"invalid {btn_dims}: invalid '{string}' subentry "
  113. + f"for state id '{state_id}': must be a string"
  114. )
  115. for color_pair in ("bg_color", DEFAULT_BUTTON_BG_COLOR), (
  116. "fg_color",
  117. DEFAULT_BUTTON_FG_COLOR,
  118. ):
  119. if not isinstance(
  120. color := state.get(color_pair[0], color_pair[1]),
  121. str,
  122. ) or not is_valid_hexcolor(color):
  123. raise CustomException(
  124. f"invalid {btn_dims}: '{color_pair[0]}' subentry "
  125. + f"for state '{state_id}': '{color}'"
  126. )
  127. follow_up_state = state.get("follow_up_state", 0)
  128. if not isinstance(follow_up_state, int):
  129. raise CustomException(
  130. f"invalid {btn_dims}: 'follow_up_state' subentry for"
  131. + f" state '{state_id}': must be int"
  132. )
  133. to_follow_up_state_ids.add(follow_up_state)
  134. button_grid[(dimensions[0], dimensions[1])] = button
  135. affects_buttons = button.get("affects_buttons", None)
  136. if isinstance(affects_buttons, list):
  137. if len(affects_buttons) == 0:
  138. raise CustomException(
  139. f"invalid {btn_dims}: 'affects_buttons' entry: must be"
  140. + "a non-empty list"
  141. )
  142. if affects_buttons:
  143. for affected_button_dimension in affects_buttons:
  144. if not self.is_valid_dimension(affected_button_dimension):
  145. raise CustomException(
  146. f"invalid {btn_dims}: 'affects_buttons' entry: "
  147. + "invalid dimensions: "
  148. + f"'{affected_button_dimension}'"
  149. )
  150. buttons_that_affect_others.add(str(dimensions))
  151. if not DEFAULT_STATE_ID in defined_state_ids:
  152. raise CustomException(
  153. f"invalid {btn_dims}: missing default state id "
  154. + f"'{DEFAULT_STATE_ID}'"
  155. )
  156. if (len(defined_state_ids) > 1) and (
  157. not ERROR_SINK_STATE_ID in defined_state_ids
  158. ):
  159. raise CustomException(
  160. f"invalid {btn_dims}: missing error sink state id "
  161. + f"'{ERROR_SINK_STATE_ID}' for unstateless button"
  162. )
  163. for follow_up_state_id in to_follow_up_state_ids:
  164. if follow_up_state_id not in defined_state_ids:
  165. raise CustomException(
  166. f"invalid {btn_dims}: invalid 'follow_up_state' "
  167. + f"subentry found: state '{follow_up_state_id}' does "
  168. + "not exist"
  169. )
  170. for btn_dims in buttons_that_affect_others:
  171. row = int(btn_dims[btn_dims.find("[") + 1 : btn_dims.find(",")])
  172. col = int(btn_dims[btn_dims.find(" ") + 1 : btn_dims.find("]")])
  173. button_dimensions = (row, col)
  174. button = button_grid[button_dimensions]
  175. affects_buttons = button["affects_buttons"]
  176. ids = []
  177. ids.append(get_state_ids(button["states"]))
  178. for affected_btn_dims in affects_buttons:
  179. try:
  180. affected_button = button_grid[
  181. (affected_btn_dims[0], affected_btn_dims[1])
  182. ]
  183. except KeyError as e:
  184. raise CustomException(
  185. f"invalid button ({row}, {col}): 'affects_buttons' "
  186. + "buttons must be defined"
  187. ) from e
  188. ids.append(get_state_ids(affected_button["states"]))
  189. for id_listing in ids[1:]:
  190. if len(id_listing) == 1:
  191. raise CustomException(
  192. f"invalid button ({row}, {col}): 'affects_buttons' "
  193. + "buttons cannot be stateless"
  194. )
  195. if id_listing != ids[0]:
  196. raise CustomException(
  197. f"invalid button ({row}, {col}): 'affects_buttons' "
  198. + "buttons must have the same state id's"
  199. )
  200. def is_valid_dimension(self, dimensions):
  201. return not (
  202. not isinstance(dimensions, list)
  203. or (not isinstance(dimensions[0], int))
  204. or (not isinstance(dimensions[1], int))
  205. or (0 > dimensions[0] or dimensions[0] > self.rows - 1)
  206. or (0 > dimensions[1] or dimensions[1] > self.columns - 1)
  207. )
  208. def __validate_dimensions(self) -> None:
  209. for dimension in (self.columns, self.rows):
  210. if not isinstance(dimension, int) or (dimension <= 0):
  211. raise CustomException(f"invalid dimension: {dimension}")
  212. def __validate_styling(self) -> None:
  213. for styling in (self.spacing, self.padding):
  214. if not isinstance(styling, int) or (styling <= 0):
  215. raise CustomException(f"invalid styling: {styling}")
  216. if not isinstance(self.borderless, bool):
  217. raise CustomException("invalid borderless value, should be boolean")