splitguides 0.10.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. splitguides/__init__.py +1 -0
  2. splitguides/__main__.py +15 -0
  3. splitguides/_version.py +2 -0
  4. splitguides/build_ui.py +71 -0
  5. splitguides/exceptions.py +4 -0
  6. splitguides/hotkeys.py +54 -0
  7. splitguides/livesplit_client.py +303 -0
  8. splitguides/note_parser.py +260 -0
  9. splitguides/server/__init__.py +1 -0
  10. splitguides/server/__main__.py +58 -0
  11. splitguides/server/split_server.py +129 -0
  12. splitguides/settings.py +231 -0
  13. splitguides/static/desktop.css +146 -0
  14. splitguides/static/server.css +160 -0
  15. splitguides/static/streamlistener.js +18 -0
  16. splitguides/templates/desktop.html +25 -0
  17. splitguides/templates/server.html +12 -0
  18. splitguides/ui/__init__.py +0 -0
  19. splitguides/ui/color.py +50 -0
  20. splitguides/ui/custom_elements/__init__.py +18 -0
  21. splitguides/ui/hotkey_manager.py +92 -0
  22. splitguides/ui/layouts/__init__.py +8 -0
  23. splitguides/ui/layouts/build/__init__.py +0 -0
  24. splitguides/ui/layouts/build/main_window.py +61 -0
  25. splitguides/ui/layouts/build/server_settings.py +349 -0
  26. splitguides/ui/layouts/build/settings.py +318 -0
  27. splitguides/ui/layouts/main_window.ui +64 -0
  28. splitguides/ui/layouts/server_settings.ui +394 -0
  29. splitguides/ui/layouts/settings.ui +382 -0
  30. splitguides/ui/main.pyproject +3 -0
  31. splitguides/ui/main_window.py +492 -0
  32. splitguides/ui/server_settings_ui.py +191 -0
  33. splitguides/ui/settings_ui.py +241 -0
  34. splitguides-0.10.1.dist-info/METADATA +199 -0
  35. splitguides-0.10.1.dist-info/RECORD +39 -0
  36. splitguides-0.10.1.dist-info/WHEEL +5 -0
  37. splitguides-0.10.1.dist-info/entry_points.txt +3 -0
  38. splitguides-0.10.1.dist-info/licenses/COPYING +674 -0
  39. splitguides-0.10.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1 @@
1
+ from ._version import __version__ as __version__
@@ -0,0 +1,15 @@
1
+ import sys
2
+ from PySide6.QtWidgets import QApplication
3
+
4
+ from splitguides.ui.main_window import MainWindow
5
+
6
+
7
+ def main() -> int:
8
+ app = QApplication(sys.argv)
9
+ window = MainWindow()
10
+ window.show()
11
+ return app.exec()
12
+
13
+
14
+ if __name__ == "__main__":
15
+ sys.exit(main())
@@ -0,0 +1,2 @@
1
+ __version__ = "0.10.1"
2
+ __version_tuple__ = (0, 10, 1)
@@ -0,0 +1,71 @@
1
+ """
2
+ Build the .ui files into .py script files.
3
+ """
4
+ import os
5
+ import sys
6
+
7
+ # In v5.14 they removed pyside2uic so this invokes uic directly
8
+ from subprocess import run
9
+ from pathlib import Path
10
+
11
+ import PySide6
12
+
13
+
14
+ def uic(infile, outfile):
15
+ """
16
+ Run the QT User Interface Compiler to convert a .ui file to a .py file
17
+
18
+ :param infile: Input path
19
+ :param outfile: Output path
20
+ :return: the CompletedProcess object from running the uic .exe
21
+ """
22
+ # This logic is largely from PySide6.scripts.pyside_tool
23
+ # The problem with calling the pyside6-uic script directly is discovery
24
+ # while inside the isolated venv
25
+ pyside_dir = Path(PySide6.__file__).resolve().parent
26
+
27
+ if sys.platform != "win32":
28
+ exe = pyside_dir / "Qt" / "libexec" / "uic"
29
+ else:
30
+ exe = pyside_dir / "uic.exe"
31
+
32
+ cmd = [os.fspath(exe), "-g", "python", "--o", str(outfile), str(infile)]
33
+
34
+ return run(cmd, capture_output=True)
35
+
36
+
37
+ def build_ui(replace=True):
38
+ """
39
+ Compile any .ui files in this folder to the build folder as .py files
40
+
41
+ :param replace: replace existing UI files
42
+ """
43
+ # Scan this folder for .ui files
44
+ root = Path(__file__).parent / "ui" / "layouts"
45
+ ui_files = list(root.glob("*.ui"))
46
+
47
+ # Make the build and __init__ files if they do not exist
48
+ Path(root / "build").mkdir(exist_ok=True)
49
+ Path(root / "build" / "__init__.py").touch(exist_ok=True)
50
+
51
+ print("Building user interface files.")
52
+
53
+ for infile in ui_files:
54
+ outfile = root / "build" / infile.with_suffix(".py").name
55
+
56
+ if replace or not outfile.exists:
57
+ result = uic(infile, outfile)
58
+
59
+ if result.returncode == 0:
60
+ print(f"Read: {infile}\nBuilt: {outfile}\n")
61
+ else:
62
+ raise RuntimeError(
63
+ "Failed to convert .uic layout file to .py: "
64
+ f"code{result.returncode}\n{result.stderr}"
65
+ )
66
+ else:
67
+ print(f"Output file {outfile} already exists")
68
+
69
+
70
+ if __name__ == "__main__":
71
+ build_ui(replace=True)
@@ -0,0 +1,4 @@
1
+ class UnsupportedPlatformError(Exception):
2
+ """
3
+ Error for project not running on Windows or Linux.
4
+ """
splitguides/hotkeys.py ADDED
@@ -0,0 +1,54 @@
1
+ """
2
+ The keyboard library does not handle numpad hotkeys correctly.
3
+
4
+ This is a rewrite of the relevant functions to handle this.
5
+ """
6
+
7
+ import queue as _queue
8
+
9
+ from ducktools.classbuilder.prefab import prefab, attribute, SlotFields
10
+ import keyboard
11
+
12
+
13
+ KEY_DOWN = "down"
14
+ KEY_UP = "up"
15
+
16
+
17
+ @prefab(dict_method=True)
18
+ class Hotkey:
19
+ __slots__ = SlotFields(scancodes=attribute(), name=attribute())
20
+ scancodes: list[int]
21
+ name: str
22
+
23
+
24
+ def hotkey_or_none(keydict):
25
+ return Hotkey(**keydict) if keydict else None
26
+
27
+
28
+ def read_hotkey(suppress: bool = True) -> Hotkey:
29
+ """
30
+ Modified read_hotkey function to correctly support numpad keys.
31
+
32
+ The original function returns just the names, this returns a Hotkey object.
33
+ The scancodes can then be stored while the name can be displayed.
34
+ """
35
+ # This function is only ever called in windows
36
+
37
+ queue = _queue.Queue()
38
+
39
+ # Replace lambda with
40
+ def hook_func(event):
41
+ queue.put(event)
42
+ return event.event_type == KEY_DOWN
43
+
44
+ hooked = keyboard.hook(hook_func, suppress=suppress)
45
+ while True:
46
+ keychange = queue.get()
47
+ if keychange.event_type == KEY_UP:
48
+ keyboard.unhook(hooked)
49
+ with keyboard._pressed_events_lock: # type: ignore
50
+ key_events = list(keyboard._pressed_events.values()) # type: ignore
51
+ key_events.append(keychange)
52
+ key_codes = [e.scan_code for e in key_events]
53
+ key_string = keyboard.get_hotkey_name([e.name for e in key_events])
54
+ return Hotkey(key_codes, key_string)
@@ -0,0 +1,303 @@
1
+ import re
2
+ import socket
3
+ from datetime import timedelta
4
+ import typing
5
+
6
+ from ducktools.classbuilder.prefab import Prefab, attribute
7
+
8
+ BUFFER_SIZE = 4096
9
+
10
+
11
+ pattern = re.compile(
12
+ r"^(?:(?P<hours>\d*):)?(?P<minutes>\d{1,2}):(?P<seconds>\d{2}).(?P<centiseconds>\d*)"
13
+ )
14
+
15
+
16
+ def parse_time(time_str: str) -> timedelta:
17
+ """
18
+ Takes the time string from livesplit and converts to a timedelta
19
+
20
+ :param time_str:
21
+ :return:
22
+ """
23
+ match = pattern.match(time_str)
24
+ if match is None:
25
+ raise RuntimeError("String time from livesplit did not match expected pattern")
26
+
27
+ hours = int(match["hours"]) if match["hours"] else 0
28
+ minutes = int(match["minutes"])
29
+ seconds = int(match["seconds"])
30
+ milliseconds = int(match["centiseconds"]) * 10
31
+
32
+ result = timedelta(
33
+ hours=hours, minutes=minutes, seconds=seconds, milliseconds=milliseconds
34
+ )
35
+
36
+ return result
37
+
38
+
39
+ class LivesplitConnection(Prefab):
40
+ """
41
+ Socket based livesplit connection model
42
+ """
43
+ server: str = "localhost"
44
+ port: int = 16834
45
+ timeout: int = 1
46
+ sock: socket.socket | None = attribute(default=None, init=False, repr=False)
47
+
48
+ def connect(self) -> bool:
49
+ """
50
+ Attempt to connect to the livesplit server
51
+ :return: True if connected, otherwise False
52
+ """
53
+ self.sock = socket.socket()
54
+ try:
55
+ self.sock.connect((self.server, self.port))
56
+ except ConnectionRefusedError:
57
+ self.sock.close()
58
+ self.sock = None
59
+ return False
60
+ except socket.gaierror:
61
+ # Could not resolve hostname
62
+ self.sock.close()
63
+ self.sock = None
64
+ return False
65
+ else:
66
+ self.sock.settimeout(self.timeout)
67
+ return True
68
+
69
+ def close(self) -> None:
70
+ if self.sock:
71
+ self.sock.close()
72
+ self.sock = None
73
+
74
+ def send(self, msg: bytes) -> None:
75
+ """
76
+ Send a message to the livesplit server - connect if not already connected.
77
+ If the connection is aborted (ie: if livesplit server has been closed)
78
+ raise a ConnectionAbortedError
79
+
80
+ :param msg: bytes message to send (should end with "\r\n")
81
+ :return:
82
+ """
83
+ if not self.sock:
84
+ self.connect()
85
+
86
+ if self.sock: # Check again in case connection failed
87
+ try:
88
+ self.sock.send(msg)
89
+ except ConnectionAbortedError:
90
+ self.sock.close()
91
+ self.sock = None
92
+ raise ConnectionAbortedError("The connection has been closed by the host")
93
+
94
+ def receive(self) -> bytes:
95
+ """
96
+ Attempt to receive a message from the livesplit server
97
+ raise ConnectionError if the connection has been terminated.
98
+
99
+ :return: bytes received from the server
100
+ """
101
+ if not self.sock:
102
+ self.connect()
103
+
104
+ if self.sock:
105
+ try:
106
+ data_received = self.sock.recv(BUFFER_SIZE)
107
+ except socket.timeout:
108
+ raise TimeoutError(
109
+ "No response received from the server within "
110
+ f"the timeout period ({self.timeout}s)"
111
+ )
112
+ except OSError:
113
+ self.sock.close()
114
+ self.sock = None
115
+ raise ConnectionError("The connection has been closed by the host")
116
+
117
+ if data_received == b"":
118
+ self.sock.close()
119
+ self.sock = None
120
+ raise ConnectionError("The connection has been closed by the host")
121
+
122
+ return data_received
123
+
124
+ return b""
125
+
126
+
127
+ class LivesplitMessaging(Prefab):
128
+ connection: LivesplitConnection
129
+
130
+ def connect(self) -> bool:
131
+ return self.connection.connect()
132
+
133
+ def close(self) -> None:
134
+ self.connection.close()
135
+
136
+ def send(self, message) -> None:
137
+ m = message.encode("UTF8")
138
+ self.connection.send(m + b"\r\n")
139
+
140
+ @typing.overload
141
+ def receive(self, datatype: typing.Literal["time"]) -> timedelta: ...
142
+ @typing.overload
143
+ def receive(self, datatype: typing.Literal["int"]) -> int: ...
144
+ @typing.overload
145
+ def receive(self, datatype: typing.Literal["text"] = "text") -> str: ...
146
+
147
+ def receive(self, datatype="text"):
148
+ result = self.connection.receive()
149
+ result = result.strip().decode("UTF8")
150
+ if datatype == "time":
151
+ result = parse_time(result)
152
+ elif datatype == "int":
153
+ return int(result)
154
+
155
+ return result
156
+
157
+ def start_timer(self) -> None:
158
+ """
159
+ Start the timer
160
+ """
161
+ self.send("starttimer")
162
+
163
+ def start_or_split(self) -> None:
164
+ """
165
+ Start the timer or split a running timer
166
+ """
167
+ self.send("startorsplit")
168
+
169
+ def split(self) -> None:
170
+ """
171
+ Split
172
+ """
173
+ self.send("split")
174
+
175
+ def unsplit(self) -> None:
176
+ """
177
+ Undo the previous split
178
+ """
179
+ self.send("unsplit")
180
+
181
+ def skip_split(self) -> None:
182
+ """
183
+ Skip the current split
184
+ """
185
+ self.send("skipsplit")
186
+
187
+ def pause(self) -> None:
188
+ """
189
+ Pause the timer
190
+ """
191
+ self.send("pause")
192
+
193
+ def resume(self) -> None:
194
+ """
195
+ Resume a paused timer
196
+ """
197
+ self.send("resume")
198
+
199
+ def reset(self) -> None:
200
+ """
201
+ Reset the timer
202
+ """
203
+ self.send("reset")
204
+
205
+ def init_game_time(self) -> None:
206
+ """
207
+ Activate the game timer
208
+ """
209
+ self.send("initgametime")
210
+
211
+ def set_game_time(self, t: str) -> None:
212
+ """
213
+ Set the game timer
214
+ :param t:
215
+ :return:
216
+ """
217
+ self.send(f"setgametime {t}")
218
+
219
+ def set_loading_times(self, t: str) -> None:
220
+ """
221
+
222
+ :param t:
223
+ """
224
+ self.send(f"setloadingtimes {t}")
225
+
226
+ def pause_game_time(self) -> None:
227
+ """
228
+ Pause the game timer
229
+ """
230
+ self.send("pausegametime")
231
+
232
+ def unpause_game_time(self) -> None:
233
+ """
234
+ Unpause the game timer
235
+ """
236
+ self.send("unpausegametime")
237
+
238
+ def set_comparison(self, comparison) -> None:
239
+ """
240
+ Change the comparison method
241
+
242
+ :param comparison: Time to compare against eg 'Personal Best' or 'Best Segments'
243
+ """
244
+ self.send(f"setcomparison {comparison}")
245
+
246
+ def get_delta(self, comparison=None) -> str:
247
+ if comparison:
248
+ self.send(f"getdelta {comparison}")
249
+ else:
250
+ self.send(f"getdelta")
251
+
252
+ return self.receive()
253
+
254
+ def get_last_split_time(self) -> timedelta:
255
+ self.send("getlastsplittime")
256
+ return self.receive("time")
257
+
258
+ def get_comparison_split_time(self) -> timedelta:
259
+ self.send("getcomparisonsplittime")
260
+ return self.receive("time")
261
+
262
+ def get_current_time(self) -> timedelta:
263
+ self.send("getcurrenttime")
264
+ return self.receive("time")
265
+
266
+ def get_final_time(self, comparison=None) -> timedelta:
267
+ if comparison:
268
+ self.send(f"getfinaltime {comparison}")
269
+ else:
270
+ self.send("getfinaltime")
271
+ return self.receive("time")
272
+
273
+ def get_predicted_time(self, comparison) -> timedelta:
274
+ self.send(f"getpredictedtime {comparison}")
275
+ return self.receive("time")
276
+
277
+ def get_best_possible_time(self) -> timedelta:
278
+ self.send("getbestpossibletime")
279
+ return self.receive("time")
280
+
281
+ def get_split_index(self) -> int:
282
+ self.send("getsplitindex")
283
+ return self.receive("int")
284
+
285
+ def get_current_split_name(self) -> str:
286
+ self.send("getcurrentsplitname")
287
+ return self.receive()
288
+
289
+ def get_previous_split_name(self) -> str:
290
+ self.send("getprevioussplitname")
291
+ return self.receive()
292
+
293
+ def get_current_timer_phase(self) -> str:
294
+ self.send("getcurrenttimerphase")
295
+ return self.receive()
296
+
297
+
298
+ def get_client(
299
+ server: str = "localhost",
300
+ port: int = 16834,
301
+ timeout: int = 1
302
+ ) -> LivesplitMessaging:
303
+ return LivesplitMessaging(connection=LivesplitConnection(server, port, timeout))