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,276 @@
1
+ """Zero-dependency native OS file & folder dialogs (Win32 ctypes / macOS osascript / Linux zenity).
2
+
3
+ QuantumGUI never depends on tkinter, Qt, GTK, or any other third-party GUI toolkit.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import ctypes
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ from typing import Sequence
14
+
15
+
16
+ def build_win32_filter(filetypes: Sequence[tuple[str, str]]) -> str:
17
+ """Convert `(label, pattern)` pairs into a Win32 double-null-terminated filter string."""
18
+ if not filetypes:
19
+ filetypes = (("Todos los archivos", "*.*"),)
20
+ parts: list[str] = []
21
+ for label, pattern in filetypes:
22
+ # Normalize space-separated patterns ("*.png *.jpg") to Win32 semicolon format ("*.png;*.jpg")
23
+ norm = ";".join(tok.strip() for tok in pattern.replace(";", " ").split() if tok.strip()) or "*.*"
24
+ display = label if "(" in label else f"{label} ({norm})"
25
+ parts.append(display)
26
+ parts.append(norm)
27
+ return "\0".join(parts) + "\0\0"
28
+
29
+
30
+ def parse_win32_multiselect_buffer(raw: str) -> list[str]:
31
+ """Parse a Win32 `OPENFILENAMEW` buffer (single file or null-separated multi-select)."""
32
+ tokens = raw.split("\0")
33
+ if not tokens or not tokens[0]:
34
+ return []
35
+ # Multi-select format: [directory, file1, file2, ..., "", ...]
36
+ if len(tokens) > 1 and tokens[1]:
37
+ folder = tokens[0]
38
+ files: list[str] = []
39
+ for name in tokens[1:]:
40
+ if not name:
41
+ break
42
+ files.append(os.path.join(folder, name))
43
+ return files
44
+ return [tokens[0]]
45
+
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # Windows Win32 Implementation (comdlg32 + shell32 via ctypes)
49
+ # ---------------------------------------------------------------------------
50
+
51
+ if sys.platform == "win32":
52
+ from ctypes import wintypes
53
+
54
+ OFN_OVERWRITEPROMPT = 0x00000002
55
+ OFN_NOCHANGEDIR = 0x00000008
56
+ OFN_ALLOWMULTISELECT = 0x00000200
57
+ OFN_PATHMUSTEXIST = 0x00000800
58
+ OFN_FILEMUSTEXIST = 0x00001000
59
+ OFN_EXPLORER = 0x00080000
60
+
61
+ BIF_RETURNONLYFSDIRS = 0x00000001
62
+ BIF_NEWDIALOGSTYLE = 0x00000040
63
+ COINIT_APARTMENTTHREADED = 0x2
64
+
65
+ class _OPENFILENAMEW(ctypes.Structure):
66
+ _fields_ = [
67
+ ("lStructSize", wintypes.DWORD),
68
+ ("hwndOwner", wintypes.HWND),
69
+ ("hInstance", wintypes.HINSTANCE),
70
+ ("lpstrFilter", wintypes.LPCWSTR),
71
+ ("lpstrCustomFilter", wintypes.LPWSTR),
72
+ ("nMaxCustFilter", wintypes.DWORD),
73
+ ("nFilterIndex", wintypes.DWORD),
74
+ ("lpstrFile", wintypes.LPWSTR),
75
+ ("nMaxFile", wintypes.DWORD),
76
+ ("lpstrFileTitle", wintypes.LPWSTR),
77
+ ("nMaxFileTitle", wintypes.DWORD),
78
+ ("lpstrInitialDir", wintypes.LPCWSTR),
79
+ ("lpstrTitle", wintypes.LPCWSTR),
80
+ ("Flags", wintypes.DWORD),
81
+ ("nFileOffset", wintypes.WORD),
82
+ ("nFileExtension", wintypes.WORD),
83
+ ("lpstrDefExt", wintypes.LPCWSTR),
84
+ ("lCustData", wintypes.LPARAM),
85
+ ("lpfnHook", ctypes.c_void_p),
86
+ ("lpTemplateName", wintypes.LPCWSTR),
87
+ ("pvReserved", ctypes.c_void_p),
88
+ ("dwReserved", wintypes.DWORD),
89
+ ("FlagsEx", wintypes.DWORD),
90
+ ]
91
+
92
+ class _BROWSEINFOW(ctypes.Structure):
93
+ _fields_ = [
94
+ ("hwndOwner", wintypes.HWND),
95
+ ("pidlRoot", ctypes.c_void_p),
96
+ ("pszDisplayName", wintypes.LPWSTR),
97
+ ("lpszTitle", wintypes.LPCWSTR),
98
+ ("ulFlags", wintypes.UINT),
99
+ ("lpfn", ctypes.c_void_p),
100
+ ("lParam", wintypes.LPARAM),
101
+ ("iImage", ctypes.c_int),
102
+ ]
103
+
104
+ def _win32_open_file(
105
+ title: str,
106
+ filetypes: Sequence[tuple[str, str]],
107
+ multiple: bool,
108
+ owner_hwnd: int,
109
+ ) -> list[str]:
110
+ buf_size = 65536 if multiple else 4096
111
+ buf = ctypes.create_unicode_buffer(buf_size)
112
+ flt = build_win32_filter(filetypes)
113
+
114
+ ofn = _OPENFILENAMEW()
115
+ ofn.lStructSize = ctypes.sizeof(_OPENFILENAMEW)
116
+ ofn.hwndOwner = owner_hwnd or None
117
+ ofn.lpstrFilter = flt
118
+ ofn.nFilterIndex = 1
119
+ ofn.lpstrFile = ctypes.cast(buf, wintypes.LPWSTR)
120
+ ofn.nMaxFile = buf_size
121
+ ofn.lpstrTitle = title
122
+ flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR
123
+ if multiple:
124
+ flags |= OFN_ALLOWMULTISELECT
125
+ ofn.Flags = flags
126
+
127
+ comdlg32 = ctypes.windll.comdlg32
128
+ comdlg32.GetOpenFileNameW.argtypes = [ctypes.POINTER(_OPENFILENAMEW)]
129
+ comdlg32.GetOpenFileNameW.restype = wintypes.BOOL
130
+ if not comdlg32.GetOpenFileNameW(ctypes.byref(ofn)):
131
+ return []
132
+
133
+ raw = ctypes.wstring_at(buf, buf_size)
134
+ return parse_win32_multiselect_buffer(raw)
135
+
136
+ def _win32_save_file(
137
+ title: str,
138
+ filetypes: Sequence[tuple[str, str]],
139
+ default_name: str,
140
+ owner_hwnd: int,
141
+ ) -> str:
142
+ buf_size = 4096
143
+ buf = ctypes.create_unicode_buffer(default_name, buf_size)
144
+ flt = build_win32_filter(filetypes)
145
+
146
+ ofn = _OPENFILENAMEW()
147
+ ofn.lStructSize = ctypes.sizeof(_OPENFILENAMEW)
148
+ ofn.hwndOwner = owner_hwnd or None
149
+ ofn.lpstrFilter = flt
150
+ ofn.nFilterIndex = 1
151
+ ofn.lpstrFile = ctypes.cast(buf, wintypes.LPWSTR)
152
+ ofn.nMaxFile = buf_size
153
+ ofn.lpstrTitle = title
154
+ ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR
155
+
156
+ comdlg32 = ctypes.windll.comdlg32
157
+ comdlg32.GetSaveFileNameW.argtypes = [ctypes.POINTER(_OPENFILENAMEW)]
158
+ comdlg32.GetSaveFileNameW.restype = wintypes.BOOL
159
+ if not comdlg32.GetSaveFileNameW(ctypes.byref(ofn)):
160
+ return ""
161
+ return buf.value
162
+
163
+ def _win32_open_folder(title: str, owner_hwnd: int) -> str:
164
+ ole32 = ctypes.windll.ole32
165
+ shell32 = ctypes.windll.shell32
166
+ ole32.CoInitializeEx(None, COINIT_APARTMENTTHREADED)
167
+
168
+ display_buf = ctypes.create_unicode_buffer(260)
169
+ bi = _BROWSEINFOW()
170
+ bi.hwndOwner = owner_hwnd or None
171
+ bi.pszDisplayName = ctypes.cast(display_buf, wintypes.LPWSTR)
172
+ bi.lpszTitle = title
173
+ bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE
174
+
175
+ shell32.SHBrowseForFolderW.argtypes = [ctypes.POINTER(_BROWSEINFOW)]
176
+ shell32.SHBrowseForFolderW.restype = ctypes.c_void_p
177
+ shell32.SHGetPathFromIDListW.argtypes = [ctypes.c_void_p, wintypes.LPWSTR]
178
+ shell32.SHGetPathFromIDListW.restype = wintypes.BOOL
179
+ ole32.CoTaskMemFree.argtypes = [ctypes.c_void_p]
180
+
181
+ pidl = shell32.SHBrowseForFolderW(ctypes.byref(bi))
182
+ if not pidl:
183
+ return ""
184
+ try:
185
+ path_buf = ctypes.create_unicode_buffer(4096)
186
+ if shell32.SHGetPathFromIDListW(pidl, path_buf):
187
+ return path_buf.value
188
+ return ""
189
+ finally:
190
+ ole32.CoTaskMemFree(pidl)
191
+
192
+
193
+ # ---------------------------------------------------------------------------
194
+ # macOS (osascript) & Linux (zenity / kdialog) Fallbacks
195
+ # ---------------------------------------------------------------------------
196
+
197
+
198
+ def _macos_dialog(script: str) -> str:
199
+ res = subprocess.run(["osascript", "-e", script], capture_output=True, text=True, check=False)
200
+ return res.stdout.strip() if res.returncode == 0 else ""
201
+
202
+
203
+ def _linux_dialog(cmd: list[str]) -> str:
204
+ res = subprocess.run(cmd, capture_output=True, text=True, check=False)
205
+ return res.stdout.strip() if res.returncode == 0 else ""
206
+
207
+
208
+ # ---------------------------------------------------------------------------
209
+ # Public Cross-Platform API
210
+ # ---------------------------------------------------------------------------
211
+
212
+
213
+ def open_file_dialog(
214
+ title: str = "Abrir archivo",
215
+ filetypes: Sequence[tuple[str, str]] = (("Todos los archivos", "*.*"),),
216
+ *,
217
+ multiple: bool = False,
218
+ owner_hwnd: int = 0,
219
+ ) -> list[str]:
220
+ """Open the native OS file-open dialog and return selected file paths."""
221
+ if sys.platform == "win32":
222
+ return _win32_open_file(title, filetypes, multiple, owner_hwnd)
223
+ if sys.platform == "darwin":
224
+ if multiple:
225
+ out = _macos_dialog(
226
+ f'set f to choose file with prompt "{title}" with multiple selections allowed\n'
227
+ 'set out to ""\nrepeat with x in f\nset out to out & POSIX path of x & "\\n"\nend repeat\nreturn out'
228
+ )
229
+ return [p for p in out.splitlines() if p]
230
+ out = _macos_dialog(f'POSIX path of (choose file with prompt "{title}")')
231
+ return [out] if out else []
232
+ if shutil.which("zenity"):
233
+ cmd = ["zenity", "--file-selection", f"--title={title}"]
234
+ if multiple:
235
+ cmd += ["--multiple", "--separator=\n"]
236
+ out = _linux_dialog(cmd)
237
+ return [p for p in out.splitlines() if p]
238
+ if shutil.which("kdialog"):
239
+ cmd = ["kdialog", "--getopenfilename", "--title", title]
240
+ if multiple:
241
+ cmd.append("--multiple")
242
+ out = _linux_dialog(cmd)
243
+ return out.split() if multiple else ([out] if out else [])
244
+ return []
245
+
246
+
247
+ def save_file_dialog(
248
+ title: str = "Guardar archivo",
249
+ filetypes: Sequence[tuple[str, str]] = (("Todos los archivos", "*.*"),),
250
+ *,
251
+ default_name: str = "",
252
+ owner_hwnd: int = 0,
253
+ ) -> str:
254
+ """Open the native OS file-save dialog and return the chosen path or empty string."""
255
+ if sys.platform == "win32":
256
+ return _win32_save_file(title, filetypes, default_name, owner_hwnd)
257
+ if sys.platform == "darwin":
258
+ return _macos_dialog(f'POSIX path of (choose file name with prompt "{title}")')
259
+ if shutil.which("zenity"):
260
+ return _linux_dialog(["zenity", "--file-selection", "--save", "--confirm-overwrite", f"--title={title}"])
261
+ if shutil.which("kdialog"):
262
+ return _linux_dialog(["kdialog", "--getsavefilename", "--title", title])
263
+ return ""
264
+
265
+
266
+ def open_folder_dialog(title: str = "Seleccionar carpeta", *, owner_hwnd: int = 0) -> str:
267
+ """Open the native OS folder-picker dialog and return the chosen folder path or empty string."""
268
+ if sys.platform == "win32":
269
+ return _win32_open_folder(title, owner_hwnd)
270
+ if sys.platform == "darwin":
271
+ return _macos_dialog(f'POSIX path of (choose folder with prompt "{title}")')
272
+ if shutil.which("zenity"):
273
+ return _linux_dialog(["zenity", "--file-selection", "--directory", f"--title={title}"])
274
+ if shutil.which("kdialog"):
275
+ return _linux_dialog(["kdialog", "--getexistingdirectory", "--title", title])
276
+ return ""
@@ -0,0 +1,390 @@
1
+ """Native Skia Vector Multi-Page PDF Report & Invoice Builder (`ui.pdf_report`).
2
+
3
+ Zero external dependencies: renders crisp vector PDFs with corporate headers, KPI strips,
4
+ wrapped paragraphs, automatic multi-page table pagination (repeating headers), totals row,
5
+ and "Página X de Y" footers directly via `skia.PDF.MakeDocument`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any, Literal, Mapping, Sequence
13
+
14
+ import skia
15
+
16
+ from ..theme import Color, Theme
17
+ from .draw import draw_text_centered_y, font_for_style, make_rrect, measure_text
18
+ from .geometry import Rect
19
+
20
+ PageFormat = Literal["A4", "Letter", "Legal"]
21
+ PageOrientation = Literal["portrait", "landscape"]
22
+
23
+ _PAGE_SIZES: dict[str, tuple[float, float]] = {
24
+ "A4": (595.0, 842.0),
25
+ "Letter": (612.0, 792.0),
26
+ "Legal": (612.0, 1008.0),
27
+ }
28
+
29
+
30
+ @dataclass
31
+ class _Block:
32
+ kind: str
33
+ payload: Any
34
+
35
+
36
+ class PDFReport:
37
+ """Fluent multi-page vector PDF report builder backed by Skia PDF."""
38
+
39
+ def __init__(
40
+ self,
41
+ title: str = "Reporte",
42
+ *,
43
+ subtitle: str = "",
44
+ page_size: PageFormat = "A4",
45
+ orientation: PageOrientation = "portrait",
46
+ margin: float = 38.0,
47
+ theme: Theme | None = None,
48
+ ) -> None:
49
+ self.title = title
50
+ self.subtitle = subtitle
51
+ w, h = _PAGE_SIZES.get(page_size, _PAGE_SIZES["A4"])
52
+ if orientation == "landscape":
53
+ w, h = h, w
54
+ self.page_w = float(w)
55
+ self.page_h = float(h)
56
+ self.margin = float(margin)
57
+ self.theme = theme or Theme(seed="#6750A4", mode="light")
58
+
59
+ self._company: str = ""
60
+ self._meta: list[tuple[str, str]] = []
61
+ self._footer_text: str = title
62
+ self._blocks: list[_Block] = []
63
+ self._last_page_count: int = 0
64
+
65
+ @property
66
+ def page_count(self) -> int:
67
+ return self._last_page_count
68
+
69
+ def header(
70
+ self,
71
+ company: str,
72
+ *,
73
+ subtitle: str | None = None,
74
+ meta: Mapping[str, Any] | None = None,
75
+ ) -> PDFReport:
76
+ self._company = str(company)
77
+ if subtitle is not None:
78
+ self.subtitle = str(subtitle)
79
+ if meta is not None:
80
+ self._meta = [(str(k), str(v)) for k, v in meta.items()]
81
+ return self
82
+
83
+ def footer(self, text: str) -> PDFReport:
84
+ self._footer_text = str(text)
85
+ return self
86
+
87
+ def section(self, heading: str) -> PDFReport:
88
+ self._blocks.append(_Block("section", str(heading)))
89
+ return self
90
+
91
+ def text(self, paragraph: str) -> PDFReport:
92
+ self._blocks.append(_Block("text", str(paragraph)))
93
+ return self
94
+
95
+ def kpi_row(self, items: Sequence[tuple[str, str]]) -> PDFReport:
96
+ self._blocks.append(_Block("kpi_row", [(str(k), str(v)) for k, v in items]))
97
+ return self
98
+
99
+ def table(
100
+ self,
101
+ headers: Sequence[str],
102
+ rows: Sequence[Sequence[Any]],
103
+ *,
104
+ col_widths: Sequence[float] | None = None,
105
+ alignments: Sequence[str] | None = None,
106
+ totals: Sequence[str] | None = None,
107
+ row_height: float = 22.0,
108
+ ) -> PDFReport:
109
+ self._blocks.append(
110
+ _Block(
111
+ "table",
112
+ {
113
+ "headers": [str(h) for h in headers],
114
+ "rows": [["" if v is None else str(v) for v in r] for r in rows],
115
+ "col_widths": list(col_widths) if col_widths else None,
116
+ "alignments": list(alignments) if alignments else None,
117
+ "totals": [str(t) for t in totals] if totals else None,
118
+ "row_height": float(row_height),
119
+ },
120
+ )
121
+ )
122
+ return self
123
+
124
+ def from_grid(self, grid: Any) -> PDFReport:
125
+ """Append all filtered/sorted rows and totals from a `DataGrid` as a multi-page table."""
126
+ headers = [c.title for c in grid.columns]
127
+ alignments = [c.effective_align for c in grid.columns]
128
+ rows: list[list[str]] = []
129
+ for ri in grid._view_indices:
130
+ raw_row = grid._rows[ri]
131
+ rows.append(
132
+ [
133
+ grid.columns[ci].format_value(raw_row[ci] if ci < len(raw_row) else None)
134
+ for ci in range(len(grid.columns))
135
+ ]
136
+ )
137
+ totals = grid.totals if getattr(grid, "show_totals", False) else None
138
+ return self.table(headers, rows, alignments=alignments, totals=totals)
139
+
140
+ def _wrap_text(self, text: str, font: skia.Font, max_w: float) -> list[str]:
141
+ lines: list[str] = []
142
+ for para in text.splitlines() or [""]:
143
+ words = para.split()
144
+ if not words:
145
+ lines.append("")
146
+ continue
147
+ cur = words[0]
148
+ for w in words[1:]:
149
+ cand = f"{cur} {w}"
150
+ if measure_text(font, cand) <= max_w:
151
+ cur = cand
152
+ else:
153
+ lines.append(cur)
154
+ cur = w
155
+ lines.append(cur)
156
+ return lines
157
+
158
+ def _plan_pages(self) -> list[list[tuple[str, Any]]]:
159
+ """Lay out blocks into discrete pages so we know total `page_count` before painting."""
160
+ c_w = self.page_w - self.margin * 2.0
161
+ header_h = 68.0 if (self._company or self._meta) else 44.0
162
+ footer_h = 28.0
163
+ usable_top = self.margin + header_h + 10.0
164
+ usable_bot = self.page_h - self.margin - footer_h
165
+
166
+ body_font = font_for_style(self.theme.font_family, self.theme.typography.body_small)
167
+
168
+ pages: list[list[tuple[str, Any]]] = [[]]
169
+ y = usable_top
170
+
171
+ def _new_page() -> None:
172
+ nonlocal y
173
+ pages.append([])
174
+ y = usable_top
175
+
176
+ for blk in self._blocks:
177
+ if blk.kind == "section":
178
+ h = 26.0
179
+ if y + h > usable_bot and pages[-1]:
180
+ _new_page()
181
+ pages[-1].append(("section", (y, blk.payload)))
182
+ y += h
183
+ elif blk.kind == "text":
184
+ lines = self._wrap_text(blk.payload, body_font, c_w)
185
+ line_h = 15.0
186
+ for ln in lines:
187
+ if y + line_h > usable_bot and pages[-1]:
188
+ _new_page()
189
+ pages[-1].append(("text_line", (y, ln)))
190
+ y += line_h
191
+ y += 6.0
192
+ elif blk.kind == "kpi_row":
193
+ h = 54.0
194
+ if y + h > usable_bot and pages[-1]:
195
+ _new_page()
196
+ pages[-1].append(("kpi_row", (y, blk.payload)))
197
+ y += h + 10.0
198
+ elif blk.kind == "table":
199
+ spec = blk.payload
200
+ hdrs = spec["headers"]
201
+ rows = spec["rows"]
202
+ rh = spec["row_height"]
203
+ hdr_h = 24.0
204
+ n_cols = max(1, len(hdrs))
205
+ widths = spec["col_widths"] or [c_w / n_cols] * n_cols
206
+ aligns = spec["alignments"] or ["left"] * n_cols
207
+
208
+ idx = 0
209
+ first_chunk = True
210
+ while idx < len(rows) or first_chunk:
211
+ first_chunk = False
212
+ if y + hdr_h + rh > usable_bot and pages[-1]:
213
+ _new_page()
214
+ chunk_y = y
215
+ y += hdr_h
216
+ chunk_rows: list[list[str]] = []
217
+ while idx < len(rows) and y + rh <= usable_bot:
218
+ chunk_rows.append(rows[idx])
219
+ y += rh
220
+ idx += 1
221
+ is_last = idx >= len(rows)
222
+ totals_here = None
223
+ if is_last and spec["totals"]:
224
+ if y + rh <= usable_bot:
225
+ totals_here = spec["totals"]
226
+ y += rh
227
+ else:
228
+ pages[-1].append(
229
+ (
230
+ "table_chunk",
231
+ (chunk_y, hdrs, chunk_rows, widths, aligns, rh, None),
232
+ )
233
+ )
234
+ _new_page()
235
+ pages[-1].append(
236
+ (
237
+ "table_chunk",
238
+ (y, hdrs, [], widths, aligns, rh, spec["totals"]),
239
+ )
240
+ )
241
+ y += hdr_h + rh + 8.0
242
+ break
243
+ pages[-1].append(
244
+ (
245
+ "table_chunk",
246
+ (chunk_y, hdrs, chunk_rows, widths, aligns, rh, totals_here),
247
+ )
248
+ )
249
+ if idx < len(rows):
250
+ _new_page()
251
+ y += 10.0
252
+
253
+ return pages
254
+
255
+ def save(self, path: str | Path) -> Path:
256
+ """Render all pages into a native Skia vector PDF file and return its `Path`."""
257
+ dest = Path(path)
258
+ dest.parent.mkdir(parents=True, exist_ok=True)
259
+
260
+ pages = self._plan_pages()
261
+ self._last_page_count = len(pages)
262
+ total_pages = len(pages)
263
+
264
+ c = self.theme.colors
265
+ m = self.margin
266
+ c_w = self.page_w - m * 2.0
267
+
268
+ title_f = font_for_style(self.theme.font_family, self.theme.typography.title_large)
269
+ sec_f = font_for_style(self.theme.font_family, self.theme.typography.title_small)
270
+ hdr_f = font_for_style(self.theme.font_family, self.theme.typography.label_medium)
271
+ body_f = font_for_style(self.theme.font_family, self.theme.typography.body_small)
272
+ small_f = font_for_style(self.theme.font_family, self.theme.typography.label_small)
273
+
274
+ stream = skia.FILEWStream(str(dest))
275
+ doc = skia.PDF.MakeDocument(stream)
276
+
277
+ for p_idx, ops in enumerate(pages, start=1):
278
+ canvas = doc.beginPage(self.page_w, self.page_h)
279
+ canvas.clear(Color(255, 255, 255).to_skia())
280
+
281
+ # Page Header
282
+ hy = m
283
+ if self._company:
284
+ draw_text_centered_y(canvas, self._company, m, hy + 10.0, small_f, c.primary)
285
+ draw_text_centered_y(canvas, self.title, m, hy + 30.0, title_f, c.on_surface)
286
+ if self.subtitle:
287
+ draw_text_centered_y(canvas, self.subtitle, m, hy + 50.0, body_f, c.on_surface_variant)
288
+ else:
289
+ draw_text_centered_y(canvas, self.title, m, hy + 16.0, title_f, c.on_surface)
290
+ if self.subtitle:
291
+ draw_text_centered_y(canvas, self.subtitle, m, hy + 34.0, body_f, c.on_surface_variant)
292
+
293
+ # Right-aligned metadata
294
+ my = hy + 10.0
295
+ for mk, mv in self._meta:
296
+ txt = f"{mk}: {mv}"
297
+ tw = measure_text(small_f, txt)
298
+ draw_text_centered_y(canvas, txt, self.page_w - m - tw, my, small_f, c.on_surface_variant)
299
+ my += 14.0
300
+
301
+ div_y = m + (64.0 if (self._company or self._meta) else 42.0)
302
+ canvas.drawLine(m, div_y, self.page_w - m, div_y, skia.Paint(Color=c.primary.to_skia(), StrokeWidth=1.5))
303
+
304
+ # Page Body Ops
305
+ for kind, payload in ops:
306
+ if kind == "section":
307
+ y, heading = payload
308
+ draw_text_centered_y(canvas, heading, m, y + 12.0, sec_f, c.primary)
309
+ elif kind == "text_line":
310
+ y, ln = payload
311
+ draw_text_centered_y(canvas, ln, m, y + 7.0, body_f, c.on_surface)
312
+ elif kind == "kpi_row":
313
+ y, items = payload
314
+ if items:
315
+ gap = 8.0
316
+ kw = (c_w - gap * (len(items) - 1)) / len(items)
317
+ for i, (kl, kv) in enumerate(items):
318
+ kr = Rect(m + i * (kw + gap), y, kw, 48.0)
319
+ canvas.drawRRect(
320
+ make_rrect(kr, 8.0),
321
+ skia.Paint(AntiAlias=True, Color=c.surface_container_low.to_skia()),
322
+ )
323
+ draw_text_centered_y(canvas, kl, kr.x + 10.0, kr.y + 14.0, small_f, c.on_surface_variant)
324
+ draw_text_centered_y(canvas, kv, kr.x + 10.0, kr.y + 33.0, sec_f, c.on_surface)
325
+ elif kind == "table_chunk":
326
+ ty, hdrs, rows, widths, aligns, rh, totals = payload
327
+ hdr_h = 24.0
328
+ # Table Header
329
+ canvas.drawRect(
330
+ skia.Rect.MakeXYWH(m, ty, c_w, hdr_h),
331
+ skia.Paint(Color=c.surface_container.to_skia()),
332
+ )
333
+ cx = m
334
+ for ci, htxt in enumerate(hdrs):
335
+ w = widths[ci]
336
+ al = aligns[ci] if ci < len(aligns) else "left"
337
+ tw = measure_text(hdr_f, htxt)
338
+ tx = cx + 6.0 if al == "left" else (cx + (w - tw) * 0.5 if al == "center" else cx + w - tw - 6.0)
339
+ draw_text_centered_y(canvas, htxt, tx, ty + hdr_h * 0.5, hdr_f, c.on_surface)
340
+ cx += w
341
+ ry = ty + hdr_h
342
+
343
+ # Rows
344
+ div_p = skia.Paint(Color=c.outline_variant.to_skia(), StrokeWidth=0.6)
345
+ for r_i, row in enumerate(rows):
346
+ if r_i % 2 == 1:
347
+ canvas.drawRect(
348
+ skia.Rect.MakeXYWH(m, ry, c_w, rh),
349
+ skia.Paint(Color=c.surface_container_lowest.to_skia()),
350
+ )
351
+ cx = m
352
+ for ci in range(len(hdrs)):
353
+ w = widths[ci]
354
+ val = row[ci] if ci < len(row) else ""
355
+ al = aligns[ci] if ci < len(aligns) else "left"
356
+ tw = measure_text(body_f, val)
357
+ tx = cx + 6.0 if al == "left" else (cx + (w - tw) * 0.5 if al == "center" else cx + w - tw - 6.0)
358
+ draw_text_centered_y(canvas, val, tx, ry + rh * 0.5, body_f, c.on_surface)
359
+ cx += w
360
+ canvas.drawLine(m, ry + rh, m + c_w, ry + rh, div_p)
361
+ ry += rh
362
+
363
+ # Totals Footer
364
+ if totals:
365
+ canvas.drawRect(
366
+ skia.Rect.MakeXYWH(m, ry, c_w, rh),
367
+ skia.Paint(Color=c.primary_container.to_skia()),
368
+ )
369
+ cx = m
370
+ for ci in range(len(hdrs)):
371
+ w = widths[ci]
372
+ val = totals[ci] if ci < len(totals) else ""
373
+ al = aligns[ci] if ci < len(aligns) else "left"
374
+ tw = measure_text(hdr_f, val)
375
+ tx = cx + 6.0 if al == "left" else (cx + (w - tw) * 0.5 if al == "center" else cx + w - tw - 6.0)
376
+ draw_text_centered_y(canvas, val, tx, ry + rh * 0.5, hdr_f, c.on_primary_container)
377
+ cx += w
378
+
379
+ # Page Footer + "Página X de Y"
380
+ fy = self.page_h - m - 12.0
381
+ canvas.drawLine(m, fy - 10.0, self.page_w - m, fy - 10.0, skia.Paint(Color=c.outline_variant.to_skia(), StrokeWidth=0.6))
382
+ draw_text_centered_y(canvas, self._footer_text, m, fy, small_f, c.on_surface_variant)
383
+ p_txt = f"Página {p_idx} de {total_pages}"
384
+ pw = measure_text(small_f, p_txt)
385
+ draw_text_centered_y(canvas, p_txt, self.page_w - m - pw, fy, small_f, c.on_surface_variant)
386
+
387
+ doc.endPage()
388
+
389
+ doc.close()
390
+ return dest