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,216 @@
1
+ # this_file: src/pythonqtside/_app_cleanup.py
2
+ """Disconnect and stop owned work before deleting roots of the owned graph."""
3
+
4
+ import inspect
5
+ from collections.abc import Callable
6
+ from functools import partial
7
+ from typing import Any
8
+
9
+ from . import _app_native
10
+
11
+
12
+ def native_slot(value: Any) -> bool:
13
+ """A bound native Qt slot, such as ``dialog.reject`` (measured type name)."""
14
+ return type(value).__name__ == "builtin_qt_slot"
15
+
16
+
17
+ def same(left: Any, right: Any) -> bool:
18
+ """Equality that never lets PythonQt compare a native slot with another type.
19
+
20
+ PythonQt's slot comparison casts both operands to slot objects; comparing a
21
+ native slot with a bound method of the same object segfaults FontLab
22
+ (pqs-g04/fixtures/crash2-disconnect.md)."""
23
+ return left is right or (type(left) is type(right) and bool(left == right))
24
+
25
+
26
+ def _same_args(left: tuple, right: tuple) -> bool:
27
+ return len(left) == len(right) and all(same(a, b) for a, b in zip(left, right))
28
+
29
+
30
+ def slot_forwarder(slot: Any) -> Callable:
31
+ """Connect a native slot through a Python function.
32
+
33
+ PythonQt passes every signal argument to a native slot, so
34
+ ``clicked.connect(label.clear)`` fails with "wrong number of arguments"; Qt
35
+ drops trailing arguments the slot does not take. The forwarder retries with
36
+ fewer leading arguments and remembers the count that worked. Holding only
37
+ Python functions in PythonQt's handler list also keeps its disconnect
38
+ comparison away from native slots."""
39
+ accepted: list[int] = []
40
+
41
+ def forward(*args: Any) -> Any:
42
+ if accepted:
43
+ return slot(*args[: accepted[0]])
44
+ for count in range(len(args), -1, -1):
45
+ try:
46
+ result = slot(*args[:count])
47
+ except ValueError as error:
48
+ message = str(error)
49
+ if count and (
50
+ "wrong number of arguments" in message
51
+ or "Could not find matching overload" in message
52
+ ):
53
+ continue
54
+ raise
55
+ accepted.append(count)
56
+ return result
57
+ return None
58
+
59
+ forward.__wrapped__ = slot
60
+ return forward
61
+
62
+
63
+ def _required(callback: Any) -> int | None:
64
+ """Positional parameters a Python callback needs; None for *args or unknown."""
65
+ try:
66
+ parameters = inspect.signature(callback).parameters.values()
67
+ except (TypeError, ValueError):
68
+ return None
69
+ if any(p.kind is p.VAR_POSITIONAL for p in parameters):
70
+ return None
71
+ return sum(
72
+ p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) and p.default is p.empty
73
+ for p in parameters
74
+ )
75
+
76
+
77
+ def overload_signature(signal: Any, name: str, callback: Any) -> str | None:
78
+ """``"2finished(int,QProcess::ExitStatus)"`` when the callback needs more
79
+ arguments than PythonQt's default (first declared) overload delivers.
80
+
81
+ PythonQt connects ``process.finished`` to the deprecated ``finished(int)``, so a
82
+ PySide2 ``lambda code, status: ...`` never runs (pqs-g04/fixtures)."""
83
+ required = _required(callback)
84
+ if required is None:
85
+ return None
86
+ try:
87
+ overloads = [tuple(types) for types in signal.parameterTypes()]
88
+ except Exception: # noqa: BLE001 - not a PythonQt signal wrapper
89
+ return None
90
+ if len(overloads) < 2 or required <= len(overloads[0]):
91
+ return None
92
+ fits = [types for types in overloads if len(types) >= required]
93
+ if not fits:
94
+ return None
95
+ return "2" + name + "(" + ",".join(min(fits, key=len)) + ")"
96
+
97
+
98
+ def connection_call(
99
+ receiver: Any,
100
+ name: str,
101
+ value: Any,
102
+ records: list[tuple],
103
+ owner: Any = None,
104
+ signal_name: str | None = None,
105
+ ) -> Callable:
106
+ """Track successful native connects and mirror explicit disconnects.
107
+
108
+ Records are ``(signal, args, kwargs, undo, owner)``; ``undo`` disconnects an
109
+ overload-specific connection made through ``owner.connect(signature, ...)``;
110
+ ``owner`` is the signal's QObject when the call site named it."""
111
+
112
+ def connect(*args: Any, **kwargs: Any) -> Any:
113
+ if args and native_slot(args[0]):
114
+ args = (slot_forwarder(args[0]), *args[1:])
115
+ signature = (
116
+ overload_signature(receiver, signal_name, args[0])
117
+ if owner is not None and signal_name and len(args) == 1 and not kwargs
118
+ else None
119
+ )
120
+ if signature is not None and owner.connect(signature, args[0]):
121
+ undo = partial(owner.disconnect, signature, args[0])
122
+ records.append((receiver, args, {}, undo, owner))
123
+ return True
124
+ result = value(*args, **kwargs)
125
+ if result is not False:
126
+ records.append((receiver, args, dict(kwargs), None, owner))
127
+ return result
128
+
129
+ def disconnect(*args: Any, **kwargs: Any) -> Any:
130
+ mine = [
131
+ r for r in records if _app_native.same_connection_receiver(r[0], receiver)
132
+ ]
133
+ if args and native_slot(args[0]):
134
+ wrapped = [
135
+ r for r in mine if same(getattr(r[1][0], "__wrapped__", None), args[0])
136
+ ]
137
+ if not wrapped:
138
+ return False # PythonQt would compare the slot with every handler
139
+ args = (wrapped[0][1][0], *args[1:])
140
+ matched = [
141
+ r for r in mine if not args or (_same_args(r[1], args) and r[2] == kwargs)
142
+ ]
143
+ undone = [r for r in matched if r[3] is not None]
144
+ for record in undone:
145
+ record[3]()
146
+ # Only overload connections made through owner.connect() are undone here;
147
+ # everything else, including callbacks this handle never tracked, goes to
148
+ # PythonQt (native-slot arguments were mapped or refused above).
149
+ result = (
150
+ True if undone and len(undone) == len(matched) else value(*args, **kwargs)
151
+ )
152
+ if result is not False:
153
+ records[:] = [r for r in records if not any(r is m for m in matched)]
154
+ return result
155
+
156
+ return connect if name == "connect" else disconnect
157
+
158
+
159
+ def disconnect_connections(connections: list[tuple]) -> tuple[str, ...]:
160
+ """Disconnect tracked callbacks independently of owned native object deletion."""
161
+ errors = []
162
+ for receiver, args, kwargs, undo, owner in reversed(connections):
163
+ try:
164
+ if owner is not None and _app_native.destroyed(owner):
165
+ continue # Qt deleted the sender; its PythonQt handlers went with it
166
+ if undo is not None:
167
+ undo()
168
+ else:
169
+ receiver.disconnect(*args, **kwargs)
170
+ except Exception as error: # noqa: BLE001 - record host-specific teardown failures
171
+ errors.append(f"{type(error).__name__}: {error}")
172
+ return tuple(errors)
173
+
174
+
175
+ def cleanup(
176
+ objects: list[Any], connections: list[tuple]
177
+ ) -> tuple[tuple[str, ...], list[Any]]:
178
+ errors = list(disconnect_connections(connections))
179
+ # Qt may already have deleted owned objects (a delegate's editor); their
180
+ # wrappers raise on use, so they are gone rather than cleanup failures.
181
+ objects = [obj for obj in objects if not _app_native.destroyed(obj)]
182
+
183
+ def attempt(action: Callable[[], Any]) -> None:
184
+ try:
185
+ action()
186
+ except Exception as error: # noqa: BLE001 - teardown must retain the original startup error
187
+ errors.append(f"{type(error).__name__}: {error}")
188
+
189
+ unstopped = []
190
+ for obj in objects:
191
+ try:
192
+ _app_native.stop_owned(obj)
193
+ except Exception as error: # noqa: BLE001 - cleanup failures are reported without masking startup errors
194
+ errors.append(f"{type(error).__name__}: {error}")
195
+ unstopped.append(obj)
196
+ # Never delete an owned ancestor of work that failed to stop.
197
+ for obj in tuple(unstopped):
198
+ try:
199
+ parent = obj.parent()
200
+ while parent is not None and any(parent is owned for owned in objects):
201
+ if not any(parent is kept for kept in unstopped):
202
+ unstopped.append(parent)
203
+ parent = parent.parent()
204
+ except Exception as error: # noqa: BLE001 - teardown cannot replace an execution error
205
+ errors.append(f"{type(error).__name__}: {error}")
206
+ unstopped[:] = objects
207
+ for obj in objects:
208
+ try:
209
+ root = not any(obj.parent() is owned for owned in objects)
210
+ except Exception as error: # noqa: BLE001 - already-deleted native wrappers can fail in host-specific ways
211
+ errors.append(f"{type(error).__name__}: {error}")
212
+ continue
213
+ if root and not any(obj is live for live in unstopped):
214
+ attempt(partial(_app_native.close_owned_widget, obj))
215
+ attempt(lambda obj=obj: obj.deleteLater())
216
+ return tuple(errors), unstopped
@@ -0,0 +1,106 @@
1
+ # this_file: src/pythonqtside/_app_conversions.py
2
+ """Measured PySide2 implicit enum -> value-class conversions for native calls.
3
+
4
+ PythonQt rejects e.g. ``setEasingCurve(QEasingCurve.OutElastic)`` where PySide2
5
+ converts the enum through ``QEasingCurve(type)``. Positions come from the generated
6
+ ``_implicit_conversions.json``; callers in ``_app_native`` gate on a native receiver
7
+ without a Python override. Values are wrapped only when they are instances of the
8
+ measured native enum type; anything else, including plain ints, passes through.
9
+ """
10
+
11
+ import json
12
+ import sys
13
+ from functools import cache, partial
14
+ from importlib import import_module
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+
19
+ @cache
20
+ def _table() -> dict[str, tuple[tuple[str, dict], ...]]:
21
+ """Generated table by method name: (native class path, entry) pairs."""
22
+ path = Path(__file__).with_name("_implicit_conversions.json")
23
+ data = json.loads(path.read_text(encoding="utf-8"))
24
+ by_method: dict[str, list] = {}
25
+ for key, methods in sorted(data["classes"].items()):
26
+ for method, index in sorted(methods.items()):
27
+ by_method.setdefault(method, []).append((key, data["entries"][index]))
28
+ return {method: tuple(pairs) for method, pairs in by_method.items()}
29
+
30
+
31
+ # Native path -> (PythonQt module it came from, object or None). One lookup per
32
+ # path: setCursor alone has ~95 candidate classes, resolved on every attribute call.
33
+ _RESOLVED: dict[str, tuple[Any, Any]] = {}
34
+
35
+
36
+ def _lookup(root: Any, path: str) -> Any:
37
+ result = root
38
+ for part in path.split("."):
39
+ result = getattr(result, part, None)
40
+ if result is None:
41
+ return None
42
+ return result
43
+
44
+
45
+ def _native(path: str) -> Any:
46
+ """``QtCore.Qt.GlobalColor`` -> the PythonQt object, or None when absent."""
47
+ root = sys.modules.get("PythonQt")
48
+ if root is None:
49
+ try:
50
+ root = import_module("PythonQt")
51
+ except ModuleNotFoundError:
52
+ return None
53
+ cached = _RESOLVED.get(path)
54
+ if cached is None or cached[0] is not root:
55
+ cached = _RESOLVED[path] = (root, _lookup(root, path))
56
+ return cached[1]
57
+
58
+
59
+ def _entry(receiver: Any, candidates: tuple) -> dict | None:
60
+ """The most-derived table class matching the receiver (class: static only)."""
61
+ matches = []
62
+ for key, entry in candidates:
63
+ cls = _native(key)
64
+ if not isinstance(cls, type):
65
+ continue
66
+ if isinstance(receiver, type):
67
+ matched = entry["static"] and issubclass(receiver, cls)
68
+ else:
69
+ matched = isinstance(receiver, cls)
70
+ if matched:
71
+ matches.append((len(cls.__mro__), entry))
72
+ return max(matches, key=lambda m: m[0])[1] if matches else None
73
+
74
+
75
+ def _converted(value: Any, conversions: dict[str, str]) -> Any:
76
+ if type(value) in (int, bool):
77
+ return value
78
+ for enum, target in conversions.items():
79
+ enum_type = _native(enum)
80
+ if isinstance(enum_type, type) and isinstance(value, enum_type):
81
+ cls = _native(target)
82
+ return value if cls is None else cls(value)
83
+ return value
84
+
85
+
86
+ def _with_conversions(method: Any, positions: list, *args: Any, **kwargs: Any) -> Any:
87
+ """Positional PySide2 call -> measured enums wrapped -> one native call."""
88
+ if kwargs:
89
+ return method(*args, **kwargs)
90
+ converted = list(args)
91
+ for position in positions:
92
+ index, (low, high) = position["index"], position["arities"]
93
+ if index < len(args) and low <= len(args) <= high:
94
+ converted[index] = _converted(args[index], position["conversions"])
95
+ return method(*converted)
96
+
97
+
98
+ def conversion_call(receiver: Any, name: str, method: Any) -> Any:
99
+ """A wrapping callable for a measured method, or None when nothing applies."""
100
+ candidates = _table().get(name)
101
+ if candidates is None:
102
+ return None
103
+ entry = _entry(receiver, candidates)
104
+ if entry is None or not entry["positions"]:
105
+ return None
106
+ return partial(_with_conversions, method, entry["positions"])
@@ -0,0 +1,74 @@
1
+ # this_file: src/pythonqtside/_app_dialogs.py
2
+ """PySide2's ``(path, selectedFilter)`` result for the QFileDialog static pickers.
3
+
4
+ PythonQt's ``getOpenFileName``/``getSaveFileName`` return a str and
5
+ ``getOpenFileNames`` a tuple; all take ``(parent, caption, dir, filter,
6
+ selectedFilter, options)`` (measured in FontLab 9). PySide2 takes ``(parent,
7
+ caption, dir, filter, options)`` and code unpacks ``path, _ =
8
+ QFileDialog.getOpenFileName(...)``. The adapter inserts ``selectedFilter=""``
9
+ before ``options``: it is an out-parameter PythonQt cannot fill, so the returned
10
+ filter is always ``""``. PySide2 has no ``selectedFilter`` keyword; passing one
11
+ raises TypeError.
12
+ """
13
+
14
+ from functools import partial
15
+ from importlib import import_module
16
+ from typing import Any
17
+
18
+ PICKERS = frozenset({"getOpenFileName", "getSaveFileName", "getOpenFileNames"})
19
+ # PySide2 names and defaults, in PySide2 order; native inserts selectedFilter
20
+ # before options.
21
+ PARAMETERS = (
22
+ ("parent", None),
23
+ ("caption", ""),
24
+ ("dir", ""),
25
+ ("filter", ""),
26
+ ("options", 0),
27
+ )
28
+ _NAMES = tuple(n for n, _ in PARAMETERS)
29
+
30
+
31
+ def _is_file_dialog(receiver: Any) -> bool:
32
+ try:
33
+ dialog = import_module("PythonQt").QtGui.QFileDialog
34
+ except (ModuleNotFoundError, AttributeError):
35
+ return False
36
+ if isinstance(receiver, type):
37
+ return issubclass(receiver, dialog)
38
+ return isinstance(receiver, dialog)
39
+
40
+
41
+ def file_dialog_call(receiver: Any, name: str, method: Any) -> Any:
42
+ """Adapter for a native, unoverridden picker, or None when none applies."""
43
+ if name not in PICKERS or not _is_file_dialog(receiver):
44
+ return None
45
+ return partial(_with_filter, name, method)
46
+
47
+
48
+ def _with_filter(name: str, method: Any, *args: Any, **kwargs: Any) -> Any:
49
+ if "selectedFilter" in kwargs:
50
+ raise TypeError(
51
+ f"QFileDialog.{name}() got an unexpected keyword argument "
52
+ "'selectedFilter' (PySide2 has none; the filter is returned)"
53
+ )
54
+ if (
55
+ len(args) > len(_NAMES)
56
+ or set(kwargs) - set(_NAMES)
57
+ or set(kwargs) & set(_NAMES[: len(args)])
58
+ ):
59
+ return method(
60
+ *args, **kwargs
61
+ ) # not a PySide2 form: native raises its own error
62
+ given = dict(zip(_NAMES, args)) | kwargs
63
+ if "options" in given: # native: selectedFilter (unfillable) sits before options
64
+ filled = [given.get(n, d) for n, d in PARAMETERS[:4]]
65
+ filled += ["", given["options"]]
66
+ else:
67
+ last = max((_NAMES.index(n) for n in given), default=-1)
68
+ filled = [given.get(n, d) for n, d in PARAMETERS[: last + 1]]
69
+ result = method(*filled)
70
+ if name == "getOpenFileNames":
71
+ return list(result), ""
72
+ if isinstance(result, tuple) and len(result) == 2:
73
+ return result # already the (path, filter) pair
74
+ return result, ""
@@ -0,0 +1,79 @@
1
+ # this_file: src/pythonqtside/_app_flags.py
2
+ """PySide2 QFlags arguments where a native enum overload would win the dispatch.
3
+
4
+ ``QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)`` passes a plain
5
+ int in PythonQt, which selects the ``Qt.Orientation`` overload (no buttons). At the
6
+ positions in the generated ``_flags.json`` a plain int, or an enum value other than
7
+ the competing overload's enum, is wrapped in the native QFlags class first.
8
+ """
9
+
10
+ import json
11
+ from functools import cache, partial
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from ._app_conversions import _native
16
+
17
+
18
+ @cache
19
+ def _table() -> dict[str, tuple[tuple[str, dict], ...]]:
20
+ data = json.loads(Path(__file__).with_name("_flags.json").read_text("utf-8"))
21
+ by_method: dict[str, list] = {}
22
+ for key, methods in sorted(data["classes"].items()):
23
+ for method, entry in sorted(methods.items()):
24
+ by_method.setdefault(method, []).append((key, entry))
25
+ return {method: tuple(pairs) for method, pairs in by_method.items()}
26
+
27
+
28
+ def _entry(receiver: Any, name: str) -> dict | None:
29
+ for key, entry in _table().get(name, ()):
30
+ cls = _native(key)
31
+ if not isinstance(cls, type):
32
+ continue
33
+ if name == "__init__":
34
+ matched = receiver is cls
35
+ elif isinstance(receiver, type):
36
+ matched = entry["static"] and issubclass(receiver, cls)
37
+ else:
38
+ matched = isinstance(receiver, cls)
39
+ if matched:
40
+ return entry
41
+ return None
42
+
43
+
44
+ def _wrapped(value: Any, position: dict) -> Any:
45
+ if not isinstance(value, int) or type(value) is bool:
46
+ return value
47
+ if any(
48
+ isinstance(t, type) and isinstance(value, t)
49
+ for t in map(_native, position["keep"])
50
+ ):
51
+ return value
52
+ flags = _native(position["flags"])
53
+ return value if flags is None else flags(value)
54
+
55
+
56
+ def convert(receiver: Any, name: str, args: tuple) -> tuple:
57
+ """Positional arguments with measured QFlags positions wrapped."""
58
+ entry = _entry(receiver, name) if name in _table() else None
59
+ if entry is None:
60
+ return args
61
+ result = list(args)
62
+ for position in entry["positions"]:
63
+ index, (low, high) = position["index"], position["arities"]
64
+ if index < len(args) and low <= len(args) <= high:
65
+ result[index] = _wrapped(args[index], position)
66
+ return tuple(result)
67
+
68
+
69
+ def _with_flags(
70
+ receiver: Any, name: str, method: Any, *args: Any, **kwargs: Any
71
+ ) -> Any:
72
+ return method(*convert(receiver, name, args), **kwargs)
73
+
74
+
75
+ def flags_call(receiver: Any, name: str, method: Any) -> Any:
76
+ """Wrap a measured method, or return it unchanged."""
77
+ if name not in _table() or _entry(receiver, name) is None:
78
+ return method
79
+ return partial(_with_flags, receiver, name, method)
@@ -0,0 +1,146 @@
1
+ # this_file: src/pythonqtside/_app_imports.py
2
+ """A retained, private import graph with source provenance and no aliases."""
3
+
4
+ import builtins
5
+ import hashlib
6
+ import uuid
7
+ from importlib import import_module
8
+ from importlib.util import resolve_name
9
+ from pathlib import Path
10
+ from types import MappingProxyType, ModuleType
11
+ from typing import Any
12
+
13
+ from ._app_source import adapt_source
14
+
15
+
16
+ def freeze(value: Any) -> Any:
17
+ """Freeze nested report structures while retaining native identity objects."""
18
+ if isinstance(value, dict):
19
+ return MappingProxyType({key: freeze(item) for key, item in value.items()})
20
+ if isinstance(value, list):
21
+ return tuple(freeze(item) for item in value)
22
+ return value
23
+
24
+
25
+ class ImportContext:
26
+ """Route PySide2 and local Python files through one app's private builtins."""
27
+
28
+ def __init__(self, handle: Any, root: Path) -> None:
29
+ self.handle = handle
30
+ self.root = root
31
+ self.modules = {}
32
+ self.reports = {}
33
+ self.identities = {}
34
+ self.original_import = builtins.__import__
35
+ self.builtins = dict(vars(builtins), __import__=self.importer)
36
+ suffix = uuid.uuid4().hex
37
+ self.call_name = "_pythonqtside_call_" + suffix
38
+ self.resolve_name = "_pythonqtside_resolve_" + suffix
39
+
40
+ def execute(self, path: Path, namespace: dict) -> None:
41
+ """Decode via Python's encoding-cookie rules and retain exact original bytes."""
42
+ import tokenize
43
+ from io import BytesIO
44
+
45
+ original = path.read_bytes()
46
+ encoding, _ = tokenize.detect_encoding(BytesIO(original).readline)
47
+ source = original.decode(encoding)
48
+ tree, report = adapt_source(
49
+ source, str(path), call_name=self.call_name, resolve_name=self.resolve_name
50
+ )
51
+ report.update(
52
+ original_bytes=original,
53
+ source_sha256=hashlib.sha256(original).hexdigest(),
54
+ filename=str(path),
55
+ encoding=encoding,
56
+ limitations=("Dynamic exec/eval strings are not adapted.",),
57
+ )
58
+ self.reports[str(path)] = freeze(report)
59
+ namespace.update(__file__=str(path), __builtins__=self.builtins)
60
+ namespace[self.call_name] = self.handle._prepare
61
+ namespace[self.resolve_name] = self.handle._resolve
62
+ exec(compile(tree, str(path), "exec"), namespace) # noqa: S102 - explicit local source runner
63
+
64
+ def _local_path(self, name: str) -> tuple[Path, bool] | None:
65
+ candidate = self.root.joinpath(*name.split("."))
66
+ if candidate.with_suffix(".py").is_file():
67
+ return candidate.with_suffix(".py"), False
68
+ if (candidate / "__init__.py").is_file():
69
+ return candidate / "__init__.py", True
70
+ return None
71
+
72
+ def _qt_module(self, name: str) -> ModuleType:
73
+ module = ModuleType(name)
74
+ module.__package__ = "PySide2" if "." in name else ""
75
+ if name == "PySide2":
76
+ module.__path__ = []
77
+ module.__getattr__ = lambda member: self._load("PySide2." + member)
78
+ else:
79
+ target = import_module("pythonqtside." + name.split(".", 1)[1])
80
+
81
+ def member(attribute: str) -> Any:
82
+ value = getattr(target, attribute)
83
+ if any(value is cls for cls in self.handle._application_classes):
84
+ value = self.handle._application
85
+ if isinstance(value, type):
86
+ self.identities[name + "." + attribute] = value
87
+ return value
88
+
89
+ module.__getattr__ = member
90
+ module.__dir__ = lambda: dir(target)
91
+ return module
92
+
93
+ def _load(self, name: str) -> ModuleType:
94
+ if name in self.modules:
95
+ return self.modules[name]
96
+ parent_name, _, child = name.rpartition(".")
97
+ parent = self._load(parent_name) if parent_name else None
98
+ if name == "PySide2" or name.startswith("PySide2."):
99
+ module = self._qt_module(name)
100
+ self.modules[name] = module
101
+ else:
102
+ found = self._local_path(name)
103
+ if found is None:
104
+ raise ModuleNotFoundError(
105
+ f"No private app module named {name!r}", name=name
106
+ )
107
+ path, package = found
108
+ module = ModuleType(name)
109
+ module.__package__ = name if package else parent_name
110
+ if package:
111
+ module.__path__ = [str(path.parent)]
112
+ self.modules[name] = module
113
+ try:
114
+ self.execute(path, vars(module))
115
+ except BaseException:
116
+ self.modules.pop(name, None)
117
+ raise
118
+ if parent is not None:
119
+ setattr(parent, child, module)
120
+ return module
121
+
122
+ def importer(
123
+ self,
124
+ name: str,
125
+ globals: dict | None = None,
126
+ locals: dict | None = None,
127
+ fromlist: tuple = (),
128
+ level: int = 0,
129
+ ) -> ModuleType:
130
+ """Match Python's top-package/fromlist return convention in the private graph."""
131
+ self.handle._require_open()
132
+ if level:
133
+ package = (globals or {}).get("__package__", "")
134
+ name = resolve_name("." * level + name, package)
135
+ root = name.partition(".")[0]
136
+ if root != "PySide2" and self._local_path(root) is None:
137
+ return self.original_import(name, globals, locals, fromlist, 0)
138
+ module = self._load(name)
139
+ for item in fromlist or ():
140
+ if (
141
+ item != "*"
142
+ and item not in vars(module)
143
+ and self._local_path(name + "." + item)
144
+ ):
145
+ self._load(name + "." + item)
146
+ return module if fromlist else self._load(root)