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.
Files changed (73) hide show
  1. quantumgui/__init__.py +9 -0
  2. quantumgui/__main__.py +6 -0
  3. quantumgui/cli.py +341 -0
  4. quantumgui/core/__init__.py +39 -0
  5. quantumgui/core/animation.py +221 -0
  6. quantumgui/core/audit.py +323 -0
  7. quantumgui/core/context.py +54 -0
  8. quantumgui/core/data_source.py +426 -0
  9. quantumgui/core/draw.py +428 -0
  10. quantumgui/core/enterprise.py +402 -0
  11. quantumgui/core/enterprise_app.py +419 -0
  12. quantumgui/core/events.py +34 -0
  13. quantumgui/core/geometry.py +108 -0
  14. quantumgui/core/native_dialogs.py +276 -0
  15. quantumgui/core/pdf_report.py +390 -0
  16. quantumgui/core/rules.py +284 -0
  17. quantumgui/core/state.py +42 -0
  18. quantumgui/core/task_runner.py +181 -0
  19. quantumgui/core/widget.py +498 -0
  20. quantumgui/core/window.py +920 -0
  21. quantumgui/core/xlsx_export.py +145 -0
  22. quantumgui/py.typed +0 -0
  23. quantumgui/theme/__init__.py +32 -0
  24. quantumgui/theme/hct.py +191 -0
  25. quantumgui/theme/theme.py +93 -0
  26. quantumgui/theme/tokens.py +423 -0
  27. quantumgui/ui.py +2142 -0
  28. quantumgui/widgets/__init__.py +168 -0
  29. quantumgui/widgets/advanced.py +499 -0
  30. quantumgui/widgets/button.py +224 -0
  31. quantumgui/widgets/charts.py +625 -0
  32. quantumgui/widgets/charts_bi.py +528 -0
  33. quantumgui/widgets/charts_extra.py +430 -0
  34. quantumgui/widgets/charts_pro.py +568 -0
  35. quantumgui/widgets/checkbox.py +199 -0
  36. quantumgui/widgets/chip.py +219 -0
  37. quantumgui/widgets/containers.py +321 -0
  38. quantumgui/widgets/data_controls.py +487 -0
  39. quantumgui/widgets/data_grid.py +956 -0
  40. quantumgui/widgets/data_table.py +551 -0
  41. quantumgui/widgets/date_picker.py +407 -0
  42. quantumgui/widgets/display_media.py +372 -0
  43. quantumgui/widgets/display_pro.py +407 -0
  44. quantumgui/widgets/drawer.py +252 -0
  45. quantumgui/widgets/enterprise_controls.py +934 -0
  46. quantumgui/widgets/fab.py +261 -0
  47. quantumgui/widgets/forms_pro.py +703 -0
  48. quantumgui/widgets/forms_pro_media.py +587 -0
  49. quantumgui/widgets/inputs.py +870 -0
  50. quantumgui/widgets/layout_pro.py +162 -0
  51. quantumgui/widgets/list_view.py +307 -0
  52. quantumgui/widgets/masked_input.py +131 -0
  53. quantumgui/widgets/master_detail.py +155 -0
  54. quantumgui/widgets/navigation.py +382 -0
  55. quantumgui/widgets/overlays.py +355 -0
  56. quantumgui/widgets/productivity.py +500 -0
  57. quantumgui/widgets/productivity_boards.py +544 -0
  58. quantumgui/widgets/radio.py +209 -0
  59. quantumgui/widgets/scroll_view.py +129 -0
  60. quantumgui/widgets/select.py +373 -0
  61. quantumgui/widgets/sheets.py +249 -0
  62. quantumgui/widgets/slider.py +209 -0
  63. quantumgui/widgets/switch.py +196 -0
  64. quantumgui/widgets/tabs.py +175 -0
  65. quantumgui/widgets/text.py +101 -0
  66. quantumgui/widgets/text_field.py +490 -0
  67. quantumgui/widgets/time_picker.py +499 -0
  68. quantumgui-1.0.0.dist-info/METADATA +137 -0
  69. quantumgui-1.0.0.dist-info/RECORD +73 -0
  70. quantumgui-1.0.0.dist-info/WHEEL +5 -0
  71. quantumgui-1.0.0.dist-info/entry_points.txt +2 -0
  72. quantumgui-1.0.0.dist-info/licenses/LICENSE +32 -0
  73. quantumgui-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,402 @@
1
+ """Enterprise utilities: ShortcutManager, background tasks, Skia PDF export, and Form validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import threading
7
+ import time
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING, Any, Callable, Sequence
10
+
11
+ import glfw
12
+ import skia
13
+
14
+ from .geometry import Constraints, Rect
15
+
16
+ if TYPE_CHECKING:
17
+ from .widget import Widget
18
+ from .window import Window
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # 1. Global Keyboard Shortcut Manager
22
+ # ---------------------------------------------------------------------------
23
+
24
+ _KEY_NAME_MAP: dict[str, int] = {
25
+ "SPACE": glfw.KEY_SPACE,
26
+ "ENTER": glfw.KEY_ENTER,
27
+ "RETURN": glfw.KEY_ENTER,
28
+ "TAB": glfw.KEY_TAB,
29
+ "ESC": glfw.KEY_ESCAPE,
30
+ "ESCAPE": glfw.KEY_ESCAPE,
31
+ "BACKSPACE": glfw.KEY_BACKSPACE,
32
+ "DELETE": glfw.KEY_DELETE,
33
+ "DEL": glfw.KEY_DELETE,
34
+ "INSERT": glfw.KEY_INSERT,
35
+ "HOME": glfw.KEY_HOME,
36
+ "END": glfw.KEY_END,
37
+ "PAGEUP": glfw.KEY_PAGE_UP,
38
+ "PAGEDOWN": glfw.KEY_PAGE_DOWN,
39
+ "UP": glfw.KEY_UP,
40
+ "DOWN": glfw.KEY_DOWN,
41
+ "LEFT": glfw.KEY_LEFT,
42
+ "RIGHT": glfw.KEY_RIGHT,
43
+ "PLUS": glfw.KEY_EQUAL,
44
+ "MINUS": glfw.KEY_MINUS,
45
+ **{chr(c): getattr(glfw, f"KEY_{chr(c)}") for c in range(ord("A"), ord("Z") + 1)},
46
+ **{str(d): getattr(glfw, f"KEY_{d}") for d in range(10)},
47
+ **{f"F{n}": getattr(glfw, f"KEY_F{n}") for n in range(1, 13)},
48
+ }
49
+
50
+ _MOD_MASK = glfw.MOD_CONTROL | glfw.MOD_SHIFT | glfw.MOD_ALT | glfw.MOD_SUPER
51
+
52
+
53
+ def parse_shortcut(combo: str) -> tuple[int, int]:
54
+ """Parse a human-readable shortcut like `'Ctrl+Shift+S'` or `'F2'` into `(glfw_key, mods)`."""
55
+ parts = [p.strip().upper() for p in combo.split("+") if p.strip()]
56
+ if not parts:
57
+ raise ValueError(f"Invalid empty shortcut: {combo!r}")
58
+ mods = 0
59
+ key_token = parts[-1]
60
+ for mod in parts[:-1]:
61
+ if mod in ("CTRL", "CONTROL"):
62
+ mods |= glfw.MOD_CONTROL
63
+ elif mod == "SHIFT":
64
+ mods |= glfw.MOD_SHIFT
65
+ elif mod == "ALT":
66
+ mods |= glfw.MOD_ALT
67
+ elif mod in ("CMD", "META", "SUPER", "WIN"):
68
+ mods |= glfw.MOD_SUPER
69
+ else:
70
+ raise ValueError(f"Unknown shortcut modifier {mod!r} in {combo!r}")
71
+ if key_token not in _KEY_NAME_MAP:
72
+ raise ValueError(f"Unknown shortcut key {key_token!r} in {combo!r}")
73
+ return (_KEY_NAME_MAP[key_token], mods)
74
+
75
+
76
+ class ShortcutManager:
77
+ """Window-scoped global keyboard shortcut registry."""
78
+
79
+ def __init__(self) -> None:
80
+ self._bindings: dict[tuple[int, int], Callable[[], None]] = {}
81
+
82
+ def register(self, combo: str, callback: Callable[[], None]) -> None:
83
+ key, mods = parse_shortcut(combo)
84
+ self._bindings[(key, mods)] = callback
85
+
86
+ def unregister(self, combo: str) -> None:
87
+ key, mods = parse_shortcut(combo)
88
+ self._bindings.pop((key, mods), None)
89
+
90
+ def clear(self) -> None:
91
+ self._bindings.clear()
92
+
93
+ def dispatch(self, key: int, mods: int) -> bool:
94
+ cb = self._bindings.get((key, mods & _MOD_MASK))
95
+ if cb is None:
96
+ return False
97
+ cb()
98
+ return True
99
+
100
+
101
+ # ---------------------------------------------------------------------------
102
+ # 2. Thread-Safe Background Execution & Timers
103
+ # ---------------------------------------------------------------------------
104
+
105
+
106
+ def run_in_background(
107
+ task: Callable[[], Any],
108
+ *,
109
+ on_done: Callable[[Any], None] | None = None,
110
+ on_error: Callable[[Exception], None] | None = None,
111
+ window: Window | None = None,
112
+ ) -> threading.Thread:
113
+ """Execute `task` on a daemon worker thread and marshal callbacks to the UI thread."""
114
+ from .window import window_manager
115
+
116
+ def _worker() -> None:
117
+ try:
118
+ result = task()
119
+ except Exception as exc: # noqa: BLE001
120
+ if on_error is not None:
121
+ window_manager.call_soon(lambda e=exc: on_error(e))
122
+ elif window is not None:
123
+ window_manager.call_soon(lambda e=exc: window._handle_error(e))
124
+ return
125
+ if on_done is not None:
126
+ window_manager.call_soon(lambda r=result: on_done(r))
127
+ elif window is not None:
128
+ window_manager.call_soon(window.request_redraw)
129
+
130
+ t = threading.Thread(target=_worker, daemon=True)
131
+ t.start()
132
+ return t
133
+
134
+
135
+ def call_later(delay_seconds: float, callback: Callable[[], None]) -> threading.Timer:
136
+ """Schedule `callback` to execute on the main UI thread after `delay_seconds`."""
137
+ from .window import window_manager
138
+
139
+ def _fire() -> None:
140
+ window_manager.call_soon(callback)
141
+
142
+ timer = threading.Timer(max(0.0, float(delay_seconds)), _fire)
143
+ timer.daemon = True
144
+ timer.start()
145
+ return timer
146
+
147
+
148
+ # ---------------------------------------------------------------------------
149
+ # 3. Native Vector PDF Export via Skia (`skia.PDF`)
150
+ # ---------------------------------------------------------------------------
151
+
152
+ PAGE_SIZES: dict[str, tuple[float, float]] = {
153
+ "A4": (595.0, 842.0),
154
+ "A4_LANDSCAPE": (842.0, 595.0),
155
+ "LETTER": (612.0, 792.0),
156
+ "LETTER_LANDSCAPE": (792.0, 612.0),
157
+ }
158
+
159
+
160
+ def export_pdf(
161
+ target: Window | Widget,
162
+ path: str | Path | None = None,
163
+ *,
164
+ page_size: str | tuple[float, float] | None = None,
165
+ margin: float = 24.0,
166
+ ) -> Path | bytes:
167
+ """Render a `Window` or standalone `Widget` to a crisp vector PDF using Skia's native PDF backend.
168
+
169
+ If `path` is provided, writes the PDF to disk and returns the `Path`.
170
+ If `path` is `None`, returns the raw PDF `bytes`.
171
+ """
172
+ from ..theme import Theme
173
+ from .window import Window
174
+
175
+ if isinstance(target, Window):
176
+ logical_w = float(target.width)
177
+ logical_h = float(target.height)
178
+ paint_fn = lambda canvas: target._paint_frame( # noqa: E731
179
+ canvas, logical_w, logical_h, 1.0, time.perf_counter()
180
+ )
181
+ else:
182
+ win = target.window
183
+ theme = win.theme if win is not None else Theme()
184
+ if target.rect.width <= 0.0 or target.rect.height <= 0.0:
185
+ sz = target.measure(Constraints(0.0, 800.0, 0.0, float("inf")), theme)
186
+ target.layout(Rect(0.0, 0.0, max(1.0, sz.width), max(1.0, sz.height)), theme)
187
+ logical_w = max(1.0, target.rect.width)
188
+ logical_h = max(1.0, target.rect.height)
189
+
190
+ def paint_fn(canvas: skia.Canvas) -> None:
191
+ canvas.save()
192
+ canvas.translate(-target.rect.x, -target.rect.y)
193
+ target.paint(canvas, theme, time.perf_counter())
194
+ canvas.restore()
195
+
196
+ if page_size is None:
197
+ pw, ph = logical_w + margin * 2.0, logical_h + margin * 2.0
198
+ elif isinstance(page_size, str):
199
+ key = page_size.upper()
200
+ if key not in PAGE_SIZES:
201
+ raise ValueError(f"Unknown page_size {page_size!r}. Use one of {list(PAGE_SIZES)} or (w, h).")
202
+ pw, ph = PAGE_SIZES[key]
203
+ else:
204
+ pw, ph = float(page_size[0]), float(page_size[1])
205
+
206
+ avail_w = max(1.0, pw - margin * 2.0)
207
+ avail_h = max(1.0, ph - margin * 2.0)
208
+ scale = min(avail_w / logical_w, avail_h / logical_h, 1.0)
209
+
210
+ stream = skia.DynamicMemoryWStream()
211
+ doc = skia.PDF.MakeDocument(stream)
212
+ canvas = doc.beginPage(pw, ph)
213
+ canvas.save()
214
+ canvas.translate(margin, margin)
215
+ canvas.scale(scale, scale)
216
+ paint_fn(canvas)
217
+ canvas.restore()
218
+ doc.endPage()
219
+ doc.close()
220
+
221
+ pdf_bytes = bytes(stream.detachAsData())
222
+ if path is None:
223
+ return pdf_bytes
224
+ out = Path(path)
225
+ out.parent.mkdir(parents=True, exist_ok=True)
226
+ out.write_bytes(pdf_bytes)
227
+ return out
228
+
229
+
230
+ # ---------------------------------------------------------------------------
231
+ # 4. Enterprise Form Validation Engine
232
+ # ---------------------------------------------------------------------------
233
+
234
+ ValidatorFn = Callable[[Any], str | None]
235
+
236
+
237
+ class Validators:
238
+ """Built-in declarative validation rules for `ui.form()`."""
239
+
240
+ @staticmethod
241
+ def required(message: str = "Este campo es obligatorio") -> ValidatorFn:
242
+ def _check(val: Any) -> str | None:
243
+ if val is None:
244
+ return message
245
+ if isinstance(val, str) and not val.strip():
246
+ return message
247
+ return None
248
+
249
+ return _check
250
+
251
+ @staticmethod
252
+ def min_length(n: int, message: str | None = None) -> ValidatorFn:
253
+ msg = message or f"Debe tener al menos {n} caracteres"
254
+
255
+ def _check(val: Any) -> str | None:
256
+ s = "" if val is None else str(val)
257
+ return None if len(s) >= n else msg
258
+
259
+ return _check
260
+
261
+ @staticmethod
262
+ def max_length(n: int, message: str | None = None) -> ValidatorFn:
263
+ msg = message or f"Máximo {n} caracteres"
264
+
265
+ def _check(val: Any) -> str | None:
266
+ s = "" if val is None else str(val)
267
+ return None if len(s) <= n else msg
268
+
269
+ return _check
270
+
271
+ @staticmethod
272
+ def email(message: str = "Ingresa un correo electrónico válido") -> ValidatorFn:
273
+ pat = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
274
+
275
+ def _check(val: Any) -> str | None:
276
+ s = "" if val is None else str(val).strip()
277
+ if not s:
278
+ return None
279
+ return None if pat.match(s) else message
280
+
281
+ return _check
282
+
283
+ @staticmethod
284
+ def regex(pattern: str, message: str = "Formato inválido") -> ValidatorFn:
285
+ pat = re.compile(pattern)
286
+
287
+ def _check(val: Any) -> str | None:
288
+ s = "" if val is None else str(val)
289
+ if not s:
290
+ return None
291
+ return None if pat.match(s) else message
292
+
293
+ return _check
294
+
295
+ @staticmethod
296
+ def number_range(
297
+ min_val: float | None = None,
298
+ max_val: float | None = None,
299
+ message: str | None = None,
300
+ ) -> ValidatorFn:
301
+ def _check(val: Any) -> str | None:
302
+ if val is None or val == "":
303
+ return None
304
+ try:
305
+ num = float(val)
306
+ except (TypeError, ValueError):
307
+ return message or "Debe ser un número válido"
308
+ if min_val is not None and num < min_val:
309
+ return message or f"Debe ser mayor o igual a {min_val}"
310
+ if max_val is not None and num > max_val:
311
+ return message or f"Debe ser menor o igual a {max_val}"
312
+ return None
313
+
314
+ return _check
315
+
316
+ @staticmethod
317
+ def complete_mask(message: str = "Completa todos los caracteres requeridos") -> ValidatorFn:
318
+ def _check(val: Any) -> str | None:
319
+ return None # Handled with field-level `is_complete` inside Form.validate
320
+
321
+ _check._is_mask_rule = True # type: ignore[attr-defined]
322
+ _check._message = message # type: ignore[attr-defined]
323
+ return _check
324
+
325
+ @staticmethod
326
+ def custom(predicate: Callable[[Any], bool], message: str = "Valor inválido") -> ValidatorFn:
327
+ def _check(val: Any) -> str | None:
328
+ return None if predicate(val) else message
329
+
330
+ return _check
331
+
332
+
333
+ validators = Validators()
334
+
335
+
336
+ class Form:
337
+ """Declarative form controller managing validation, dirty state, values, and reset."""
338
+
339
+ def __init__(self, *, on_submit: Callable[[dict[str, Any]], None] | None = None) -> None:
340
+ self.on_submit = on_submit
341
+ self._fields: dict[str, tuple[Any, list[ValidatorFn], Any]] = {}
342
+ self._errors: dict[str, str] = {}
343
+
344
+ def field(self, name: str, widget: Any, rules: Sequence[ValidatorFn] = ()) -> Any:
345
+ """Register a widget under `name` with validation `rules`; returns `widget` for chaining."""
346
+ initial = getattr(widget, "value", None)
347
+ self._fields[name] = (widget, list(rules), initial)
348
+ return widget
349
+
350
+ @property
351
+ def values(self) -> dict[str, Any]:
352
+ return {name: getattr(w, "value", None) for name, (w, _, _) in self._fields.items()}
353
+
354
+ @property
355
+ def errors(self) -> dict[str, str]:
356
+ return dict(self._errors)
357
+
358
+ @property
359
+ def is_dirty(self) -> bool:
360
+ return any(getattr(w, "value", None) != initial for _, (w, _, initial) in self._fields.items())
361
+
362
+ def mark_clean(self) -> None:
363
+ """Snapshot current field values as the new clean baseline."""
364
+ for name, (w, rules, _) in list(self._fields.items()):
365
+ self._fields[name] = (w, rules, getattr(w, "value", None))
366
+
367
+ def validate(self) -> bool:
368
+ """Run all validation rules, update `error_text` on every field, and return `True` if valid."""
369
+ self._errors.clear()
370
+ for name, (w, rules, _) in self._fields.items():
371
+ val = getattr(w, "value", None)
372
+ err: str | None = None
373
+ for rule in rules:
374
+ if getattr(rule, "_is_mask_rule", False):
375
+ if hasattr(w, "is_complete") and not w.is_complete:
376
+ err = getattr(rule, "_message", "Campo incompleto")
377
+ else:
378
+ err = rule(val)
379
+ if err is not None:
380
+ break
381
+ if hasattr(w, "error_text"):
382
+ w.error_text = err
383
+ if err is not None:
384
+ self._errors[name] = err
385
+ return not self._errors
386
+
387
+ def submit(self) -> bool:
388
+ """Validate the form and invoke `on_submit(values)` if valid."""
389
+ if not self.validate():
390
+ return False
391
+ if self.on_submit is not None:
392
+ self.on_submit(self.values)
393
+ return True
394
+
395
+ def reset(self) -> None:
396
+ """Restore all fields to their initial baseline values and clear errors."""
397
+ self._errors.clear()
398
+ for _, (w, _, initial) in self._fields.items():
399
+ if hasattr(w, "value"):
400
+ w.value = initial
401
+ if hasattr(w, "error_text"):
402
+ w.error_text = None