pyweft 0.2.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.
- pyweft/__init__.py +60 -0
- pyweft/__main__.py +4 -0
- pyweft/background.py +203 -0
- pyweft/binding.py +118 -0
- pyweft/cli.py +1006 -0
- pyweft/component.py +487 -0
- pyweft/desktop.py +606 -0
- pyweft/dialogs.py +123 -0
- pyweft/differ.py +195 -0
- pyweft/dommodel.py +63 -0
- pyweft/effects.py +191 -0
- pyweft/events.py +102 -0
- pyweft/expressions.py +184 -0
- pyweft/hotreload.py +122 -0
- pyweft/packaging.py +186 -0
- pyweft/parser.py +426 -0
- pyweft/prerender.py +121 -0
- pyweft/renderer.py +802 -0
- pyweft/routing.py +364 -0
- pyweft/static/loading.html +102 -0
- pyweft/static/runtime.js +341 -0
- pyweft/static/shell.html +693 -0
- pyweft/static/worker.js +89 -0
- pyweft/store.py +118 -0
- pyweft/styles.py +171 -0
- pyweft/vdom.py +57 -0
- pyweft-0.2.0.dist-info/METADATA +324 -0
- pyweft-0.2.0.dist-info/RECORD +31 -0
- pyweft-0.2.0.dist-info/WHEEL +4 -0
- pyweft-0.2.0.dist-info/entry_points.txt +2 -0
- pyweft-0.2.0.dist-info/licenses/LICENSE +21 -0
pyweft/expressions.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Expression compilation and evaluation.
|
|
2
|
+
|
|
3
|
+
Every ``{{ expr }}`` and every directive value is compiled once with
|
|
4
|
+
``compile(..., "eval")`` and cached by source text, then evaluated against a
|
|
5
|
+
``Scope`` at render time. Compiling at parse time rather than calling ``eval``
|
|
6
|
+
on a string every render is the single biggest perf lever in the render loop.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import builtins
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Mapping, MutableMapping
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ExpressionError(RuntimeError):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_CACHE: dict[str, Any] = {}
|
|
22
|
+
_GLOBALS: dict[str, Any] = {"__builtins__": builtins}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def compile_expr(src: str):
|
|
26
|
+
src = src.strip()
|
|
27
|
+
code = _CACHE.get(src)
|
|
28
|
+
if code is None:
|
|
29
|
+
try:
|
|
30
|
+
code = compile(src, "<pyweft>", "eval")
|
|
31
|
+
except SyntaxError as exc:
|
|
32
|
+
raise ExpressionError(f"bad expression {src!r}: {exc}") from exc
|
|
33
|
+
_CACHE[src] = code
|
|
34
|
+
return code
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Scope(MutableMapping):
|
|
38
|
+
"""Name resolution for template expressions.
|
|
39
|
+
|
|
40
|
+
Looks in loop variables first, then falls back to attributes on the
|
|
41
|
+
component instance. Passed to ``eval`` as the locals mapping, so a bare
|
|
42
|
+
name in a template resolves the way you'd expect without the component
|
|
43
|
+
needing to copy its state into a dict every render. ``self`` names the
|
|
44
|
+
component itself.
|
|
45
|
+
|
|
46
|
+
It is also the locals mapping for inline handler *statements*
|
|
47
|
+
(``@click="count += 1"``): a store to a loop variable stays in the scope,
|
|
48
|
+
a store to anything else becomes component state.
|
|
49
|
+
|
|
50
|
+
Known limitation: comprehensions and lambdas inside an expression build
|
|
51
|
+
their own frame and only see globals, so ``{{ [x for x in items] }}``
|
|
52
|
+
cannot see ``items``. Assign such values in the code block instead.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
__slots__ = ("component", "vars")
|
|
56
|
+
|
|
57
|
+
def __init__(self, component: Any, vars: dict | None = None):
|
|
58
|
+
self.component = component
|
|
59
|
+
self.vars = dict(vars) if vars else {}
|
|
60
|
+
|
|
61
|
+
def child(self, **extra) -> Scope:
|
|
62
|
+
scope = Scope(self.component, self.vars)
|
|
63
|
+
scope.vars.update(extra)
|
|
64
|
+
return scope
|
|
65
|
+
|
|
66
|
+
def __getitem__(self, name: str) -> Any:
|
|
67
|
+
if name in self.vars:
|
|
68
|
+
return self.vars[name]
|
|
69
|
+
if name == "self":
|
|
70
|
+
return self.component
|
|
71
|
+
try:
|
|
72
|
+
return getattr(self.component, name)
|
|
73
|
+
except AttributeError:
|
|
74
|
+
raise KeyError(name) from None
|
|
75
|
+
|
|
76
|
+
def __setitem__(self, name: str, value: Any) -> None:
|
|
77
|
+
if name in self.vars:
|
|
78
|
+
self.vars[name] = value
|
|
79
|
+
else:
|
|
80
|
+
setattr(self.component, name, value)
|
|
81
|
+
|
|
82
|
+
def __delitem__(self, name: str) -> None:
|
|
83
|
+
if name in self.vars:
|
|
84
|
+
del self.vars[name]
|
|
85
|
+
else:
|
|
86
|
+
delattr(self.component, name)
|
|
87
|
+
|
|
88
|
+
def __iter__(self):
|
|
89
|
+
seen = set(self.vars)
|
|
90
|
+
yield from self.vars
|
|
91
|
+
for name in dir(self.component):
|
|
92
|
+
if not name.startswith("_") and name not in seen:
|
|
93
|
+
yield name
|
|
94
|
+
|
|
95
|
+
def __len__(self) -> int:
|
|
96
|
+
return sum(1 for _ in self)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def eval_expr(src: str, scope: Mapping) -> Any:
|
|
100
|
+
code = compile_expr(src)
|
|
101
|
+
try:
|
|
102
|
+
return eval(code, _GLOBALS, scope)
|
|
103
|
+
except ExpressionError:
|
|
104
|
+
raise
|
|
105
|
+
except Exception as exc:
|
|
106
|
+
raise ExpressionError(
|
|
107
|
+
f"error evaluating {src!r}: {type(exc).__name__}: {exc}"
|
|
108
|
+
) from exc
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
_HANDLER_CACHE: dict[str, tuple[Any, bool]] = {}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def compile_handler(src: str) -> tuple[Any, bool]:
|
|
115
|
+
"""Compile a handler value; returns ``(code, is_expression)``.
|
|
116
|
+
|
|
117
|
+
A handler is normally an expression (``remove(item)``), but the simple
|
|
118
|
+
inline cases people reach for are statements (``count += 1``,
|
|
119
|
+
``show = not show``, ``a = 1; b = 2``), so fall back to ``exec`` mode when
|
|
120
|
+
``eval`` mode does not parse.
|
|
121
|
+
"""
|
|
122
|
+
src = src.strip()
|
|
123
|
+
hit = _HANDLER_CACHE.get(src)
|
|
124
|
+
if hit is None:
|
|
125
|
+
try:
|
|
126
|
+
hit = (compile(src, "<pyweft>", "eval"), True)
|
|
127
|
+
except SyntaxError:
|
|
128
|
+
try:
|
|
129
|
+
hit = (compile(src, "<pyweft>", "exec"), False)
|
|
130
|
+
except SyntaxError as exc:
|
|
131
|
+
raise ExpressionError(f"bad handler {src!r}: {exc}") from exc
|
|
132
|
+
_HANDLER_CACHE[src] = hit
|
|
133
|
+
return hit
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def run_handler(src: str, scope: MutableMapping) -> Any:
|
|
137
|
+
"""Evaluate an expression handler, or execute a statement handler
|
|
138
|
+
(returning ``None``), against ``scope``."""
|
|
139
|
+
code, is_expr = compile_handler(src)
|
|
140
|
+
try:
|
|
141
|
+
if is_expr:
|
|
142
|
+
return eval(code, _GLOBALS, scope)
|
|
143
|
+
exec(code, _GLOBALS, scope)
|
|
144
|
+
return None
|
|
145
|
+
except ExpressionError:
|
|
146
|
+
raise
|
|
147
|
+
except Exception as exc:
|
|
148
|
+
raise ExpressionError(
|
|
149
|
+
f"error running handler {src!r}: {type(exc).__name__}: {exc}"
|
|
150
|
+
) from exc
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
_INTERP = re.compile(r"\{\{(.*?)\}\}", re.S)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def parse_interpolation(text: str) -> list[tuple[str, str]]:
|
|
157
|
+
"""'a {{x}} b' -> [('static','a '), ('expr','x'), ('static',' b')]"""
|
|
158
|
+
parts: list[tuple[str, str]] = []
|
|
159
|
+
pos = 0
|
|
160
|
+
for match in _INTERP.finditer(text):
|
|
161
|
+
if match.start() > pos:
|
|
162
|
+
parts.append(("static", text[pos : match.start()]))
|
|
163
|
+
parts.append(("expr", match.group(1).strip()))
|
|
164
|
+
pos = match.end()
|
|
165
|
+
if pos < len(text):
|
|
166
|
+
parts.append(("static", text[pos:]))
|
|
167
|
+
return parts or [("static", "")]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def render_parts(parts: list[tuple[str, str]], scope: Mapping) -> str:
|
|
171
|
+
if len(parts) == 1 and parts[0][0] == "static":
|
|
172
|
+
return parts[0][1]
|
|
173
|
+
out = []
|
|
174
|
+
for kind, val in parts:
|
|
175
|
+
if kind == "static":
|
|
176
|
+
out.append(val)
|
|
177
|
+
else:
|
|
178
|
+
value = eval_expr(val, scope)
|
|
179
|
+
out.append("" if value is None else str(value))
|
|
180
|
+
return "".join(out)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def is_static(parts: list[tuple[str, str]]) -> bool:
|
|
184
|
+
return all(kind == "static" for kind, _ in parts)
|
pyweft/hotreload.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Hot reload: move live components onto freshly compiled classes.
|
|
2
|
+
|
|
3
|
+
During development the host recompiles the app from its files and calls
|
|
4
|
+
``hot_swap``. Each live instance -- root and children -- has its class
|
|
5
|
+
replaced by the new class compiled from the same file, keeping the instance's
|
|
6
|
+
``__dict__``: that dict *is* the component's state, so counters, typed input
|
|
7
|
+
and lists survive the edit. The next render shows the new template and the
|
|
8
|
+
differ patches only what changed.
|
|
9
|
+
|
|
10
|
+
The swap has to happen before rendering: the renderer replaces a child whose
|
|
11
|
+
class is not the one its parent's registry names, which would reset it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import copy
|
|
17
|
+
import traceback
|
|
18
|
+
from pathlib import PurePosixPath
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from .effects import dispose_effects
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _source_file(cls: type) -> str | None:
|
|
25
|
+
# Own attribute only: a subclass of a loaded component is not that file.
|
|
26
|
+
return vars(cls).get("__weft_file__")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def classes_by_file(root: type) -> dict[str, type]:
|
|
30
|
+
"""Every class reachable from ``root`` through ``components``
|
|
31
|
+
registries, keyed by the file it was loaded from."""
|
|
32
|
+
found: dict[str, type] = {}
|
|
33
|
+
seen: set[type] = set()
|
|
34
|
+
|
|
35
|
+
def walk(cls: type) -> None:
|
|
36
|
+
if cls in seen:
|
|
37
|
+
return
|
|
38
|
+
seen.add(cls)
|
|
39
|
+
source = _source_file(cls)
|
|
40
|
+
if source is not None:
|
|
41
|
+
found.setdefault(source, cls)
|
|
42
|
+
for child in getattr(cls, "components", {}).values():
|
|
43
|
+
walk(child)
|
|
44
|
+
|
|
45
|
+
walk(root)
|
|
46
|
+
return found
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _add_new_defaults(instance: Any, cls: type) -> None:
|
|
50
|
+
"""Fields added in the edit read their class default; mutable ones must
|
|
51
|
+
be copied per instance, exactly as Component.__init__ does."""
|
|
52
|
+
for name in dir(cls):
|
|
53
|
+
if name.startswith("_") or name == "components" or name in vars(instance):
|
|
54
|
+
continue
|
|
55
|
+
try:
|
|
56
|
+
value = getattr(cls, name)
|
|
57
|
+
except AttributeError:
|
|
58
|
+
continue
|
|
59
|
+
if isinstance(value, (list, dict, set)):
|
|
60
|
+
setattr(instance, name, copy.deepcopy(value))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def hot_swap(renderer: Any, new_root: type) -> list[str]:
|
|
64
|
+
"""Move every live component of ``renderer`` onto its class in the newly
|
|
65
|
+
loaded tree under ``new_root``. Returns the files whose source changed.
|
|
66
|
+
|
|
67
|
+
State (instance attributes) is kept. Components whose source changed
|
|
68
|
+
have their effects cleaned up and reset, so they run again with the new
|
|
69
|
+
code after the next render; ``on_init`` does not run again.
|
|
70
|
+
"""
|
|
71
|
+
by_file = classes_by_file(new_root)
|
|
72
|
+
changed: list[str] = []
|
|
73
|
+
for instance in [renderer.component, *renderer.instances.values()]:
|
|
74
|
+
old = type(instance)
|
|
75
|
+
if instance is renderer.component:
|
|
76
|
+
new = new_root
|
|
77
|
+
else:
|
|
78
|
+
new = by_file.get(_source_file(old) or "")
|
|
79
|
+
if new is None or new is old:
|
|
80
|
+
continue # not from a file, or the file is gone: render decides
|
|
81
|
+
if vars(old).get("__weft_src__") != vars(new).get("__weft_src__"):
|
|
82
|
+
dispose_effects(instance)
|
|
83
|
+
instance.__dict__.pop("_pw_effects", None)
|
|
84
|
+
source = _source_file(new)
|
|
85
|
+
if source is not None and source not in changed:
|
|
86
|
+
changed.append(source)
|
|
87
|
+
instance.__class__ = new
|
|
88
|
+
_add_new_defaults(instance, new)
|
|
89
|
+
instance._dirty = True
|
|
90
|
+
return changed
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def format_error(exc: BaseException, root: str | None = None) -> str:
|
|
94
|
+
"""A short, readable description of an error raised while reloading:
|
|
95
|
+
the location in the ``.weft`` file where possible, then the error itself.
|
|
96
|
+
Paths are shown relative to ``root`` when given."""
|
|
97
|
+
|
|
98
|
+
def where(path: str) -> str:
|
|
99
|
+
if root:
|
|
100
|
+
try:
|
|
101
|
+
return str(PurePosixPath(path).relative_to(root))
|
|
102
|
+
except ValueError:
|
|
103
|
+
pass
|
|
104
|
+
return path
|
|
105
|
+
|
|
106
|
+
lines: list[str] = []
|
|
107
|
+
frames = [
|
|
108
|
+
(f.filename, f.lineno, f.line) for f in traceback.extract_tb(exc.__traceback__)
|
|
109
|
+
]
|
|
110
|
+
# Raised by run_in_background: where it failed in the background too.
|
|
111
|
+
frames += getattr(exc, "_pyweft_background_frames", [])
|
|
112
|
+
for filename, lineno, line in frames:
|
|
113
|
+
if filename.endswith(".weft"):
|
|
114
|
+
code = f": {line.strip()}" if line else ""
|
|
115
|
+
lines.append(f"{where(filename)}, line {lineno}{code}")
|
|
116
|
+
if isinstance(exc, SyntaxError) and exc.filename and exc.filename.endswith(".weft"):
|
|
117
|
+
text = (exc.text or "").strip()
|
|
118
|
+
lines.append(f"{where(exc.filename)}, line {exc.lineno}: {text}".rstrip(": "))
|
|
119
|
+
lines.append(f"SyntaxError: {exc.msg}")
|
|
120
|
+
else:
|
|
121
|
+
lines.append(f"{type(exc).__name__}: {exc}")
|
|
122
|
+
return "\n".join(lines)
|
pyweft/packaging.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""A desktop app to hand out: ``pyweft build APP --desktop``.
|
|
2
|
+
|
|
3
|
+
PyInstaller bundles Python, the app's files and everything they use into
|
|
4
|
+
one runnable file: an .exe on Windows, a .app on macOS, a program on Linux.
|
|
5
|
+
The people who run it need nothing installed.
|
|
6
|
+
|
|
7
|
+
PyInstaller finds what to bundle by following ``import`` statements in
|
|
8
|
+
``.py`` files. An app's imports mostly live in ``.weft`` code blocks, which
|
|
9
|
+
it never reads, so this file reads them (and the app's own modules, and its
|
|
10
|
+
component libraries) and names every imported module for it. Component
|
|
11
|
+
libraries are collected whole, since their ``.weft`` files are data.
|
|
12
|
+
|
|
13
|
+
Host-only, like cli.py: never shipped to the browser.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import ast
|
|
19
|
+
import re
|
|
20
|
+
import shutil
|
|
21
|
+
import subprocess
|
|
22
|
+
import sys
|
|
23
|
+
import tempfile
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from .cli import (
|
|
27
|
+
ASSETS_DIR,
|
|
28
|
+
HEAD_FILE,
|
|
29
|
+
CliError,
|
|
30
|
+
app_assets,
|
|
31
|
+
app_css_files,
|
|
32
|
+
app_identity,
|
|
33
|
+
app_libraries,
|
|
34
|
+
app_python_files,
|
|
35
|
+
app_pyweft_files,
|
|
36
|
+
)
|
|
37
|
+
from .parser import split_source
|
|
38
|
+
|
|
39
|
+
_SEP = ";" if sys.platform == "win32" else ":" # PyInstaller's --add-data
|
|
40
|
+
_LAUNCHER = """\
|
|
41
|
+
# Generated by `pyweft build --desktop`: starts the packaged app.
|
|
42
|
+
import sys
|
|
43
|
+
from pathlib import Path
|
|
44
|
+
|
|
45
|
+
from pyweft.desktop import run_packaged
|
|
46
|
+
|
|
47
|
+
run_packaged(Path(getattr(sys, "_MEIPASS", Path(__file__).parent)) / "app")
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def code_imports(source: str) -> set[str]:
|
|
52
|
+
"""Top-level modules a piece of Python imports (``csv``, ``pyweft_ui``),
|
|
53
|
+
relative imports aside. Unparseable code imports nothing here: the
|
|
54
|
+
app's own error shows when it runs."""
|
|
55
|
+
try:
|
|
56
|
+
tree = ast.parse(source)
|
|
57
|
+
except SyntaxError:
|
|
58
|
+
return set()
|
|
59
|
+
names: set[str] = set()
|
|
60
|
+
for node in ast.walk(tree):
|
|
61
|
+
if isinstance(node, ast.Import):
|
|
62
|
+
names.update(alias.name.split(".")[0] for alias in node.names)
|
|
63
|
+
elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
|
|
64
|
+
names.add(node.module.split(".")[0])
|
|
65
|
+
return names
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _weft_imports(path: Path) -> set[str]:
|
|
69
|
+
try:
|
|
70
|
+
_, code, _ = split_source(path.read_text(encoding="utf-8"))
|
|
71
|
+
except Exception: # noqa: BLE001 - a broken file fails at run time instead
|
|
72
|
+
return set()
|
|
73
|
+
return code_imports(code)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def app_imports(app_dir: Path) -> set[str]:
|
|
77
|
+
"""Every module the app's code imports, from its .weft code blocks, its
|
|
78
|
+
own .py modules and its component libraries, minus its own modules
|
|
79
|
+
(bundled as files, not found by PyInstaller)."""
|
|
80
|
+
names: set[str] = set()
|
|
81
|
+
for rel in app_pyweft_files(app_dir):
|
|
82
|
+
names |= _weft_imports(app_dir / rel)
|
|
83
|
+
own = set()
|
|
84
|
+
for rel in app_python_files(app_dir):
|
|
85
|
+
names |= code_imports((app_dir / rel).read_text(encoding="utf-8"))
|
|
86
|
+
own.add(Path(rel).parts[0].removesuffix(".py"))
|
|
87
|
+
for library in app_libraries(app_dir):
|
|
88
|
+
for rel in library.files:
|
|
89
|
+
path = library.folder / rel
|
|
90
|
+
if rel.endswith(".weft"):
|
|
91
|
+
names |= _weft_imports(path)
|
|
92
|
+
elif rel.endswith(".py"):
|
|
93
|
+
names |= code_imports(path.read_text(encoding="utf-8"))
|
|
94
|
+
# Browser-only modules don't exist here; code that needs them guards.
|
|
95
|
+
return names - own - {"js", "pyodide", "pyodide_js", "micropip", "__future__"}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def app_file_name(title: str) -> str:
|
|
99
|
+
"""The title as a file name: ``Acme Orders`` stays, ``A/B: C`` loses
|
|
100
|
+
what file systems refuse."""
|
|
101
|
+
name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "", title).strip(" .")
|
|
102
|
+
return name or "app"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _stage(app_dir: Path, into: Path) -> None:
|
|
106
|
+
# Only what the app ships: never dist/, a .venv or anything else lying
|
|
107
|
+
# around in its folder.
|
|
108
|
+
files = app_pyweft_files(app_dir) + app_python_files(app_dir) + app_css_files(app_dir)
|
|
109
|
+
files += [f"{ASSETS_DIR}/{rel}" for rel in app_assets(app_dir)]
|
|
110
|
+
files += [name for name in ("pyproject.toml", HEAD_FILE) if (app_dir / name).is_file()]
|
|
111
|
+
for rel in files:
|
|
112
|
+
target = into / rel
|
|
113
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
114
|
+
shutil.copy2(app_dir / rel, target)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _icon_args(app_dir: Path, icon: str | None) -> list[str]:
|
|
118
|
+
# PyInstaller wants an .ico on Windows and an .icns on macOS; Linux
|
|
119
|
+
# programs carry no icon of their own.
|
|
120
|
+
if icon is None:
|
|
121
|
+
return []
|
|
122
|
+
wanted = {"win32": ".ico", "darwin": ".icns"}.get(sys.platform)
|
|
123
|
+
if wanted and icon.lower().endswith(wanted):
|
|
124
|
+
return ["--icon", str((app_dir / icon).resolve())]
|
|
125
|
+
if wanted:
|
|
126
|
+
print(f"pyweft: the built app keeps the default icon: {icon} isn't an {wanted} file")
|
|
127
|
+
return []
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def pyinstaller_args(app_dir: Path, out: Path, work: Path) -> list[str]:
|
|
131
|
+
"""The PyInstaller command line for an app, staged in ``work``."""
|
|
132
|
+
app_dir = Path(app_dir).resolve()
|
|
133
|
+
identity = app_identity(app_dir)
|
|
134
|
+
staged = work / "app"
|
|
135
|
+
launcher = work / "launch.py"
|
|
136
|
+
args = [
|
|
137
|
+
str(launcher),
|
|
138
|
+
"--onefile",
|
|
139
|
+
"--windowed", # no console window behind the app
|
|
140
|
+
"--noconfirm",
|
|
141
|
+
"--log-level", "WARN",
|
|
142
|
+
"--name", app_file_name(identity.title),
|
|
143
|
+
"--distpath", str(Path(out).resolve()),
|
|
144
|
+
"--workpath", str(work / "build"),
|
|
145
|
+
"--specpath", str(work),
|
|
146
|
+
"--add-data", f"{staged}{_SEP}app",
|
|
147
|
+
"--collect-all", "pyweft", # the runtime, the page, every module
|
|
148
|
+
]
|
|
149
|
+
for library in app_libraries(app_dir):
|
|
150
|
+
args += ["--collect-all", library.name]
|
|
151
|
+
for name in sorted(app_imports(app_dir)):
|
|
152
|
+
args += ["--hidden-import", name]
|
|
153
|
+
return args + _icon_args(app_dir, identity.icon)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def build_desktop(app_dir: Path, out: Path) -> Path:
|
|
157
|
+
"""Build the app into ``out`` and return what was built."""
|
|
158
|
+
app_dir = Path(app_dir).resolve()
|
|
159
|
+
app_pyweft_files(app_dir) # fails fast without an app.weft
|
|
160
|
+
identity = app_identity(app_dir) # and on a mistake in the settings
|
|
161
|
+
from .desktop import window_options
|
|
162
|
+
|
|
163
|
+
window_options(app_dir)
|
|
164
|
+
try:
|
|
165
|
+
import PyInstaller # noqa: F401
|
|
166
|
+
import webview # noqa: F401
|
|
167
|
+
except ImportError:
|
|
168
|
+
raise CliError(
|
|
169
|
+
"building a desktop app needs PyInstaller and pywebview: "
|
|
170
|
+
'uv add --dev "pyweft[package]" (or: pip install "pyweft[package]")'
|
|
171
|
+
) from None
|
|
172
|
+
|
|
173
|
+
with tempfile.TemporaryDirectory(prefix="pyweft-build-") as tmp:
|
|
174
|
+
work = Path(tmp)
|
|
175
|
+
_stage(app_dir, work / "app")
|
|
176
|
+
(work / "launch.py").write_text(_LAUNCHER, encoding="utf-8")
|
|
177
|
+
args = pyinstaller_args(app_dir, out, work)
|
|
178
|
+
print(f"pyweft: building {identity.title} with PyInstaller (this takes a minute)")
|
|
179
|
+
result = subprocess.run([sys.executable, "-m", "PyInstaller", *args], cwd=work)
|
|
180
|
+
if result.returncode != 0:
|
|
181
|
+
raise CliError("PyInstaller failed; its messages are above")
|
|
182
|
+
|
|
183
|
+
name = app_file_name(identity.title)
|
|
184
|
+
built = Path(out) / {"win32": f"{name}.exe", "darwin": f"{name}.app"}.get(sys.platform, name)
|
|
185
|
+
print(f"built {built}")
|
|
186
|
+
return built
|