pythonqtside 1.1.12__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 (42) hide show
  1. pythonqtside/Qt.py +14 -0
  2. pythonqtside/QtCore.py +14 -0
  3. pythonqtside/QtGui.py +14 -0
  4. pythonqtside/QtNetwork.py +14 -0
  5. pythonqtside/QtOpenGL.py +14 -0
  6. pythonqtside/QtSvg.py +14 -0
  7. pythonqtside/QtUiTools.py +14 -0
  8. pythonqtside/QtWidgets.py +14 -0
  9. pythonqtside/QtXmlPatterns.py +14 -0
  10. pythonqtside/__init__.py +34 -0
  11. pythonqtside/_app.py +319 -0
  12. pythonqtside/_app_cleanup.py +216 -0
  13. pythonqtside/_app_conversions.py +106 -0
  14. pythonqtside/_app_dialogs.py +74 -0
  15. pythonqtside/_app_flags.py +79 -0
  16. pythonqtside/_app_imports.py +146 -0
  17. pythonqtside/_app_keywords.py +210 -0
  18. pythonqtside/_app_native.py +404 -0
  19. pythonqtside/_app_proxy.py +43 -0
  20. pythonqtside/_app_source.py +110 -0
  21. pythonqtside/_differences.json +9808 -0
  22. pythonqtside/_flags.json +210 -0
  23. pythonqtside/_implicit_conversions.json +1975 -0
  24. pythonqtside/_inventory.json +115478 -0
  25. pythonqtside/_keywords.json +1 -0
  26. pythonqtside/_out_parameters.json +465 -0
  27. pythonqtside/_qtwidgets.json +202 -0
  28. pythonqtside/_routing.py +95 -0
  29. pythonqtside/compat.py +44 -0
  30. pythonqtside/tooling/__init__.py +2 -0
  31. pythonqtside/tooling/conversions.py +433 -0
  32. pythonqtside/tooling/differences.py +290 -0
  33. pythonqtside/tooling/flags.py +156 -0
  34. pythonqtside/tooling/inventory.py +149 -0
  35. pythonqtside/tooling/join.py +184 -0
  36. pythonqtside/tooling/keywords.py +259 -0
  37. pythonqtside/tooling/surface.py +191 -0
  38. pythonqtside-1.1.12.dist-info/METADATA +468 -0
  39. pythonqtside-1.1.12.dist-info/RECORD +42 -0
  40. pythonqtside-1.1.12.dist-info/WHEEL +4 -0
  41. pythonqtside-1.1.12.dist-info/licenses/LICENSE +201 -0
  42. pythonqtside-1.1.12.dist-info/licenses/NOTICE +7 -0
@@ -0,0 +1,95 @@
1
+ # this_file: src/pythonqtside/_routing.py
2
+ """Inventory-based namespace placement retaining original native class identity."""
3
+
4
+ import json
5
+ from importlib import import_module
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ INVENTORY = json.loads(
10
+ Path(__file__).with_name("_inventory.json").read_text(encoding="utf-8")
11
+ )
12
+ _ROUTES = {
13
+ module: data["classes"] | data["members"]
14
+ for module, data in INVENTORY["modules"].items()
15
+ }
16
+ _OWNERS: dict[str, list[str]] = {}
17
+ for _module, _entries in _ROUTES.items():
18
+ for _name in _entries:
19
+ _OWNERS.setdefault(_name, []).append(_module)
20
+ WIDGET_CLASSES = frozenset(
21
+ n for n, route in _ROUTES["QtWidgets"].items() if route["native_module"]
22
+ )
23
+
24
+
25
+ def _target(module: str) -> Any:
26
+ try:
27
+ return import_module("fontlab_echopy.PythonQt." + module)
28
+ except ModuleNotFoundError as error:
29
+ if error.name not in {
30
+ "fontlab_echopy",
31
+ "fontlab_echopy.PythonQt",
32
+ f"fontlab_echopy.PythonQt.{module}",
33
+ }:
34
+ raise
35
+ raise AttributeError(f"Native module {module} is unavailable") from error
36
+
37
+
38
+ def _native_member(module: str, name: str, family: str) -> Any:
39
+ """Translate a missing export/module, without hiding broken dependency imports."""
40
+ try:
41
+ return getattr(_target(module), name)
42
+ except AttributeError:
43
+ pass
44
+ raise AttributeError(
45
+ f"pythonqtside.{family}.{name} is not available in FontLab's PythonQt"
46
+ )
47
+
48
+
49
+ def member(module: str, name: str) -> Any:
50
+ """Resolve the pinned join while preserving each actual native object."""
51
+ if module == "Qt":
52
+ return getattr(_target(module), name)
53
+ route = _ROUTES[module].get(name)
54
+ if route is None and name in _OWNERS:
55
+ owners = ", ".join(f"pythonqtside.{owner}" for owner in _OWNERS[name])
56
+ raise AttributeError(f"{name} is exposed by {owners}")
57
+ if route is None:
58
+ if module != "QtWidgets":
59
+ try:
60
+ return _native_member(module, name, module)
61
+ except AttributeError:
62
+ pass
63
+ raise AttributeError(f"pythonqtside.{module} has no known name {name!r}")
64
+ target = route["native_module"]
65
+ if module == "QtCore" and name == "QObject":
66
+ try:
67
+ return _native_member("QtCore", name, module)
68
+ except AttributeError:
69
+ pass
70
+ if target is None:
71
+ raise AttributeError(
72
+ f"pythonqtside.{module}.{name} is not available in FontLab's PythonQt"
73
+ )
74
+ return _native_member(target, name, module)
75
+
76
+
77
+ def names(module: str) -> list[str]:
78
+ """Advertise resolving joined names and preserve native family extensions."""
79
+ if module == "Qt":
80
+ return sorted(n for n in dir(_target(module)) if not n.startswith("_"))
81
+ try:
82
+ local = set(dir(_target(module))) if module != "QtWidgets" else set()
83
+ except AttributeError:
84
+ local = set()
85
+ public = []
86
+ for name in sorted(
87
+ _ROUTES[module].keys() | {n for n in local if not n.startswith("_")}
88
+ ):
89
+ try:
90
+ member(module, name)
91
+ except AttributeError:
92
+ pass
93
+ else:
94
+ public.append(name)
95
+ return public
pythonqtside/compat.py ADDED
@@ -0,0 +1,44 @@
1
+ # this_file: src/pythonqtside/compat.py
2
+ """Opt-in PySide2-style member access for new code running in FontLab PythonQt."""
3
+
4
+ from typing import Any
5
+
6
+ from ._app_keywords import construct, native_init
7
+ from ._app_native import resolve
8
+
9
+ __all__ = ["pyside_construct", "pyside_method"]
10
+
11
+
12
+ def pyside_method(obj: Any, name: str) -> Any:
13
+ """Return ``obj.name`` as PySide2 code would call it, without altering ``obj``.
14
+
15
+ Native Qt properties confirmed by ``metaObject().indexOfProperty()`` become
16
+ zero-argument getters. Measured out-parameter methods listed in
17
+ ``_out_parameters.json`` return PySide2's ``(value, ok)`` tuple:
18
+ QTransform/QMatrix ``inverted()`` via the native ``isInvertible()``, and 37
19
+ others (``QLocale.toInt``, ``QInputDialog.getText`` and so on) by passing a
20
+ native ``PythonQt.BoolResult`` in the out-parameter slot. Pass ``obj`` as the
21
+ class for static methods. Keyword calls and calls that already pass a
22
+ ``BoolResult`` stay native. Methods listed in ``_implicit_conversions.json``
23
+ wrap a measured native enum argument as PySide2's implicit value class
24
+ (``setEasingCurve(QEasingCurve.OutElastic)`` passes
25
+ ``QEasingCurve(OutElastic)``); plain ints and other values pass through.
26
+ Keyword arguments, which PythonQt rejects on every native method, are mapped to
27
+ positions by the PySide2 parameter names in ``_keywords.json``.
28
+ Everything else is the ordinary attribute.
29
+ The same rules apply to calls in sources run with ``run_app``.
30
+ """
31
+ return resolve(obj, name, keywords=True)
32
+
33
+
34
+ def pyside_construct(cls: type, *args: Any, **kwargs: Any) -> Any:
35
+ """``cls(*args, **kwargs)`` with PySide2 constructor keywords.
36
+
37
+ ``pyside_construct(QLabel, "Name", parent=window)`` calls ``QLabel("Name",
38
+ window)``; keywords naming a Qt property or signal (``QTimer, interval=50``,
39
+ ``QPushButton, "OK", clicked=accept``) are set or connected afterwards. A class
40
+ with its own Python ``__init__`` receives the keywords unchanged.
41
+ """
42
+ if not kwargs or not native_init(cls):
43
+ return cls(*args, **kwargs)
44
+ return construct(cls, args, kwargs)
@@ -0,0 +1,2 @@
1
+ # this_file: src/pythonqtside/tooling/__init__.py
2
+ """Host-independent metadata tools; never import a Qt binding."""
@@ -0,0 +1,433 @@
1
+ # this_file: src/pythonqtside/tooling/conversions.py
2
+ """Measure PySide2 implicit enum -> value-class conversions against native PythonQt.
3
+
4
+ _inventory.json keeps parameter names but not annotations, so this command reads
5
+ the same PySide2 and native stubs the inventory pins, verified against its
6
+ recorded SHA256 inputs, and takes routing and native enum layout from it.
7
+ """
8
+
9
+ import argparse
10
+ import ast
11
+ import hashlib
12
+ import json
13
+ from pathlib import Path
14
+ from zipfile import ZipFile
15
+
16
+ from .join import MODULES
17
+ from .surface import extract
18
+
19
+ PACKAGE = Path(__file__).resolve().parents[1]
20
+ REASONS = {
21
+ "pyside_enum_or_int_overload": "A PySide2 overload of the same call arity takes an enum or int here; PySide2 dispatches directly, and the native overload set may too.",
22
+ "pyside_numeric_overload": "A PySide2 overload of the same call arity takes float or a numeric sequence here; an int-like enum could dispatch to it.",
23
+ "native_missing": "The routed native class declares no method of this name.",
24
+ "native_int_parameter": "The recorded native signature types this position int.",
25
+ "native_signature_mismatch": "The recorded native signature has no parameter at this position.",
26
+ }
27
+ # Shiboken converts implicitly only to value types (a public copy constructor in
28
+ # the stub) through non-explicit constructors. Stubs omit `explicit`; these Qt 5.15
29
+ # value types declare their one-argument enum constructor explicit in the headers.
30
+ EXPLICIT = frozenset(
31
+ {
32
+ "QtCore.QEvent",
33
+ "QtGui.QOpenGLBuffer",
34
+ "QtGui.QPageSize",
35
+ "QtOpenGL.QGLBuffer",
36
+ "QtWidgets.QTileRules",
37
+ }
38
+ )
39
+ # Sibling annotations an int-like enum value could satisfy besides int and enums.
40
+ NUMERIC = frozenset({"float", "typing.Sequence[float]", "typing.Sequence[int]"})
41
+ LIMITATIONS = [
42
+ "Stubs omit C++ explicit; value types other than the EXPLICIT list are assumed to convert implicitly.",
43
+ "Native stubs record one Any-typed signature per method; PySide2's overload family stands in for the native set.",
44
+ "native_int_parameter and native_signature_mismatch cannot fire on the current native stubs: every measured position is Any-typed and present (both count 0); they guard future stubs only.",
45
+ "Exclusion is per call arity: a sibling overload excludes a position only at the arities it accepts; partial exclusions are keyed index@low-high.",
46
+ "Plain int and QFlags parameters are never converted; only enum types the inventory finds natively.",
47
+ "Constructors and module functions are not adapted; run_app resolves attribute calls only.",
48
+ "Entries repeat per routed subclass: native stubs record no Qt base chain, so isinstance cannot be assumed to follow it.",
49
+ "Derived from declarations; native acceptance is unverified until FontLab runs the checklist.",
50
+ ]
51
+
52
+
53
+ def _parameters(node: ast.FunctionDef) -> dict:
54
+ args = node.args.posonlyargs + node.args.args
55
+ receiver = bool(args) and args[0].arg in {"self", "cls"}
56
+ names = args[receiver:]
57
+ decorators = {ast.unparse(d).split(".")[-1] for d in node.decorator_list}
58
+ return {
59
+ "parameters": [
60
+ [a.arg, ast.unparse(a.annotation).removeprefix("PySide2.")]
61
+ if a.annotation
62
+ else [a.arg, None]
63
+ for a in names
64
+ ],
65
+ "required": len(names) - len(node.args.defaults),
66
+ "static": "staticmethod" in decorators or not receiver,
67
+ }
68
+
69
+
70
+ def declarations(source: bytes) -> dict[str, dict]:
71
+ """Top-level classes: bases, constructor and method overloads with annotations."""
72
+ result = {}
73
+ for node in ast.parse(source).body:
74
+ if not isinstance(node, ast.ClassDef):
75
+ continue
76
+ methods: dict[str, list] = {}
77
+ for item in node.body:
78
+ if isinstance(item, ast.FunctionDef):
79
+ methods.setdefault(item.name, []).append(_parameters(item))
80
+ result[node.name] = {
81
+ "bases": [ast.unparse(b).removeprefix("PySide2.") for b in node.bases],
82
+ "methods": methods,
83
+ }
84
+ return result
85
+
86
+
87
+ def _route(inventory: dict, key: str) -> dict | None:
88
+ module, _, name = key.partition(".")
89
+ record = inventory["modules"].get(module, {}).get("classes", {}).get(name)
90
+ return record if record and record["native_module"] else None
91
+
92
+
93
+ def _native_enum(inventory: dict, path: str) -> bool:
94
+ """The enum's owner is routed and the inventory finds the enum type natively."""
95
+ module, owner, enum = path.split(".", 2)
96
+ record = _route(inventory, f"{module}.{owner}")
97
+ layout = record and record["differences"]["nested_enums"].get(enum)
98
+ return bool(layout) and layout["native_layout"] != "absent"
99
+
100
+
101
+ def value_classes(inventory: dict, pyside: dict, enums: set[str]) -> dict:
102
+ """Routed value types constructible implicitly from one native enum argument."""
103
+ result = {}
104
+ for module, classes in pyside.items():
105
+ for name, decl in classes.items():
106
+ key = f"{module}.{name}"
107
+ inits = decl["methods"].get("__init__", [])
108
+ copyable = any(
109
+ o["parameters"] == [[o["parameters"][0][0], key]]
110
+ for o in inits
111
+ if o["parameters"]
112
+ )
113
+ if not copyable or key in EXPLICIT or _route(inventory, key) is None:
114
+ continue
115
+ accepted = {
116
+ o["parameters"][0][1]
117
+ for o in inits
118
+ if o["parameters"] and o["required"] <= 1
119
+ }
120
+ accepted = sorted(e for e in accepted & enums if _native_enum(inventory, e))
121
+ if accepted:
122
+ result[key] = accepted
123
+ return result
124
+
125
+
126
+ def _covers(overload: dict, arity: int) -> bool:
127
+ return overload["required"] <= arity <= len(overload["parameters"])
128
+
129
+
130
+ def _direct(overloads: list[dict], index: int, enums: set[str]) -> str | None:
131
+ """Reason a sibling overload (already filtered to the call arity) wins here."""
132
+ found = {o["parameters"][index][1] for o in overloads}
133
+ if found & enums or "int" in found:
134
+ return "pyside_enum_or_int_overload"
135
+ return "pyside_numeric_overload" if found & NUMERIC else None
136
+
137
+
138
+ def _conversions(typed: list[dict], index: int, values: dict) -> dict:
139
+ owners: dict[str, set[str]] = {}
140
+ for overload in typed:
141
+ value = overload["parameters"][index][1]
142
+ for enum in values[value]:
143
+ owners.setdefault(enum, set()).add(value)
144
+ # An enum two value classes accept at one position is ambiguous: dropped.
145
+ return {e: v.pop() for e, v in sorted(owners.items()) if len(v) == 1}
146
+
147
+
148
+ def _outcomes(overloads, index, values, enums, native_reason) -> list[tuple]:
149
+ """(arity, conversions, reason) for each call arity a typed overload covers."""
150
+ result = []
151
+ width = max(len(o["parameters"]) for o in overloads)
152
+ for arity in range(index + 1, width + 1):
153
+ covering = [o for o in overloads if _covers(o, arity)]
154
+ typed = [o for o in covering if o["parameters"][index][1] in values]
155
+ conversions = _conversions(typed, index, values)
156
+ if conversions:
157
+ reason = _direct(covering, index, enums) or native_reason
158
+ result.append((arity, conversions, reason))
159
+ return result
160
+
161
+
162
+ def _ranges(outcomes: list[tuple]) -> list[list]:
163
+ """Merge consecutive arities with the same outcome: [low, high, conv, reason]."""
164
+ merged: list[list] = []
165
+ for arity, conversions, reason in outcomes:
166
+ last = merged[-1] if merged else None
167
+ if last and last[1] == arity - 1 and last[2:] == [conversions, reason]:
168
+ last[1] = arity
169
+ else:
170
+ merged.append([arity, arity, conversions, reason])
171
+ return merged
172
+
173
+
174
+ def _native_reason(native: list[dict] | None, index: int) -> str | None:
175
+ if native is None:
176
+ return "native_missing"
177
+ for overload in native:
178
+ if len(overload["parameters"]) <= index:
179
+ return "native_signature_mismatch"
180
+ if overload["parameters"][index][1] == "int":
181
+ return "native_int_parameter"
182
+ return None
183
+
184
+
185
+ def _native_methods(native: dict, inventory: dict, key: str) -> dict:
186
+ name = key.partition(".")[2]
187
+ module = _route(inventory, key)["native_module"]
188
+ return native.get(module, {}).get(name, {}).get("methods", {})
189
+
190
+
191
+ def _method(overloads, native, values, enums) -> tuple[list, dict]:
192
+ positions, excluded = [], {}
193
+ width = max(len(o["parameters"]) for o in overloads)
194
+ for index in range(width):
195
+ if not any(
196
+ len(o["parameters"]) > index and o["parameters"][index][1] in values
197
+ for o in overloads
198
+ ):
199
+ continue
200
+ reason = _native_reason(native, index)
201
+ ranges = _ranges(_outcomes(overloads, index, values, enums, reason))
202
+ whole = len({r[3] for r in ranges}) == 1 and ranges[0][3]
203
+ for low, high, conversions, why in ranges:
204
+ if why is None:
205
+ positions.append(
206
+ {"index": index, "arities": [low, high], "conversions": conversions}
207
+ )
208
+ elif whole:
209
+ excluded[str(index)] = why
210
+ else:
211
+ excluded[f"{index}@{low}-{high}"] = why
212
+ return positions, excluded
213
+
214
+
215
+ def _ancestors(pyside: dict, key: str) -> list[str]:
216
+ module, _, name = key.partition(".")
217
+ result = []
218
+ for base in pyside.get(module, {}).get(name, {}).get("bases", []):
219
+ base = base if "." in base else f"{module}.{base}"
220
+ if base.partition(".")[0] in pyside:
221
+ result += [base, *_ancestors(pyside, base)]
222
+ return result
223
+
224
+
225
+ def _effective(pyside: dict, key: str) -> dict[str, list]:
226
+ """Inherited PySide2 methods; a redeclared name hides the base overloads (C++)."""
227
+ module, _, name = key.partition(".")
228
+ decl = pyside.get(module, {}).get(name)
229
+ if decl is None:
230
+ return {}
231
+ merged: dict[str, list] = {}
232
+ for base in decl["bases"]:
233
+ base = base if "." in base else f"{module}.{base}"
234
+ merged |= _effective(pyside, base)
235
+ return merged | decl["methods"]
236
+
237
+
238
+ def _measure(inventory, pyside, native, values, enums) -> tuple[dict, dict]:
239
+ """Every routed class gets its inherited methods: native wrappers expose no
240
+ Qt base chain (stubs: "Native bases: PythonQtInstanceWrapper")."""
241
+ found, unsupported = {}, {}
242
+ for module, classes in sorted(pyside.items()):
243
+ for name in sorted(classes):
244
+ key = f"{module}.{name}"
245
+ if _route(inventory, key) is None:
246
+ continue
247
+ methods = _native_methods(native, inventory, key)
248
+ for method, overloads in sorted(_effective(pyside, key).items()):
249
+ if method.startswith("_"):
250
+ continue
251
+ positions, excluded = _method(
252
+ overloads, methods.get(method), values, enums
253
+ )
254
+ static = all(o["static"] for o in overloads)
255
+ found.setdefault(key, {})[method] = (positions, static)
256
+ if excluded:
257
+ unsupported.setdefault(key, {})[method] = excluded
258
+ return found, unsupported
259
+
260
+
261
+ def _table(inventory: dict, pyside: dict, found: dict) -> tuple[dict, int]:
262
+ """Entries per routed class; an empty entry shadows a converting ancestor."""
263
+ table, shadows = {}, 0
264
+ for key, methods in found.items():
265
+ native_key = (
266
+ f"{_route(inventory, key)['native_module']}.{key.partition('.')[2]}"
267
+ )
268
+ for method, (positions, static) in methods.items():
269
+ inherited = any(
270
+ found.get(a, {}).get(method, ([], False))[0]
271
+ for a in _ancestors(pyside, key)
272
+ )
273
+ if positions or inherited:
274
+ shadows += not positions
275
+ entry = {"static": static, "positions": positions}
276
+ table.setdefault(native_key, {})[method] = entry
277
+ return table, shadows
278
+
279
+
280
+ def _native_paths(inventory: dict, table: dict) -> dict:
281
+ """Rewrite PySide2 module paths of enums and value classes to native modules."""
282
+
283
+ def native(path: str) -> str:
284
+ module, owner, *rest = path.split(".")
285
+ routed = _route(inventory, f"{module}.{owner}")["native_module"]
286
+ return ".".join([routed, owner, *rest])
287
+
288
+ for methods in table.values():
289
+ for entry in methods.values():
290
+ for position in entry["positions"]:
291
+ position["conversions"] = {
292
+ native(e): native(v) for e, v in position["conversions"].items()
293
+ }
294
+ return table
295
+
296
+
297
+ def _check_overlap(table: dict, out_parameters: dict) -> None:
298
+ for kind in ("predicate", "bool_result"):
299
+ for key, methods in out_parameters.get(kind, {}).items():
300
+ for method in methods:
301
+ if table.get(key, {}).get(method, {}).get("positions"):
302
+ raise ValueError(
303
+ f"{key}.{method} is in both conversion and out-parameter tables"
304
+ )
305
+
306
+
307
+ def _enums(sources: dict[str, bytes]) -> set[str]:
308
+ return {
309
+ f"{module}.{name}.{enum}"
310
+ for module, source in sources.items()
311
+ for name, cls in extract(source)["classes"].items()
312
+ for enum in cls["enums"]
313
+ }
314
+
315
+
316
+ def _counts(unsupported: dict, table: dict, values: int) -> dict:
317
+ reasons = [r for c in unsupported.values() for m in c.values() for r in m.values()]
318
+ positions = sum(len(e["positions"]) for c in table.values() for e in c.values())
319
+ return {r: reasons.count(r) for r in REASONS} | {
320
+ "value_classes": values,
321
+ "positions": positions,
322
+ }
323
+
324
+
325
+ def analyze(
326
+ inventory: dict,
327
+ pyside_sources: dict[str, bytes],
328
+ native_sources: dict[str, bytes],
329
+ inventory_sha256: str,
330
+ *,
331
+ out_parameters: dict,
332
+ ) -> dict:
333
+ """Deterministic table: sorted keys, counts, exclusions and source digest."""
334
+ enums = _enums(pyside_sources)
335
+ pyside = {m: declarations(s) for m, s in pyside_sources.items()}
336
+ native = {m: declarations(s) for m, s in native_sources.items()}
337
+ values = value_classes(inventory, pyside, enums)
338
+ found, unsupported = _measure(inventory, pyside, native, values, enums)
339
+ table, shadows = _table(inventory, pyside, found)
340
+ table = _native_paths(inventory, table)
341
+ _check_overlap(table, out_parameters)
342
+ counts = _counts(unsupported, table, len(values)) | {"shadow_entries": shadows}
343
+ return {
344
+ "schema_version": 2,
345
+ "inventory_sha256": inventory_sha256,
346
+ "limitations": LIMITATIONS,
347
+ "reasons": REASONS,
348
+ "counts": counts,
349
+ "value_classes": values,
350
+ "classes": table,
351
+ "unsupported": unsupported,
352
+ }
353
+
354
+
355
+ def pack(report: dict) -> dict:
356
+ """File form: each distinct entry stored once; classes refer to it by index."""
357
+ canonical = {
358
+ json.dumps(e, sort_keys=True)
359
+ for methods in report["classes"].values()
360
+ for e in methods.values()
361
+ }
362
+ entries = sorted(canonical)
363
+ index = {text: i for i, text in enumerate(entries)}
364
+ classes = {
365
+ key: {m: index[json.dumps(e, sort_keys=True)] for m, e in methods.items()}
366
+ for key, methods in report["classes"].items()
367
+ }
368
+ return report | {"classes": classes, "entries": [json.loads(e) for e in entries]}
369
+
370
+
371
+ def _verified(data: bytes, label: str, inputs: dict) -> bytes:
372
+ if hashlib.sha256(data).hexdigest() != inputs[label]["sha256"]:
373
+ raise ValueError(f"{label} SHA256 differs from _inventory.json inputs")
374
+ return data
375
+
376
+
377
+ def load_sources(echopy: Path, inventory: dict) -> tuple[dict, dict]:
378
+ """Read the inventory's pinned PySide2 wheel members and native stubs."""
379
+ inputs = inventory["inputs"]
380
+ (wheel,) = [k for k in inputs if k.endswith(".whl")]
381
+ _verified((echopy / ".cache/upstream" / wheel).read_bytes(), wheel, inputs)
382
+ with ZipFile(echopy / ".cache/upstream" / wheel) as archive:
383
+ pyside = {
384
+ m: _verified(archive.read(f"PySide2/{m}.pyi"), f"PySide2/{m}.pyi", inputs)
385
+ for m in MODULES
386
+ }
387
+ stubs = echopy / "src/fontlab_echopy/PythonQt"
388
+ native = {
389
+ m: _verified((stubs / f"{m}.pyi").read_bytes(), f"PythonQt/{m}.pyi", inputs)
390
+ for m in sorted(
391
+ {
392
+ c["native_module"]
393
+ for d in inventory["modules"].values()
394
+ for c in d["classes"].values()
395
+ }
396
+ - {None}
397
+ )
398
+ }
399
+ return pyside, native
400
+
401
+
402
+ def main() -> None:
403
+ parser = argparse.ArgumentParser(description=__doc__)
404
+ parser.add_argument("--echopy", type=Path, default=Path("../fontlab-echopy"))
405
+ parser.add_argument("--inventory", type=Path, default=PACKAGE / "_inventory.json")
406
+ parser.add_argument(
407
+ "--out-parameters", type=Path, default=PACKAGE / "_out_parameters.json"
408
+ )
409
+ parser.add_argument(
410
+ "--output", type=Path, default=PACKAGE / "_implicit_conversions.json"
411
+ )
412
+ args = parser.parse_args()
413
+ data = args.inventory.read_bytes()
414
+ inventory = json.loads(data)
415
+ pyside, native = load_sources(args.echopy, inventory)
416
+ out_parameters = json.loads(args.out_parameters.read_text(encoding="utf-8"))
417
+ report = analyze(
418
+ inventory,
419
+ pyside,
420
+ native,
421
+ hashlib.sha256(data).hexdigest(),
422
+ out_parameters=out_parameters,
423
+ )
424
+ args.output.write_text(
425
+ json.dumps(pack(report), sort_keys=True, indent=1) + "\n", encoding="utf-8"
426
+ )
427
+ digest = hashlib.sha256(args.output.read_bytes()).hexdigest()
428
+ print(f"{args.output.name}: {args.output.stat().st_size} bytes; SHA256 {digest}")
429
+ print(json.dumps(report["counts"], sort_keys=True))
430
+
431
+
432
+ if __name__ == "__main__":
433
+ main()