"""Minimal Python 2 & 3 shim around all Qt bindings

DOCUMENTATION
    Qt.py was born in the film and visual effects industry to address
    the growing need for the development of software capable of running
    with more than one flavour of the Qt bindings for Python.

    Supported Binding: PySide6, PySide2, PyQt6, PyQt5

    1. Build for one, run with all
    2. Explicit is better than implicit
    3. Support co-existence

    Default resolution order:
        - PySide6
        - PyQt6
        - PySide2
        - PyQt5

    Usage:
        >> import sys
        >> from Qt import QtWidgets
        >> app = QtWidgets.QApplication(sys.argv)
        >> button = QtWidgets.QPushButton("Hello World")
        >> button.show()
        >> app.exec_()

    All members of PySide6 are mapped from other bindings, should they exist.
    If no equivalent member exist, it is excluded from Qt.py and inaccessible.
    The idea is to highlight members that exist across all supported binding,
    and guarantee that code that runs on one binding runs on all others.

    For more details, visit https://github.com/mottosso/Qt.py

LICENSE

    See end of file for license (MIT, BSD) information.

"""

import os
import sys
import types
import shutil
import importlib
import json


__version__ = "2.0.3"

# Enable support for `from Qt import *`
__all__ = [
    "QtCompat",  # noqa: F822
]

# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING_JSON = os.getenv("QT_PREFERRED_BINDING_JSON", "")
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")

# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")


"""Common members of all bindings

This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.

The "_common_members" dictionary is generated using the "common_members.json"
file created by the membership tox environments. See _common_members_sources
for a list of the python and qt bindings used to generate this list.

Note: Some members like QtOpenGL may contain empty lists. These are targets for
assigning misplaced members according to the reference binding(PySide6). We
will need to add them to all bindings including None, so we add them here.

"""

_common_members = {
    "QtCore": [
        "QAbstractAnimation",
        "QAbstractEventDispatcher",
        "QAbstractItemModel",
        "QAbstractListModel",
        "QAbstractNativeEventFilter",
        "QAbstractProxyModel",
        "QAbstractTableModel",
        "QAnimationGroup",
        "QBasicTimer",
        "QBitArray",
        "QBuffer",
        "QByteArray",
        "QByteArrayMatcher",
        "QCborError",
        "QCborKnownTags",
        "QCborSimpleType",
        "QCborStreamReader",
        "QCborStreamWriter",
        "QChildEvent",
        "QCollator",
        "QCollatorSortKey",
        "QCommandLineOption",
        "QCommandLineParser",
        "QConcatenateTablesProxyModel",
        "QCoreApplication",
        "QCryptographicHash",
        "QDataStream",
        "QDate",
        "QDateTime",
        "QDir",
        "QDirIterator",
        "QDynamicPropertyChangeEvent",
        "QEasingCurve",
        "QElapsedTimer",
        "QEvent",
        "QEventLoop",
        "QFile",
        "QFileDevice",
        "QFileInfo",
        "QFileSelector",
        "QFileSystemWatcher",
        "QGenericArgument",
        "QGenericReturnArgument",
        "QIODevice",
        "QIdentityProxyModel",
        "QItemSelection",
        "QItemSelectionModel",
        "QItemSelectionRange",
        "QJsonDocument",
        "QJsonParseError",
        "QJsonValue",
        "QLibraryInfo",
        "QLine",
        "QLineF",
        "QLocale",
        "QLockFile",
        "QMargins",
        "QMarginsF",
        "QMessageAuthenticationCode",
        "QMessageLogContext",
        "QMetaClassInfo",
        "QMetaEnum",
        "QMetaMethod",
        "QMetaObject",
        "QMetaProperty",
        "QMimeData",
        "QMimeDatabase",
        "QMimeType",
        "QModelIndex",
        "QMutex",
        "QMutexLocker",
        "QObject",
        "QOperatingSystemVersion",
        "QParallelAnimationGroup",
        "QPauseAnimation",
        "QPersistentModelIndex",
        "QPluginLoader",
        "QPoint",
        "QPointF",
        "QProcess",
        "QProcessEnvironment",
        "QPropertyAnimation",
        "QRandomGenerator",
        "QReadLocker",
        "QReadWriteLock",
        "QRect",
        "QRectF",
        "QRegularExpression",
        "QRegularExpressionMatch",
        "QRegularExpressionMatchIterator",
        "QResource",
        "QRunnable",
        "QSaveFile",
        "QSemaphore",
        "QSemaphoreReleaser",
        "QSequentialAnimationGroup",
        "QSettings",
        "QSignalBlocker",
        "QSignalMapper",
        "QSize",
        "QSizeF",
        "QSocketNotifier",
        "QSortFilterProxyModel",
        "QStandardPaths",
        "QStorageInfo",
        "QStringListModel",
        "QSysInfo",
        "QSystemSemaphore",
        "QT_TRANSLATE_NOOP",
        "QT_TR_NOOP",
        "QTemporaryDir",
        "QTemporaryFile",
        "QTextBoundaryFinder",
        "QTextStream",
        "QTextStreamManipulator",
        "QThread",
        "QThreadPool",
        "QTime",
        "QTimeLine",
        "QTimeZone",
        "QTimer",
        "QTimerEvent",
        "QTranslator",
        "QTransposeProxyModel",
        "QUrl",
        "QUrlQuery",
        "QUuid",
        "QVariantAnimation",
        "QVersionNumber",
        "QWaitCondition",
        "QWriteLocker",
        "QXmlStreamAttribute",
        "QXmlStreamAttributes",
        "QXmlStreamEntityDeclaration",
        "QXmlStreamEntityResolver",
        "QXmlStreamNamespaceDeclaration",
        "QXmlStreamNotationDeclaration",
        "QXmlStreamReader",
        "QXmlStreamWriter",
        "Qt",
        "QtMsgType",
        "qAbs",
        "qAddPostRoutine",
        "qCompress",
        "qCritical",
        "qDebug",
        "qFatal",
        "qFuzzyCompare",
        "qInstallMessageHandler",
        "qIsFinite",
        "qIsInf",
        "qIsNaN",
        "qRegisterResourceData",
        "qUncompress",
        "qUnregisterResourceData",
        "qVersion",
        "qWarning",
    ],
    "QtGui": [
        "QAbstractTextDocumentLayout",
        "QActionEvent",
        "QBackingStore",
        "QBitmap",
        "QBrush",
        "QClipboard",
        "QCloseEvent",
        "QColor",
        "QConicalGradient",
        "QContextMenuEvent",
        "QCursor",
        "QDesktopServices",
        "QDoubleValidator",
        "QDrag",
        "QDragEnterEvent",
        "QDragLeaveEvent",
        "QDragMoveEvent",
        "QDropEvent",
        "QEnterEvent",
        "QExposeEvent",
        "QFileOpenEvent",
        "QFocusEvent",
        "QFont",
        "QFontDatabase",
        "QFontInfo",
        "QFontMetrics",
        "QFontMetricsF",
        "QGradient",
        "QGuiApplication",
        "QHelpEvent",
        "QHideEvent",
        "QHoverEvent",
        "QIcon",
        "QIconDragEvent",
        "QIconEngine",
        "QImage",
        "QImageIOHandler",
        "QImageReader",
        "QImageWriter",
        "QInputEvent",
        "QInputMethod",
        "QInputMethodEvent",
        "QInputMethodQueryEvent",
        "QIntValidator",
        "QKeyEvent",
        "QKeySequence",
        "QLinearGradient",
        "QMatrix2x2",
        "QMatrix2x3",
        "QMatrix2x4",
        "QMatrix3x2",
        "QMatrix3x3",
        "QMatrix3x4",
        "QMatrix4x2",
        "QMatrix4x3",
        "QMatrix4x4",
        "QMouseEvent",
        "QMoveEvent",
        "QMovie",
        "QNativeGestureEvent",
        "QOffscreenSurface",
        "QOpenGLContext",
        "QOpenGLContextGroup",
        "QPageLayout",
        "QPageSize",
        "QPagedPaintDevice",
        "QPaintDevice",
        "QPaintDeviceWindow",
        "QPaintEngine",
        "QPaintEngineState",
        "QPaintEvent",
        "QPainter",
        "QPainterPath",
        "QPainterPathStroker",
        "QPalette",
        "QPdfWriter",
        "QPen",
        "QPicture",
        "QPixelFormat",
        "QPixmap",
        "QPixmapCache",
        "QPointingDeviceUniqueId",
        "QPolygon",
        "QPolygonF",
        "QQuaternion",
        "QRadialGradient",
        "QRasterWindow",
        "QRawFont",
        "QRegion",
        "QResizeEvent",
        "QScreen",
        "QScrollEvent",
        "QScrollPrepareEvent",
        "QSessionManager",
        "QShortcutEvent",
        "QShowEvent",
        "QStandardItem",
        "QStandardItemModel",
        "QStaticText",
        "QStatusTipEvent",
        "QStyleHints",
        "QSurface",
        "QSurfaceFormat",
        "QSyntaxHighlighter",
        "QTabletEvent",
        "QTextBlock",
        "QTextBlockFormat",
        "QTextBlockGroup",
        "QTextBlockUserData",
        "QTextCharFormat",
        "QTextCursor",
        "QTextDocument",
        "QTextDocumentFragment",
        "QTextDocumentWriter",
        "QTextFormat",
        "QTextFragment",
        "QTextFrame",
        "QTextFrameFormat",
        "QTextImageFormat",
        "QTextInlineObject",
        "QTextItem",
        "QTextLayout",
        "QTextLength",
        "QTextLine",
        "QTextList",
        "QTextListFormat",
        "QTextObject",
        "QTextObjectInterface",
        "QTextOption",
        "QTextTable",
        "QTextTableCell",
        "QTextTableCellFormat",
        "QTextTableFormat",
        "QTouchEvent",
        "QTransform",
        "QValidator",
        "QVector2D",
        "QVector3D",
        "QVector4D",
        "QWhatsThisClickedEvent",
        "QWheelEvent",
        "QWindow",
        "QWindowStateChangeEvent",
        "qAlpha",
        "qBlue",
        "qGray",
        "qGreen",
        "qRed",
        "qRgb",
        "qRgba",
    ],
    "QtHelp": [
        "QCompressedHelpInfo",
        "QHelpContentItem",
        "QHelpContentModel",
        "QHelpContentWidget",
        "QHelpEngine",
        "QHelpEngineCore",
        "QHelpFilterData",
        "QHelpFilterEngine",
        "QHelpIndexModel",
        "QHelpIndexWidget",
        "QHelpSearchEngine",
        "QHelpSearchQuery",
        "QHelpSearchQueryWidget",
        "QHelpSearchResult",
        "QHelpSearchResultWidget",
    ],
    "QtMultimedia": [
        "QAudio",
        "QAudioBuffer",
        "QAudioDecoder",
        "QAudioFormat",
        "QAudioInput",
        "QAudioOutput",
        "QCamera",
        "QMediaPlayer",
        "QMediaRecorder",
        "QMediaTimeRange",
        "QSoundEffect",
        "QVideoFrame",
    ],
    "QtMultimediaWidgets": ["QGraphicsVideoItem", "QVideoWidget"],
    "QtNetwork": [
        "QAbstractNetworkCache",
        "QAbstractSocket",
        "QAuthenticator",
        "QDnsDomainNameRecord",
        "QDnsHostAddressRecord",
        "QDnsLookup",
        "QDnsMailExchangeRecord",
        "QDnsServiceRecord",
        "QDnsTextRecord",
        "QHostAddress",
        "QHostInfo",
        "QHstsPolicy",
        "QHttpMultiPart",
        "QHttpPart",
        "QLocalServer",
        "QLocalSocket",
        "QNetworkAccessManager",
        "QNetworkAddressEntry",
        "QNetworkCacheMetaData",
        "QNetworkCookie",
        "QNetworkCookieJar",
        "QNetworkDatagram",
        "QNetworkDiskCache",
        "QNetworkInterface",
        "QNetworkProxy",
        "QNetworkProxyFactory",
        "QNetworkProxyQuery",
        "QNetworkReply",
        "QNetworkRequest",
        "QOcspCertificateStatus",
        "QOcspResponse",
        "QOcspRevocationReason",
        "QPasswordDigestor",
        "QSsl",
        "QSslCertificate",
        "QSslCertificateExtension",
        "QSslCipher",
        "QSslConfiguration",
        "QSslDiffieHellmanParameters",
        "QSslError",
        "QSslKey",
        "QSslPreSharedKeyAuthenticator",
        "QSslSocket",
        "QTcpServer",
        "QTcpSocket",
        "QUdpSocket",
    ],
    "QtOpenGL": [],
    "QtPositioning": [
        "QGeoAddress",
        "QGeoAreaMonitorInfo",
        "QGeoAreaMonitorSource",
        "QGeoCircle",
        "QGeoCoordinate",
        "QGeoLocation",
        "QGeoPath",
        "QGeoPolygon",
        "QGeoPositionInfo",
        "QGeoPositionInfoSource",
        "QGeoRectangle",
        "QGeoSatelliteInfo",
        "QGeoSatelliteInfoSource",
        "QGeoShape",
        "QNmeaPositionInfoSource",
    ],
    "QtPrintSupport": [
        "QAbstractPrintDialog",
        "QPageSetupDialog",
        "QPrintDialog",
        "QPrintEngine",
        "QPrintPreviewDialog",
        "QPrintPreviewWidget",
        "QPrinter",
        "QPrinterInfo",
    ],
    "QtQml": [
        "QJSEngine",
        "QJSValue",
        "QJSValueIterator",
        "QQmlAbstractUrlInterceptor",
        "QQmlApplicationEngine",
        "QQmlComponent",
        "QQmlContext",
        "QQmlEngine",
        "QQmlError",
        "QQmlExpression",
        "QQmlExtensionPlugin",
        "QQmlFileSelector",
        "QQmlImageProviderBase",
        "QQmlIncubationController",
        "QQmlIncubator",
        "QQmlListReference",
        "QQmlNetworkAccessManagerFactory",
        "QQmlParserStatus",
        "QQmlProperty",
        "QQmlPropertyMap",
        "QQmlPropertyValueSource",
        "QQmlScriptString",
        "qmlRegisterType",
    ],
    "QtQuick": [
        "QQuickAsyncImageProvider",
        "QQuickFramebufferObject",
        "QQuickImageProvider",
        "QQuickImageResponse",
        "QQuickItem",
        "QQuickItemGrabResult",
        "QQuickPaintedItem",
        "QQuickRenderControl",
        "QQuickTextDocument",
        "QQuickTextureFactory",
        "QQuickView",
        "QQuickWindow",
        "QSGBasicGeometryNode",
        "QSGClipNode",
        "QSGDynamicTexture",
        "QSGGeometry",
        "QSGGeometryNode",
        "QSGMaterialType",
        "QSGNode",
        "QSGOpacityNode",
        "QSGSimpleRectNode",
        "QSGSimpleTextureNode",
        "QSGTexture",
        "QSGTextureProvider",
        "QSGTransformNode",
    ],
    "QtQuickWidgets": ["QQuickWidget"],
    "QtRemoteObjects": [
        "QAbstractItemModelReplica",
        "QRemoteObjectAbstractPersistedStore",
        "QRemoteObjectDynamicReplica",
        "QRemoteObjectHost",
        "QRemoteObjectHostBase",
        "QRemoteObjectNode",
        "QRemoteObjectRegistry",
        "QRemoteObjectRegistryHost",
        "QRemoteObjectReplica",
    ],
    "QtSensors": [
        "QAccelerometer",
        "QAccelerometerFilter",
        "QAccelerometerReading",
        "QAmbientLightFilter",
        "QAmbientLightReading",
        "QAmbientLightSensor",
        "QAmbientTemperatureFilter",
        "QAmbientTemperatureReading",
        "QAmbientTemperatureSensor",
        "QCompass",
        "QCompassFilter",
        "QCompassReading",
        "QGyroscope",
        "QGyroscopeFilter",
        "QGyroscopeReading",
        "QHumidityFilter",
        "QHumidityReading",
        "QHumiditySensor",
        "QIRProximityFilter",
        "QIRProximityReading",
        "QIRProximitySensor",
        "QLidFilter",
        "QLidReading",
        "QLidSensor",
        "QLightFilter",
        "QLightReading",
        "QLightSensor",
        "QMagnetometer",
        "QMagnetometerFilter",
        "QMagnetometerReading",
        "QOrientationFilter",
        "QOrientationReading",
        "QOrientationSensor",
        "QPressureFilter",
        "QPressureReading",
        "QPressureSensor",
        "QProximityFilter",
        "QProximityReading",
        "QProximitySensor",
        "QRotationFilter",
        "QRotationReading",
        "QRotationSensor",
        "QSensor",
        "QSensorFilter",
        "QSensorReading",
        "QTapFilter",
        "QTapReading",
        "QTapSensor",
        "QTiltFilter",
        "QTiltReading",
        "QTiltSensor",
        "qoutputrange",
    ],
    "QtSql": [
        "QSql",
        "QSqlDatabase",
        "QSqlDriver",
        "QSqlDriverCreatorBase",
        "QSqlError",
        "QSqlField",
        "QSqlIndex",
        "QSqlQuery",
        "QSqlQueryModel",
        "QSqlRecord",
        "QSqlRelation",
        "QSqlRelationalDelegate",
        "QSqlRelationalTableModel",
        "QSqlResult",
        "QSqlTableModel",
    ],
    "QtSvg": ["QSvgGenerator", "QSvgRenderer"],
    "QtTest": ["QTest"],
    "QtWebChannel": ["QWebChannel", "QWebChannelAbstractTransport"],
    "QtWebSockets": [
        "QMaskGenerator",
        "QWebSocket",
        "QWebSocketCorsAuthenticator",
        "QWebSocketProtocol",
        "QWebSocketServer",
    ],
    "QtWidgets": [
        "QAbstractButton",
        "QAbstractGraphicsShapeItem",
        "QAbstractItemDelegate",
        "QAbstractItemView",
        "QAbstractScrollArea",
        "QAbstractSlider",
        "QAbstractSpinBox",
        "QApplication",
        "QBoxLayout",
        "QButtonGroup",
        "QCalendarWidget",
        "QCheckBox",
        "QColorDialog",
        "QColumnView",
        "QComboBox",
        "QCommandLinkButton",
        "QCommonStyle",
        "QCompleter",
        "QDataWidgetMapper",
        "QDateEdit",
        "QDateTimeEdit",
        "QDial",
        "QDialog",
        "QDialogButtonBox",
        "QDockWidget",
        "QDoubleSpinBox",
        "QErrorMessage",
        "QFileDialog",
        "QFileIconProvider",
        "QFocusFrame",
        "QFontComboBox",
        "QFontDialog",
        "QFormLayout",
        "QFrame",
        "QGesture",
        "QGestureEvent",
        "QGestureRecognizer",
        "QGraphicsAnchor",
        "QGraphicsAnchorLayout",
        "QGraphicsBlurEffect",
        "QGraphicsColorizeEffect",
        "QGraphicsDropShadowEffect",
        "QGraphicsEffect",
        "QGraphicsEllipseItem",
        "QGraphicsGridLayout",
        "QGraphicsItem",
        "QGraphicsItemGroup",
        "QGraphicsLayout",
        "QGraphicsLayoutItem",
        "QGraphicsLineItem",
        "QGraphicsLinearLayout",
        "QGraphicsObject",
        "QGraphicsOpacityEffect",
        "QGraphicsPathItem",
        "QGraphicsPixmapItem",
        "QGraphicsPolygonItem",
        "QGraphicsProxyWidget",
        "QGraphicsRectItem",
        "QGraphicsRotation",
        "QGraphicsScale",
        "QGraphicsScene",
        "QGraphicsSceneContextMenuEvent",
        "QGraphicsSceneDragDropEvent",
        "QGraphicsSceneEvent",
        "QGraphicsSceneHelpEvent",
        "QGraphicsSceneHoverEvent",
        "QGraphicsSceneMouseEvent",
        "QGraphicsSceneMoveEvent",
        "QGraphicsSceneResizeEvent",
        "QGraphicsSceneWheelEvent",
        "QGraphicsSimpleTextItem",
        "QGraphicsTextItem",
        "QGraphicsTransform",
        "QGraphicsView",
        "QGraphicsWidget",
        "QGridLayout",
        "QGroupBox",
        "QHBoxLayout",
        "QHeaderView",
        "QInputDialog",
        "QItemDelegate",
        "QItemEditorCreatorBase",
        "QItemEditorFactory",
        "QKeySequenceEdit",
        "QLCDNumber",
        "QLabel",
        "QLayout",
        "QLayoutItem",
        "QLineEdit",
        "QListView",
        "QListWidget",
        "QListWidgetItem",
        "QMainWindow",
        "QMdiArea",
        "QMdiSubWindow",
        "QMenu",
        "QMenuBar",
        "QMessageBox",
        "QPanGesture",
        "QPinchGesture",
        "QPlainTextDocumentLayout",
        "QPlainTextEdit",
        "QProgressBar",
        "QProgressDialog",
        "QProxyStyle",
        "QPushButton",
        "QRadioButton",
        "QRubberBand",
        "QScrollArea",
        "QScrollBar",
        "QScroller",
        "QScrollerProperties",
        "QSizeGrip",
        "QSizePolicy",
        "QSlider",
        "QSpacerItem",
        "QSpinBox",
        "QSplashScreen",
        "QSplitter",
        "QSplitterHandle",
        "QStackedLayout",
        "QStackedWidget",
        "QStatusBar",
        "QStyle",
        "QStyleFactory",
        "QStyleHintReturn",
        "QStyleHintReturnMask",
        "QStyleHintReturnVariant",
        "QStyleOption",
        "QStyleOptionButton",
        "QStyleOptionComboBox",
        "QStyleOptionComplex",
        "QStyleOptionDockWidget",
        "QStyleOptionFocusRect",
        "QStyleOptionFrame",
        "QStyleOptionGraphicsItem",
        "QStyleOptionGroupBox",
        "QStyleOptionHeader",
        "QStyleOptionMenuItem",
        "QStyleOptionProgressBar",
        "QStyleOptionRubberBand",
        "QStyleOptionSizeGrip",
        "QStyleOptionSlider",
        "QStyleOptionSpinBox",
        "QStyleOptionTab",
        "QStyleOptionTabBarBase",
        "QStyleOptionTabWidgetFrame",
        "QStyleOptionTitleBar",
        "QStyleOptionToolBar",
        "QStyleOptionToolBox",
        "QStyleOptionToolButton",
        "QStyleOptionViewItem",
        "QStylePainter",
        "QStyledItemDelegate",
        "QSwipeGesture",
        "QSystemTrayIcon",
        "QTabBar",
        "QTabWidget",
        "QTableView",
        "QTableWidget",
        "QTableWidgetItem",
        "QTableWidgetSelectionRange",
        "QTapAndHoldGesture",
        "QTapGesture",
        "QTextBrowser",
        "QTextEdit",
        "QTimeEdit",
        "QToolBar",
        "QToolBox",
        "QToolButton",
        "QToolTip",
        "QTreeView",
        "QTreeWidget",
        "QTreeWidgetItem",
        "QTreeWidgetItemIterator",
        "QUndoView",
        "QVBoxLayout",
        "QWhatsThis",
        "QWidget",
        "QWidgetAction",
        "QWidgetItem",
        "QWizard",
        "QWizardPage",
    ],
    "QtXml": [
        "QDomAttr",
        "QDomCDATASection",
        "QDomCharacterData",
        "QDomComment",
        "QDomDocument",
        "QDomDocumentFragment",
        "QDomDocumentType",
        "QDomElement",
        "QDomEntity",
        "QDomEntityReference",
        "QDomImplementation",
        "QDomNamedNodeMap",
        "QDomNode",
        "QDomNodeList",
        "QDomNotation",
        "QDomProcessingInstruction",
        "QDomText",
    ],
}

"""The above common members are common between these python and qt bindings.

The "_common_members_sources" list is generated using the
"common_members.json" file created by the membership tox environments.

"""
_common_members_sources = [
    "PyQt5-5.13.2_py-3.7.17",
    "PyQt5-5.15.11_py-3.9.25",
    "PyQt6-6.7.1_py-3.11.14",
    "PySide2-5.13.2_py-3.7.17",
    "PySide2-5.15.2.1_py-3.9.25",
    "PySide6-6.5.3_py-3.11.14",
]

""" Missing members

This mapping describes members that have been deprecated
in one or more bindings and have been left out of the
_common_members mapping.

The member can provide an extra details string to be
included in exceptions and warnings.
"""

_missing_members = {
    "QtGui": {
        "QMatrix": "Deprecated in PyQt5",
    },
}


def _qInstallMessageHandler(handler):
    """Install a message handler that works in all bindings

    Args:
        handler: A function that takes 3 arguments, or None
    """

    def messageOutputHandler(*args):
        # TODO: Can this be removed by dropping Qt4?
        # In Qt4 bindings, message handlers are passed 2 arguments
        # In Qt5 bindings, message handlers are passed 3 arguments
        # The first argument is a QtMsgType
        # The last argument is the message to be printed
        # The Middle argument (if passed) is a QMessageLogContext
        if len(args) == 3:
            msgType, logContext, msg = args
        elif len(args) == 2:
            msgType, msg = args
            logContext = None
        else:
            raise TypeError(
                "handler expected 2 or 3 arguments, got {0}".format(len(args))
            )

        if isinstance(msg, bytes):
            # In python 3, some bindings pass a bytestring, which cannot be
            # used elsewhere. Decoding a python 2 or 3 bytestring object will
            # consistently return a unicode object.
            msg = msg.decode()

        handler(msgType, logContext, msg)

    passObject = messageOutputHandler if handler else handler
    return Qt._QtCore.qInstallMessageHandler(passObject)


def _getcpppointer(object):
    if hasattr(Qt, "_shiboken6"):
        return Qt._shiboken6.getCppPointer(object)[0]
    elif hasattr(Qt, "_shiboken2"):
        return Qt._shiboken2.getCppPointer(object)[0]
    elif hasattr(Qt, "_sip"):
        return Qt._sip.unwrapinstance(object)
    raise AttributeError("'module' has no attribute 'getCppPointer'")


def _wrapinstance(ptr, base=None):
    """Enable implicit cast of pointer to most suitable class

    This behaviour is available in sip per default.

    Based on http://nathanhorne.com/pyqtpyside-wrap-instance

    Usage:
        This mechanism kicks in under these circumstances.
        1. Qt.py is using PySide 6 or 2.
        2. A `base` argument is not provided.

        See :func:`QtCompat.wrapInstance()`

    Arguments:
        ptr (int): Pointer to QObject in memory
        base (QObject, optional): Base class to wrap with. Defaults to QObject,
            which should handle anything.

    """

    assert isinstance(ptr, int), "Argument 'ptr' must be of type <int>"
    assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
        "Argument 'base' must be of type <QObject>"
    )

    if Qt.IsPyQt5 or Qt.IsPyQt6:
        func = Qt._sip.wrapinstance
    elif Qt.IsPySide2:
        func = Qt._shiboken2.wrapInstance
    elif Qt.IsPySide6:
        func = Qt._shiboken6.wrapInstance
    else:
        raise AttributeError("'module' has no attribute 'wrapInstance'")

    if base is None:
        if Qt.IsPyQt5:
            base = Qt.QtCore.QObject
        else:
            q_object = func(int(ptr), Qt.QtCore.QObject)
            meta_object = q_object.metaObject()

            while True:
                class_name = meta_object.className()

                try:
                    base = getattr(Qt.QtWidgets, class_name)
                except AttributeError:
                    try:
                        base = getattr(Qt.QtCore, class_name)
                    except AttributeError:
                        meta_object = meta_object.superClass()
                        continue

                break

    return func(int(ptr), base)


def _isvalid(object):
    """Check if the object is valid to use in Python runtime.

    Usage:
        See :func:`QtCompat.isValid()`

    Arguments:
        object (QObject): QObject to check the validity of.

    """
    if hasattr(Qt, "_shiboken6"):
        return Qt._shiboken6.isValid(object)

    elif hasattr(Qt, "_shiboken2"):
        return Qt._shiboken2.isValid(object)

    elif hasattr(Qt, "_sip"):
        return not Qt._sip.isdeleted(object)

    else:
        raise AttributeError("'module' has no attribute isValid")


def _translate(context, sourceText, *args):
    # TODO: Can this be removed by dropping Qt4?
    # In Qt4 bindings, translate can be passed 2 or 3 arguments
    # In Qt5 bindings, translate can be passed 2 arguments
    # The first argument is disambiguation[str]
    # The last argument is n[int]
    # The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
    try:
        app = Qt.QtCore.QCoreApplication
    except AttributeError as exc:
        raise NotImplementedError(
            "Missing QCoreApplication implementation for {}".format(Qt.__binding__)
        ) from exc

    def get_arg(index):
        try:
            return args[index]
        except IndexError:
            pass

    n = -1
    disambiguation = get_arg(0)
    n_or_encoding = get_arg(1)

    if isinstance(n_or_encoding, int):
        n = n_or_encoding

    sanitized_args = [context, sourceText, disambiguation, n]
    return app.translate(*sanitized_args)


def _loadUi(uifile, baseinstance=None):
    """Dynamically load a user interface from the given `uifile`

    This function calls `uic.loadUi` if using PyQt bindings,
    else it implements a comparable binding for PySide.

    Documentation:
        http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi

    Arguments:
        uifile (str or pathlib.Path): Absolute path to Qt Designer file.
        baseinstance (QWidget): Instantiated QWidget or subclass thereof

    Return:
        baseinstance if `baseinstance` is not `None`. Otherwise
        return the newly created instance of the user interface.

    """
    if hasattr(Qt, "_uic"):
        if not Qt.IsPyQt6:
            return Qt._uic.loadUi(uifile, baseinstance)

        # loadUi in PyQt6 chains all exceptions in their own internal exception
        # type `PyQt6.uic.exceptions.UIFileException`. This code removes the
        # extra wrapping exception and raises the underlying exception that
        # matches those raised by PyQt5, PySide2 and PySide6 exceptions. Any
        # other exceptions will still raise the original PyQt6 specific error.
        from xml.etree import ElementTree

        try:
            return Qt._uic.loadUi(uifile, baseinstance)
        except Qt._uic.exceptions.UIFileException as error:
            context = error.__context__
            # Raise the exceptions that are consistent with the other bindings
            if isinstance(context, (IOError, ElementTree.ParseError)):
                raise context  # noqa: B904
            # Otherwise raise the original PyQt6 specific exception.
            raise

    elif hasattr(Qt, "_QtUiTools"):
        # Implement `PyQt5.uic.loadUi` for PySide(2/6)

        class _UiLoader(Qt._QtUiTools.QUiLoader):
            """Create the user interface in a base instance.

            Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
            create a new instance of the top-level widget, but creates the user
            interface in an existing instance of the top-level class if needed.

            This mimics the behaviour of `PyQt5.uic.loadUi`.

            """

            def __init__(self, baseinstance):
                super(_UiLoader, self).__init__(baseinstance)
                self.baseinstance = baseinstance
                self.custom_widgets = {}

            def _loadCustomWidgets(self, etree):
                """
                Workaround to pyside-77 bug.

                From QUiLoader doc we should use registerCustomWidget method.
                But this causes a segfault on some platforms.

                Instead we fetch from customwidgets DOM node the python class
                objects. Then we can directly use them in createWidget method.
                """

                def headerToModule(header):
                    """
                    Translate a header file to python module path
                    foo/bar.h => foo.bar
                    """
                    # Remove header extension
                    module = os.path.splitext(header)[0]

                    # Replace os separator by python module separator
                    return module.replace("/", ".").replace("\\", ".")

                custom_widgets = etree.find("customwidgets")

                if custom_widgets is None:
                    return

                for custom_widget in custom_widgets:
                    class_name = custom_widget.find("class").text
                    header = custom_widget.find("header").text

                    try:
                        # try to import the module using the header as defined by the user
                        module = importlib.import_module(header)
                    except ImportError:
                        # try again, but use the customized conversion of a path to a module
                        module = importlib.import_module(headerToModule(header))

                    self.custom_widgets[class_name] = getattr(module, class_name)

            def load(self, uifile, *args, **kwargs):
                from xml.etree.ElementTree import ElementTree

                # Note: Python 3.9 and PySide2 for py3.9 and PyQt/PySide for
                # Python 3.7 requires converting pathlib.Path objects to str
                uifile = str(uifile)

                # For whatever reason, if this doesn't happen then
                # reading an invalid or non-existing .ui file throws
                # a RuntimeError.
                etree = ElementTree()
                etree.parse(uifile)
                self._loadCustomWidgets(etree)

                widget = Qt._QtUiTools.QUiLoader.load(self, uifile, *args, **kwargs)

                # Workaround for PySide 1.0.9, see issue #208
                widget.parentWidget()

                return widget

            def createWidget(self, class_name, parent=None, name=""):
                """Called for each widget defined in ui file

                Overridden here to populate `baseinstance` instead.

                """

                if parent is None and self.baseinstance:
                    # Supposed to create the top-level widget,
                    # return the base instance instead
                    return self.baseinstance

                # For some reason, Line is not in the list of available
                # widgets, but works fine, so we have to special case it here.
                if class_name in self.availableWidgets() + ["Line"]:
                    # Create a new widget for child widgets
                    widget = Qt._QtUiTools.QUiLoader.createWidget(
                        self, class_name, parent, name
                    )
                elif class_name in self.custom_widgets:
                    widget = self.custom_widgets[class_name](parent=parent)
                else:
                    raise Exception("Custom widget '%s' not supported" % class_name)

                if self.baseinstance:
                    # Set an attribute for the new child widget on the base
                    # instance, just like PyQt5.uic.loadUi does.
                    setattr(self.baseinstance, name, widget)

                return widget

        widget = _UiLoader(baseinstance).load(uifile)
        Qt.QtCore.QMetaObject.connectSlotsByName(widget)

        return widget

    else:
        raise NotImplementedError("No implementation available for loadUi")


def _enum_to_value(enum):
    """Returns the int value of the given enum."""
    return enum.value


def _enum_to_int(enum):
    """Returns the int value of the given enum."""
    return int(enum)


def _convert_font_weights(weight, in_qt, out_qt="enum"):
    """Helper function to convert between legacy Qt and OpenType font weights.

    Converted to python from the Qt source code for QFont.
    https://code.qt.io/cgit/qt/qtbase.git/tree/src/gui/text/qfont.cpp?h=6.8.3#n146

    Args:
        weight(int): The font weight to convert.
        inverted(bool): `True` converts OpenType to legacy(Qt6->Qt5). `False`
            converts legacy to OpenType(Qt5->Qt6).
    """
    if not hasattr(Qt._QtGui.QFont.Weight, "Thin"):
        # Qt4 and older versions of Qt5 don't support fully qualified enum
        # names and don't define all of the enums.
        # Map of (Qt4, Qt6, Enum) for the various font weights.
        legacy_to_opentype_map = [
            (0, 100, 0),  # Ultralight
            (25, 300, Qt._QtGui.QFont.Light),
            (50, 400, Qt._QtGui.QFont.Normal),
            (63, 600, Qt._QtGui.QFont.DemiBold),
            (75, 700, Qt._QtGui.QFont.Bold),
            (87, 900, Qt._QtGui.QFont.Black),
        ]
    else:
        # Map of (Qt5, Qt6, Enum) for the various font weights.
        legacy_to_opentype_map = [
            (0, 100, Qt._QtGui.QFont.Weight.Thin),
            (12, 200, Qt._QtGui.QFont.Weight.ExtraLight),
            (25, 300, Qt._QtGui.QFont.Weight.Light),
            (50, 400, Qt._QtGui.QFont.Weight.Normal),
            (57, 500, Qt._QtGui.QFont.Weight.Medium),
            (63, 600, Qt._QtGui.QFont.Weight.DemiBold),
            (75, 700, Qt._QtGui.QFont.Weight.Bold),
            (81, 800, Qt._QtGui.QFont.Weight.ExtraBold),
            (87, 900, Qt._QtGui.QFont.Weight.Black),
        ]
    # Convert the Qt version to the correct column index in the map
    qt_version_map = {4: 0, 5: 0, 6: 1, "enum": 2}
    in_qt = qt_version_map[in_qt]
    out_qt = qt_version_map[out_qt]

    closest_dist = sys.maxsize
    result = None

    for mapping in legacy_to_opentype_map:
        weight_old = mapping[in_qt]
        weight_new = mapping[out_qt]
        dist = abs(weight_old - weight)

        if dist < closest_dist:
            result = weight_new
            closest_dist = dist
        else:
            break

    return result


def _qfont_from_qt6(descrip):
    """Convert font strings generated in Qt6 to Qt4 and 5 compliant strings.

    Qt6: "Courier New,8.25,-1,5,400,0,0,0,0,0,0,0,0,0,0,1"
    Qt5: "Courier New,8.25,-1,5,50,0,0,0,0,0"

    A Font string is a comma separated list of 9-11 items for Qt4,5 and 16-17
    items for Qt 6. Here is a breakdown of each column's data.
    # Qt4,5 and 6
    - Font family
    - Point size
    - Pixel size
    - Style hint
    - Font weight (See _convert_font_weights for how weight is valued.)
    - Font style
    - Underline
    - Strike out
    - Fixed pitch
    - Always 0
    # Qt6 only
    - Capitalization
    - Letter spacing
    - Word spacing
    - Stretch
    - Style strategy
    # Qt4,5 and 6. Optional and always last if specified.
    - Font style (omitted when unavailable)
    """

    # Convert Qt6 strings into Qt5 formats.
    parts = descrip.split(",")
    if len(parts) <= 11:
        # Qt5 style strings have 10 or 11 parts. We don't need to process
        # strings with fewer parts.
        return descrip

    style = parts[-1] if len(parts) == 17 else None

    # Convert from the Open Type to legacy font weight.
    weight = int(parts[4])
    weight = _convert_font_weights(weight, 6, 5)
    parts[4] = str(weight)

    ret = parts[:10]
    if style is not None:
        ret.append(style)

    return ",".join(ret)


def _fromStringQt5(func):
    # Decorator for Qt5 to handle converting a Qt6 QFont string to Qt5.
    def wrapper(self, descrip):
        descrip = _qfont_from_qt6(descrip)
        return func(self, descrip)

    wrapper.__doc__ = func.__doc__
    wrapper.__name__ = func.__name__

    return wrapper


"""Misplaced members

These members from the original submodule are misplaced relative PySide6

NOTE: For bindings where a member is not replaced, they still
      need to be added such that they are added to Qt.py

NOTE: The members should be sorted alphabetically for ease of maintenance.

Example of possible ways to specify misplaced members:

{
    "binding": {
        # A string specifying the destination to store the src on
        "src_module.src_class": "dest_module.dest_class",
        # A 2 item list specifying a destination to store a custom function
        # instead of src
        "src_module.src_class": ["dest_module.dest_class", _function],
        # If the first item in a list is True, the list contains multiple
        # misplaced members. Each following item can be any of the above defs.
        "src_module.src_class": [
            True, "dest_module.dest_class", "other_dest_module.dest_class", ...
        ],
    }
}

The __extras__ key contains any modules that need to be imported to handle
misplaced members. They are not _common_members but need treated the same way.

"""
_misplaced_members = {
    "PySide6": {
        "__extras__": ["QtSvgWidgets", "QtUiTools"],
        "QtCore.Property": "QtCore.Property",
        "QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
        "QtCore.QCoreApplication.translate": ["QtCompat.translate", _translate],
        "QtCore.qInstallMessageHandler": [
            "QtCompat.qInstallMessageHandler",
            _qInstallMessageHandler,
        ],
        "QtCore.QItemSelection": "QtCore.QItemSelection",
        "QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
        "QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
        "QtCore.QRegularExpression": "QtCore.QRegExp",
        "QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
        "QtCore.QStringListModel": "QtCore.QStringListModel",
        "QtCore.Signal": "QtCore.Signal",
        "QtCore.Slot": "QtCore.Slot",
        # Preserve backwards compatibility for the old location of QAction
        "QtGui.QAction": [True, "QtGui.QAction", "QtWidgets.QAction"],
        "QtGui.QActionGroup": "QtWidgets.QActionGroup",
        "QtWidgets.QFileSystemModel": "QtWidgets.QFileSystemModel",
        "QtGui.QRegularExpressionValidator": "QtGui.QRegExpValidator",
        "QtGui.QShortcut": "QtWidgets.QShortcut",
        "QtGui.QUndoCommand": "QtWidgets.QUndoCommand",
        "QtGui.QUndoGroup": "QtWidgets.QUndoGroup",
        "QtGui.QUndoStack": "QtWidgets.QUndoStack",
        "QtOpenGL.QAbstractOpenGLFunctions": "QtOpenGL.QAbstractOpenGLFunctions",
        "QtOpenGL.QOpenGLBuffer": "QtOpenGL.QOpenGLBuffer",
        "QtOpenGL.QOpenGLFunctions_2_0": "QtOpenGL.QOpenGLFunctions_2_0",
        "QtOpenGL.QOpenGLFunctions_2_1": "QtOpenGL.QOpenGLFunctions_2_1",
        "QtOpenGL.QOpenGLFunctions_4_1_Core": "QtOpenGL.QOpenGLFunctions_4_1_Core",
        "QtStateMachine.QState": "QtCore.QState",
        "QtStateMachine.QStateMachine": "QtCore.QStateMachine",
        "QtSvgWidgets.QGraphicsSvgItem": "QtSvg.QGraphicsSvgItem",
        "QtSvgWidgets.QSvgWidget": "QtSvg.QSvgWidget",
        "QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
        "QtWidgets.qApp": "QtWidgets.QApplication.instance()",
        "QtWidgets.QApplication.translate": ["QtCompat.translate", _translate],
        "QtWidgets.QStyleOptionViewItem": "QtCompat.QStyleOptionViewItemV4",
        "shiboken6.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
        "shiboken6.isValid": ["QtCompat.isValid", _isvalid],
        "shiboken6.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
    },
    "PyQt6": {
        "__extras__": ["QtSvgWidgets", "sip", "uic"],
        "QtCore.pyqtProperty": "QtCore.Property",
        "QtCore.pyqtSignal": "QtCore.Signal",
        "QtCore.pyqtSlot": "QtCore.Slot",
        "QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
        "QtCore.QCoreApplication.translate": ["QtCompat.translate", _translate],
        "QtCore.qInstallMessageHandler": [
            "QtCompat.qInstallMessageHandler",
            _qInstallMessageHandler,
        ],
        "QtCore.QItemSelection": "QtCore.QItemSelection",
        "QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
        "QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
        "QtCore.QRegularExpression": "QtCore.QRegExp",
        "QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
        "QtCore.QStringListModel": "QtCore.QStringListModel",
        "QtGui.QAction": [True, "QtGui.QAction", "QtWidgets.QAction"],
        "QtGui.QActionGroup": "QtWidgets.QActionGroup",
        "QtGui.QFileSystemModel": "QtWidgets.QFileSystemModel",
        "QtGui.QRegularExpressionValidator": "QtGui.QRegExpValidator",
        "QtGui.QShortcut": "QtWidgets.QShortcut",
        "QtGui.QUndoCommand": "QtWidgets.QUndoCommand",
        "QtGui.QUndoGroup": "QtWidgets.QUndoGroup",
        "QtGui.QUndoStack": "QtWidgets.QUndoStack",
        "QtOpenGL.QAbstractOpenGLFunctions": "QtOpenGL.QAbstractOpenGLFunctions",
        "QtOpenGL.QOpenGLBuffer": "QtOpenGL.QOpenGLBuffer",
        "QtOpenGL.QOpenGLFunctions_2_0": "QtOpenGL.QOpenGLFunctions_2_0",
        "QtOpenGL.QOpenGLFunctions_2_1": "QtOpenGL.QOpenGLFunctions_2_1",
        "QtOpenGL.QOpenGLFunctions_4_1_Core": "QtOpenGL.QOpenGLFunctions_4_1_Core",
        "QtStateMachine.QState": "QtCore.QState",
        "QtStateMachine.QStateMachine": "QtCore.QStateMachine",
        "QtSvgWidgets.QGraphicsSvgItem": "QtSvg.QGraphicsSvgItem",
        "QtSvgWidgets.QSvgWidget": "QtSvg.QSvgWidget",
        "QtWidgets.qApp": "QtWidgets.QApplication.instance()",
        "QtWidgets.QApplication.translate": ["QtCompat.translate", _translate],
        "QtWidgets.QStyleOptionViewItem": "QtCompat.QStyleOptionViewItemV4",
        "sip.isdeleted": ["QtCompat.isValid", _isvalid],
        "sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
        "sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
        "uic.loadUi": ["QtCompat.loadUi", _loadUi],
    },
    "PySide2": {
        "__extras__": ["QtOpenGLFunctions", "QtUiTools"],
        "QtCore.Property": "QtCore.Property",
        "QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
        "QtCore.QCoreApplication.translate": ["QtCompat.translate", _translate],
        "QtCore.qInstallMessageHandler": [
            "QtCompat.qInstallMessageHandler",
            _qInstallMessageHandler,
        ],
        "QtCore.QItemSelection": "QtCore.QItemSelection",
        "QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
        "QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
        "QtCore.QRegExp": "QtCore.QRegExp",
        "QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
        "QtCore.QStringListModel": "QtCore.QStringListModel",
        "QtCore.Signal": "QtCore.Signal",
        "QtCore.Slot": "QtCore.Slot",
        "QtGui.QAbstractOpenGLFunctions": "QtOpenGL.QAbstractOpenGLFunctions",
        "QtWidgets.QFileSystemModel": "QtWidgets.QFileSystemModel",
        "QtGui.QOpenGLBuffer": "QtOpenGL.QOpenGLBuffer",
        "QtGui.QRegExpValidator": "QtGui.QRegExpValidator",
        # Older versions of PySide2 still left this in QtGui, this accounts for those too
        "QtGui.QStringListModel": "QtCore.QStringListModel",
        "QtOpenGLFunctions.QOpenGLFunctions_2_0": "QtOpenGL.QOpenGLFunctions_2_0",
        "QtOpenGLFunctions.QOpenGLFunctions_2_1": "QtOpenGL.QOpenGLFunctions_2_1",
        "QtOpenGLFunctions.QOpenGLFunctions_4_1_Core": "QtOpenGL.QOpenGLFunctions_4_1_Core",
        "QtSvg.QGraphicsSvgItem": "QtSvg.QGraphicsSvgItem",
        "QtSvg.QSvgWidget": "QtSvg.QSvgWidget",
        "QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
        "QtWidgets.QAction": [True, "QtWidgets.QAction", "QtGui.QAction"],
        "QtWidgets.QActionGroup": "QtWidgets.QActionGroup",
        "QtWidgets.qApp": "QtWidgets.QApplication.instance()",
        "QtWidgets.QApplication.translate": ["QtCompat.translate", _translate],
        "QtWidgets.QShortcut": "QtWidgets.QShortcut",
        "QtWidgets.QStyleOptionViewItem": "QtCompat.QStyleOptionViewItemV4",
        "QtWidgets.QUndoCommand": "QtWidgets.QUndoCommand",
        "QtWidgets.QUndoGroup": "QtWidgets.QUndoGroup",
        "QtWidgets.QUndoStack": "QtWidgets.QUndoStack",
        "shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
        "shiboken2.isValid": ["QtCompat.isValid", _isvalid],
        "shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
    },
    "PyQt5": {
        "__extras__": [
            "_QOpenGLFunctions_2_0",
            "_QOpenGLFunctions_2_1",
            "_QOpenGLFunctions_4_1_Core",
            "sip",
            "uic",
        ],
        "_QOpenGLFunctions_2_0.QOpenGLFunctions_2_0": "QtOpenGL.QOpenGLFunctions_2_0",
        "_QOpenGLFunctions_2_1.QOpenGLFunctions_2_1": "QtOpenGL.QOpenGLFunctions_2_1",
        "_QOpenGLFunctions_4_1_Core.QOpenGLFunctions_4_1_Core": "QtOpenGL.QOpenGLFunctions_4_1_Core",
        "QtCore.pyqtProperty": "QtCore.Property",
        "QtCore.pyqtSignal": "QtCore.Signal",
        "QtCore.pyqtSlot": "QtCore.Slot",
        "QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
        "QtCore.QCoreApplication.translate": ["QtCompat.translate", _translate],
        "QtCore.qInstallMessageHandler": [
            "QtCompat.qInstallMessageHandler",
            _qInstallMessageHandler,
        ],
        "QtCore.QItemSelection": "QtCore.QItemSelection",
        "QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
        "QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
        "QtCore.QRegExp": "QtCore.QRegExp",
        "QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
        "QtCore.QStringListModel": "QtCore.QStringListModel",
        "QtGui.QAbstractOpenGLFunctions": "QtOpenGL.QAbstractOpenGLFunctions",
        "QtWidgets.QFileSystemModel": "QtWidgets.QFileSystemModel",
        "QtGui.QOpenGLBuffer": "QtOpenGL.QOpenGLBuffer",
        "QtGui.QRegExpValidator": "QtGui.QRegExpValidator",
        "QtSvg.QGraphicsSvgItem": "QtSvg.QGraphicsSvgItem",
        "QtSvg.QSvgWidget": "QtSvg.QSvgWidget",
        "QtWidgets.QAction": [True, "QtWidgets.QAction", "QtGui.QAction"],
        "QtWidgets.QActionGroup": "QtWidgets.QActionGroup",
        "QtWidgets.qApp": "QtWidgets.QApplication.instance()",
        "QtWidgets.QApplication.translate": ["QtCompat.translate", _translate],
        "QtWidgets.QShortcut": "QtWidgets.QShortcut",
        "QtWidgets.QStyleOptionViewItem": "QtCompat.QStyleOptionViewItemV4",
        "QtWidgets.QUndoCommand": "QtWidgets.QUndoCommand",
        "QtWidgets.QUndoGroup": "QtWidgets.QUndoGroup",
        "QtWidgets.QUndoStack": "QtWidgets.QUndoStack",
        "sip.isdeleted": ["QtCompat.isValid", _isvalid],
        "sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
        "sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
        "uic.loadUi": ["QtCompat.loadUi", _loadUi],
    },
}

""" Compatibility Members

This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.

{
    "binding": {
        "classname": {
            "targetname": "binding_namespace",
        }
    }
}
"""
_compatibility_members = {
    "PySide6": {
        "QApplication": {
            "exec_": "QtWidgets.QApplication.exec",
        },
        "QCoreApplication": {
            "exec_": "QtCore.QCoreApplication.exec",
        },
        "QWidget": {
            "grab": "QtWidgets.QWidget.grab",
        },
        "QHeaderView": {
            "sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
            "setSectionsClickable": "QtWidgets.QHeaderView.setSectionsClickable",
            "sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
            "setSectionResizeMode": "QtWidgets.QHeaderView.setSectionResizeMode",
            "sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
            "setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
        },
        "QFileDialog": {
            "getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
            "getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
            "getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
        },
        "QFont": {
            "fromString": "QtGui.QFont.fromString",
            "setWeight": "QtGui.QFont.setWeight",
        },
        "QMouseEvent": {
            "globalPosition": "QtGui.QMouseEvent.globalPosition",
            "position": "QtGui.QMouseEvent.position",
            "scenePosition": "QtGui.QMouseEvent.scenePosition",
        },
        "Qt": {
            "MidButton": "QtCore.Qt.MiddleButton",
        },
    },
    "PyQt6": {
        "QApplication": {
            "exec_": "QtWidgets.QApplication.exec",
        },
        "QCoreApplication": {
            "exec_": "QtCore.QCoreApplication.exec",
        },
        "QWidget": {
            "grab": "QtWidgets.QWidget.grab",
        },
        "QHeaderView": {
            "sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
            "setSectionsClickable": "QtWidgets.QHeaderView.setSectionsClickable",
            "sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
            "setSectionResizeMode": "QtWidgets.QHeaderView.setSectionResizeMode",
            "sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
            "setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
        },
        "QFileDialog": {
            "getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
            "getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
            "getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
        },
        "QFont": {
            "fromString": "QtGui.QFont.fromString",
            "setWeight": "QtGui.QFont.setWeight",
        },
        "QMouseEvent": {
            "globalPosition": "QtGui.QMouseEvent.globalPosition",
            "position": "QtGui.QMouseEvent.position",
            "scenePosition": "QtGui.QMouseEvent.scenePosition",
        },
        "Qt": {
            "MidButton": "QtCore.Qt.MouseButton.MiddleButton",
            "WindowMinMaxButtonsHint": "QtCore.Qt.WindowType.WindowMinMaxButtonsHint",
        },
    },
    "PySide2": {
        "QApplication": {
            "exec_": "QtWidgets.QApplication.exec_",
        },
        "QCoreApplication": {
            "exec_": "QtCore.QCoreApplication.exec_",
        },
        "QWidget": {
            "grab": "QtWidgets.QWidget.grab",
        },
        "QHeaderView": {
            "sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
            "setSectionsClickable": "QtWidgets.QHeaderView.setSectionsClickable",
            "sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
            "setSectionResizeMode": "QtWidgets.QHeaderView.setSectionResizeMode",
            "sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
            "setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
        },
        "QFileDialog": {
            "getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
            "getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
            "getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
        },
        "QFont": {
            "fromString": "QtGui.QFont.fromString",
            "setWeight": "QtGui.QFont.setWeight",
        },
        "QMouseEvent": {
            "globalPosition": "QtGui.QMouseEvent.screenPos",
            "position": "QtGui.QMouseEvent.localPos",
            "scenePosition": "QtGui.QMouseEvent.windowPos",
        },
        "Qt": {
            "MidButton": "QtCore.Qt.MiddleButton",
        },
    },
    "PyQt5": {
        "QApplication": {
            "exec_": "QtWidgets.QApplication.exec_",
        },
        "QCoreApplication": {
            "exec_": "QtCore.QCoreApplication.exec_",
        },
        "QWidget": {
            "grab": "QtWidgets.QWidget.grab",
        },
        "QHeaderView": {
            "sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
            "setSectionsClickable": "QtWidgets.QHeaderView.setSectionsClickable",
            "sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
            "setSectionResizeMode": "QtWidgets.QHeaderView.setSectionResizeMode",
            "sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
            "setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
        },
        "QFileDialog": {
            "getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
            "getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
            "getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
        },
        "QFont": {
            "fromString": "QtGui.QFont.fromString",
            "setWeight": "QtGui.QFont.setWeight",
        },
        "QMouseEvent": {
            "globalPosition": "QtGui.QMouseEvent.screenPos",
            "position": "QtGui.QMouseEvent.localPos",
            "scenePosition": "QtGui.QMouseEvent.windowPos",
        },
        "Qt": {
            "MidButton": "QtCore.Qt.MiddleButton",
        },
    },
}


def _apply_site_config():
    try:
        import QtSiteConfig
    except ImportError:
        # If no QtSiteConfig module found, no modifications
        # to _common_members are needed.
        pass
    else:
        # Provide the ability to modify the dicts used to build Qt.py
        if hasattr(QtSiteConfig, "update_members"):
            QtSiteConfig.update_members(_common_members)

        if hasattr(QtSiteConfig, "update_misplaced_members"):
            QtSiteConfig.update_misplaced_members(members=_misplaced_members)

        if hasattr(QtSiteConfig, "update_compatibility_members"):
            QtSiteConfig.update_compatibility_members(members=_compatibility_members)


def _new_module(name):
    return types.ModuleType(__name__ + "." + name)


def _import_sub_module(module, name):
    """import_sub_module will mimic the function of importlib.import_module"""
    module = __import__(module.__name__ + "." + name)
    for level in name.split("."):
        module = getattr(module, level)
    return module


def _setup(module, extras):
    """Install common submodules"""

    Qt.__binding__ = module.__name__

    def _warn_import_error(exc, module):
        msg = str(exc)
        if "No module named" in msg:
            return
        _warn("ImportError(%s): %s" % (module, msg))

    # Process the __extras__ modules as if they were common
    _extras = _misplaced_members.get(Qt.__binding__, {})
    _extras = _extras.get("__extras__", [])
    extras = extras + _extras

    for name in list(_common_members) + extras:
        try:
            submodule = _import_sub_module(module, name)
        except ImportError as e:
            try:
                # For extra modules like sip and shiboken that may not be
                # children of the binding.
                submodule = __import__(name)
            except ImportError as e2:
                _warn_import_error(e, name)
                _warn_import_error(e2, name)
                continue

        setattr(Qt, "_" + name, submodule)

        if name not in extras:
            # Store reference to original binding,
            # but don't store speciality modules
            # such as uic or QtUiTools
            setattr(Qt, name, _new_module(name))


def _reassign_misplaced_members(binding):
    """Apply misplaced members from `binding` to Qt.py

    Arguments:
        binding (str): The Qt binding ("PySide6", "PyQt6")

    """

    for src, dsts in _misplaced_members[binding].items():
        if src == "__extras__":
            # Don't process this key here.
            continue
        # Normalize dsts to a list of potentially multiple misplaced members
        if isinstance(dsts, str):
            # A single string is treated as a single item lists
            dsts = [dsts]
        elif isinstance(dsts, (list, tuple)) and dsts:
            if dsts[0] is True:
                # This is a multi-destination list, remove the tag and process
                # each item in the list. The items can be str or lists
                dsts = dsts[1:]
            else:
                # This is a single item list, process it as a single item
                dsts = [dsts]

        # process each misplaced member defined for this source
        for dst in dsts:
            dst_value = None

            src_parts = src.split(".")
            src_module = src_parts[0]
            src_member = None
            if len(src_parts) > 1:
                src_member = src_parts[1:]

            if isinstance(dst, (list, tuple)):
                dst, dst_value = dst

            dst_parts = dst.split(".")
            dst_module = dst_parts[0]
            dst_member = None
            if len(dst_parts) > 1:
                dst_member = dst_parts[1]

            # Get the member we want to store in the namespace.
            if not dst_value:
                try:
                    _part = getattr(Qt, "_" + src_module)
                    while src_member:
                        member = src_member.pop(0)
                        _part = getattr(_part, member)
                    dst_value = _part
                except AttributeError:
                    # If the member we want to store in the namespace does not
                    # exist, there is no need to continue. This can happen if a
                    # request was made to rename a member that didn't exist,
                    # for example if QtWidgets isn't available on the target
                    # platform.
                    _log("Misplaced member has no source: {0}".format(src))
                    continue

            try:
                src_object = getattr(Qt, dst_module)
            except AttributeError:
                if dst_module not in _common_members:
                    # Only create the Qt parent module if its listed in
                    # _common_members. Without this check, if you remove QtCore
                    # from _common_members, the default _misplaced_members will
                    # add Qt.QtCore so it can add Signal, Slot, etc.
                    msg = 'Not creating missing member module "{m}" for "{c}"'
                    _log(msg.format(m=dst_module, c=dst_member))
                    continue
                # If the dst is valid but the Qt parent module does not exist
                # then go ahead and create a new module to contain the member.
                setattr(Qt, dst_module, _new_module(dst_module))
                src_object = getattr(Qt, dst_module)
                # Enable direct import of the new module
                sys.modules[__name__ + "." + dst_module] = src_object

            if not dst_value:
                dst_value = getattr(Qt, "_" + src_module)
                if src_member:
                    dst_value = getattr(dst_value, src_member)

            setattr(src_object, dst_member or dst_module, dst_value)


def _build_compatibility_members(binding, decorators=None):
    """Apply `binding` to QtCompat

    Arguments:
        binding (str): Top level binding in _compatibility_members.
        decorators (dict, optional): Provides the ability to decorate the
            original Qt methods when needed by a binding. This can be used
            to change the returned value to a standard value. The key should
            be the classname, the value is a dict where the keys are the
            target method names, and the values are the decorator functions.

    """

    decorators = decorators or {}

    # Allow optional site-level customization of the compatibility members.
    # This method does not need to be implemented in QtSiteConfig.
    try:
        import QtSiteConfig
    except ImportError:
        pass
    else:
        if hasattr(QtSiteConfig, "update_compatibility_decorators"):
            QtSiteConfig.update_compatibility_decorators(binding, decorators)

    _QtCompat = type("QtCompat", (object,), {})

    for classname, bindings in _compatibility_members[binding].items():
        attrs = {}
        for target, binding in bindings.items():
            namespaces = binding.split(".")
            try:
                src_object = getattr(Qt, "_" + namespaces[0])
            except AttributeError as e:
                _log("QtCompat: AttributeError: %s" % e)
                # Skip reassignment of non-existing members.
                # This can happen if a request was made to
                # rename a member that didn't exist, for example
                # if QtWidgets isn't available on the target platform.
                continue

            # Walk down any remaining namespace getting the object assuming
            # that if the first namespace exists the rest will exist.
            for namespace in namespaces[1:]:
                src_object = getattr(src_object, namespace)

            # decorate the Qt method if a decorator was provided.
            if target in decorators.get(classname, []):
                # staticmethod must be called on the decorated method to
                # prevent a TypeError being raised when the decorated method
                # is called.
                src_object = staticmethod(decorators[classname][target](src_object))

            attrs[target] = src_object

        # Create the QtCompat class and install it into the namespace
        compat_class = type(classname, (_QtCompat,), attrs)
        setattr(Qt.QtCompat, classname, compat_class)


def _pyside6():
    """Initialise PySide6

    These functions serve to test the existence of a binding
    along with set it up in such a way that it aligns with
    the final step; adding members from the original binding
    to Qt.py

    """

    import PySide6 as module  # noqa: N813

    extras = []
    try:
        import shiboken6

        extras.append("shiboken6")
    except ImportError as e:
        print("ImportError: %s" % e)

    _setup(module, extras)
    Qt.__binding_version__ = module.__version__
    Qt.QtCompat.enumValue = _enum_to_value

    if hasattr(Qt, "_shiboken6"):
        Qt.QtCompat.wrapInstance = _wrapinstance
        Qt.QtCompat.getCppPointer = _getcpppointer
        Qt.QtCompat.delete = shiboken6.delete

    if hasattr(Qt, "_QtUiTools"):
        Qt.QtCompat.loadUi = _loadUi

    if hasattr(Qt, "_QtCore"):
        Qt.__qt_version__ = Qt._QtCore.qVersion()
        Qt.QtCompat.dataChanged = lambda self, topleft, bottomright, roles=None: (
            self.dataChanged.emit(topleft, bottomright, roles or [])
        )

    if hasattr(Qt, "_QtWidgets"):
        Qt.QtCompat.setSectionResizeMode = (
            Qt._QtWidgets.QHeaderView.setSectionResizeMode
        )

    def setWeight(func):
        def wrapper(self, weight):
            # PySide6 requires passing Enum data types not int values.
            weight = _convert_font_weights(weight, 6)
            return func(self, weight)

        wrapper.__doc__ = func.__doc__
        wrapper.__name__ = func.__name__

        return wrapper

    decorators = {
        "QFont": {
            "setWeight": setWeight,
        }
    }

    _reassign_misplaced_members("PySide6")
    _build_compatibility_members("PySide6", decorators)


def _pyside2():
    """Initialise PySide2

    These functions serve to test the existence of a binding
    along with set it up in such a way that it aligns with
    the final step; adding members from the original binding
    to Qt.py

    """

    import PySide2 as module  # noqa: N813

    extras = []
    try:
        try:
            # Before merge of PySide and shiboken
            import shiboken2
        except ImportError:
            # After merge of PySide and shiboken, May 2017
            from PySide2 import shiboken2
        extras.append("shiboken2")
    except ImportError:
        pass

    _setup(module, extras)
    Qt.__binding_version__ = module.__version__
    Qt.QtCompat.enumValue = _enum_to_int

    if hasattr(Qt, "_shiboken2"):
        Qt.QtCompat.wrapInstance = _wrapinstance
        Qt.QtCompat.getCppPointer = _getcpppointer
        Qt.QtCompat.delete = shiboken2.delete

    if hasattr(Qt, "_QtUiTools"):
        Qt.QtCompat.loadUi = _loadUi

    if hasattr(Qt, "_QtCore"):
        Qt.__qt_version__ = Qt._QtCore.qVersion()
        Qt.QtCompat.dataChanged = lambda self, topleft, bottomright, roles=None: (
            self.dataChanged.emit(topleft, bottomright, roles or [])
        )

    if hasattr(Qt, "_QtWidgets"):
        Qt.QtCompat.setSectionResizeMode = (
            Qt._QtWidgets.QHeaderView.setSectionResizeMode
        )

    decorators = {
        "QFont": {
            "fromString": _fromStringQt5,
        },
    }

    _reassign_misplaced_members("PySide2")
    _build_compatibility_members("PySide2", decorators)


def _pyqt6():
    """Initialise PyQt6"""

    import PyQt6 as module  # noqa: N813
    from PyQt6 import sip

    Qt.QtCompat.enumValue = _enum_to_value

    _setup(module, [])
    if hasattr(Qt, "_sip"):
        Qt.QtCompat.wrapInstance = _wrapinstance
        Qt.QtCompat.getCppPointer = _getcpppointer
        Qt.QtCompat.delete = sip.delete

    if hasattr(Qt, "_uic"):
        Qt.QtCompat.loadUi = _loadUi

    if hasattr(Qt, "_QtCore"):
        Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
        Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
        Qt.QtCompat.dataChanged = lambda self, topleft, bottomright, roles=None: (
            self.dataChanged.emit(topleft, bottomright, roles or [])
        )

    if hasattr(Qt, "_QtWidgets"):
        Qt.QtCompat.setSectionResizeMode = (
            Qt._QtWidgets.QHeaderView.setSectionResizeMode
        )

    _reassign_misplaced_members("PyQt6")
    _build_compatibility_members("PyQt6")


def _pyqt5():
    """Initialise PyQt5"""

    import PyQt5 as module  # noqa: N813
    from PyQt5 import sip

    Qt.QtCompat.enumValue = _enum_to_int

    _setup(module, [])
    if hasattr(Qt, "_sip"):
        Qt.QtCompat.wrapInstance = _wrapinstance
        Qt.QtCompat.getCppPointer = _getcpppointer
        Qt.QtCompat.delete = sip.delete

    if hasattr(Qt, "_uic"):
        Qt.QtCompat.loadUi = _loadUi

    if hasattr(Qt, "_QtCore"):
        Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
        Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
        Qt.QtCompat.dataChanged = lambda self, topleft, bottomright, roles=None: (
            self.dataChanged.emit(topleft, bottomright, roles or [])
        )

    if hasattr(Qt, "_QtWidgets"):
        Qt.QtCompat.setSectionResizeMode = (
            Qt._QtWidgets.QHeaderView.setSectionResizeMode
        )

    decorators = {
        "QFont": {
            "fromString": _fromStringQt5,
        },
    }

    _reassign_misplaced_members("PyQt5")
    _build_compatibility_members("PyQt5", decorators)


def _none():
    """Internal option (used in installer)"""

    Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})

    Qt.__binding__ = "None"
    Qt.__qt_version__ = "0.0.0"
    Qt.__binding_version__ = "0.0.0"
    Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
    Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None

    for submodule in _common_members.keys():
        setattr(Qt, submodule, Mock())
        setattr(Qt, "_" + submodule, Mock())


def _log(text):
    if QT_VERBOSE:
        print("Qt.py [info]: %s" % text)


def _warn(text):
    try:
        print(f"Qt.py [warning]: {text}", file=sys.stderr)
    except UnicodeDecodeError:
        import locale

        encoding = locale.getpreferredencoding()
        print(f"Qt.py [warning]: {text.decode(encoding)}", file=sys.stderr)


def _convert(lines):
    """Convert compiled .ui file from PySide2 to Qt.py

    Arguments:
        lines (list): Each line of of .ui file

    Usage:
        >> with open("myui.py") as f:
        ..   lines = _convert(f.readlines())

    """

    def parse(line):
        line = line.replace("from PySide2", "from Qt")
        line = line.replace("QtWidgets.QApplication.translate", "QtCompat.translate")
        line = line.replace("QCoreApplication.translate", "QtCompat.translate")
        if "QtCore.SIGNAL" in line:
            raise NotImplementedError(
                "QtCore.SIGNAL is missing from PyQt5 "
                "and so Qt.py does not support it: you "
                "should avoid defining signals inside "
                "your ui files."
            )
        return line

    parsed = [parse(line) for line in lines]
    qt_compat_imported = any("from Qt import QtCompat" in line for line in parsed)

    if not qt_compat_imported:
        try:
            last_qt_import_line = max(
                i for i, line in enumerate(parsed) if line.startswith("from Qt")
            )
        except ValueError:
            last_qt_import_line = 0
        parsed.insert(last_qt_import_line + 1, "from Qt import QtCompat\n")

    return parsed


def _cli(args):
    """Qt.py command-line interface"""
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--convert", help="Path to compiled Python module, e.g. my_ui.py"
    )
    parser.add_argument(
        "--compile",
        help="Accept raw .ui file and compile with native PySide2 compiler.",
    )
    parser.add_argument(
        "--stdout", help="Write to stdout instead of file", action="store_true"
    )
    parser.add_argument(
        "--stdin", help="Read from stdin instead of file", action="store_true"
    )

    args = parser.parse_args(args)

    if args.stdout:
        raise NotImplementedError("--stdout")

    if args.stdin:
        raise NotImplementedError("--stdin")

    if args.compile:
        raise NotImplementedError("--compile")

    if args.convert:
        sys.stdout.write(
            "#\n"
            "# WARNING: --convert is an ALPHA feature.\n#\n"
            "# See https://github.com/mottosso/Qt.py/pull/132\n"
            "# for details.\n"
            "#\n"
        )

        #
        # ------> Read
        #
        with open(args.convert) as f:
            lines = _convert(f.readlines())

        backup = "%s_backup%s" % os.path.splitext(args.convert)
        sys.stdout.write('Creating "%s"..\n' % backup)
        shutil.copy(args.convert, backup)

        #
        # <------ Write
        #
        with open(args.convert, "w") as f:
            f.writelines(lines)

        sys.stdout.write('Successfully converted "%s"\n' % args.convert)


class MissingMember(object):
    """
    A placeholder type for a missing Qt object not
    included in Qt.py

    Args:
        name (str): The name of the missing type
        details (str): An optional custom error message
    """

    ERR_TMPL = (
        "{} is not a common object across PySide2 "
        "and the other Qt bindings. It is not included "
        "as a common member in the Qt.py layer"
    )

    def __init__(self, name, details=""):
        self.__name = name
        self.__err = self.ERR_TMPL.format(name)

        if details:
            self.__err = "{}: {}".format(self.__err, details)

    def __repr__(self):
        return "<{}: {}>".format(self.__class__.__name__, self.__name)

    def __getattr__(self, name):
        raise NotImplementedError(self.__err)

    def __call__(self, *a, **kw):
        raise NotImplementedError(self.__err)


def _install():
    # Default order (customize order and content via QT_PREFERRED_BINDING)
    default_order = ("PySide6", "PyQt6", "PySide2", "PyQt5")
    preferred_order = None
    if QT_PREFERRED_BINDING_JSON:
        # A per-vendor preferred binding customization was defined
        # This should be a dictionary of the full Qt.py module namespace to
        # apply binding settings to. The "default" key can be used to apply
        # custom bindings to all modules not explicitly defined. If the json
        # data is invalid this will raise a exception.
        # Example:
        #   {"mylibrary.vendor.Qt": ["PySide2"], "default":["PyQt5","PyQt6"]}
        try:
            preferred_bindings = json.loads(QT_PREFERRED_BINDING_JSON)
        except ValueError:
            # Python 2 raises ValueError, Python 3 raises json.JSONDecodeError
            # a subclass of ValueError
            _warn(
                "Failed to parse QT_PREFERRED_BINDING_JSON='%s'"
                % QT_PREFERRED_BINDING_JSON
            )
            _warn("Falling back to default preferred order")
        else:
            preferred_order = preferred_bindings.get(__name__)
            # If no matching binding was used, optionally apply a default.
            if preferred_order is None:
                preferred_order = preferred_bindings.get("default", None)
    if preferred_order is None:
        # If a json preferred binding was not used use, respect the
        # QT_PREFERRED_BINDING environment variable if defined.
        preferred_order = [b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b]

    order = preferred_order or default_order

    available = {
        "PySide6": _pyside6,
        "PyQt6": _pyqt6,
        "PySide2": _pyside2,
        "PyQt5": _pyqt5,
        "None": _none,
    }

    _log("Order: '%s'" % "', '".join(order))

    # Allow site-level customization of the available modules.
    _apply_site_config()

    found_binding = False
    for name in order:
        _log("Trying %s" % name)

        try:
            available[name]()
            found_binding = True
            break

        except ImportError as e:
            _log("ImportError: %s" % e)

        except KeyError:
            _log("ImportError: Preferred binding '%s' not found." % name)

    if not found_binding:
        # If not binding were found, throw this error
        raise ImportError("No Qt binding were found.")

    # Install individual members
    for name, members in _common_members.items():
        try:
            their_submodule = getattr(Qt, "_%s" % name)
        except AttributeError:
            continue

        our_submodule = getattr(Qt, name)

        # Enable import *
        __all__.append(name)

        # Enable direct import of submodule,
        # e.g. import Qt.QtCore
        sys.modules[__name__ + "." + name] = our_submodule

        for member in members:
            # Accept that a submodule may miss certain members.
            try:
                their_member = getattr(their_submodule, member)
            except AttributeError:
                _log("'%s.%s' was missing." % (name, member))
                continue

            setattr(our_submodule, member, their_member)

    # Install missing member placeholders
    for name, members in _missing_members.items():
        our_submodule = getattr(Qt, name)

        for member in members:
            # If the submodule already has this member installed,
            # either by the common members, or the site config,
            # then skip installing this one over it.
            if hasattr(our_submodule, member):
                continue

            placeholder = MissingMember(
                "{}.{}".format(name, member), details=members[member]
            )
            setattr(our_submodule, member, placeholder)

    # Enable direct import of QtCompat
    sys.modules[__name__ + ".QtCompat"] = Qt.QtCompat

    # Backwards compatibility
    if hasattr(Qt.QtCompat, "loadUi"):
        Qt.QtCompat.load_ui = Qt.QtCompat.loadUi


_install()

# Setup Binding Enum states
Qt.IsPySide6 = Qt.__binding__ == "PySide6"
Qt.IsPyQt6 = Qt.__binding__ == "PyQt6"
Qt.IsPySide2 = Qt.__binding__ == "PySide2"
Qt.IsPyQt5 = Qt.__binding__ == "PyQt5"
# Qt4 is deprecated, These are left for compatibility
Qt.IsPySide = False
Qt.IsPyQt4 = False

"""Augment QtCompat

QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.

"""

Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert

# Enable command-line interface
if __name__ == "__main__":
    _cli(sys.argv[1:])


# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the
#    distribution.
#  * Neither the name of the Glue project nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.