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,290 @@
1
+ # this_file: src/pythonqtside/tooling/differences.py
2
+ """Derive measured PySide2-versus-PythonQt adapter tables from _inventory.json only."""
3
+
4
+ import argparse
5
+ import ast
6
+ import hashlib
7
+ import json
8
+ from pathlib import Path
9
+
10
+ PACKAGE = Path(__file__).resolve().parents[1]
11
+ TOP = 10
12
+ # Qt semantics: inverted()'s bool out-parameter equals isInvertible() on the same
13
+ # value. Pairs apply only when the native class declares the predicate.
14
+ PREDICATES = {"inverted": "isInvertible"}
15
+ # Native bool* parameter names in the FontLab stubs; PythonQt fills them through
16
+ # PythonQt.BoolResult (native probe: QMatrix4x4().inverted(BoolResult())).
17
+ OUT_PARAMETERS = ("ok", "invertible", "timedOut")
18
+ # Qt 5.15 declaration defaults for native parameters before the out-parameter, as
19
+ # quoted in the Echopy QtGui/QtNetwork stub docstrings. PySide2 callers may omit
20
+ # them, but PythonQt needs them positionally before the BoolResult. A
21
+ # {"native": "Module.Class.Name"} value is looked up in PythonQt at call time.
22
+ QT_DEFAULTS = {
23
+ "QInputDialog.getText": {"echo": {"native": "QtGui.QLineEdit.Normal"}, "text": ""},
24
+ "QInputDialog.getMultiLineText": {"text": ""},
25
+ "QInputDialog.getInt": {
26
+ "value": 0,
27
+ "minValue": -2147483647,
28
+ "maxValue": 2147483647,
29
+ "step": 1,
30
+ },
31
+ "QInputDialog.getDouble": {
32
+ "value": 0.0,
33
+ "minValue": -2147483647.0,
34
+ "maxValue": 2147483647.0,
35
+ "decimals": 1,
36
+ },
37
+ "QInputDialog.getItem": {"current": 0, "editable": True},
38
+ "QLocalServer.waitForNewConnection": {"msec": 0},
39
+ "QTcpServer.waitForNewConnection": {"msec": 0},
40
+ }
41
+ REASONS = {
42
+ "native_missing": "The routed native class declares no method of this name.",
43
+ "multiple_or_non_flag_outputs": "PySide2 returns several values or no trailing bool; native out-parameters carry them.",
44
+ "no_native_out_parameter": "No native overload declares a bool out-parameter at one consistent position.",
45
+ "ambiguous_pyside_overload": "PySide2 also declares a non-tuple overload of the same arity; its result shape is unknown.",
46
+ "stub_runtime_mismatch": "PySide2's documented runtime result differs from its stub annotation.",
47
+ }
48
+ # Stub annotations PySide2's runtime contradicts. QFontDialog.getFont returns
49
+ # (ok, font) at runtime (PySide2 docs: `(ok, font) = QFontDialog.getFont(self)`),
50
+ # not the annotated (QFont, bool); the native (ok, parent) overload is also
51
+ # undeclared in the stub. Measured-only: excluded (controller ruling, phase 3b).
52
+ STUB_RUNTIME_MISMATCHES = {"QFontDialog.getFont"}
53
+ LIMITATIONS = [
54
+ "Derived from _inventory.json declarations; native behavior is unverified until FontLab acceptance.",
55
+ "Accessor names are stub matches; run_app still requires metaObject().indexOfProperty() evidence.",
56
+ "Opaque native nested enums have unknown membership and are counted, not listed as missing.",
57
+ "Native constructors declared as *args/**kwargs give no keyword-rejection evidence; constructor_keywords.native records the FontLab measurement instead.",
58
+ "Predicate adapters cover zero-argument PySide2 calls on instances; arguments pass through natively.",
59
+ "BoolResult adapters cover positional PySide2 calls; keyword calls reach them only after _keywords.json maps the keywords to positions, and explicit BoolResult calls pass through.",
60
+ ]
61
+ # Measured in FontLab 9.0.9780 (issue 104). The stubs cannot show this: every native
62
+ # constructor stub declares *args/**kwargs.
63
+ NATIVE_KEYWORDS = {
64
+ "result": "rejected",
65
+ "scope": "every native constructor and method measured, instance and static",
66
+ "error": "ValueError: Called <signature> with keyword arguments, but called slot does not support kwargs.",
67
+ "evidence": "verification/issue-101-ecosystem/evidence/pqs-g04/probe_keywords.json",
68
+ "adapter": "_keywords.json (python -m pythonqtside.tooling.keywords): PySide2 keyword names mapped to positions in run_app and compat",
69
+ }
70
+
71
+
72
+ def _routed(inventory: dict):
73
+ for module, data in sorted(inventory["modules"].items()):
74
+ for name, cls in sorted(data["classes"].items()):
75
+ if cls["native_module"] is not None:
76
+ yield f"{module}.{name}", cls
77
+
78
+
79
+ def _category(table: dict[str, list[str]]) -> dict:
80
+ ranked = sorted(table.items(), key=lambda item: (-len(item[1]), item[0]))
81
+ return {
82
+ "count": sum(map(len, table.values())),
83
+ "classes": len(table),
84
+ "top_classes": [[name, len(items)] for name, items in ranked[:TOP]],
85
+ "table": table,
86
+ }
87
+
88
+
89
+ # Measured in FontLab 9.0.9780 (issue 104) without reading property values.
90
+ NATIVE_GETTERS = {
91
+ "measured_names": 4624,
92
+ "measured_classes": 181,
93
+ "covered_by_index_of_property": 4624,
94
+ "callable_natively": 0,
95
+ "uncovered": 0,
96
+ "unmeasured_names": 740,
97
+ "unmeasured_classes": "47: 17 skipped (application, clipboard, printing, GL, platform dialogs), 30 without a default constructor; PythonQt has no staticMetaObject",
98
+ "evidence": "verification/issue-101-ecosystem/evidence/pqs-g04/getters/",
99
+ "note": "The run_app and compat getter adapter checks the live instance's metaObject() at call time, so unmeasured classes are gated the same way.",
100
+ }
101
+
102
+
103
+ def _accessors(inventory: dict) -> dict:
104
+ table = {
105
+ key: cls["differences"]["native_attributes_for_pyside_accessors"]
106
+ for key, cls in _routed(inventory)
107
+ }
108
+ return _category({k: v for k, v in table.items() if v}) | {"native": NATIVE_GETTERS}
109
+
110
+
111
+ def _enums(inventory: dict) -> dict:
112
+ table, opaque = {}, 0
113
+ for key, cls in _routed(inventory):
114
+ diff = cls["differences"]
115
+ names = list(diff["enum_members_only_pyside"])
116
+ for enum, record in sorted(diff["nested_enums"].items()):
117
+ if record["members_only_pyside"] is None:
118
+ opaque += 1
119
+ else:
120
+ names += [f"{enum}.{m}" for m in record["members_only_pyside"]]
121
+ if names:
122
+ table[key] = sorted(names)
123
+ return _category(table) | {"opaque_nested_enums": opaque}
124
+
125
+
126
+ def _flag_pair(annotation: str) -> bool:
127
+ """True for Tuple[Value, bool]: one value plus a trailing success flag."""
128
+ node = ast.parse(annotation, mode="eval").body
129
+ items = getattr(getattr(node, "slice", None), "elts", [])
130
+ return len(items) == 2 and ast.unparse(items[1]) == "bool"
131
+
132
+
133
+ def _out_parameter(native: list[dict]) -> tuple[int, str] | None:
134
+ """The single bool out-parameter position shared by every native overload."""
135
+ found = set()
136
+ for overload in native:
137
+ hits = [
138
+ (i, n) for i, n in enumerate(overload["parameters"]) if n in OUT_PARAMETERS
139
+ ]
140
+ if len(hits) != 1:
141
+ return None
142
+ found.add(hits[0])
143
+ if len(found) != 1:
144
+ return None
145
+ index, name = found.pop()
146
+ # Every overload must agree on the parameters before the slot, or the
147
+ # adapter cannot know which native names its defaults and arity refer to.
148
+ prefixes = {tuple(o["parameters"][:index]) for o in native}
149
+ return (index, name) if len(prefixes) == 1 else None
150
+
151
+
152
+ def _ambiguous(record: dict) -> bool:
153
+ pairs = [
154
+ o
155
+ for o in record["pyside_overloads"]
156
+ if o["returns"] in record["pyside_returns"]
157
+ ]
158
+ arities = {len(o["parameters"]) for o in pairs}
159
+ others = [o for o in record["pyside_overloads"] if o not in pairs]
160
+ return any(len(o["parameters"]) in arities for o in others)
161
+
162
+
163
+ def _classify(key: str, method: str, record: dict, predicates: list[str]) -> str:
164
+ if record["native_overloads"] is None:
165
+ return "native_missing"
166
+ if f"{key.partition('.')[2]}.{method}" in STUB_RUNTIME_MISMATCHES:
167
+ return "stub_runtime_mismatch"
168
+ if not all(_flag_pair(a) for a in record["pyside_returns"]):
169
+ return "multiple_or_non_flag_outputs"
170
+ if _out_parameter(record["native_overloads"]) is None:
171
+ return "no_native_out_parameter"
172
+ if _ambiguous(record):
173
+ return "ambiguous_pyside_overload"
174
+ return "adapter" if PREDICATES.get(method) in predicates else "bool_result"
175
+
176
+
177
+ def _bool_result(name: str, method: str, record: dict) -> dict:
178
+ """How to call natively: BoolResult at out_index, defaults before it."""
179
+ index, out = _out_parameter(record["native_overloads"])
180
+ native = min((o["parameters"] for o in record["native_overloads"]), key=len)
181
+ pairs = [
182
+ o
183
+ for o in record["pyside_overloads"]
184
+ if o["returns"] in record["pyside_returns"]
185
+ ]
186
+ defaults = QT_DEFAULTS.get(f"{name}.{method}", {})
187
+ if not set(defaults) <= set(native[:index]):
188
+ raise ValueError(f"QT_DEFAULTS for {name}.{method} name no native parameter")
189
+ return {
190
+ "defaults": defaults,
191
+ "max_arguments": min(max(len(o["parameters"]) for o in pairs), len(native) - 1),
192
+ "out_index": index,
193
+ "out_parameter": out,
194
+ "parameters": native[:index],
195
+ "static": all(o.get("static", False) for o in pairs),
196
+ }
197
+
198
+
199
+ def _out_parameters(inventory: dict) -> dict:
200
+ adapters, bool_results, unsupported = {}, {}, {}
201
+ counts = dict.fromkeys(REASONS, 0) | {"adapters": 0, "bool_result_adapters": 0}
202
+ for key, cls in _routed(inventory):
203
+ diff, name = cls["differences"], key.partition(".")[2]
204
+ native_key = f"{cls['native_module']}.{name}"
205
+ for method, record in sorted(diff["tuple_returns"].items()):
206
+ kind = _classify(key, method, record, diff["native_bool_predicates"])
207
+ if kind == "adapter":
208
+ adapters.setdefault(native_key, {})[method] = PREDICATES[method]
209
+ counts["adapters"] += 1
210
+ elif kind == "bool_result":
211
+ entry = _bool_result(name, method, record)
212
+ bool_results.setdefault(native_key, {})[method] = entry
213
+ counts["bool_result_adapters"] += 1
214
+ else:
215
+ unsupported.setdefault(key, {})[method] = kind
216
+ counts[kind] += 1
217
+ return {
218
+ "adapters": adapters,
219
+ "bool_result_adapters": bool_results,
220
+ "unsupported": unsupported,
221
+ "counts": counts,
222
+ "reasons": REASONS,
223
+ }
224
+
225
+
226
+ def _constructor_keywords(inventory: dict) -> dict:
227
+ without = [
228
+ key
229
+ for key, cls in _routed(inventory)
230
+ if cls["constructors"]["native"]
231
+ and not any(shape["kwargs"] for shape in cls["constructors"]["native"])
232
+ ]
233
+ return {
234
+ "status": "measured" if without else "unmeasured",
235
+ "native_without_kwargs": without,
236
+ "native": NATIVE_KEYWORDS,
237
+ }
238
+
239
+
240
+ def analyze(inventory: dict, inventory_sha256: str) -> dict:
241
+ """Deterministic report: sorted tables, counts and the source inventory digest."""
242
+ return {
243
+ "schema_version": 2,
244
+ "inventory_sha256": inventory_sha256,
245
+ "limitations": LIMITATIONS,
246
+ "callable_accessors": _accessors(inventory),
247
+ "enum_members_missing_natively": _enums(inventory),
248
+ "out_parameters": _out_parameters(inventory),
249
+ "constructor_keywords": _constructor_keywords(inventory),
250
+ }
251
+
252
+
253
+ def runtime_table(report: dict) -> dict:
254
+ """The small file _app_native loads; the full report stays a report."""
255
+ out = report["out_parameters"]
256
+ return {
257
+ "inventory_sha256": report["inventory_sha256"],
258
+ "predicate": out["adapters"],
259
+ "bool_result": out["bool_result_adapters"],
260
+ }
261
+
262
+
263
+ def write_report(report: dict, output: Path) -> None:
264
+ output.write_text(
265
+ json.dumps(report, sort_keys=True, indent=2) + "\n", encoding="utf-8"
266
+ )
267
+
268
+
269
+ def main() -> None:
270
+ parser = argparse.ArgumentParser(description=__doc__)
271
+ parser.add_argument("--inventory", type=Path, default=PACKAGE / "_inventory.json")
272
+ parser.add_argument("--output", type=Path, default=PACKAGE / "_differences.json")
273
+ parser.add_argument("--table", type=Path, default=PACKAGE / "_out_parameters.json")
274
+ args = parser.parse_args()
275
+ data = args.inventory.read_bytes()
276
+ report = analyze(json.loads(data), hashlib.sha256(data).hexdigest())
277
+ write_report(report, args.output)
278
+ write_report(runtime_table(report), args.table)
279
+ for path in (args.output, args.table):
280
+ digest = hashlib.sha256(path.read_bytes()).hexdigest()
281
+ print(f"{path.name}: {path.stat().st_size} bytes; SHA256 {digest}")
282
+ keys = ("callable_accessors", "enum_members_missing_natively")
283
+ summary = {k: {f: report[k][f] for f in ("count", "classes")} for k in keys}
284
+ summary["out_parameters"] = report["out_parameters"]["counts"]
285
+ summary["constructor_keywords"] = report["constructor_keywords"]["status"]
286
+ print(json.dumps(summary, sort_keys=True))
287
+
288
+
289
+ if __name__ == "__main__":
290
+ main()
@@ -0,0 +1,156 @@
1
+ # this_file: src/pythonqtside/tooling/flags.py
2
+ """Measure PySide2 QFlags parameters that compete with an enum overload natively.
3
+
4
+ In FontLab's PythonQt ``QDialogButtonBox.Ok | QDialogButtonBox.Cancel`` is a plain
5
+ int, and ``QDialogButtonBox(Ok | Cancel)`` dispatches to the ``Qt.Orientation``
6
+ overload: no buttons (pqs-g04/fixtures/probe_overload_connect.json). PySide2 passes
7
+ a ``StandardButtons`` value. This command lists, per routed class, the constructor
8
+ and method positions where one PySide2 overload takes a QFlags type and another
9
+ overload of the same call arity takes an enum there (but none takes int).
10
+ """
11
+
12
+ import argparse
13
+ import ast
14
+ import hashlib
15
+ import json
16
+ from pathlib import Path
17
+
18
+ from .conversions import _effective, _enums, _route, declarations, load_sources
19
+
20
+ PACKAGE = Path(__file__).resolve().parents[1]
21
+ LIMITATIONS = [
22
+ "QFlags classes are PySide2 nested classes with an empty body that are not enums.",
23
+ "Positions where an overload of the same arity takes int are left out: an int cannot be attributed.",
24
+ "Native acceptance covers the QDialogButtonBox constructor; the modal QMessageBox statics are unverified.",
25
+ ]
26
+
27
+
28
+ def flag_classes(sources: dict[str, bytes], enums: set[str]) -> set[str]:
29
+ found = set()
30
+ for module, source in sources.items():
31
+ for node in ast.parse(source).body:
32
+ if not isinstance(node, ast.ClassDef):
33
+ continue
34
+ for item in node.body:
35
+ path = f"{module}.{node.name}.{getattr(item, 'name', '')}"
36
+ if (
37
+ isinstance(item, ast.ClassDef)
38
+ and len(item.body) == 1
39
+ and isinstance(item.body[0], ast.Expr)
40
+ and path not in enums
41
+ ):
42
+ found.add(path)
43
+ return found
44
+
45
+
46
+ def _positions(overloads: list[dict], flags: set[str], enums: set[str]) -> list[dict]:
47
+ result = []
48
+ width = max((len(o["parameters"]) for o in overloads), default=0)
49
+ for index in range(width):
50
+ for arity in range(index + 1, width + 1):
51
+ covering = [
52
+ o for o in overloads if o["required"] <= arity <= len(o["parameters"])
53
+ ]
54
+ found = {o["parameters"][index][1] for o in covering}
55
+ wanted, keep = found & flags, found & enums
56
+ if len(wanted) != 1 or not keep or "int" in found:
57
+ continue
58
+ entry = {"index": index, "flags": wanted.pop(), "keep": sorted(keep)}
59
+ last = result[-1] if result else None
60
+ if (
61
+ last
62
+ and last["index"] == index
63
+ and last["arities"][1] == arity - 1
64
+ and (
65
+ last["flags"],
66
+ last["keep"],
67
+ )
68
+ == (entry["flags"], entry["keep"])
69
+ ):
70
+ last["arities"][1] = arity
71
+ else:
72
+ result.append(entry | {"arities": [arity, arity]})
73
+ return result
74
+
75
+
76
+ def _native(inventory: dict, path: str) -> str:
77
+ module, owner, *rest = path.split(".")
78
+ return ".".join(
79
+ [_route(inventory, f"{module}.{owner}")["native_module"], owner, *rest]
80
+ )
81
+
82
+
83
+ def analyze(
84
+ inventory: dict, pyside_sources: dict[str, bytes], inventory_sha256: str
85
+ ) -> dict:
86
+ enums = _enums(pyside_sources)
87
+ flags = flag_classes(pyside_sources, enums)
88
+ pyside = {m: declarations(s) for m, s in pyside_sources.items()}
89
+ classes = {}
90
+ for module, decls in sorted(pyside.items()):
91
+ for name in sorted(decls):
92
+ key = f"{module}.{name}"
93
+ route = _route(inventory, key)
94
+ if route is None:
95
+ continue
96
+ methods = {"__init__": decls[name]["methods"].get("__init__", [])}
97
+ methods |= {
98
+ m: o
99
+ for m, o in _effective(pyside, key).items()
100
+ if not m.startswith("_")
101
+ }
102
+ for method, overloads in sorted(methods.items()):
103
+ positions = [
104
+ p
105
+ | {
106
+ "flags": _native(inventory, p["flags"]),
107
+ "keep": [_native(inventory, k) for k in p["keep"]],
108
+ }
109
+ for p in _positions(overloads, flags, enums)
110
+ if _route(inventory, ".".join(p["flags"].split(".")[:2]))
111
+ ]
112
+ if positions:
113
+ static = method != "__init__" and all(
114
+ o["static"] for o in overloads
115
+ )
116
+ classes.setdefault(f"{route['native_module']}.{name}", {})[
117
+ method
118
+ ] = {
119
+ "static": static,
120
+ "positions": positions,
121
+ }
122
+ return {
123
+ "schema_version": 1,
124
+ "inventory_sha256": inventory_sha256,
125
+ "limitations": LIMITATIONS,
126
+ "counts": {
127
+ "flag_classes": len(flags),
128
+ "methods": sum(len(m) for m in classes.values()),
129
+ "positions": sum(
130
+ len(e["positions"]) for m in classes.values() for e in m.values()
131
+ ),
132
+ },
133
+ "classes": classes,
134
+ }
135
+
136
+
137
+ def main() -> None:
138
+ parser = argparse.ArgumentParser(description=__doc__)
139
+ parser.add_argument("--echopy", type=Path, default=Path("../fontlab-echopy"))
140
+ parser.add_argument("--inventory", type=Path, default=PACKAGE / "_inventory.json")
141
+ parser.add_argument("--output", type=Path, default=PACKAGE / "_flags.json")
142
+ args = parser.parse_args()
143
+ data = args.inventory.read_bytes()
144
+ inventory = json.loads(data)
145
+ pyside, _ = load_sources(args.echopy, inventory)
146
+ report = analyze(inventory, pyside, hashlib.sha256(data).hexdigest())
147
+ args.output.write_text(
148
+ json.dumps(report, sort_keys=True, indent=1) + "\n", encoding="utf-8"
149
+ )
150
+ digest = hashlib.sha256(args.output.read_bytes()).hexdigest()
151
+ print(f"{args.output.name}: {args.output.stat().st_size} bytes; SHA256 {digest}")
152
+ print(json.dumps(report["counts"], sort_keys=True))
153
+
154
+
155
+ if __name__ == "__main__":
156
+ main()
@@ -0,0 +1,149 @@
1
+ # this_file: src/pythonqtside/tooling/inventory.py
2
+ """Generate the pinned inventory and widget map using only standard-library parsers."""
3
+
4
+ import argparse
5
+ import hashlib
6
+ import json
7
+ from email.parser import BytesParser
8
+ from pathlib import Path
9
+ from zipfile import ZipFile
10
+
11
+ from .join import MODULES, NATIVE_MODULES, join_surfaces
12
+ from .surface import Surface, extract
13
+
14
+ PACKAGE = Path(__file__).resolve().parents[1]
15
+ LIMITATIONS = [
16
+ "Host versions come only from _provenance.json native_host; unrecorded fields are null.",
17
+ "Public declarations only; imports, docstrings and private methods are excluded; class dunders are retained and __init__ arities summarized separately.",
18
+ "Bases within the eight PySide2 modules are expanded; external bases are not inspected.",
19
+ "Constructor entries are declared arity shapes, not proven native overloads; variadic stubs give no dispatch evidence.",
20
+ "Native type attributes are opaque; nested enum membership is null, not assumed missing.",
21
+ "Extra native enum candidates are uppercase Any/int attributes, not confirmed enum membership or values.",
22
+ "Accessor matches require a zero-argument declared getter and a same-name native attribute; behavior is unverified.",
23
+ "Object is retained as a missing class declaration and flagged as an empty stub helper.",
24
+ ]
25
+
26
+
27
+ def _sha(path: Path) -> str:
28
+ with path.open("rb") as stream:
29
+ return hashlib.file_digest(stream, "sha256").hexdigest()
30
+
31
+
32
+ def _read(path: Path, label: str, inputs: dict) -> bytes:
33
+ data = path.read_bytes()
34
+ inputs[label] = {"sha256": hashlib.sha256(data).hexdigest()}
35
+ return data
36
+
37
+
38
+ def _upstream(cache: Path, manifest: dict, inputs: dict) -> dict[str, Surface]:
39
+ wheel = cache / manifest["wheel"]
40
+ digest = _sha(wheel)
41
+ if digest != manifest["sha256"]:
42
+ raise ValueError("PySide2 wheel SHA256 does not match pyside-manifest.json")
43
+ inputs[wheel.name] = {"sha256": digest}
44
+ modules = {}
45
+ with ZipFile(wheel) as archive:
46
+ (metadata_name,) = [
47
+ n for n in archive.namelist() if n.endswith(".dist-info/METADATA")
48
+ ]
49
+ metadata = archive.read(metadata_name)
50
+ inputs[metadata_name] = {
51
+ "sha256": hashlib.sha256(metadata).hexdigest(),
52
+ "container": wheel.name,
53
+ }
54
+ if BytesParser().parsebytes(metadata)["Version"] != manifest["version"]:
55
+ raise ValueError(
56
+ "PySide2 wheel version does not match pyside-manifest.json"
57
+ )
58
+ for module in MODULES:
59
+ name = f"PySide2/{module}.pyi"
60
+ data = archive.read(name)
61
+ inputs[name] = {
62
+ "sha256": hashlib.sha256(data).hexdigest(),
63
+ "container": wheel.name,
64
+ }
65
+ modules[module] = extract(data)
66
+ return modules
67
+
68
+
69
+ def _native(source: Path, provenance: dict, inputs: dict) -> dict[str, Surface]:
70
+ modules = {}
71
+ for module in NATIVE_MODULES:
72
+ name = f"PythonQt/{module}.pyi"
73
+ data = _read(source / name, name, inputs)
74
+ recorded = provenance.get("merged_outputs", {}).get(name)
75
+ if recorded is not None and recorded != inputs[name]["sha256"]:
76
+ raise ValueError(f"Native SHA256 does not match _provenance.json: {name}")
77
+ modules[module] = extract(data)
78
+ return modules
79
+
80
+
81
+ def build_report(echopy: Path) -> dict:
82
+ """Verify source identities before joining; store logical names, never local paths."""
83
+ inputs: dict = {}
84
+ cache, source = echopy / ".cache/upstream", echopy / "src/fontlab_echopy"
85
+ manifest = json.loads(
86
+ _read(cache / "pyside-manifest.json", "pyside-manifest.json", inputs)
87
+ )
88
+ provenance = json.loads(
89
+ _read(source / "_provenance.json", "_provenance.json", inputs)
90
+ )
91
+ pyside = _upstream(cache, manifest, inputs)
92
+ native = _native(source, provenance, inputs)
93
+ host = provenance.get("native_host", {})
94
+ return {
95
+ "schema_version": 1,
96
+ "pyside_version": manifest["version"],
97
+ "native_host": {
98
+ key: host.get(key)
99
+ for key in ("fontlab_version", "python_version", "qt_version")
100
+ },
101
+ "inputs": inputs,
102
+ "limitations": LIMITATIONS,
103
+ "modules": join_surfaces(pyside, native),
104
+ "native_modules": {
105
+ m: {"classes": sorted(d["classes"]), "members": sorted(d["members"])}
106
+ for m, d in native.items()
107
+ },
108
+ }
109
+
110
+
111
+ def write_reports(report: dict, output: Path, widgets_output: Path) -> None:
112
+ """Both products derive from one join; sorted JSON has no timestamps."""
113
+ classes = report["modules"]["QtWidgets"]["classes"]
114
+ (wheel,) = [v for k, v in report["inputs"].items() if k.endswith(".whl")]
115
+ widgets = {
116
+ "classes": sorted(
117
+ n for n, c in classes.items() if c["native_module"] is not None
118
+ ),
119
+ "pyside_version": report["pyside_version"],
120
+ "wheel_sha256": wheel["sha256"],
121
+ "source": f"https://pypi.org/project/PySide2/{report['pyside_version']}/",
122
+ }
123
+ for path, data in ((output, report), (widgets_output, widgets)):
124
+ path.write_text(
125
+ json.dumps(data, sort_keys=True, indent=2) + "\n", encoding="utf-8"
126
+ )
127
+
128
+
129
+ def main() -> None:
130
+ parser = argparse.ArgumentParser(description=__doc__)
131
+ parser.add_argument("--echopy", type=Path, default=Path("../fontlab-echopy"))
132
+ parser.add_argument("--output", type=Path, default=PACKAGE / "_inventory.json")
133
+ parser.add_argument(
134
+ "--widgets-output", type=Path, default=PACKAGE / "_qtwidgets.json"
135
+ )
136
+ args = parser.parse_args()
137
+ report = build_report(args.echopy)
138
+ write_reports(report, args.output, args.widgets_output)
139
+ for path in (args.output, args.widgets_output):
140
+ print(f"{path.name}: {path.stat().st_size} bytes; SHA256 {_sha(path)}")
141
+ print(
142
+ json.dumps(
143
+ {m: d["summary"] for m, d in report["modules"].items()}, sort_keys=True
144
+ )
145
+ )
146
+
147
+
148
+ if __name__ == "__main__":
149
+ main()