load.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. )
  22. @dataclass
  23. class ConfigLoader:
  24. config_path: str
  25. def __post_init__(self) -> None:
  26. self.buttons = []
  27. self.columns = 0
  28. self.rows = 0
  29. self.padding = 0
  30. self.spacing = 0
  31. self.borderless = False
  32. def get_config(self) -> Config | str:
  33. try:
  34. with open(self.config_path, "r", encoding="utf-8") as config_reader:
  35. yaml_config = yaml.safe_load(config_reader)
  36. self.columns = yaml_config.get("columns")
  37. self.rows = yaml_config.get("rows")
  38. self.buttons = yaml_config.get("buttons")
  39. self.padding = yaml_config.get("padding", 5)
  40. self.spacing = yaml_config.get("spacing", 5)
  41. self.borderless = yaml_config.get("borderless", False)
  42. return self.__interpret_config()
  43. except (FileNotFoundError, PermissionError, IOError) as error:
  44. return f"Error: Could not access config file at {self.config_path}. Reason: {error}"
  45. except (yaml.YAMLError, CustomException) as error:
  46. return f"Error parsing config file. Reason: {error}"
  47. def __interpret_config(self) -> Config:
  48. self.__validate_dimensions()
  49. self.__validate_buttons()
  50. self.__validate_styling()
  51. return Config(
  52. self.columns,
  53. self.rows,
  54. self.buttons,
  55. self.spacing,
  56. self.padding,
  57. self.borderless,
  58. )
  59. def __validate_buttons(self) -> None:
  60. if not isinstance(self.buttons, list):
  61. raise CustomException(
  62. "invalid button config. needs to be a list of dicts."
  63. )
  64. for button in self.buttons:
  65. if not isinstance(button, dict):
  66. raise CustomException(
  67. "invalid button config. needs to be a list of dicts."
  68. )
  69. if (
  70. not isinstance(dimensions := button.get("position", ""), list)
  71. or (not isinstance(dimensions[0], int))
  72. or (not isinstance(dimensions[1], int))
  73. or (0 > dimensions[0] or dimensions[0] > self.rows - 1)
  74. or (0 > dimensions[1] or dimensions[1] > self.columns - 1)
  75. ):
  76. raise CustomException(
  77. f"invalid 'position' subentry: '{dimensions}'"
  78. )
  79. btn_dims = f"button ({dimensions[0]}, {dimensions[1]})"
  80. if not isinstance(states := button.get("states", ""), list):
  81. raise CustomException(
  82. f"invalid {btn_dims} 'states' subentry: '{states}'"
  83. )
  84. if len(states) == 0:
  85. raise CustomException(
  86. f"invalid {btn_dims} 'states' subentry: list cannot be empty"
  87. )
  88. if not isinstance(button.get("autostart", False), bool):
  89. raise CustomException(
  90. f"invalid {btn_dims} 'autostart' entry: must be boolean"
  91. )
  92. defined_state_ids = set()
  93. to_follow_up_state_ids = set()
  94. for state in states:
  95. if not (
  96. isinstance(state, dict)
  97. and isinstance(state_id := state.get("id", None), int)
  98. ):
  99. raise CustomException(
  100. f"invalid {btn_dims}: invalid state id detected"
  101. )
  102. state_id = state.get("id", None)
  103. if isinstance(state_id, int):
  104. if state_id in defined_state_ids:
  105. raise CustomException(
  106. f"invalid {btn_dims}: tried to define state "
  107. + f"'{state_id}' twice"
  108. )
  109. defined_state_ids.add(state_id)
  110. for string in ("cmd", "txt"):
  111. if not isinstance(state.get(string, ""), str):
  112. raise CustomException(
  113. f"invalid {btn_dims}: invalid '{string}' subentry "
  114. + f"for state id '{state_id}': must be a string"
  115. )
  116. for color_pair in ("bg_color", DEFAULT_BUTTON_BG_COLOR), (
  117. "fg_color",
  118. DEFAULT_BUTTON_FG_COLOR,
  119. ):
  120. if not isinstance(
  121. color := state.get(color_pair[0], color_pair[1]),
  122. str,
  123. ) or not is_valid_hexcolor(color):
  124. raise CustomException(
  125. f"invalid {btn_dims}: '{color_pair[0]}' subentry "
  126. + f"for state '{state_id}': '{color}'"
  127. )
  128. follow_up_state = state.get("follow_up_state", 0)
  129. if not isinstance(follow_up_state, int):
  130. raise CustomException(
  131. f"invalid {btn_dims}: 'follow_up_state' subentry for"
  132. + f" state '{state_id}': must be int"
  133. )
  134. to_follow_up_state_ids.add(follow_up_state)
  135. if not DEFAULT_STATE_ID in defined_state_ids:
  136. raise CustomException(
  137. f"invalid {btn_dims}: missing default state id "
  138. + f"'{DEFAULT_STATE_ID}'"
  139. )
  140. for follow_up_state_id in to_follow_up_state_ids:
  141. if follow_up_state_id not in defined_state_ids:
  142. raise CustomException(
  143. f"invalid {btn_dims}: invalid 'follow_up_state' "
  144. + f"subentry found: state '{follow_up_state_id}' does "
  145. + "not exist"
  146. )
  147. def __validate_dimensions(self) -> None:
  148. for dimension in (self.columns, self.rows):
  149. if not isinstance(dimension, int) or (dimension <= 0):
  150. raise CustomException(f"invalid dimension: {dimension}")
  151. def __validate_styling(self) -> None:
  152. for styling in (self.spacing, self.padding):
  153. if not isinstance(styling, int) or (styling <= 0):
  154. raise CustomException(f"invalid styling: {styling}")
  155. if not isinstance(self.borderless, bool):
  156. raise CustomException("invalid borderless value, should be boolean")