-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmodel.py
281 lines (234 loc) · 10.5 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# Wahoo! Results - https://github.com/JohnStrunk/wahoo-results
# Copyright (C) 2022 - John D. Strunk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Wahoo! Results data model."""
import logging
import queue
import uuid
from configparser import ConfigParser
from tkinter import BooleanVar, DoubleVar, IntVar, StringVar, Tk, Variable
from typing import Callable, Generic, List, Optional, Set, TypeVar
import PIL.Image as PILImage
from imagecast import DeviceStatus
from raceinfo import HeatData, StartList
CallbackFn = Callable[[], None]
_INI_HEADING = "wahoo-results"
_T = TypeVar("_T")
logger = logging.getLogger(__name__)
class GVar(Variable, Generic[_T]):
"""A generic variable in the flavor of StringVar, IntVar, etc."""
def __init__(self, value: _T, master=None):
"""
Create a generic variable in the flavor of StringVar, IntVar, etc.
:param value: the initial value for the variable
:param master: the master widget
"""
super().__init__(master=master, value=0)
self._value = value
def get(self) -> _T:
"""Return the value of the variable."""
_x = super().get()
return self._value
def set(self, value: _T) -> None:
"""Set the variable to a new value."""
self._value = value
super().set(super().get() + 1)
class ChromecastStatusVar(GVar[List[DeviceStatus]]):
"""A list of Chromecast devices and whether they are enabled."""
class ImageVar(GVar[PILImage.Image]):
"""Value holder for PhotoImage variables."""
class CallbackList:
"""A list of callback functions."""
_callbacks: Set[CallbackFn]
def __init__(self):
"""Initialize a set of callback functions."""
self._callbacks = set()
def run(self) -> None:
"""Invoke all registered callback functions."""
for func in self._callbacks:
func()
def add(self, callback) -> None:
"""Add a callback function to the set.
:param callback: the function to add
"""
self._callbacks.add(callback)
def remove(self, callback) -> None:
"""Remove a callback function from the set.
:param callback: the function to remove
"""
self._callbacks.discard(callback)
class StartListVar(GVar[List[StartList]]):
"""An ordered list of start lists."""
class RaceResultListVar(GVar[List[HeatData]]):
"""Holds an ordered list of race results."""
class RaceResultVar(GVar[Optional[HeatData]]):
"""A race result."""
class Model:
"""Defines the state variables (model) for the main UI."""
## Colors from USA-S visual identity standards
PANTONE282_DKBLUE = "#041e42" # Primary
PANTONE200_RED = "#ba0c2f" # Primary
BLACK = "#000000" # Secondary
PANTONE428_LTGRAY = "#c1c6c8" # Secondary
PANTONE877METALIC_MDGRAY = "#8a8d8f" # Secondary
PANTONE281_MDBLUE = "#00205b" # Tertiary
PANTONE306_LTBLUE = "#00b3e4" # Tertiary
PANTONE871METALICGOLD = "#85754e" # Tertiary
PANTONE4505FLATGOLD = "#b1953a" # Tertiary
def __init__(self, root: Tk):
"""Initialize the state variables (model) for the main UI.
:param root: the root Tkinter window
"""
self.root = root
# Initialize the event queue and start the dispatch loop
self._event_queue: queue.Queue[Callable[[], None]] = queue.Queue()
root.after_idle(self._dispatch_event)
########################################
## Dropdown menu items
self.menu_export_template = CallbackList()
self.menu_save_scoreboard = CallbackList()
self.menu_exit = CallbackList()
self.menu_docs = CallbackList()
self.menu_about = CallbackList()
########################################
## Buttons
self.bg_import = CallbackList()
self.bg_clear = CallbackList()
self.dolphin_export = CallbackList()
########################################
## Entry fields
self.font_normal = StringVar(name="font_normal")
self.font_time = StringVar(name="font_time")
self.text_spacing = DoubleVar(name="text_spacing")
self.title = StringVar(name="title")
# colors
self.image_bg = StringVar(name="image_bg")
self.color_title = StringVar(name="color_title")
self.color_event = StringVar(name="color_event")
self.color_even = StringVar(name="color_even")
self.color_odd = StringVar(name="color_odd")
self.color_first = StringVar(name="color_first")
self.color_second = StringVar(name="color_second")
self.color_third = StringVar(name="color_third")
self.color_bg = StringVar(name="color_bg")
self.brightness_bg = IntVar(name="brightness_bg")
# features
self.num_lanes = IntVar(name="num_lanes")
self.min_times = IntVar(name="min_times")
self.time_threshold = DoubleVar(name="time_threshold")
# Preview
self.appearance_preview = ImageVar(PILImage.Image())
# Directories
self.dir_startlist = StringVar(name="dir_startlist")
self.startlist_contents = StartListVar([])
self.dir_results = StringVar(name="dir_results")
self.results_contents = RaceResultListVar([])
# Run tab
self.cc_status = ChromecastStatusVar([])
self.scoreboard = ImageVar(PILImage.Image())
self.latest_result = RaceResultVar(None)
# misc
self.client_id = StringVar(name="client_id")
self.analytics = BooleanVar(name="analytics")
self.version = StringVar(name="version")
self.statustext = StringVar(name="statustext")
self.statusclick = CallbackList()
def load(self, filename: str) -> None:
"""Load the user's preferences.
:param filename: the name of the file to load
"""
config = ConfigParser(interpolation=None)
config.read(filename, encoding="utf-8")
if _INI_HEADING not in config:
config.add_section(_INI_HEADING)
data = config[_INI_HEADING]
# Calibri (sans serif) is standard since Vista
# It's also part of USA-S visual identity standards
# https://www.usaswimming.org/docs/default-source/marketingdocuments/usa-swimming-logo-standards-manual.pdf
self.font_normal.set(data.get("font_normal", "Calibri"))
# Consolas (monospace) is standard since Vista
self.font_time.set(data.get("font_time", "Consolas"))
self.text_spacing.set(data.getfloat("text_spacing", 1.1))
self.title.set(data.get("title", "Wahoo! Results"))
self.image_bg.set(data.get("image_bg", ""))
self.color_title.set(data.get("color_title", self.PANTONE200_RED))
self.color_event.set(data.get("color_event", self.PANTONE4505FLATGOLD))
self.color_even.set(data.get("color_even", self.PANTONE877METALIC_MDGRAY))
self.color_odd.set(data.get("color_odd", self.PANTONE428_LTGRAY))
self.color_first.set(data.get("color_first", self.PANTONE306_LTBLUE))
self.color_second.set(data.get("color_second", self.PANTONE200_RED))
self.color_third.set(data.get("color_third", self.PANTONE4505FLATGOLD))
self.color_bg.set(data.get("color_bg", self.BLACK))
self.brightness_bg.set(data.getint("brightness_bg", 100))
self.num_lanes.set(data.getint("num_lanes", 10))
self.min_times.set(data.getint("min_times", 2))
self.time_threshold.set(data.getfloat("time_threshold", 0.30))
self.dir_startlist.set(data.get("dir_startlist", "C:\\swmeets8"))
self.dir_results.set(data.get("dir_results", "C:\\CTSDolphin"))
client_id = data.get("client_id")
if client_id is None or len(client_id) == 0:
client_id = str(uuid.uuid4())
try:
uuid.UUID(client_id)
except ValueError:
client_id = str(uuid.uuid4())
self.client_id.set(client_id)
self.analytics.set(data.getboolean("analytics", True))
def save(self, filename: str) -> None:
"""Save the user's preferences.
:param filename: the name of the file to save
"""
config = ConfigParser(interpolation=None)
config[_INI_HEADING] = {
"font_normal": self.font_normal.get(),
"font_time": self.font_time.get(),
"text_spacing": str(self.text_spacing.get()),
"title": self.title.get(),
"image_bg": self.image_bg.get(),
"color_title": self.color_title.get(),
"color_event": self.color_event.get(),
"color_even": self.color_even.get(),
"color_odd": self.color_odd.get(),
"color_first": self.color_first.get(),
"color_second": self.color_second.get(),
"color_third": self.color_third.get(),
"color_bg": self.color_bg.get(),
"brightness_bg": str(self.brightness_bg.get()),
"num_lanes": str(self.num_lanes.get()),
"min_times": str(self.min_times.get()),
"time_threshold": str(self.time_threshold.get()),
"dir_startlist": self.dir_startlist.get(),
"dir_results": self.dir_results.get(),
"client_id": self.client_id.get(),
"analytics": str(self.analytics.get()),
}
with open(filename, "w", encoding="utf-8") as file:
config.write(file)
def enqueue(self, func: Callable[[], None]) -> None:
"""Enqueue a function to be executed by the tkinter main thread.
:param func: the function to enqueue
"""
self._event_queue.put(func)
def _dispatch_event(self) -> None:
try:
func = self._event_queue.get_nowait()
logger.debug("Dispatching function from queue: %s", func.__name__)
func()
self._event_queue.task_done()
# Give tkinter a chance to process events
self.root.after_idle(self._dispatch_event)
except queue.Empty:
# No more events to process, check again later
self.root.after(10, self._dispatch_event)