compilekv 0.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.
compilekv/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """Compile Kivy KV files into Python classes.
2
+
3
+ A library, meant to be imported:
4
+
5
+ import compilekv
6
+ compilekv.compile_file("ui/style.kv")
7
+
8
+ The conversion is a Swift package compiled to WebAssembly, so the wheel is
9
+ platform independent. `python -m compilekv` exists but is not the interface.
10
+ """
11
+
12
+ from .compiler import (
13
+ Project,
14
+ collect_directives,
15
+ compile_file,
16
+ compile_tree,
17
+ find_kv_files,
18
+ output_path_for,
19
+ source_path_for,
20
+ )
21
+ from .runtime import KvCompileError, KvCompiler, default_compiler
22
+
23
+ __all__ = [
24
+ "Project",
25
+ "KvCompileError",
26
+ "KvCompiler",
27
+ "collect_directives",
28
+ "compile_file",
29
+ "compile_tree",
30
+ "default_compiler",
31
+ "find_kv_files",
32
+ "output_path_for",
33
+ "source_path_for",
34
+ ]
compilekv/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Entry point for ``python -m compilekv``."""
2
+
3
+ from .cli import run
4
+
5
+ raise SystemExit(run())
compilekv/cli.py ADDED
@@ -0,0 +1,83 @@
1
+ """Argument parsing for `python -m compilekv`. The library is in compiler.py."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .compiler import Project, compile_file, find_kv_files
10
+ from .runtime import KvCompileError, default_compiler
11
+
12
+
13
+ def run(argv: list[str] | None = None) -> int:
14
+ parser = argparse.ArgumentParser(
15
+ prog="compilekv",
16
+ description="Compile Kivy KV files into Python classes using the CompileKvWasm module.",
17
+ )
18
+ parser.add_argument(
19
+ "paths",
20
+ nargs="*",
21
+ default=["."],
22
+ help="KV files or directories to compile (defaults to the current directory).",
23
+ )
24
+ parser.add_argument(
25
+ "-o",
26
+ "--output",
27
+ help="Output directory, or a file name when compiling a single KV file. "
28
+ "Defaults to writing next to each .kv.",
29
+ )
30
+ parser.add_argument(
31
+ "--no-recursive",
32
+ action="store_true",
33
+ help="Do not descend into subdirectories.",
34
+ )
35
+ parser.add_argument(
36
+ "-q",
37
+ "--quiet",
38
+ action="store_true",
39
+ help="Only report errors.",
40
+ )
41
+ args = parser.parse_args(argv)
42
+
43
+ roots = [Path(path) for path in args.paths]
44
+ for root in roots:
45
+ if not root.exists():
46
+ print(f"error: {root} does not exist", file=sys.stderr)
47
+ return 1
48
+
49
+ # Everything is read before anything is written, so a `#:set` in the last
50
+ # file scanned is still available to the first file generated.
51
+ project = Project.scan(roots, recursive=not args.no_recursive)
52
+ if not project.kv_files:
53
+ print("No .kv files found.", file=sys.stderr)
54
+ return 1
55
+
56
+ compiler = default_compiler()
57
+ failures = 0
58
+ for root in roots:
59
+ for kv_path in find_kv_files(root, recursive=not args.no_recursive):
60
+ try:
61
+ written = compile_file(
62
+ kv_path,
63
+ _target_for(kv_path, root, args.output),
64
+ compiler,
65
+ project.directives,
66
+ )
67
+ except KvCompileError as error:
68
+ print(f"error: {kv_path}: {error}", file=sys.stderr)
69
+ failures += 1
70
+ continue
71
+ if not args.quiet:
72
+ print(f"{kv_path} -> {written}")
73
+
74
+ return 1 if failures else 0
75
+
76
+
77
+ def _target_for(kv_path: Path, root: Path, output: str | None) -> Path | None:
78
+ """A directory input means a directory output, mirroring the tree under it."""
79
+ if output is None:
80
+ return None
81
+ if root.is_file():
82
+ return Path(output)
83
+ return Path(output) / kv_path.parent.relative_to(root)
Binary file
compilekv/compiler.py ADDED
@@ -0,0 +1,144 @@
1
+ """Find .kv files, run them through wasm, write the .py."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Iterable
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from .runtime import KvCompiler, default_compiler
11
+
12
+
13
+ def output_path_for(kv_path: str | Path, output: str | Path | None = None) -> Path:
14
+ """Where `kv_path` is written. `output` may be a directory or a file name."""
15
+ kv_path = Path(kv_path)
16
+ if output is None:
17
+ return kv_path.with_suffix(".py")
18
+ output = Path(output)
19
+ if output.is_dir() or not output.suffix:
20
+ return output / kv_path.with_suffix(".py").name
21
+ return output
22
+
23
+
24
+ def source_path_for(kv_path: str | Path) -> Path:
25
+ """The hand written .py beside the .kv, whose contents get extended."""
26
+ return Path(kv_path).with_suffix(".py")
27
+
28
+
29
+ # `#: set` with a space is as valid as `#:set`.
30
+ SHARED_DIRECTIVE = re.compile(r"^#:\s*(set|import)\s+\S+\s+\S.*$")
31
+
32
+
33
+ def collect_directives(paths: Iterable[str | Path]) -> str:
34
+ """The `#:set` and `#:import` lines from every given file.
35
+
36
+ KV puts both in one namespace shared by everything Builder loads -- a
37
+ theme file defines the constants, one widget file imports a helper another
38
+ one uses -- so compiling any file needs the directives from all of them.
39
+
40
+ Python files are worth reading for the same reason: KV passed to
41
+ `Builder.load_string()` carries directives that the .kv files rely on.
42
+ """
43
+ lines: list[str] = []
44
+ for path in paths:
45
+ try:
46
+ source = Path(path).read_text(encoding="utf-8")
47
+ except (OSError, UnicodeDecodeError):
48
+ continue
49
+ for line in source.splitlines():
50
+ stripped = line.strip()
51
+ if SHARED_DIRECTIVE.match(stripped) and stripped not in lines:
52
+ lines.append(stripped)
53
+ return "\n".join(lines)
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Project:
58
+ """The .kv files to compile, and everything they share.
59
+
60
+ Gathered in full before anything is generated, so a file can use a
61
+ `#:set` from a file that comes later in the walk -- a theme file is
62
+ usually last alphabetically and always needed first.
63
+ """
64
+
65
+ kv_files: tuple[Path, ...]
66
+ directives: str
67
+
68
+ @classmethod
69
+ def scan(cls, roots: str | Path | Iterable[str | Path], recursive: bool = True) -> "Project":
70
+ if isinstance(roots, (str, Path)):
71
+ roots = [roots]
72
+ roots = [Path(root) for root in roots]
73
+
74
+ kv_files: list[Path] = []
75
+ for root in roots:
76
+ for path in find_kv_files(root, recursive=recursive):
77
+ if path not in kv_files:
78
+ kv_files.append(path)
79
+
80
+ # Python files can hold KV too, inside Builder.load_string(), and the
81
+ # directives in it are shared with every .kv file.
82
+ sources = list(kv_files)
83
+ pattern = "**/*.py" if recursive else "*.py"
84
+ for root in roots:
85
+ directory = root if root.is_dir() else root.parent
86
+ sources.extend(sorted(p for p in directory.glob(pattern) if p.is_file()))
87
+
88
+ return cls(tuple(kv_files), collect_directives(sources))
89
+
90
+
91
+ def compile_file(
92
+ kv_path: str | Path,
93
+ output: str | Path | None = None,
94
+ compiler: KvCompiler | None = None,
95
+ directives: str = "",
96
+ ) -> Path:
97
+ """Compile one .kv, extending the .py next to it. Returns the file written."""
98
+ kv_path = Path(kv_path)
99
+ target = output_path_for(kv_path, output)
100
+ compiler = compiler or default_compiler()
101
+
102
+ source = source_path_for(kv_path)
103
+ py_source = source.read_text(encoding="utf-8") if source.is_file() else ""
104
+
105
+ generated = compiler.compile_source(
106
+ kv_path.read_text(encoding="utf-8"), py_source, directives
107
+ )
108
+
109
+ target.parent.mkdir(parents=True, exist_ok=True)
110
+ target.write_text(generated, encoding="utf-8")
111
+ return target
112
+
113
+
114
+ def find_kv_files(root: str | Path, recursive: bool = True) -> list[Path]:
115
+ """The .kv files under `root`, or `root` itself if it is one."""
116
+ root = Path(root)
117
+ if root.is_file():
118
+ return [root]
119
+ pattern = "**/*.kv" if recursive else "*.kv"
120
+ return sorted(p for p in root.glob(pattern) if p.is_file())
121
+
122
+
123
+ def compile_tree(
124
+ root: str | Path,
125
+ output_dir: str | Path | None = None,
126
+ recursive: bool = True,
127
+ compiler: KvCompiler | None = None,
128
+ ) -> list[Path]:
129
+ """Compile every .kv under `root` into `output_dir`. Returns what was written."""
130
+ root = Path(root)
131
+ compiler = compiler or default_compiler()
132
+
133
+ # Scan the whole tree before writing anything.
134
+ project = Project.scan(root, recursive=recursive)
135
+
136
+ written = []
137
+ for kv_path in project.kv_files:
138
+ target = None
139
+ if output_dir is not None:
140
+ # Mirror the tree under root so same-named .kv files cannot collide.
141
+ relative = kv_path.parent.relative_to(root) if root.is_dir() else Path()
142
+ target = Path(output_dir) / relative
143
+ written.append(compile_file(kv_path, target, compiler, project.directives))
144
+ return written
compilekv/runtime.py ADDED
@@ -0,0 +1,122 @@
1
+ """Wrapper around the CompileKvWasm module. Strings in, strings out."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from functools import lru_cache
7
+ from importlib import resources
8
+ from pathlib import Path
9
+
10
+ from wasmtime import Engine, Instance, Linker, Module, Store, WasiConfig
11
+
12
+ WASM_FILENAME = "compilekv.wasm"
13
+
14
+ _default_compiler: "KvCompiler | None" = None
15
+ _default_lock = threading.Lock()
16
+
17
+
18
+ def default_compiler() -> "KvCompiler":
19
+ """The process-wide compiler shared by every caller."""
20
+ global _default_compiler
21
+ with _default_lock:
22
+ if _default_compiler is None:
23
+ _default_compiler = KvCompiler()
24
+ return _default_compiler
25
+
26
+
27
+ class KvCompileError(RuntimeError):
28
+ """Raised when the wasm module fails to convert a KV source string."""
29
+
30
+
31
+ def _default_wasm_path() -> Path:
32
+ return Path(str(resources.files(__package__).joinpath(WASM_FILENAME)))
33
+
34
+
35
+ @lru_cache(maxsize=None)
36
+ def _compile_module(path: str, fingerprint: tuple[int, int]) -> tuple[Engine, Module]:
37
+ """Compile once per process; `fingerprint` is (mtime, size) to catch rebuilds."""
38
+ del fingerprint
39
+ engine = Engine()
40
+ return engine, Module.from_file(engine, path)
41
+
42
+
43
+ class KvCompiler:
44
+ """One wasm instance with its own linear memory."""
45
+
46
+ def __init__(self, wasm_path: str | Path | None = None) -> None:
47
+ path = Path(wasm_path) if wasm_path is not None else _default_wasm_path()
48
+ if not path.is_file():
49
+ raise FileNotFoundError(
50
+ f"wasm module not found at {path}. "
51
+ "Build it with `python setup.py build_wasm` or reinstall compilekv."
52
+ )
53
+ self.wasm_path = path
54
+ self._lock = threading.Lock()
55
+
56
+ stat = path.stat()
57
+ engine, module = _compile_module(str(path), (stat.st_mtime_ns, stat.st_size))
58
+
59
+ self._store = Store(engine)
60
+ self._store.set_wasi(WasiConfig())
61
+
62
+ linker = Linker(engine)
63
+ linker.define_wasi()
64
+ self._instance: Instance = linker.instantiate(self._store, module)
65
+
66
+ exports = self._instance.exports(self._store)
67
+ self._memory = exports["memory"]
68
+ self._alloc = exports["kv_alloc"]
69
+ self._dealloc = exports["kv_dealloc"]
70
+ self._convert = exports["kv_convert"]
71
+ self._result_ptr = exports["kv_result_ptr"]
72
+ self._result_len = exports["kv_result_len"]
73
+ self._result_free = exports["kv_result_free"]
74
+
75
+ # A reactor is initialized explicitly, not through `_start`.
76
+ exports["_initialize"](self._store)
77
+
78
+ def _write(self, data: bytes) -> tuple[int, int]:
79
+ if not data:
80
+ return 0, 0
81
+ pointer = self._alloc(self._store, len(data))
82
+ self._memory.write(self._store, data, pointer)
83
+ return pointer, len(data)
84
+
85
+ def _take_result(self) -> str:
86
+ pointer = self._result_ptr(self._store)
87
+ length = self._result_len(self._store)
88
+ if not length:
89
+ return ""
90
+ return bytes(self._memory.read(self._store, pointer, pointer + length)).decode("utf-8")
91
+
92
+ def compile_source(
93
+ self, kv_source: str, py_source: str = "", directives: str = ""
94
+ ) -> str:
95
+ """Convert KV source to Python.
96
+
97
+ `py_source` is the existing .py, if any. `directives` holds `#:set`
98
+ and `#:import` lines from other KV files, which KV shares across a
99
+ project.
100
+ """
101
+ with self._lock:
102
+ kv_ptr, kv_len = self._write(kv_source.encode("utf-8"))
103
+ py_ptr, py_len = self._write(py_source.encode("utf-8"))
104
+ const_ptr, const_len = self._write(directives.encode("utf-8"))
105
+ try:
106
+ status = self._convert(
107
+ self._store, kv_ptr, kv_len, py_ptr, py_len, const_ptr, const_len
108
+ )
109
+ output = self._take_result()
110
+ self._result_free(self._store)
111
+ finally:
112
+ for pointer, length in (
113
+ (kv_ptr, kv_len),
114
+ (py_ptr, py_len),
115
+ (const_ptr, const_len),
116
+ ):
117
+ if length:
118
+ self._dealloc(self._store, pointer, length)
119
+
120
+ if status != 0:
121
+ raise KvCompileError(output or "unknown error")
122
+ return output
@@ -0,0 +1,324 @@
1
+ Metadata-Version: 2.4
2
+ Name: compilekv
3
+ Version: 0.0.0
4
+ Summary: Compile Kivy KV files into Python classes using a Swift WebAssembly module
5
+ Author-email: psychowasp <psychowaspx@gmail.com>
6
+ Requires-Python: >=3.13
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ License-File: LICENSE.txt
10
+ Requires-Dist: wasmtime>=25
11
+ Dynamic: license-file
12
+
13
+ # compilekv
14
+
15
+ **An importable Python module.** `import compilekv` and call it from your own
16
+ code — a build step, an editor plugin, a test fixture, whatever. It compiles
17
+ Kivy `.kv` files into plain Python classes, so widgets can be built without
18
+ `Builder`.
19
+
20
+ ## Why WebAssembly
21
+
22
+ The conversion is [KvToPyClass](KvToPyClass/), a Swift package. Shipping that
23
+ as a native binary would mean a wheel per platform, built on a machine with a
24
+ Swift toolchain, and no wheel at all for anything you did not build for — which
25
+ is fine for a command line tool you install yourself, and useless for a module
26
+ other people import.
27
+
28
+ Compiled to wasm instead, the conversion is just data: one
29
+ `compilekv-0.1.0-py3-none-any.whl` that installs and imports anywhere Python
30
+ runs. Python owns the filesystem — it walks the tree, reads the `.kv` and any
31
+ existing `.py`, and writes the result. The wasm module only ever sees and
32
+ returns strings, so nothing in it is platform specific.
33
+
34
+ The one native piece is the `wasmtime` runtime, which publishes wheels for
35
+ macOS (x86_64, arm64), Linux (x86_64, aarch64; glibc and musl), Windows
36
+ (amd64, arm64) and Android.
37
+
38
+ ## Usage
39
+
40
+ compilekv is a library. Import it and call the helpers:
41
+
42
+ ```python
43
+ from compilekv import compile_file, compile_tree, find_kv_files
44
+
45
+ compile_tree("ui/") # every .kv under a directory, in place
46
+ compile_tree("ui/", "build/") # ... or into a separate tree
47
+ compile_file("ui/style.kv") # one file
48
+ compile_file("ui/style.kv", "build/") # ... written to build/style.py
49
+ ```
50
+
51
+ Each `style.kv` compiles to `style.py`. Give an output directory and the tree
52
+ under the input is mirrored into it, so `ui/panels/style.kv` becomes
53
+ `build/panels/style.py` and same-named files in different directories cannot
54
+ collide. Pass a path with a suffix instead and it is used verbatim as the file
55
+ name.
56
+
57
+ ### Extending, not replacing
58
+
59
+ The `.py` **next to the `.kv`** is the source. It is read whether or not you
60
+ compile into a separate output directory, and the result is that file with the
61
+ generated code folded in: imports the rules need are added to the ones already
62
+ there, a class the KV defines is merged with the same-named class in place, and
63
+ rules with no matching class are appended. Everything else -- module docstring,
64
+ constants, helper functions, unrelated classes -- stays where you put it.
65
+
66
+ Inside a class the author's body is the starting point, so properties,
67
+ annotations, the class docstring, nested classes and hand written methods all
68
+ survive. A generated method replaces the one it shares a name with, with one
69
+ exception: `__init__` is **appended to**, not replaced. Your setup runs first,
70
+ then the widget tree:
71
+
72
+ ```python
73
+ def __init__(self, **kwargs):
74
+ super().__init__(**kwargs)
75
+ self.counter = 0 # yours
76
+ self._bindings = [] # generated from here down
77
+ self.orientation = "vertical"
78
+ ...
79
+ ```
80
+
81
+ Your signature and your `super()` call are the ones kept. Everything from
82
+ `self._bindings = []` onwards is treated as output from a previous run and
83
+ replaced, which is what keeps regenerating from stacking copies of the tree.
84
+
85
+ A `<Name>:` rule styles a class that already exists, so its bases come from
86
+ your Python; `<Name@Base>:` declares them inline. With neither, it falls back
87
+ to `Widget`.
88
+
89
+ Output is deterministic and regenerating is idempotent -- compiling twice
90
+ leaves the files byte for byte identical, which keeps generated code reviewable
91
+ in version control.
92
+
93
+ One consequence of extending rather than replacing: compiling **in place**,
94
+ where the source and the output are the same file, cannot tell a class it
95
+ emitted last run from one you wrote, so deleting a rule leaves its class
96
+ behind. Compile into an output directory for a file that only ever reflects
97
+ the current `.kv`.
98
+
99
+ For direct control over the strings, skipping the file layer entirely:
100
+
101
+ ```python
102
+ from compilekv import default_compiler
103
+
104
+ python_source = default_compiler().compile_source(kv_source, existing_py_source)
105
+ ```
106
+
107
+ `compile_source` raises `KvCompileError` with the parser's message when the KV
108
+ is invalid.
109
+
110
+ ### One wasm module per process
111
+
112
+ Compiling the wasm module takes a few seconds against ~3 ms per conversion, so
113
+ it happens once. `default_compiler()` returns a process-wide instance shared by
114
+ every caller, so any number of modules can import compilekv and convert as often
115
+ as they like without reloading:
116
+
117
+ ```python
118
+ # module_a.py # module_b.py
119
+ from compilekv import compile_file import compilekv
120
+ compile_file("a.kv") compilekv.compile_file("b.kv")
121
+ # ^ pays the load # ^ ~1 ms, same instance
122
+ ```
123
+
124
+ Conversions are serialized on the instance's own lock, so sharing it across
125
+ threads is safe. `KvCompiler()` still builds an isolated instance with its own
126
+ linear memory when you want one; the compiled module is cached either way.
127
+
128
+ ### Command line
129
+
130
+ Secondary, for one-off runs. No console script is installed.
131
+
132
+ ```console
133
+ $ python -m compilekv [paths...] [-o OUT] [--no-recursive] [-q]
134
+ ```
135
+
136
+ `-o` is a directory when the input is one, mirroring its layout, and may be a
137
+ file name when compiling a single `.kv`.
138
+
139
+ ## Tests
140
+
141
+ ```console
142
+ $ COMPILEKV_SKIP_WASM_BUILD=1 uv run --group dev pytest
143
+ ```
144
+
145
+ Drop the environment variable to rebuild the wasm module first. The suite covers
146
+ the wasm ABI, the file walking layer, and the CLI, and finishes with a round trip
147
+ that prints both inputs and the generated output.
148
+
149
+ ## Building from source
150
+
151
+ The wheel bundles a prebuilt `compilekv.wasm`. Rebuilding it needs a Swift
152
+ toolchain plus a matching [Swift SDK for WebAssembly](https://www.swift.org/documentation/articles/wasm-getting-started.html),
153
+ `KvToPyClass/` is vendored in this repo and referenced by relative path, so no
154
+ extra checkout is needed.
155
+
156
+ ```console
157
+ $ python scripts/build_wasm.py # just the wasm module
158
+ $ python -m build --wheel # wasm + wheel
159
+ ```
160
+
161
+ The build picks a wasm SDK matching the active toolchain, falling back to
162
+ `swiftly run +<version>` when the default toolchain is a different version.
163
+ Override with `COMPILEKV_SWIFT`, `COMPILEKV_WASM_SDK`, or set
164
+ `COMPILEKV_SKIP_WASM_BUILD=1` to reuse the module already in `src/compilekv/`.
165
+
166
+ The module is ~46 MB because Swift's Foundation is statically linked (about
167
+ 36 MB of that is Foundation's data tables); the wheel compresses to ~18 MB.
168
+
169
+ ## Wasm ABI
170
+
171
+ The Swift package builds as a WASI reactor exporting:
172
+
173
+ | Export | Purpose |
174
+ | --- | --- |
175
+ | `kv_alloc(size) -> ptr` | allocate an input buffer in linear memory |
176
+ | `kv_dealloc(ptr, size)` | release one |
177
+ | `kv_convert(kv_ptr, kv_len, py_ptr, py_len) -> status` | convert; 0 on success, 1 on error |
178
+ | `kv_result_ptr()` / `kv_result_len()` | the generated source, or the error message |
179
+ | `kv_result_free()` | release the result buffer |
180
+
181
+ ### `root`, `self`, and bindings
182
+
183
+ `root` in KV is the widget the rule applies to, so it becomes `self`:
184
+
185
+ ```kv
186
+ <Card>:
187
+ Label:
188
+ text: root.title
189
+ ```
190
+
191
+ ```python
192
+ label_1.text = self.title
193
+ self.bind(title=label_1.setter("text"))
194
+ ```
195
+
196
+ `self` is the widget whose block the value was written in, so under a child
197
+ it is that child, not the rule:
198
+
199
+ ```kv
200
+ <Card>:
201
+ Label:
202
+ height: self.texture_size[1]
203
+ ```
204
+
205
+ ```python
206
+ label_1.height = label_1.texture_size[1]
207
+ label_1.bind(texture_size=_callback_0)
208
+ ```
209
+
210
+ The `bind` call is only emitted when the attribute is a Kivy property of
211
+ whichever object it is read from. That is answered by the widget registry for
212
+ anything Kivy ships, by the rule for a widget another rule defines, and by the
213
+ class itself for one in your `.py` -- `title = StringProperty("")` binds,
214
+ `title = "x"` does not, because `bind()` on a non-property raises. A widget
215
+ from outside the module cannot be checked, so it is assumed bindable. In a
216
+ mixed expression the bindable names are bound and the rest are read once.
217
+
218
+ ### Directives
219
+
220
+ KV's `#:set` directives are substituted into the generated code, since there is
221
+ no Builder at runtime to resolve them:
222
+
223
+ ```kv
224
+ #:set plex_16 sp(16)
225
+
226
+ <Item>:
227
+ font_size: plex_16
228
+ ```
229
+
230
+ ```python
231
+ from kivy.metrics import sp
232
+ ...
233
+ self.font_size = sp(16)
234
+ ```
235
+
236
+ The file that declares a `#:set` also publishes it, so `.kv` files loaded at
237
+ runtime still resolve the name -- Builder only knows the directives from files
238
+ it has already parsed:
239
+
240
+ ```python
241
+ from kivy.lang.parser import global_idmap
242
+
243
+ global_idmap["plex_16"] = sp(16)
244
+ ```
245
+
246
+ Only the declaring file does this; one that merely uses the constant gets the
247
+ substituted value and nothing else.
248
+
249
+ `#:import` becomes a real import, but only for the names the generated code
250
+ actually reads:
251
+
252
+ ```kv
253
+ #:import get_font_name carbonkivy.utils.get_font_name
254
+ ```
255
+
256
+ ```python
257
+ from carbonkivy.utils import get_font_name
258
+ ```
259
+
260
+ KV puts both kinds in one namespace shared by everything Builder loads, so the
261
+ whole project is read before anything is written. `Project.scan(roots)` walks
262
+ every `.kv` -- and every `.py`, since KV passed to `Builder.load_string()`
263
+ carries directives the `.kv` files rely on -- and `compile_tree` and
264
+ `python -m compilekv` both go through it. Nothing depends on which file is
265
+ walked first. A `#:set` in the file itself wins over a shared one.
266
+ `collect_directives(paths)` exposes the gathering, and
267
+ `compile_file(..., directives=...)` takes the result.
268
+
269
+ ### Declared property types
270
+
271
+ A bare unquoted word normally becomes a string, but not when the property it is
272
+ assigned to cannot hold one. `font_size: SOME_GLOBAL` on a `NumericProperty`
273
+ emits the name, not `"SOME_GLOBAL"`. The type comes from the widget registry or
274
+ from the property your class declares, so `my_size = NumericProperty()` in your
275
+ `.py` is taken into account.
276
+
277
+ ### Canvas
278
+
279
+ A canvas layer becomes a `with` block, the way it is written by hand:
280
+
281
+ ```kv
282
+ <Card>:
283
+ canvas.before:
284
+ Color:
285
+ rgba: (1, 0, 0, 1)
286
+ Rectangle:
287
+ pos: self.pos
288
+ size: self.size
289
+ ```
290
+
291
+ ```python
292
+ with self.canvas.before:
293
+ Color(rgba=(1, 0, 0, 1))
294
+ self.rectangle_1 = Rectangle(pos=self.pos, size=self.size)
295
+ self.bind(pos=_callback_1, size=_callback_2)
296
+ ```
297
+
298
+ An instruction whose properties track something is named so the bindings have
299
+ an object to update; the rest stay anonymous. Child widgets get their own
300
+ canvas blocks, where `self` is that child.
301
+
302
+ ### Factory registration
303
+
304
+ Every generated class is registered, so other KV files and `Builder` can
305
+ resolve it by name:
306
+
307
+ ```python
308
+ Factory.register("MyButton", cls=MyButton)
309
+ ```
310
+
311
+ Existing registrations in your `.py` are left alone rather than duplicated.
312
+
313
+ A widget the KV references that Kivy does not ship and this module does not
314
+ define is assumed to be a custom widget registered elsewhere, so it is taken
315
+ off the Factory instead of guessed at with a `kivy.uix` import:
316
+
317
+ ```python
318
+ MyWidget = Factory.MyWidget
319
+ ```
320
+
321
+ This is a plain constant, not `type MyWidget = Factory.MyWidget`. The PEP 695
322
+ form resolves lazily, which would be nicer, but a `TypeAliasType` is not
323
+ callable and the generated code has to construct the widget. The constant is
324
+ read at import time, so the widget must be registered by then.
@@ -0,0 +1,12 @@
1
+ compilekv/__init__.py,sha256=Iy31Fe314YgXot8QmSbhahpp_FAPVHvTOsWW6eS_J0I,755
2
+ compilekv/__main__.py,sha256=uCxLeKybEIMwwIaDUc072zPbY93L8llRrJkp7pP_jjY,94
3
+ compilekv/cli.py,sha256=NkXJtp_PCeZLdQSyXTOkoA0Ba4o3tTrLwts7nXlJVDg,2665
4
+ compilekv/compilekv.wasm,sha256=VNswOvuodYnnvKBkltINdGknmYE4WbBMtACVQ39Uwco,54575107
5
+ compilekv/compiler.py,sha256=-pidtSxoqQrrleVxK2J2XMMmHb91mrheGCLLjJyStHg,5043
6
+ compilekv/runtime.py,sha256=IqUMFtMKHPFO06k4-eo0cYDJJ8k59zcwaO5OvyS9aUE,4282
7
+ compilekv-0.0.0.dist-info/licenses/LICENSE,sha256=1ang70jO8tCyRHiKyfow8CwzWT5VVqzmi_FciPsP3Cw,1068
8
+ compilekv-0.0.0.dist-info/licenses/LICENSE.txt,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ compilekv-0.0.0.dist-info/METADATA,sha256=RLxzwsFF8Z2NWdweJxrVdgNZ8qcAjDXIDRsLm6MyfjQ,11418
10
+ compilekv-0.0.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
11
+ compilekv-0.0.0.dist-info/top_level.txt,sha256=wvY5qbspjpgq24GkezGcU2ZdgpdUZYfbrCCUeT78cTc,10
12
+ compilekv-0.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kivy School
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ compilekv