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,426 @@
1
+ """Universal zero-dependency DataSource connectors for QuantumGUI tables & grids.
2
+
3
+ Supports:
4
+ - SQLite paths & any Python DB-API 2.0 connection (`sqlite3`, `psycopg`, `pymysql`, `pyodbc`, SQLAlchemy)
5
+ - `list[dict]` (JSON / REST APIs / ORMs)
6
+ - CSV files (`ui.csv_source`)
7
+ - pandas / polars DataFrames (duck-typed, zero required dependency)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import csv
13
+ import re
14
+ import sqlite3
15
+ from pathlib import Path
16
+ from typing import Any, Callable, Mapping, Sequence
17
+
18
+ ColTypeHint = str # "text" | "int" | "float" | "bool"
19
+ _SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
20
+
21
+
22
+ def _quote_ident(name: str) -> str:
23
+ if not _SAFE_IDENT.match(name):
24
+ raise ValueError(f"Unsafe SQL identifier: {name!r}")
25
+ return f'"{name}"'
26
+
27
+
28
+ def _infer_col_type(values: Sequence[Any]) -> ColTypeHint:
29
+ saw_int = False
30
+ saw_float = False
31
+ saw_bool = False
32
+ for v in values:
33
+ if v is None or v == "":
34
+ continue
35
+ if isinstance(v, bool):
36
+ saw_bool = True
37
+ elif isinstance(v, int):
38
+ saw_int = True
39
+ elif isinstance(v, float):
40
+ saw_float = True
41
+ else:
42
+ return "text"
43
+ if saw_float:
44
+ return "float"
45
+ if saw_int:
46
+ return "int"
47
+ if saw_bool:
48
+ return "bool"
49
+ return "text"
50
+
51
+
52
+ def _parse_scalar(raw: str) -> Any:
53
+ s = raw.strip()
54
+ if s == "":
55
+ return ""
56
+ low = s.lower()
57
+ if low in ("true", "false"):
58
+ return low == "true"
59
+ try:
60
+ if "." not in s and "e" not in low:
61
+ return int(s)
62
+ return float(s)
63
+ except ValueError:
64
+ return raw
65
+
66
+
67
+ class DataSource:
68
+ """Base protocol for reactive tabular data sources bound to `DataGrid` / `DataTable`."""
69
+
70
+ def __init__(self) -> None:
71
+ self._listeners: list[Callable[[], None]] = []
72
+
73
+ @property
74
+ def columns(self) -> list[str]:
75
+ return []
76
+
77
+ @property
78
+ def column_types(self) -> dict[str, ColTypeHint]:
79
+ return {}
80
+
81
+ def count(self) -> int:
82
+ return len(self.fetch())
83
+
84
+ def fetch(self, *, limit: int | None = None, offset: int = 0) -> list[list[Any]]:
85
+ return []
86
+
87
+ def update_cell(self, row_index: int, col_name: str, new_value: Any, row_data: Sequence[Any]) -> bool:
88
+ return False
89
+
90
+ def insert(self, record: Mapping[str, Any]) -> Any:
91
+ raise NotImplementedError("This DataSource is read-only")
92
+
93
+ def delete(self, pk_value: Any) -> bool:
94
+ raise NotImplementedError("This DataSource is read-only")
95
+
96
+ def subscribe(self, fn: Callable[[], None]) -> None:
97
+ if fn not in self._listeners:
98
+ self._listeners.append(fn)
99
+
100
+ def notify(self) -> None:
101
+ for fn in list(self._listeners):
102
+ fn()
103
+
104
+
105
+ class SQLDataSource(DataSource):
106
+ """Direct SQL connector for SQLite paths or any Python DB-API 2.0 / SQLAlchemy connection.
107
+
108
+ Example:
109
+ ds = ui.sql_source("erp.db", table="clientes", primary_key="id")
110
+ ui.data_grid(source=ds, editable=True, page_size=100, virtualized=True)
111
+ """
112
+
113
+ def __init__(
114
+ self,
115
+ connection: str | Path | Any,
116
+ *,
117
+ table: str | None = None,
118
+ query: str | None = None,
119
+ params: Sequence[Any] = (),
120
+ primary_key: str | None = None,
121
+ auto_commit: bool = True,
122
+ ) -> None:
123
+ super().__init__()
124
+ if not table and not query:
125
+ raise ValueError("SQLDataSource requires either `table=` or `query=`.")
126
+ self._owns_conn = False
127
+ if isinstance(connection, (str, Path)):
128
+ self._conn = sqlite3.connect(str(connection), check_same_thread=False)
129
+ self._owns_conn = True
130
+ elif hasattr(connection, "raw_connection"):
131
+ # SQLAlchemy Engine
132
+ self._conn = connection.raw_connection()
133
+ elif hasattr(connection, "connection") and callable(connection.connection):
134
+ # SQLAlchemy Session
135
+ self._conn = connection.connection().connection
136
+ else:
137
+ self._conn = connection
138
+
139
+ self.table = table
140
+ self.query = query.strip().rstrip(";") if query else None
141
+ self.params = tuple(params)
142
+ self.primary_key = primary_key
143
+ self.auto_commit = auto_commit
144
+ self._placeholder = self._detect_placeholder()
145
+
146
+ self._columns: list[str] = []
147
+ self._col_types: dict[str, ColTypeHint] = {}
148
+ self._pk_index: int | None = None
149
+ self._inspect_schema()
150
+
151
+ def _detect_placeholder(self) -> str:
152
+ mod = type(self._conn).__module__.lower()
153
+ if "sqlite" in mod or "pyodbc" in mod or "odbc" in mod:
154
+ return "?"
155
+ return "%s"
156
+
157
+ def _base_select(self) -> str:
158
+ if self.query:
159
+ return self.query
160
+ assert self.table is not None
161
+ return f"SELECT * FROM {_quote_ident(self.table)}"
162
+
163
+ def _inspect_schema(self) -> None:
164
+ cur = self._conn.cursor()
165
+ try:
166
+ sql = self._base_select()
167
+ cur.execute(f"SELECT * FROM ({sql}) AS _qgui_sub LIMIT 25", self.params)
168
+ desc = cur.description or ()
169
+ self._columns = [str(d[0]) for d in desc]
170
+ sample = cur.fetchall()
171
+ self._col_types = {}
172
+ for ci, col_name in enumerate(self._columns):
173
+ vals = [r[ci] for r in sample if ci < len(r)]
174
+ self._col_types[col_name] = _infer_col_type(vals)
175
+ if self.primary_key and self.primary_key in self._columns:
176
+ self._pk_index = self._columns.index(self.primary_key)
177
+ else:
178
+ self._pk_index = None
179
+ finally:
180
+ cur.close()
181
+
182
+ @property
183
+ def columns(self) -> list[str]:
184
+ return list(self._columns)
185
+
186
+ @property
187
+ def column_types(self) -> dict[str, ColTypeHint]:
188
+ return dict(self._col_types)
189
+
190
+ def count(self) -> int:
191
+ cur = self._conn.cursor()
192
+ try:
193
+ sql = self._base_select()
194
+ cur.execute(f"SELECT COUNT(*) FROM ({sql}) AS _qgui_cnt", self.params)
195
+ row = cur.fetchone()
196
+ return int(row[0]) if row else 0
197
+ finally:
198
+ cur.close()
199
+
200
+ def fetch(self, *, limit: int | None = None, offset: int = 0) -> list[list[Any]]:
201
+ cur = self._conn.cursor()
202
+ try:
203
+ sql = self._base_select()
204
+ if limit is not None:
205
+ ph = self._placeholder
206
+ cur.execute(
207
+ f"SELECT * FROM ({sql}) AS _qgui_page LIMIT {ph} OFFSET {ph}",
208
+ self.params + (int(limit), max(0, int(offset))),
209
+ )
210
+ else:
211
+ cur.execute(sql, self.params)
212
+ if not self._columns and cur.description:
213
+ self._columns = [str(d[0]) for d in cur.description]
214
+ return [list(r) for r in cur.fetchall()]
215
+ finally:
216
+ cur.close()
217
+
218
+ def update_cell(self, row_index: int, col_name: str, new_value: Any, row_data: Sequence[Any]) -> bool:
219
+ if not self.table or not self.primary_key or self._pk_index is None:
220
+ return False
221
+ if col_name not in self._columns or self._pk_index >= len(row_data):
222
+ return False
223
+ pk_val = row_data[self._pk_index]
224
+ ph = self._placeholder
225
+ sql = f"UPDATE {_quote_ident(self.table)} SET {_quote_ident(col_name)} = {ph} WHERE {_quote_ident(self.primary_key)} = {ph}"
226
+ cur = self._conn.cursor()
227
+ try:
228
+ cur.execute(sql, (new_value, pk_val))
229
+ if self.auto_commit:
230
+ self._conn.commit()
231
+ return True
232
+ finally:
233
+ cur.close()
234
+
235
+ def insert(self, record: Mapping[str, Any]) -> Any:
236
+ if not self.table:
237
+ raise ValueError("`insert()` requires `table=` on SQLDataSource.")
238
+ cols = list(record.keys())
239
+ ph = self._placeholder
240
+ cols_sql = ", ".join(_quote_ident(c) for c in cols)
241
+ vals_sql = ", ".join(ph for _ in cols)
242
+ sql = f"INSERT INTO {_quote_ident(self.table)} ({cols_sql}) VALUES ({vals_sql})"
243
+ cur = self._conn.cursor()
244
+ try:
245
+ cur.execute(sql, tuple(record[c] for c in cols))
246
+ if self.auto_commit:
247
+ self._conn.commit()
248
+ last_id = getattr(cur, "lastrowid", None)
249
+ finally:
250
+ cur.close()
251
+ self.notify()
252
+ return last_id
253
+
254
+ def delete(self, pk_value: Any) -> bool:
255
+ if not self.table or not self.primary_key:
256
+ raise ValueError("`delete()` requires `table=` and `primary_key=` on SQLDataSource.")
257
+ ph = self._placeholder
258
+ sql = f"DELETE FROM {_quote_ident(self.table)} WHERE {_quote_ident(self.primary_key)} = {ph}"
259
+ cur = self._conn.cursor()
260
+ try:
261
+ cur.execute(sql, (pk_value,))
262
+ if self.auto_commit:
263
+ self._conn.commit()
264
+ affected = cur.rowcount
265
+ finally:
266
+ cur.close()
267
+ self.notify()
268
+ return affected != 0
269
+
270
+ def close(self) -> None:
271
+ if self._owns_conn and self._conn is not None:
272
+ self._conn.close()
273
+ self._owns_conn = False
274
+
275
+
276
+ class DictListDataSource(DataSource):
277
+ """In-memory DataSource backed by a list of dictionaries (`list[dict[str, Any]]`)."""
278
+
279
+ def __init__(self, records: Sequence[Mapping[str, Any]]) -> None:
280
+ super().__init__()
281
+ self._records: list[dict[str, Any]] = [dict(r) for r in records]
282
+ cols: list[str] = []
283
+ seen: set[str] = set()
284
+ for r in self._records:
285
+ for k in r.keys():
286
+ ks = str(k)
287
+ if ks not in seen:
288
+ seen.add(ks)
289
+ cols.append(ks)
290
+ self._columns = cols
291
+ self._col_types = {
292
+ c: _infer_col_type([r.get(c) for r in self._records[:50]]) for c in cols
293
+ }
294
+
295
+ @property
296
+ def columns(self) -> list[str]:
297
+ return list(self._columns)
298
+
299
+ @property
300
+ def column_types(self) -> dict[str, ColTypeHint]:
301
+ return dict(self._col_types)
302
+
303
+ def count(self) -> int:
304
+ return len(self._records)
305
+
306
+ def fetch(self, *, limit: int | None = None, offset: int = 0) -> list[list[Any]]:
307
+ sl = self._records[offset : (offset + limit) if limit is not None else None]
308
+ return [[r.get(c) for c in self._columns] for r in sl]
309
+
310
+ def update_cell(self, row_index: int, col_name: str, new_value: Any, row_data: Sequence[Any]) -> bool:
311
+ if 0 <= row_index < len(self._records):
312
+ self._records[row_index][col_name] = new_value
313
+ return True
314
+ return False
315
+
316
+ def insert(self, record: Mapping[str, Any]) -> Any:
317
+ rec = dict(record)
318
+ for k in rec:
319
+ if str(k) not in self._columns:
320
+ self._columns.append(str(k))
321
+ self._records.append(rec)
322
+ self.notify()
323
+ return len(self._records) - 1
324
+
325
+ def delete(self, pk_value: Any) -> bool:
326
+ idx = int(pk_value)
327
+ if 0 <= idx < len(self._records):
328
+ self._records.pop(idx)
329
+ self.notify()
330
+ return True
331
+ return False
332
+
333
+
334
+ class CSVDataSource(DataSource):
335
+ """Zero-dependency CSV file DataSource with automatic scalar type inference."""
336
+
337
+ def __init__(self, path: str | Path, *, delimiter: str = ",", encoding: str = "utf-8-sig") -> None:
338
+ super().__init__()
339
+ self.path = Path(path)
340
+ self.delimiter = delimiter
341
+ self.encoding = encoding
342
+ self._columns: list[str] = []
343
+ self._rows: list[list[Any]] = []
344
+ self._col_types: dict[str, ColTypeHint] = {}
345
+ self.reload_file()
346
+
347
+ def reload_file(self) -> None:
348
+ with self.path.open("r", encoding=self.encoding, newline="") as fh:
349
+ reader = csv.reader(fh, delimiter=self.delimiter)
350
+ raw_rows = list(reader)
351
+ if not raw_rows:
352
+ self._columns = []
353
+ self._rows = []
354
+ self._col_types = {}
355
+ return
356
+ self._columns = [str(c).strip() for c in raw_rows[0]]
357
+ self._rows = [[_parse_scalar(cell) for cell in r] for r in raw_rows[1:]]
358
+ self._col_types = {
359
+ c: _infer_col_type([r[i] for r in self._rows[:50] if i < len(r)])
360
+ for i, c in enumerate(self._columns)
361
+ }
362
+
363
+ @property
364
+ def columns(self) -> list[str]:
365
+ return list(self._columns)
366
+
367
+ @property
368
+ def column_types(self) -> dict[str, ColTypeHint]:
369
+ return dict(self._col_types)
370
+
371
+ def count(self) -> int:
372
+ return len(self._rows)
373
+
374
+ def fetch(self, *, limit: int | None = None, offset: int = 0) -> list[list[Any]]:
375
+ sl = self._rows[offset : (offset + limit) if limit is not None else None]
376
+ return [list(r) for r in sl]
377
+
378
+
379
+ class DataFrameDataSource(DataSource):
380
+ """Duck-typed connector for pandas / polars DataFrames (no hard dependency)."""
381
+
382
+ def __init__(self, df: Any) -> None:
383
+ super().__init__()
384
+ self._columns = [str(c) for c in list(df.columns)]
385
+ if hasattr(df, "rows") and callable(df.rows):
386
+ # Polars
387
+ self._rows = [list(r) for r in df.rows()]
388
+ else:
389
+ # Pandas
390
+ self._rows = [list(r) for r in df.values.tolist()]
391
+ self._col_types = {
392
+ c: _infer_col_type([r[i] for r in self._rows[:50] if i < len(r)])
393
+ for i, c in enumerate(self._columns)
394
+ }
395
+
396
+ @property
397
+ def columns(self) -> list[str]:
398
+ return list(self._columns)
399
+
400
+ @property
401
+ def column_types(self) -> dict[str, ColTypeHint]:
402
+ return dict(self._col_types)
403
+
404
+ def count(self) -> int:
405
+ return len(self._rows)
406
+
407
+ def fetch(self, *, limit: int | None = None, offset: int = 0) -> list[list[Any]]:
408
+ sl = self._rows[offset : (offset + limit) if limit is not None else None]
409
+ return [list(r) for r in sl]
410
+
411
+
412
+ def coerce_data_source(source: Any) -> DataSource:
413
+ """Convert any supported data source into a `DataSource` instance."""
414
+ if isinstance(source, DataSource):
415
+ return source
416
+ if isinstance(source, (str, Path)) and str(source).lower().endswith(".csv"):
417
+ return CSVDataSource(source)
418
+ if hasattr(source, "columns") and (hasattr(source, "values") or hasattr(source, "rows")):
419
+ return DataFrameDataSource(source)
420
+ if isinstance(source, Sequence) and not isinstance(source, (str, bytes)):
421
+ if len(source) == 0 or isinstance(source[0], Mapping):
422
+ return DictListDataSource(source) # type: ignore[arg-type]
423
+ raise TypeError(
424
+ f"Unsupported DataSource type {type(source).__name__!r}. "
425
+ "Pass `ui.sql_source(...)`, `ui.csv_source(...)`, a `list[dict]`, or a DataFrame."
426
+ )