quantumgui 1.0.0__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.
- quantumgui/__init__.py +9 -0
- quantumgui/__main__.py +6 -0
- quantumgui/cli.py +341 -0
- quantumgui/core/__init__.py +39 -0
- quantumgui/core/animation.py +221 -0
- quantumgui/core/audit.py +323 -0
- quantumgui/core/context.py +54 -0
- quantumgui/core/data_source.py +426 -0
- quantumgui/core/draw.py +428 -0
- quantumgui/core/enterprise.py +402 -0
- quantumgui/core/enterprise_app.py +419 -0
- quantumgui/core/events.py +34 -0
- quantumgui/core/geometry.py +108 -0
- quantumgui/core/native_dialogs.py +276 -0
- quantumgui/core/pdf_report.py +390 -0
- quantumgui/core/rules.py +284 -0
- quantumgui/core/state.py +42 -0
- quantumgui/core/task_runner.py +181 -0
- quantumgui/core/widget.py +498 -0
- quantumgui/core/window.py +920 -0
- quantumgui/core/xlsx_export.py +145 -0
- quantumgui/py.typed +0 -0
- quantumgui/theme/__init__.py +32 -0
- quantumgui/theme/hct.py +191 -0
- quantumgui/theme/theme.py +93 -0
- quantumgui/theme/tokens.py +423 -0
- quantumgui/ui.py +2142 -0
- quantumgui/widgets/__init__.py +168 -0
- quantumgui/widgets/advanced.py +499 -0
- quantumgui/widgets/button.py +224 -0
- quantumgui/widgets/charts.py +625 -0
- quantumgui/widgets/charts_bi.py +528 -0
- quantumgui/widgets/charts_extra.py +430 -0
- quantumgui/widgets/charts_pro.py +568 -0
- quantumgui/widgets/checkbox.py +199 -0
- quantumgui/widgets/chip.py +219 -0
- quantumgui/widgets/containers.py +321 -0
- quantumgui/widgets/data_controls.py +487 -0
- quantumgui/widgets/data_grid.py +956 -0
- quantumgui/widgets/data_table.py +551 -0
- quantumgui/widgets/date_picker.py +407 -0
- quantumgui/widgets/display_media.py +372 -0
- quantumgui/widgets/display_pro.py +407 -0
- quantumgui/widgets/drawer.py +252 -0
- quantumgui/widgets/enterprise_controls.py +934 -0
- quantumgui/widgets/fab.py +261 -0
- quantumgui/widgets/forms_pro.py +703 -0
- quantumgui/widgets/forms_pro_media.py +587 -0
- quantumgui/widgets/inputs.py +870 -0
- quantumgui/widgets/layout_pro.py +162 -0
- quantumgui/widgets/list_view.py +307 -0
- quantumgui/widgets/masked_input.py +131 -0
- quantumgui/widgets/master_detail.py +155 -0
- quantumgui/widgets/navigation.py +382 -0
- quantumgui/widgets/overlays.py +355 -0
- quantumgui/widgets/productivity.py +500 -0
- quantumgui/widgets/productivity_boards.py +544 -0
- quantumgui/widgets/radio.py +209 -0
- quantumgui/widgets/scroll_view.py +129 -0
- quantumgui/widgets/select.py +373 -0
- quantumgui/widgets/sheets.py +249 -0
- quantumgui/widgets/slider.py +209 -0
- quantumgui/widgets/switch.py +196 -0
- quantumgui/widgets/tabs.py +175 -0
- quantumgui/widgets/text.py +101 -0
- quantumgui/widgets/text_field.py +490 -0
- quantumgui/widgets/time_picker.py +499 -0
- quantumgui-1.0.0.dist-info/METADATA +137 -0
- quantumgui-1.0.0.dist-info/RECORD +73 -0
- quantumgui-1.0.0.dist-info/WHEEL +5 -0
- quantumgui-1.0.0.dist-info/entry_points.txt +2 -0
- quantumgui-1.0.0.dist-info/licenses/LICENSE +32 -0
- quantumgui-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
"""Enterprise Application Architecture:
|
|
2
|
+
- AuthContext (RBAC roles & permissions with live reactive UI updates)
|
|
3
|
+
- I18n (multi-language translations + regional number/currency/date formatting)
|
|
4
|
+
- Router (path routing with `:param` extraction, history back/forward, and RBAC guards)
|
|
5
|
+
- PreferencesStore (JSON persistence for window geometry, theme, locale, and user prefs)
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from datetime import date, datetime
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING, Any, Callable, Iterable, Literal, Mapping
|
|
15
|
+
|
|
16
|
+
from .context import context
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from ..theme import Theme
|
|
20
|
+
from ..widgets.containers import Column
|
|
21
|
+
|
|
22
|
+
# ---------------------------------------------------------------------------
|
|
23
|
+
# 1. RBAC — AuthContext (Roles & Permissions)
|
|
24
|
+
# ---------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AuthContext:
|
|
28
|
+
"""Reactive Role-Based Access Control (RBAC) state for Enterprise apps."""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
*,
|
|
33
|
+
user: str | None = None,
|
|
34
|
+
roles: Iterable[str] = (),
|
|
35
|
+
permissions: Iterable[str] = (),
|
|
36
|
+
) -> None:
|
|
37
|
+
self._user: str | None = user
|
|
38
|
+
self._roles: set[str] = set(roles)
|
|
39
|
+
self._permissions: set[str] = set(permissions)
|
|
40
|
+
self._listeners: list[Callable[[AuthContext], None]] = []
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def user(self) -> str | None:
|
|
44
|
+
return self._user
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def is_authenticated(self) -> bool:
|
|
48
|
+
return self._user is not None
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def roles(self) -> frozenset[str]:
|
|
52
|
+
return frozenset(self._roles)
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def permissions(self) -> frozenset[str]:
|
|
56
|
+
return frozenset(self._permissions)
|
|
57
|
+
|
|
58
|
+
def set_user(
|
|
59
|
+
self,
|
|
60
|
+
user: str | None,
|
|
61
|
+
*,
|
|
62
|
+
roles: Iterable[str] = (),
|
|
63
|
+
permissions: Iterable[str] = (),
|
|
64
|
+
) -> None:
|
|
65
|
+
self._user = user
|
|
66
|
+
self._roles = set(roles)
|
|
67
|
+
self._permissions = set(permissions)
|
|
68
|
+
self._notify()
|
|
69
|
+
|
|
70
|
+
def logout(self) -> None:
|
|
71
|
+
self.set_user(None, roles=(), permissions=())
|
|
72
|
+
|
|
73
|
+
def has_role(self, role: str | Iterable[str]) -> bool:
|
|
74
|
+
if isinstance(role, str):
|
|
75
|
+
return role in self._roles
|
|
76
|
+
return any(r in self._roles for r in role)
|
|
77
|
+
|
|
78
|
+
def has_permission(self, permission: str | Iterable[str]) -> bool:
|
|
79
|
+
if isinstance(permission, str):
|
|
80
|
+
return permission in self._permissions
|
|
81
|
+
return any(p in self._permissions for p in permission)
|
|
82
|
+
|
|
83
|
+
def subscribe(self, listener: Callable[[AuthContext], None]) -> Callable[[], None]:
|
|
84
|
+
self._listeners.append(listener)
|
|
85
|
+
|
|
86
|
+
def _unsub() -> None:
|
|
87
|
+
if listener in self._listeners:
|
|
88
|
+
self._listeners.remove(listener)
|
|
89
|
+
|
|
90
|
+
return _unsub
|
|
91
|
+
|
|
92
|
+
def _notify(self) -> None:
|
|
93
|
+
for fn in list(self._listeners):
|
|
94
|
+
fn(self)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
default_auth = AuthContext()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# ---------------------------------------------------------------------------
|
|
101
|
+
# 2. I18n — Multi-language Translations & Regional Formats
|
|
102
|
+
# ---------------------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
_LOCALE_FORMATS: dict[str, dict[str, str]] = {
|
|
105
|
+
"es": {"thousands": ".", "decimal": ",", "date": "%d/%m/%Y"},
|
|
106
|
+
"pt": {"thousands": ".", "decimal": ",", "date": "%d/%m/%Y"},
|
|
107
|
+
"de": {"thousands": ".", "decimal": ",", "date": "%d.%m.%Y"},
|
|
108
|
+
"fr": {"thousands": " ", "decimal": ",", "date": "%d/%m/%Y"},
|
|
109
|
+
"en": {"thousands": ",", "decimal": ".", "date": "%m/%d/%Y"},
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class I18n:
|
|
114
|
+
"""Reactive internationalization & regional formatting engine (zero external deps)."""
|
|
115
|
+
|
|
116
|
+
def __init__(
|
|
117
|
+
self,
|
|
118
|
+
locale: str = "es",
|
|
119
|
+
translations: Mapping[str, Mapping[str, str]] | None = None,
|
|
120
|
+
*,
|
|
121
|
+
fallback_locale: str = "es",
|
|
122
|
+
) -> None:
|
|
123
|
+
self._locale = locale.lower()
|
|
124
|
+
self.fallback_locale = fallback_locale.lower()
|
|
125
|
+
self._translations: dict[str, dict[str, str]] = {
|
|
126
|
+
k.lower(): dict(v) for k, v in (translations or {}).items()
|
|
127
|
+
}
|
|
128
|
+
self._listeners: list[Callable[[str], None]] = []
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def locale(self) -> str:
|
|
132
|
+
return self._locale
|
|
133
|
+
|
|
134
|
+
@locale.setter
|
|
135
|
+
def locale(self, value: str) -> None:
|
|
136
|
+
val = value.lower()
|
|
137
|
+
if val != self._locale:
|
|
138
|
+
self._locale = val
|
|
139
|
+
for fn in list(self._listeners):
|
|
140
|
+
fn(val)
|
|
141
|
+
|
|
142
|
+
def add_translations(self, locale: str, mapping: Mapping[str, str]) -> None:
|
|
143
|
+
loc = locale.lower()
|
|
144
|
+
self._translations.setdefault(loc, {}).update(mapping)
|
|
145
|
+
|
|
146
|
+
def subscribe(self, listener: Callable[[str], None]) -> Callable[[], None]:
|
|
147
|
+
self._listeners.append(listener)
|
|
148
|
+
|
|
149
|
+
def _unsub() -> None:
|
|
150
|
+
if listener in self._listeners:
|
|
151
|
+
self._listeners.remove(listener)
|
|
152
|
+
|
|
153
|
+
return _unsub
|
|
154
|
+
|
|
155
|
+
def t(self, key: str, **kwargs: Any) -> str:
|
|
156
|
+
"""Translate `key` in the active locale (with fallback & `{var}` interpolation)."""
|
|
157
|
+
lang_short = self._locale.split("-")[0].split("_")[0]
|
|
158
|
+
raw = (
|
|
159
|
+
self._translations.get(self._locale, {}).get(key)
|
|
160
|
+
or self._translations.get(lang_short, {}).get(key)
|
|
161
|
+
or self._translations.get(self.fallback_locale, {}).get(key)
|
|
162
|
+
or key
|
|
163
|
+
)
|
|
164
|
+
return raw.format(**kwargs) if kwargs else raw
|
|
165
|
+
|
|
166
|
+
def text(self, key: str, **kwargs: Any) -> Callable[[], str]:
|
|
167
|
+
"""Return a reactive zero-arg callable for `ui.text(i18n.text('hello'))`."""
|
|
168
|
+
return lambda: self.t(key, **kwargs)
|
|
169
|
+
|
|
170
|
+
def _fmt_spec(self) -> dict[str, str]:
|
|
171
|
+
short = self._locale.split("-")[0].split("_")[0]
|
|
172
|
+
return _LOCALE_FORMATS.get(short, _LOCALE_FORMATS["en"])
|
|
173
|
+
|
|
174
|
+
def format_number(self, value: float, decimals: int = 2) -> str:
|
|
175
|
+
spec = self._fmt_spec()
|
|
176
|
+
formatted = f"{float(value):,.{decimals}f}"
|
|
177
|
+
if spec["thousands"] == "," and spec["decimal"] == ".":
|
|
178
|
+
return formatted
|
|
179
|
+
return (
|
|
180
|
+
formatted.replace(",", "\x00")
|
|
181
|
+
.replace(".", spec["decimal"])
|
|
182
|
+
.replace("\x00", spec["thousands"])
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
def format_currency(self, value: float, symbol: str = "$", decimals: int = 2) -> str:
|
|
186
|
+
sign = "-" if value < 0 else ""
|
|
187
|
+
return f"{sign}{symbol}{self.format_number(abs(value), decimals=decimals)}"
|
|
188
|
+
|
|
189
|
+
def format_date(self, value: date | datetime) -> str:
|
|
190
|
+
return value.strftime(self._fmt_spec()["date"])
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
# ---------------------------------------------------------------------------
|
|
194
|
+
# 3. Router — History, `:param` Matching, RBAC Guards & Reactive View
|
|
195
|
+
# ---------------------------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class _RouteEntry:
|
|
199
|
+
def __init__(
|
|
200
|
+
self,
|
|
201
|
+
pattern: str,
|
|
202
|
+
builder: Callable[[dict[str, str]], None],
|
|
203
|
+
*,
|
|
204
|
+
required_role: str | Iterable[str] | None = None,
|
|
205
|
+
required_permission: str | Iterable[str] | None = None,
|
|
206
|
+
) -> None:
|
|
207
|
+
self.pattern = pattern
|
|
208
|
+
self.builder = builder
|
|
209
|
+
self.required_role = required_role
|
|
210
|
+
self.required_permission = required_permission
|
|
211
|
+
# Convert `/clients/:id/orders/:oid` -> regex with named groups
|
|
212
|
+
regex_str = re.sub(r":([A-Za-z_][A-Za-z0-9_]*)", r"(?P<\1>[^/]+)", pattern.rstrip("/") or "/")
|
|
213
|
+
self._regex = re.compile(f"^{regex_str}$")
|
|
214
|
+
|
|
215
|
+
def match(self, path: str) -> dict[str, str] | None:
|
|
216
|
+
norm = path.rstrip("/") or "/"
|
|
217
|
+
m = self._regex.match(norm)
|
|
218
|
+
return m.groupdict() if m else None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class Router:
|
|
222
|
+
"""Desktop SPA Router with history stack (back/forward), `:param` extraction, and RBAC guards."""
|
|
223
|
+
|
|
224
|
+
def __init__(
|
|
225
|
+
self,
|
|
226
|
+
*,
|
|
227
|
+
initial: str = "/",
|
|
228
|
+
auth: AuthContext | None = None,
|
|
229
|
+
on_denied: Callable[[str], None] | None = None,
|
|
230
|
+
) -> None:
|
|
231
|
+
self.auth = auth or default_auth
|
|
232
|
+
self.on_denied = on_denied
|
|
233
|
+
self._routes: list[_RouteEntry] = []
|
|
234
|
+
self._history: list[str] = [initial.rstrip("/") or "/"]
|
|
235
|
+
self._index: int = 0
|
|
236
|
+
self._params: dict[str, str] = {}
|
|
237
|
+
self._host: Column | None = None
|
|
238
|
+
self._listeners: list[Callable[[str, dict[str, str]], None]] = []
|
|
239
|
+
|
|
240
|
+
@property
|
|
241
|
+
def current_path(self) -> str:
|
|
242
|
+
return self._history[self._index]
|
|
243
|
+
|
|
244
|
+
@property
|
|
245
|
+
def params(self) -> dict[str, str]:
|
|
246
|
+
return dict(self._params)
|
|
247
|
+
|
|
248
|
+
@property
|
|
249
|
+
def can_go_back(self) -> bool:
|
|
250
|
+
return self._index > 0
|
|
251
|
+
|
|
252
|
+
@property
|
|
253
|
+
def can_go_forward(self) -> bool:
|
|
254
|
+
return self._index < len(self._history) - 1
|
|
255
|
+
|
|
256
|
+
def route(
|
|
257
|
+
self,
|
|
258
|
+
pattern: str,
|
|
259
|
+
builder: Callable[[dict[str, str]], None],
|
|
260
|
+
*,
|
|
261
|
+
required_role: str | Iterable[str] | None = None,
|
|
262
|
+
required_permission: str | Iterable[str] | None = None,
|
|
263
|
+
) -> Router:
|
|
264
|
+
self._routes.append(
|
|
265
|
+
_RouteEntry(
|
|
266
|
+
pattern,
|
|
267
|
+
builder,
|
|
268
|
+
required_role=required_role,
|
|
269
|
+
required_permission=required_permission,
|
|
270
|
+
)
|
|
271
|
+
)
|
|
272
|
+
return self
|
|
273
|
+
|
|
274
|
+
def subscribe(self, listener: Callable[[str, dict[str, str]], None]) -> Callable[[], None]:
|
|
275
|
+
self._listeners.append(listener)
|
|
276
|
+
|
|
277
|
+
def _unsub() -> None:
|
|
278
|
+
if listener in self._listeners:
|
|
279
|
+
self._listeners.remove(listener)
|
|
280
|
+
|
|
281
|
+
return _unsub
|
|
282
|
+
|
|
283
|
+
def _resolve(self, path: str) -> tuple[_RouteEntry | None, dict[str, str]]:
|
|
284
|
+
for entry in self._routes:
|
|
285
|
+
params = entry.match(path)
|
|
286
|
+
if params is not None:
|
|
287
|
+
return (entry, params)
|
|
288
|
+
return (None, {})
|
|
289
|
+
|
|
290
|
+
def _check_access(self, entry: _RouteEntry, path: str) -> bool:
|
|
291
|
+
if entry.required_role is not None and not self.auth.has_role(entry.required_role):
|
|
292
|
+
if self.on_denied is not None:
|
|
293
|
+
self.on_denied(path)
|
|
294
|
+
return False
|
|
295
|
+
if entry.required_permission is not None and not self.auth.has_permission(entry.required_permission):
|
|
296
|
+
if self.on_denied is not None:
|
|
297
|
+
self.on_denied(path)
|
|
298
|
+
return False
|
|
299
|
+
return True
|
|
300
|
+
|
|
301
|
+
def navigate(self, path: str) -> bool:
|
|
302
|
+
norm = path.rstrip("/") or "/"
|
|
303
|
+
entry, params = self._resolve(norm)
|
|
304
|
+
if entry is None:
|
|
305
|
+
return False
|
|
306
|
+
if not self._check_access(entry, norm):
|
|
307
|
+
return False
|
|
308
|
+
if norm != self.current_path:
|
|
309
|
+
self._history = self._history[: self._index + 1]
|
|
310
|
+
self._history.append(norm)
|
|
311
|
+
self._index = len(self._history) - 1
|
|
312
|
+
self._params = params
|
|
313
|
+
self._render_current()
|
|
314
|
+
for fn in list(self._listeners):
|
|
315
|
+
fn(norm, dict(params))
|
|
316
|
+
return True
|
|
317
|
+
|
|
318
|
+
def back(self) -> bool:
|
|
319
|
+
if not self.can_go_back:
|
|
320
|
+
return False
|
|
321
|
+
target = self._history[self._index - 1]
|
|
322
|
+
entry, params = self._resolve(target)
|
|
323
|
+
if entry is None or not self._check_access(entry, target):
|
|
324
|
+
return False
|
|
325
|
+
self._index -= 1
|
|
326
|
+
self._params = params
|
|
327
|
+
self._render_current()
|
|
328
|
+
for fn in list(self._listeners):
|
|
329
|
+
fn(target, dict(params))
|
|
330
|
+
return True
|
|
331
|
+
|
|
332
|
+
def forward(self) -> bool:
|
|
333
|
+
if not self.can_go_forward:
|
|
334
|
+
return False
|
|
335
|
+
target = self._history[self._index + 1]
|
|
336
|
+
entry, params = self._resolve(target)
|
|
337
|
+
if entry is None or not self._check_access(entry, target):
|
|
338
|
+
return False
|
|
339
|
+
self._index += 1
|
|
340
|
+
self._params = params
|
|
341
|
+
self._render_current()
|
|
342
|
+
for fn in list(self._listeners):
|
|
343
|
+
fn(target, dict(params))
|
|
344
|
+
return True
|
|
345
|
+
|
|
346
|
+
def view(self, *, gap: float = 12.0) -> Column:
|
|
347
|
+
"""Create and mount the reactive route host container inside the current `with` block."""
|
|
348
|
+
from ..widgets.containers import Column
|
|
349
|
+
|
|
350
|
+
host = Column(gap=gap, align="stretch").fill_width()
|
|
351
|
+
self._host = host
|
|
352
|
+
self._render_current()
|
|
353
|
+
return host
|
|
354
|
+
|
|
355
|
+
def _render_current(self) -> None:
|
|
356
|
+
if self._host is None:
|
|
357
|
+
return
|
|
358
|
+
entry, params = self._resolve(self.current_path)
|
|
359
|
+
self._params = params
|
|
360
|
+
self._host.children.clear()
|
|
361
|
+
if entry is not None and self._check_access(entry, self.current_path):
|
|
362
|
+
with self._host:
|
|
363
|
+
entry.builder(dict(params))
|
|
364
|
+
self._host.invalidate()
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
# ---------------------------------------------------------------------------
|
|
368
|
+
# 4. PreferencesStore — Automatic JSON Persistence
|
|
369
|
+
# ---------------------------------------------------------------------------
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
class PreferencesStore:
|
|
373
|
+
"""Lightweight JSON preference store for persisting theme, locale, window geometry & settings."""
|
|
374
|
+
|
|
375
|
+
def __init__(self, app_name: str = "quantumgui_app", *, path: str | Path | None = None) -> None:
|
|
376
|
+
self.path: Path = (
|
|
377
|
+
Path(path)
|
|
378
|
+
if path is not None
|
|
379
|
+
else Path.home() / ".quantumgui" / f"{app_name}.json"
|
|
380
|
+
)
|
|
381
|
+
self._data: dict[str, Any] = {}
|
|
382
|
+
self.load()
|
|
383
|
+
|
|
384
|
+
def load(self) -> None:
|
|
385
|
+
if self.path.exists():
|
|
386
|
+
try:
|
|
387
|
+
loaded = json.loads(self.path.read_text(encoding="utf-8"))
|
|
388
|
+
if isinstance(loaded, dict):
|
|
389
|
+
self._data = loaded
|
|
390
|
+
except Exception:
|
|
391
|
+
self._data = {}
|
|
392
|
+
|
|
393
|
+
def save(self) -> None:
|
|
394
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
395
|
+
self.path.write_text(json.dumps(self._data, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
396
|
+
|
|
397
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
398
|
+
return self._data.get(key, default)
|
|
399
|
+
|
|
400
|
+
def set(self, key: str, value: Any, *, auto_save: bool = True) -> None:
|
|
401
|
+
self._data[key] = value
|
|
402
|
+
if auto_save:
|
|
403
|
+
self.save()
|
|
404
|
+
|
|
405
|
+
def bind_theme(self, theme: Theme) -> None:
|
|
406
|
+
"""Restore saved `theme.seed`/`theme.mode` and persist future changes automatically."""
|
|
407
|
+
saved_seed = self.get("theme.seed")
|
|
408
|
+
saved_mode = self.get("theme.mode")
|
|
409
|
+
if isinstance(saved_seed, str):
|
|
410
|
+
theme.seed = saved_seed
|
|
411
|
+
if saved_mode in ("light", "dark"):
|
|
412
|
+
theme.mode = saved_mode
|
|
413
|
+
|
|
414
|
+
def _on_change() -> None:
|
|
415
|
+
self._data["theme.seed"] = theme.seed.to_hex()
|
|
416
|
+
self._data["theme.mode"] = theme.mode
|
|
417
|
+
self.save()
|
|
418
|
+
|
|
419
|
+
theme.subscribe(_on_change)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Input event dataclasses."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(slots=True)
|
|
9
|
+
class MouseEvent:
|
|
10
|
+
x: float
|
|
11
|
+
y: float
|
|
12
|
+
button: int = 0 # 0=left, 1=right, 2=middle
|
|
13
|
+
mods: int = 0
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(slots=True)
|
|
17
|
+
class KeyEvent:
|
|
18
|
+
key: int
|
|
19
|
+
scancode: int
|
|
20
|
+
action: int # 1=press, 2=repeat, 0=release
|
|
21
|
+
mods: int
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(slots=True)
|
|
25
|
+
class CharEvent:
|
|
26
|
+
char: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(slots=True)
|
|
30
|
+
class ScrollEvent:
|
|
31
|
+
x: float
|
|
32
|
+
y: float
|
|
33
|
+
dx: float
|
|
34
|
+
dy: float
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Geometry primitives for layout and hit-testing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class Size:
|
|
10
|
+
width: float
|
|
11
|
+
height: float
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True, slots=True)
|
|
15
|
+
class Rect:
|
|
16
|
+
x: float
|
|
17
|
+
y: float
|
|
18
|
+
width: float
|
|
19
|
+
height: float
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def right(self) -> float:
|
|
23
|
+
return self.x + self.width
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def bottom(self) -> float:
|
|
27
|
+
return self.y + self.height
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def center_x(self) -> float:
|
|
31
|
+
return self.x + self.width * 0.5
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def center_y(self) -> float:
|
|
35
|
+
return self.y + self.height * 0.5
|
|
36
|
+
|
|
37
|
+
def contains(self, px: float, py: float) -> bool:
|
|
38
|
+
return self.x <= px <= self.right and self.y <= py <= self.bottom
|
|
39
|
+
|
|
40
|
+
def inset(self, insets: EdgeInsets) -> Rect:
|
|
41
|
+
return Rect(
|
|
42
|
+
self.x + insets.left,
|
|
43
|
+
self.y + insets.top,
|
|
44
|
+
max(0.0, self.width - insets.horizontal),
|
|
45
|
+
max(0.0, self.height - insets.vertical),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True, slots=True)
|
|
50
|
+
class EdgeInsets:
|
|
51
|
+
top: float = 0.0
|
|
52
|
+
right: float = 0.0
|
|
53
|
+
bottom: float = 0.0
|
|
54
|
+
left: float = 0.0
|
|
55
|
+
|
|
56
|
+
@classmethod
|
|
57
|
+
def all(cls, value: float) -> EdgeInsets:
|
|
58
|
+
v = float(value)
|
|
59
|
+
return cls(v, v, v, v)
|
|
60
|
+
|
|
61
|
+
@classmethod
|
|
62
|
+
def symmetric(cls, *, horizontal: float = 0.0, vertical: float = 0.0) -> EdgeInsets:
|
|
63
|
+
return cls(float(vertical), float(horizontal), float(vertical), float(horizontal))
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def parse(
|
|
67
|
+
cls,
|
|
68
|
+
value: float | tuple[float, float] | tuple[float, float, float, float] | EdgeInsets,
|
|
69
|
+
) -> EdgeInsets:
|
|
70
|
+
if isinstance(value, EdgeInsets):
|
|
71
|
+
return value
|
|
72
|
+
if isinstance(value, (int, float)):
|
|
73
|
+
return cls.all(float(value))
|
|
74
|
+
if isinstance(value, tuple):
|
|
75
|
+
if len(value) == 2:
|
|
76
|
+
return cls.symmetric(vertical=value[0], horizontal=value[1])
|
|
77
|
+
if len(value) == 4:
|
|
78
|
+
return cls(float(value[0]), float(value[1]), float(value[2]), float(value[3]))
|
|
79
|
+
raise ValueError(f"Unsupported insets value: {value!r}")
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def horizontal(self) -> float:
|
|
83
|
+
return self.left + self.right
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def vertical(self) -> float:
|
|
87
|
+
return self.top + self.bottom
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True, slots=True)
|
|
91
|
+
class Constraints:
|
|
92
|
+
min_width: float = 0.0
|
|
93
|
+
max_width: float = float("inf")
|
|
94
|
+
min_height: float = 0.0
|
|
95
|
+
max_height: float = float("inf")
|
|
96
|
+
|
|
97
|
+
def clamp_width(self, w: float) -> float:
|
|
98
|
+
return max(self.min_width, min(self.max_width, w))
|
|
99
|
+
|
|
100
|
+
def clamp_height(self, h: float) -> float:
|
|
101
|
+
return max(self.min_height, min(self.max_height, h))
|
|
102
|
+
|
|
103
|
+
def deflate(self, insets: EdgeInsets) -> Constraints:
|
|
104
|
+
max_w = max(0.0, self.max_width - insets.horizontal) if self.max_width != float("inf") else float("inf")
|
|
105
|
+
max_h = max(0.0, self.max_height - insets.vertical) if self.max_height != float("inf") else float("inf")
|
|
106
|
+
min_w = max(0.0, min(self.min_width - insets.horizontal, max_w))
|
|
107
|
+
min_h = max(0.0, min(self.min_height - insets.vertical, max_h))
|
|
108
|
+
return Constraints(min_w, max_w, min_h, max_h)
|