from __future__ import annotations
import importlib
import importlib.machinery
import os
import sys
from . import _qt_stub as _stub
BACKEND_ENV = "FERROCAD_PYSIDE_BACKEND"
_STUB_BACKEND = "stub"
_SUBMODULES = ("QtCore", "QtGui", "QtWidgets")
def _selected_backend() -> str:
value = os.environ.get(BACKEND_ENV, "").strip()
return _STUB_BACKEND if not value else value
def _new_stub_module(name: str, exports: dict) -> _stub.QtStubModule:
module = _stub.QtStubModule(
f"{__name__}.{name}",
_STUB_DOCS.get(name, f"Pure-Python stand-in for PySide.{name}."),
)
module.__package__ = __name__
module.__spec__ = importlib.machinery.ModuleSpec(module.__name__, None)
module.__file__ = _stub.__file__
module.__all__ = tuple(sorted(exports))
setattr(module, _stub.STUB_MARKER, True)
for key, value in exports.items():
setattr(module, key, value)
sys.modules[module.__name__] = module
globals()[name] = module
return module
_STUB_DOCS = {
"QtCore": (
"Pure-Python QtCore subset: translation, timers, objects and loose-file "
"access for upstream Draft. No Qt runtime is imported."
),
"QtGui": (
"Pure-Python QtGui stand-in. The headless Draft import path evaluates no "
"QtGui name, so this module exports none; a missing name raises. GUI "
"modules (e.g. gui_hyperlink's QDesktopServices) still fail loudly."
),
"QtWidgets": (
"Pure-Python QtWidgets stand-in: QApplication.translate and the class "
"bases Draft subclasses at import time. Widgets are not constructed."
),
}
def _install_stub() -> list[str]:
exports_by_module = {
"QtCore": _stub.QTCORE_EXPORTS,
"QtGui": _stub.QTGUI_EXPORTS,
"QtWidgets": _stub.QTWIDGETS_EXPORTS,
}
installed = []
for name in _SUBMODULES:
_new_stub_module(name, dict(exports_by_module[name]))
installed.append(name)
return installed
def _install_real(distribution: str) -> list[str]:
installed = []
for name in (*_SUBMODULES, "QtSvg"):
try:
module = importlib.import_module(f"{distribution}.{name}")
except ImportError:
if name == "QtSvg":
continue
raise
sys.modules[f"{__name__}.{name}"] = module
globals()[name] = module
installed.append(name)
return installed
_backend = _selected_backend()
if _backend == _STUB_BACKEND:
_INSTALLED = _install_stub()
_USING_STUB = True
elif _backend in {"PySide6", "PySide2"}:
_INSTALLED = _install_real(_backend)
_USING_STUB = False
else:
raise RuntimeError(
f"{BACKEND_ENV}={_backend!r} is not a known PySide backend; "
"leave it unset (pure-Python stub) or set it to PySide6/PySide2"
)
if _USING_STUB:
QT_TRANSLATE_NOOP = QtCore.QT_TRANSLATE_NOOP
else:
QT_TRANSLATE_NOOP = getattr(QtCore, "QT_TRANSLATE_NOOP", _stub.QT_TRANSLATE_NOOP)
USING_STUB = _USING_STUB
globals()[_stub.STUB_MARKER] = _USING_STUB
__all__ = ["QT_TRANSLATE_NOOP", *_INSTALLED]
def __getattr__(name):
if name.startswith("__") and name.endswith("__"):
raise AttributeError(name)
raise AttributeError(
f"module {__name__!r} has no attribute {name!r}; "
f"it exports only {{{', '.join(__all__)}}}. "
"Set FERROCAD_PYSIDE_BACKEND=PySide6 to import a real Qt."
)