load.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. for state in states:
  94. if not (
  95. isinstance(state, dict)
  96. or isinstance(state.get("id", None), int)
  97. or isinstance(state.get("cmd", None), str)
  98. or isinstance(state.get("txt", None), str)
  99. ):
  100. raise CustomException(
  101. f"invalid {btn_dims}: invalid state detected"
  102. )
  103. state_id = state.get("id", None)
  104. if isinstance(state_id, int):
  105. if state_id in defined_state_ids:
  106. raise CustomException(
  107. f"invalid {btn_dims}: tried to define state {state_id} twice"
  108. )
  109. defined_state_ids.add(state_id)
  110. for color_pair in ("bg_color", DEFAULT_BUTTON_BG_COLOR), (
  111. "fg_color",
  112. DEFAULT_BUTTON_FG_COLOR,
  113. ):
  114. if not isinstance(
  115. color := state.get(color_pair[0], color_pair[1]),
  116. str,
  117. ) or not is_valid_hexcolor(color):
  118. raise CustomException(
  119. f"invalid {btn_dims} '{color_pair[0]}' subentry: '{color}'"
  120. )
  121. if not DEFAULT_STATE_ID in defined_state_ids:
  122. raise CustomException(
  123. f"invalid {btn_dims}: missing default state id '{DEFAULT_STATE_ID}'"
  124. )
  125. def __validate_dimensions(self) -> None:
  126. for dimension in (self.columns, self.rows):
  127. if not isinstance(dimension, int) or (dimension <= 0):
  128. raise CustomException(f"invalid dimension: {dimension}")
  129. def __validate_styling(self) -> None:
  130. for styling in (self.spacing, self.padding):
  131. if not isinstance(styling, int) or (styling <= 0):
  132. raise CustomException(f"invalid styling: {styling}")
  133. if not isinstance(self.borderless, bool):
  134. raise CustomException("invalid borderless value, should be boolean")