load.py 11 KB

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