load.py 11 KB

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