diff options
Diffstat (limited to 'src/platformsupport')
217 files changed, 1502 insertions, 37240 deletions
diff --git a/src/platformsupport/CMakeLists.txt b/src/platformsupport/CMakeLists.txt new file mode 100644 index 0000000000..686c6213d2 --- /dev/null +++ b/src/platformsupport/CMakeLists.txt @@ -0,0 +1,11 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: BSD-3-Clause + +add_subdirectory(devicediscovery) +add_subdirectory(fbconvenience) +if(QT_FEATURE_evdev OR QT_FEATURE_integrityhid OR QT_FEATURE_libinput OR QT_FEATURE_tslib OR QT_FEATURE_xkbcommon) + add_subdirectory(input) +endif() +if(QT_FEATURE_kms) + add_subdirectory(kmsconvenience) +endif() diff --git a/src/platformsupport/accessibility/accessibility.pro b/src/platformsupport/accessibility/accessibility.pro deleted file mode 100644 index 1806d75630..0000000000 --- a/src/platformsupport/accessibility/accessibility.pro +++ /dev/null @@ -1,15 +0,0 @@ -TARGET = QtAccessibilitySupport -MODULE = accessibility_support - -QT = core-private gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII - -HEADERS += \ - qaccessiblebridgeutils_p.h - -SOURCES += \ - qaccessiblebridgeutils.cpp - -load(qt_module) diff --git a/src/platformsupport/accessibility/qaccessiblebridgeutils.cpp b/src/platformsupport/accessibility/qaccessiblebridgeutils.cpp deleted file mode 100644 index f280e65c29..0000000000 --- a/src/platformsupport/accessibility/qaccessiblebridgeutils.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#include "qaccessiblebridgeutils_p.h" -#include <QtCore/qmath.h> - -QT_BEGIN_NAMESPACE - -namespace QAccessibleBridgeUtils { - -static bool performAction(QAccessibleInterface *iface, const QString &actionName) -{ - if (QAccessibleActionInterface *actionIface = iface->actionInterface()) { - if (actionIface->actionNames().contains(actionName)) { - actionIface->doAction(actionName); - return true; - } - } - return false; -} - -QStringList effectiveActionNames(QAccessibleInterface *iface) -{ - QStringList actions; - if (QAccessibleActionInterface *actionIface = iface->actionInterface()) - actions = actionIface->actionNames(); - - if (iface->valueInterface()) { - if (!actions.contains(QAccessibleActionInterface::increaseAction())) - actions << QAccessibleActionInterface::increaseAction(); - if (!actions.contains(QAccessibleActionInterface::decreaseAction())) - actions << QAccessibleActionInterface::decreaseAction(); - } - return actions; -} - -bool performEffectiveAction(QAccessibleInterface *iface, const QString &actionName) -{ - if (!iface) - return false; - if (performAction(iface, actionName)) - return true; - if (actionName != QAccessibleActionInterface::increaseAction() - && actionName != QAccessibleActionInterface::decreaseAction()) - return false; - - QAccessibleValueInterface *valueIface = iface->valueInterface(); - if (!valueIface) - return false; - bool success; - const QVariant currentVariant = valueIface->currentValue(); - double stepSize = valueIface->minimumStepSize().toDouble(&success); - if (!success || qFuzzyIsNull(stepSize)) { - const double min = valueIface->minimumValue().toDouble(&success); - if (!success) - return false; - const double max = valueIface->maximumValue().toDouble(&success); - if (!success) - return false; - stepSize = (max - min) / 10; // this is pretty arbitrary, we just need to provide something - const int typ = currentVariant.type(); - if (typ != QMetaType::Float && typ != QMetaType::Double) { - // currentValue is an integer. Round it up to ensure stepping in case it was below 1 - stepSize = qCeil(stepSize); - } - } - const double current = currentVariant.toDouble(&success); - if (!success) - return false; - if (actionName == QAccessibleActionInterface::decreaseAction()) - stepSize = -stepSize; - valueIface->setCurrentValue(current + stepSize); - return true; -} - -} //namespace - -QT_END_NAMESPACE diff --git a/src/platformsupport/accessibility/qaccessiblebridgeutils_p.h b/src/platformsupport/accessibility/qaccessiblebridgeutils_p.h deleted file mode 100644 index cf8e126894..0000000000 --- a/src/platformsupport/accessibility/qaccessiblebridgeutils_p.h +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QACCESSIBLEBRIDGEUTILS_H -#define QACCESSIBLEBRIDGEUTILS_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qtguiglobal_p.h> - -#include <QtCore/qstringlist.h> -#include <QtGui/qaccessible.h> - -QT_REQUIRE_CONFIG(accessibility); - -QT_BEGIN_NAMESPACE - -namespace QAccessibleBridgeUtils { - QStringList effectiveActionNames(QAccessibleInterface *iface); - bool performEffectiveAction(QAccessibleInterface *iface, const QString &actionName); -} - -QT_END_NAMESPACE - -#endif //QACCESSIBLEBRIDGEUTILS_H diff --git a/src/platformsupport/clipboard/clipboard.pro b/src/platformsupport/clipboard/clipboard.pro deleted file mode 100644 index 916f6b0c06..0000000000 --- a/src/platformsupport/clipboard/clipboard.pro +++ /dev/null @@ -1,15 +0,0 @@ -TARGET = QtClipboardSupport -MODULE = clipboard_support - -QT = core-private gui -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII - -HEADERS += qmacmime_p.h -SOURCES += qmacmime.mm - -LIBS += -framework ImageIO -macos: LIBS_PRIVATE += -framework AppKit - -load(qt_module) diff --git a/src/platformsupport/clipboard/qmacmime.mm b/src/platformsupport/clipboard/qmacmime.mm deleted file mode 100644 index 76e9c8712c..0000000000 --- a/src/platformsupport/clipboard/qmacmime.mm +++ /dev/null @@ -1,1045 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <ImageIO/ImageIO.h> - -#include <QtCore/qsystemdetection.h> -#include <QtGui/qimage.h> - -#if defined(Q_OS_OSX) -#import <AppKit/AppKit.h> -#else -#include <MobileCoreServices/MobileCoreServices.h> -#endif - -#if defined(QT_PLATFORM_UIKIT) -#import <UIKit/UIKit.h> -#endif - -#include "qmacmime_p.h" -#include "qguiapplication.h" -#include "private/qcore_mac_p.h" - -QT_BEGIN_NAMESPACE - -typedef QList<QMacInternalPasteboardMime*> MimeList; -Q_GLOBAL_STATIC(MimeList, globalMimeList) -Q_GLOBAL_STATIC(QStringList, globalDraggedTypesList) - -void qt_mac_addToGlobalMimeList(QMacInternalPasteboardMime *macMime) -{ - // globalMimeList is in decreasing priority order. Recently added - // converters take prioity over previously added converters: prepend - // to the list. - globalMimeList()->prepend(macMime); -} - -void qt_mac_removeFromGlobalMimeList(QMacInternalPasteboardMime *macMime) -{ - if (!QGuiApplication::closingDown()) - globalMimeList()->removeAll(macMime); -} - -/*! - \fn void qRegisterDraggedTypes(const QStringList &types) - \relates QMacPasteboardMime - - Registers the given \a types as custom pasteboard types. - - This function should be called to enable the Drag and Drop events - for custom pasteboard types on Cocoa implementations. This is required - in addition to a QMacPasteboardMime subclass implementation. By default - drag and drop is enabled for all standard pasteboard types. - - \sa QMacPasteboardMime -*/ -void qt_mac_registerDraggedTypes(const QStringList &types) -{ - (*globalDraggedTypesList()) += types; -} - -const QStringList& qt_mac_enabledDraggedTypes() -{ - return (*globalDraggedTypesList()); -} - -/***************************************************************************** - QDnD debug facilities - *****************************************************************************/ -//#define DEBUG_MIME_MAPS - -/*! - \class QMacPasteboardMime - \brief The QMacPasteboardMime class converts between a MIME type and a - \l{http://developer.apple.com/macosx/uniformtypeidentifiers.html}{Uniform - Type Identifier (UTI)} format. - \since 4.2 - - \ingroup draganddrop - \inmodule QtWidgets - - Qt's drag and drop and clipboard facilities use the MIME - standard. On X11, this maps trivially to the Xdnd protocol. On - Mac, although some applications use MIME to describe clipboard - contents, it is more common to use Apple's UTI format. - - QMacPasteboardMime's role is to bridge the gap between MIME and UTI; - By subclasses this class, one can extend Qt's drag and drop - and clipboard handling to convert to and from unsupported, or proprietary, UTI formats. - - A subclass of QMacPasteboardMime will automatically be registered, and active, upon instantiation. - - Qt has predefined support for the following UTIs: - \list - \i public.utf8-plain-text - converts to "text/plain" - \i public.utf16-plain-text - converts to "text/plain" - \i public.text - converts to "text/plain" - \i public.html - converts to "text/html" - \i public.url - converts to "text/uri-list" - \i public.file-url - converts to "text/uri-list" - \i public.tiff - converts to "application/x-qt-image" - \i public.vcard - converts to "text/plain" - \i com.apple.traditional-mac-plain-text - converts to "text/plain" - \i com.apple.pict - converts to "application/x-qt-image" - \endlist - - When working with MIME data, Qt will interate through all instances of QMacPasteboardMime to - find an instance that can convert to, or from, a specific MIME type. It will do this by calling - canConvert() on each instance, starting with (and choosing) the last created instance first. - The actual conversions will be done by using convertToMime() and convertFromMime(). - - \note The API uses the term "flavor" in some cases. This is for backwards - compatibility reasons, and should now be understood as UTIs. -*/ - -/*! \enum QMacPasteboardMime::QMacPasteboardMimeType - \internal -*/ - -/*! - Constructs a new conversion object of type \a t, adding it to the - globally accessed list of available convertors. -*/ -QMacInternalPasteboardMime::QMacInternalPasteboardMime(char t) : type(t) -{ - qt_mac_addToGlobalMimeList(this); -} - -/*! - Destroys a conversion object, removing it from the global - list of available convertors. -*/ -QMacInternalPasteboardMime::~QMacInternalPasteboardMime() -{ - qt_mac_removeFromGlobalMimeList(this); -} - -/*! - Returns the item count for the given \a mimeData -*/ -int QMacInternalPasteboardMime::count(QMimeData *mimeData) -{ - Q_UNUSED(mimeData); - return 1; -} - -class QMacPasteboardMimeAny : public QMacInternalPasteboardMime { -private: - -public: - QMacPasteboardMimeAny() : QMacInternalPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL) { - } - ~QMacPasteboardMimeAny() { - } - QString convertorName(); - - QString flavorFor(const QString &mime); - QString mimeFor(QString flav); - bool canConvert(const QString &mime, QString flav); - QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav); - QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav); -}; - -QString QMacPasteboardMimeAny::convertorName() -{ - return QLatin1String("Any-Mime"); -} - -QString QMacPasteboardMimeAny::flavorFor(const QString &mime) -{ - // do not handle the mime type name in the drag pasteboard - if (mime == QLatin1String("application/x-qt-mime-type-name")) - return QString(); - QString ret = QLatin1String("com.trolltech.anymime.") + mime; - return ret.replace(QLatin1Char('/'), QLatin1String("--")); -} - -QString QMacPasteboardMimeAny::mimeFor(QString flav) -{ - const QString any_prefix = QLatin1String("com.trolltech.anymime."); - if (flav.size() > any_prefix.length() && flav.startsWith(any_prefix)) - return flav.mid(any_prefix.length()).replace(QLatin1String("--"), QLatin1String("/")); - return QString(); -} - -bool QMacPasteboardMimeAny::canConvert(const QString &mime, QString flav) -{ - return mimeFor(flav) == mime; -} - -QVariant QMacPasteboardMimeAny::convertToMime(const QString &mime, QList<QByteArray> data, QString) -{ - if (data.count() > 1) - qWarning("QMacPasteboardMimeAny: Cannot handle multiple member data"); - QVariant ret; - if (mime == QLatin1String("text/plain")) - ret = QString::fromUtf8(data.first()); - else - ret = data.first(); - return ret; -} - -QList<QByteArray> QMacPasteboardMimeAny::convertFromMime(const QString &mime, QVariant data, QString) -{ - QList<QByteArray> ret; - if (mime == QLatin1String("text/plain")) - ret.append(data.toString().toUtf8()); - else - ret.append(data.toByteArray()); - return ret; -} - -class QMacPasteboardMimeTypeName : public QMacInternalPasteboardMime { -private: - -public: - QMacPasteboardMimeTypeName() : QMacInternalPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL) { - } - ~QMacPasteboardMimeTypeName() { - } - QString convertorName(); - - QString flavorFor(const QString &mime); - QString mimeFor(QString flav); - bool canConvert(const QString &mime, QString flav); - QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav); - QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav); -}; - -QString QMacPasteboardMimeTypeName::convertorName() -{ - return QLatin1String("Qt-Mime-Type"); -} - -QString QMacPasteboardMimeTypeName::flavorFor(const QString &mime) -{ - if (mime == QLatin1String("application/x-qt-mime-type-name")) - return QLatin1String("com.trolltech.qt.MimeTypeName"); - return QString(); -} - -QString QMacPasteboardMimeTypeName::mimeFor(QString) -{ - return QString(); -} - -bool QMacPasteboardMimeTypeName::canConvert(const QString &, QString) -{ - return false; -} - -QVariant QMacPasteboardMimeTypeName::convertToMime(const QString &, QList<QByteArray>, QString) -{ - QVariant ret; - return ret; -} - -QList<QByteArray> QMacPasteboardMimeTypeName::convertFromMime(const QString &, QVariant, QString) -{ - QList<QByteArray> ret; - ret.append(QString(QLatin1String("x-qt-mime-type-name")).toUtf8()); - return ret; -} - -class QMacPasteboardMimePlainTextFallback : public QMacInternalPasteboardMime { -public: - QMacPasteboardMimePlainTextFallback() : QMacInternalPasteboardMime(MIME_ALL) { } - QString convertorName(); - - QString flavorFor(const QString &mime); - QString mimeFor(QString flav); - bool canConvert(const QString &mime, QString flav); - QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav); - QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav); -}; - -QString QMacPasteboardMimePlainTextFallback::convertorName() -{ - return QLatin1String("PlainText (public.text)"); -} - -QString QMacPasteboardMimePlainTextFallback::flavorFor(const QString &mime) -{ - if (mime == QLatin1String("text/plain")) - return QLatin1String("public.text"); - return QString(); -} - -QString QMacPasteboardMimePlainTextFallback::mimeFor(QString flav) -{ - if (flav == QLatin1String("public.text")) - return QLatin1String("text/plain"); - return QString(); -} - -bool QMacPasteboardMimePlainTextFallback::canConvert(const QString &mime, QString flav) -{ - return mime == mimeFor(flav); -} - -QVariant QMacPasteboardMimePlainTextFallback::convertToMime(const QString &mimetype, QList<QByteArray> data, QString flavor) -{ - if (data.count() > 1) - qWarning("QMacPasteboardMimePlainTextFallback: Cannot handle multiple member data"); - - if (flavor == QLatin1String("public.text")) { - // Note that public.text is documented by Apple to have an undefined encoding. From - // testing it seems that utf8 is normally used, at least by Safari on iOS. - const QByteArray &firstData = data.first(); - return QString(QCFString(CFStringCreateWithBytes(kCFAllocatorDefault, - reinterpret_cast<const UInt8 *>(firstData.constData()), - firstData.size(), kCFStringEncodingUTF8, false))); - } else { - qWarning("QMime::convertToMime: unhandled mimetype: %s", qPrintable(mimetype)); - } - return QVariant(); -} - -QList<QByteArray> QMacPasteboardMimePlainTextFallback::convertFromMime(const QString &, QVariant data, QString flavor) -{ - QList<QByteArray> ret; - QString string = data.toString(); - if (flavor == QLatin1String("public.text")) - ret.append(string.toUtf8()); - return ret; -} - -class QMacPasteboardMimeUnicodeText : public QMacInternalPasteboardMime { -public: - QMacPasteboardMimeUnicodeText() : QMacInternalPasteboardMime(MIME_ALL) { } - QString convertorName(); - - QString flavorFor(const QString &mime); - QString mimeFor(QString flav); - bool canConvert(const QString &mime, QString flav); - QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav); - QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav); -}; - -QString QMacPasteboardMimeUnicodeText::convertorName() -{ - return QLatin1String("UnicodeText"); -} - -QString QMacPasteboardMimeUnicodeText::flavorFor(const QString &mime) -{ - if (mime == QLatin1String("text/plain")) - return QLatin1String("public.utf16-plain-text"); - int i = mime.indexOf(QLatin1String("charset=")); - if (i >= 0) { - QString cs(mime.mid(i+8).toLower()); - i = cs.indexOf(QLatin1Char(';')); - if (i>=0) - cs = cs.left(i); - if (cs == QLatin1String("system")) - return QLatin1String("public.utf8-plain-text"); - else if (cs == QLatin1String("iso-10646-ucs-2") - || cs == QLatin1String("utf16")) - return QLatin1String("public.utf16-plain-text"); - } - return QString(); -} - -QString QMacPasteboardMimeUnicodeText::mimeFor(QString flav) -{ - if (flav == QLatin1String("public.utf16-plain-text") || flav == QLatin1String("public.utf8-plain-text")) - return QLatin1String("text/plain"); - return QString(); -} - -bool QMacPasteboardMimeUnicodeText::canConvert(const QString &mime, QString flav) -{ - return (mime == QLatin1String("text/plain") - && (flav == QLatin1String("public.utf8-plain-text") || (flav == QLatin1String("public.utf16-plain-text")))); -} - -QVariant QMacPasteboardMimeUnicodeText::convertToMime(const QString &mimetype, QList<QByteArray> data, QString flavor) -{ - if (data.count() > 1) - qWarning("QMacPasteboardMimeUnicodeText: Cannot handle multiple member data"); - const QByteArray &firstData = data.first(); - // I can only handle two types (system and unicode) so deal with them that way - QVariant ret; - if (flavor == QLatin1String("public.utf8-plain-text")) { - ret = QString::fromUtf8(firstData); -#if QT_CONFIG(textcodec) - } else if (flavor == QLatin1String("public.utf16-plain-text")) { - ret = QTextCodec::codecForName("UTF-16")->toUnicode(firstData); -#endif - } else { - qWarning("QMime::convertToMime: unhandled mimetype: %s", qPrintable(mimetype)); - } - return ret; -} - -QList<QByteArray> QMacPasteboardMimeUnicodeText::convertFromMime(const QString &, QVariant data, QString flavor) -{ - QList<QByteArray> ret; - QString string = data.toString(); - if (flavor == QLatin1String("public.utf8-plain-text")) - ret.append(string.toUtf8()); -#if QT_CONFIG(textcodec) - else if (flavor == QLatin1String("public.utf16-plain-text")) { - QTextCodec::ConverterState state; -#if defined(Q_OS_MACOS) - // Some applications such as Microsoft Excel, don't deal well with - // a BOM present, so we follow the traditional approach of Qt on - // macOS to not generate public.utf16-plain-text with a BOM. - state.flags = QTextCodec::IgnoreHeader; -#else - // Whereas iOS applications will fail to paste if we do _not_ - // include a BOM in the public.utf16-plain-text content, most - // likely due to converting the data using NSUTF16StringEncoding - // which assumes big-endian byte order if there is no BOM. - state.flags = QTextCodec::DefaultConversion; -#endif - ret.append(QTextCodec::codecForName("UTF-16")->fromUnicode( - string.constData(), string.length(), &state)); - } -#endif - return ret; -} - -class QMacPasteboardMimeHTMLText : public QMacInternalPasteboardMime { -public: - QMacPasteboardMimeHTMLText() : QMacInternalPasteboardMime(MIME_ALL) { } - QString convertorName(); - - QString flavorFor(const QString &mime); - QString mimeFor(QString flav); - bool canConvert(const QString &mime, QString flav); - QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav); - QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav); -}; - -QString QMacPasteboardMimeHTMLText::convertorName() -{ - return QLatin1String("HTML"); -} - -QString QMacPasteboardMimeHTMLText::flavorFor(const QString &mime) -{ - if (mime == QLatin1String("text/html")) - return QLatin1String("public.html"); - return QString(); -} - -QString QMacPasteboardMimeHTMLText::mimeFor(QString flav) -{ - if (flav == QLatin1String("public.html")) - return QLatin1String("text/html"); - return QString(); -} - -bool QMacPasteboardMimeHTMLText::canConvert(const QString &mime, QString flav) -{ - return flavorFor(mime) == flav; -} - -QVariant QMacPasteboardMimeHTMLText::convertToMime(const QString &mimeType, QList<QByteArray> data, QString flavor) -{ - if (!canConvert(mimeType, flavor)) - return QVariant(); - if (data.count() > 1) - qWarning("QMacPasteboardMimeHTMLText: Cannot handle multiple member data"); - return data.first(); -} - -QList<QByteArray> QMacPasteboardMimeHTMLText::convertFromMime(const QString &mime, QVariant data, QString flavor) -{ - QList<QByteArray> ret; - if (!canConvert(mime, flavor)) - return ret; - ret.append(data.toByteArray()); - return ret; -} - -class QMacPasteboardMimeRtfText : public QMacInternalPasteboardMime { -public: - QMacPasteboardMimeRtfText() : QMacInternalPasteboardMime(MIME_ALL) { } - QString convertorName(); - - QString flavorFor(const QString &mime); - QString mimeFor(QString flav); - bool canConvert(const QString &mime, QString flav); - QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav); - QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav); -}; - -QString QMacPasteboardMimeRtfText::convertorName() -{ - return QLatin1String("Rtf"); -} - -QString QMacPasteboardMimeRtfText::flavorFor(const QString &mime) -{ - if (mime == QLatin1String("text/html")) - return QLatin1String("public.rtf"); - return QString(); -} - -QString QMacPasteboardMimeRtfText::mimeFor(QString flav) -{ - if (flav == QLatin1String("public.rtf")) - return QLatin1String("text/html"); - return QString(); -} - -bool QMacPasteboardMimeRtfText::canConvert(const QString &mime, QString flav) -{ - return mime == mimeFor(flav); -} - -QVariant QMacPasteboardMimeRtfText::convertToMime(const QString &mimeType, QList<QByteArray> data, QString flavor) -{ - if (!canConvert(mimeType, flavor)) - return QVariant(); - if (data.count() > 1) - qWarning("QMacPasteboardMimeHTMLText: Cannot handle multiple member data"); - - // Read RTF into to NSAttributedString, then convert the string to HTML - NSAttributedString *string = [[NSAttributedString alloc] initWithData:data.at(0).toNSData() - options:@{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType} - documentAttributes:nil - error:nil]; - - NSError *error; - NSRange range = NSMakeRange(0, [string length]); - NSDictionary *dict = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}; - NSData *htmlData = [string dataFromRange:range documentAttributes:dict error:&error]; - return QByteArray::fromNSData(htmlData); -} - -QList<QByteArray> QMacPasteboardMimeRtfText::convertFromMime(const QString &mime, QVariant data, QString flavor) -{ - QList<QByteArray> ret; - if (!canConvert(mime, flavor)) - return ret; - - NSAttributedString *string = [[NSAttributedString alloc] initWithData:data.toByteArray().toNSData() - options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} - documentAttributes:nil - error:nil]; - - NSError *error; - NSRange range = NSMakeRange(0, [string length]); - NSDictionary *dict = @{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType}; - NSData *rtfData = [string dataFromRange:range documentAttributes:dict error:&error]; - ret << QByteArray::fromNSData(rtfData); - return ret; -} - -class QMacPasteboardMimeFileUri : public QMacInternalPasteboardMime { -public: - QMacPasteboardMimeFileUri() : QMacInternalPasteboardMime(MIME_ALL) { } - QString convertorName(); - - QString flavorFor(const QString &mime); - QString mimeFor(QString flav); - bool canConvert(const QString &mime, QString flav); - QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav); - QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav); - int count(QMimeData *mimeData); -}; - -QString QMacPasteboardMimeFileUri::convertorName() -{ - return QLatin1String("FileURL"); -} - -QString QMacPasteboardMimeFileUri::flavorFor(const QString &mime) -{ - if (mime == QLatin1String("text/uri-list")) - return QLatin1String("public.file-url"); - return QString(); -} - -QString QMacPasteboardMimeFileUri::mimeFor(QString flav) -{ - if (flav == QLatin1String("public.file-url")) - return QLatin1String("text/uri-list"); - return QString(); -} - -bool QMacPasteboardMimeFileUri::canConvert(const QString &mime, QString flav) -{ - return mime == QLatin1String("text/uri-list") && flav == QLatin1String("public.file-url"); -} - -QVariant QMacPasteboardMimeFileUri::convertToMime(const QString &mime, QList<QByteArray> data, QString flav) -{ - if (!canConvert(mime, flav)) - return QVariant(); - QList<QVariant> ret; - for (int i = 0; i < data.size(); ++i) { - const QByteArray &a = data.at(i); - NSString *urlString = [[[NSString alloc] initWithBytesNoCopy:(void *)a.data() length:a.size() - encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease]; - NSURL *nsurl = [NSURL URLWithString:urlString]; - QUrl url; - // OS X 10.10 sends file references instead of file paths - if ([nsurl isFileReferenceURL]) { - url = QUrl::fromNSURL([nsurl filePathURL]); - } else { - url = QUrl::fromNSURL(nsurl); - } - - if (url.host().toLower() == QLatin1String("localhost")) - url.setHost(QString()); - - url.setPath(url.path().normalized(QString::NormalizationForm_C)); - ret.append(url); - } - return QVariant(ret); -} - -QList<QByteArray> QMacPasteboardMimeFileUri::convertFromMime(const QString &mime, QVariant data, QString flav) -{ - QList<QByteArray> ret; - if (!canConvert(mime, flav)) - return ret; - QList<QVariant> urls = data.toList(); - for (int i = 0; i < urls.size(); ++i) { - QUrl url = urls.at(i).toUrl(); - if (url.scheme().isEmpty()) - url.setScheme(QLatin1String("file")); - if (url.scheme() == QLatin1String("file")) { - if (url.host().isEmpty()) - url.setHost(QLatin1String("localhost")); - url.setPath(url.path().normalized(QString::NormalizationForm_D)); - } - ret.append(url.toEncoded()); - } - return ret; -} - -int QMacPasteboardMimeFileUri::count(QMimeData *mimeData) -{ - return mimeData->urls().count(); -} - -class QMacPasteboardMimeUrl : public QMacInternalPasteboardMime { -public: - QMacPasteboardMimeUrl() : QMacInternalPasteboardMime(MIME_ALL) { } - QString convertorName(); - - QString flavorFor(const QString &mime); - QString mimeFor(QString flav); - bool canConvert(const QString &mime, QString flav); - QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav); - QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav); -}; - -QString QMacPasteboardMimeUrl::convertorName() -{ - return QLatin1String("URL"); -} - -QString QMacPasteboardMimeUrl::flavorFor(const QString &mime) -{ - if (mime.startsWith(QLatin1String("text/uri-list"))) - return QLatin1String("public.url"); - return QString(); -} - -QString QMacPasteboardMimeUrl::mimeFor(QString flav) -{ - if (flav == QLatin1String("public.url")) - return QLatin1String("text/uri-list"); - return QString(); -} - -bool QMacPasteboardMimeUrl::canConvert(const QString &mime, QString flav) -{ - return flav == QLatin1String("public.url") - && mime == QLatin1String("text/uri-list"); -} - -QVariant QMacPasteboardMimeUrl::convertToMime(const QString &mime, QList<QByteArray> data, QString flav) -{ - if (!canConvert(mime, flav)) - return QVariant(); - - QList<QVariant> ret; - for (int i=0; i<data.size(); ++i) { - QUrl url = QUrl::fromEncoded(data.at(i)); - if (url.host().toLower() == QLatin1String("localhost")) - url.setHost(QString()); - url.setPath(url.path().normalized(QString::NormalizationForm_C)); - ret.append(url); - } - return QVariant(ret); -} - -QList<QByteArray> QMacPasteboardMimeUrl::convertFromMime(const QString &mime, QVariant data, QString flav) -{ - QList<QByteArray> ret; - if (!canConvert(mime, flav)) - return ret; - - QList<QVariant> urls = data.toList(); - for (int i=0; i<urls.size(); ++i) { - QUrl url = urls.at(i).toUrl(); - if (url.scheme().isEmpty()) - url.setScheme(QLatin1String("file")); - if (url.scheme() == QLatin1String("file")) { - if (url.host().isEmpty()) - url.setHost(QLatin1String("localhost")); - url.setPath(url.path().normalized(QString::NormalizationForm_D)); - } - ret.append(url.toEncoded()); - } - return ret; -} - -class QMacPasteboardMimeVCard : public QMacInternalPasteboardMime -{ -public: - QMacPasteboardMimeVCard() : QMacInternalPasteboardMime(MIME_ALL){ } - QString convertorName(); - - QString flavorFor(const QString &mime); - QString mimeFor(QString flav); - bool canConvert(const QString &mime, QString flav); - QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav); - QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav); -}; - -QString QMacPasteboardMimeVCard::convertorName() -{ - return QLatin1String("VCard"); -} - -bool QMacPasteboardMimeVCard::canConvert(const QString &mime, QString flav) -{ - return mimeFor(flav) == mime; -} - -QString QMacPasteboardMimeVCard::flavorFor(const QString &mime) -{ - if (mime.startsWith(QLatin1String("text/vcard"))) - return QLatin1String("public.vcard"); - return QString(); -} - -QString QMacPasteboardMimeVCard::mimeFor(QString flav) -{ - if (flav == QLatin1String("public.vcard")) - return QLatin1String("text/vcard"); - return QString(); -} - -QVariant QMacPasteboardMimeVCard::convertToMime(const QString &mime, QList<QByteArray> data, QString) -{ - QByteArray cards; - if (mime == QLatin1String("text/vcard")) { - for (int i=0; i<data.size(); ++i) - cards += data[i]; - } - return QVariant(cards); -} - -QList<QByteArray> QMacPasteboardMimeVCard::convertFromMime(const QString &mime, QVariant data, QString) -{ - QList<QByteArray> ret; - if (mime == QLatin1String("text/vcard")) - ret.append(data.toString().toUtf8()); - return ret; -} - -extern QImage qt_mac_toQImage(CGImageRef image); -extern CGImageRef qt_mac_toCGImage(const QImage &qImage); - -class QMacPasteboardMimeTiff : public QMacInternalPasteboardMime { -public: - QMacPasteboardMimeTiff() : QMacInternalPasteboardMime(MIME_ALL) { } - QString convertorName(); - - QString flavorFor(const QString &mime); - QString mimeFor(QString flav); - bool canConvert(const QString &mime, QString flav); - QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav); - QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav); -}; - -QString QMacPasteboardMimeTiff::convertorName() -{ - return QLatin1String("Tiff"); -} - -QString QMacPasteboardMimeTiff::flavorFor(const QString &mime) -{ - if (mime.startsWith(QLatin1String("application/x-qt-image"))) - return QLatin1String("public.tiff"); - return QString(); -} - -QString QMacPasteboardMimeTiff::mimeFor(QString flav) -{ - if (flav == QLatin1String("public.tiff")) - return QLatin1String("application/x-qt-image"); - return QString(); -} - -bool QMacPasteboardMimeTiff::canConvert(const QString &mime, QString flav) -{ - return flav == QLatin1String("public.tiff") && mime == QLatin1String("application/x-qt-image"); -} - -QVariant QMacPasteboardMimeTiff::convertToMime(const QString &mime, QList<QByteArray> data, QString flav) -{ - if (data.count() > 1) - qWarning("QMacPasteboardMimeTiff: Cannot handle multiple member data"); - - if (!canConvert(mime, flav)) - return QVariant(); - - QCFType<CFDataRef> tiffData = data.first().toRawCFData(); - QCFType<CGImageSourceRef> imageSource = CGImageSourceCreateWithData(tiffData, 0); - - if (QCFType<CGImageRef> image = CGImageSourceCreateImageAtIndex(imageSource, 0, 0)) - return QVariant(qt_mac_toQImage(image)); - - return QVariant(); -} - -QList<QByteArray> QMacPasteboardMimeTiff::convertFromMime(const QString &mime, QVariant variant, QString flav) -{ - if (!canConvert(mime, flav)) - return QList<QByteArray>(); - - QCFType<CFMutableDataRef> data = CFDataCreateMutable(0, 0); - QCFType<CGImageDestinationRef> imageDestination = CGImageDestinationCreateWithData(data, kUTTypeTIFF, 1, 0); - - if (!imageDestination) - return QList<QByteArray>(); - - QImage img = qvariant_cast<QImage>(variant); - NSDictionary *props = @{ - static_cast<NSString *>(kCGImagePropertyPixelWidth): @(img.width()), - static_cast<NSString *>(kCGImagePropertyPixelHeight): @(img.height()) - }; - - CGImageDestinationAddImage(imageDestination, qt_mac_toCGImage(img), static_cast<CFDictionaryRef>(props)); - CGImageDestinationFinalize(imageDestination); - - return QList<QByteArray>() << QByteArray::fromCFData(data); -} - -/*! - \internal - - This is an internal function. -*/ -void QMacInternalPasteboardMime::initializeMimeTypes() -{ - if (globalMimeList()->isEmpty()) { - // Create QMacPasteboardMimeAny first to put it at the end of globalMimeList - // with lowest priority. (the constructor prepends to the list) - new QMacPasteboardMimeAny; - - //standard types that we wrap - new QMacPasteboardMimeTiff; - new QMacPasteboardMimePlainTextFallback; - new QMacPasteboardMimeUnicodeText; - new QMacPasteboardMimeRtfText; - new QMacPasteboardMimeHTMLText; - new QMacPasteboardMimeFileUri; - new QMacPasteboardMimeUrl; - new QMacPasteboardMimeTypeName; - new QMacPasteboardMimeVCard; - } -} - -/*! - \internal -*/ -void QMacInternalPasteboardMime::destroyMimeTypes() -{ - MimeList *mimes = globalMimeList(); - while (!mimes->isEmpty()) - delete mimes->takeFirst(); -} - -/*! - Returns the most-recently created QMacPasteboardMime of type \a t that can convert - between the \a mime and \a flav formats. Returns 0 if no such convertor - exists. -*/ -QMacInternalPasteboardMime* -QMacInternalPasteboardMime::convertor(uchar t, const QString &mime, QString flav) -{ - MimeList *mimes = globalMimeList(); - for (MimeList::const_iterator it = mimes->constBegin(); it != mimes->constEnd(); ++it) { -#ifdef DEBUG_MIME_MAPS - qDebug("QMacPasteboardMime::convertor: seeing if %s (%d) can convert %s to %d[%c%c%c%c] [%d]", - (*it)->convertorName().toLatin1().constData(), - (*it)->type & t, mime.toLatin1().constData(), - flav, (flav >> 24) & 0xFF, (flav >> 16) & 0xFF, (flav >> 8) & 0xFF, (flav) & 0xFF, - (*it)->canConvert(mime,flav)); - for (int i = 0; i < (*it)->countFlavors(); ++i) { - int f = (*it)->flavor(i); - qDebug(" %d) %d[%c%c%c%c] [%s]", i, f, - (f >> 24) & 0xFF, (f >> 16) & 0xFF, (f >> 8) & 0xFF, (f) & 0xFF, - (*it)->convertorName().toLatin1().constData()); - } -#endif - if (((*it)->type & t) && (*it)->canConvert(mime, flav)) - return (*it); - } - return 0; -} -/*! - Returns a MIME type of type \a t for \a flav, or 0 if none exists. -*/ -QString QMacInternalPasteboardMime::flavorToMime(uchar t, QString flav) -{ - MimeList *mimes = globalMimeList(); - for (MimeList::const_iterator it = mimes->constBegin(); it != mimes->constEnd(); ++it) { -#ifdef DEBUG_MIME_MAPS - qDebug("QMacMIme::flavorToMime: attempting %s (%d) for flavor %d[%c%c%c%c] [%s]", - (*it)->convertorName().toLatin1().constData(), - (*it)->type & t, flav, (flav >> 24) & 0xFF, (flav >> 16) & 0xFF, (flav >> 8) & 0xFF, (flav) & 0xFF, - (*it)->mimeFor(flav).toLatin1().constData()); - -#endif - if ((*it)->type & t) { - QString mimeType = (*it)->mimeFor(flav); - if (!mimeType.isNull()) - return mimeType; - } - } - return QString(); -} - -/*! - Returns a list of all currently defined QMacPasteboardMime objects of type \a t. -*/ -QList<QMacInternalPasteboardMime*> QMacInternalPasteboardMime::all(uchar t) -{ - MimeList ret; - MimeList *mimes = globalMimeList(); - for (MimeList::const_iterator it = mimes->constBegin(); it != mimes->constEnd(); ++it) { - if ((*it)->type & t) - ret.append((*it)); - } - return ret; -} - - -/*! - \fn QString QMacPasteboardMime::convertorName() - - Returns a name for the convertor. - - All subclasses must reimplement this pure virtual function. -*/ - -/*! - \fn bool QMacPasteboardMime::canConvert(const QString &mime, QString flav) - - Returns \c true if the convertor can convert (both ways) between - \a mime and \a flav; otherwise returns \c false. - - All subclasses must reimplement this pure virtual function. -*/ - -/*! - \fn QString QMacPasteboardMime::mimeFor(QString flav) - - Returns the MIME UTI used for Mac flavor \a flav, or 0 if this - convertor does not support \a flav. - - All subclasses must reimplement this pure virtual function. -*/ - -/*! - \fn QString QMacPasteboardMime::flavorFor(const QString &mime) - - Returns the Mac UTI used for MIME type \a mime, or 0 if this - convertor does not support \a mime. - - All subclasses must reimplement this pure virtual function. -*/ - -/*! - \fn QVariant QMacPasteboardMime::convertToMime(const QString &mime, QList<QByteArray> data, QString flav) - - Returns \a data converted from Mac UTI \a flav to MIME type \a - mime. - - Note that Mac flavors must all be self-terminating. The input \a - data may contain trailing data. - - All subclasses must reimplement this pure virtual function. -*/ - -/*! - \fn QList<QByteArray> QMacPasteboardMime::convertFromMime(const QString &mime, QVariant data, QString flav) - - Returns \a data converted from MIME type \a mime - to Mac UTI \a flav. - - Note that Mac flavors must all be self-terminating. The return - value may contain trailing data. - - All subclasses must reimplement this pure virtual function. -*/ - -QT_END_NAMESPACE diff --git a/src/platformsupport/clipboard/qmacmime_p.h b/src/platformsupport/clipboard/qmacmime_p.h deleted file mode 100644 index 8b1b6cd10f..0000000000 --- a/src/platformsupport/clipboard/qmacmime_p.h +++ /dev/null @@ -1,98 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QMACMIME_H -#define QMACMIME_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore> - -#include <CoreFoundation/CoreFoundation.h> - -QT_BEGIN_NAMESPACE - -// Duplicate of QMacPasteboardMime in QtMacExtras. Keep in sync! -class QMacInternalPasteboardMime { - char type; -public: - enum QMacPasteboardMimeType { MIME_DND=0x01, - MIME_CLIP=0x02, - MIME_QT_CONVERTOR=0x04, - MIME_QT3_CONVERTOR=0x08, - MIME_ALL=MIME_DND|MIME_CLIP - }; - explicit QMacInternalPasteboardMime(char); - virtual ~QMacInternalPasteboardMime(); - - static void initializeMimeTypes(); - static void destroyMimeTypes(); - - static QList<QMacInternalPasteboardMime*> all(uchar); - static QMacInternalPasteboardMime *convertor(uchar, const QString &mime, QString flav); - static QString flavorToMime(uchar, QString flav); - - virtual QString convertorName() = 0; - - virtual bool canConvert(const QString &mime, QString flav) = 0; - virtual QString mimeFor(QString flav) = 0; - virtual QString flavorFor(const QString &mime) = 0; - virtual QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav) = 0; - virtual QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav) = 0; - virtual int count(QMimeData *mimeData); -}; - -void qt_mac_addToGlobalMimeList(QMacInternalPasteboardMime *macMime); -void qt_mac_removeFromGlobalMimeList(QMacInternalPasteboardMime *macMime); -void qt_mac_registerDraggedTypes(const QStringList &types); -const QStringList& qt_mac_enabledDraggedTypes(); - -QT_END_NAMESPACE - -#endif - diff --git a/src/platformsupport/devicediscovery/CMakeLists.txt b/src/platformsupport/devicediscovery/CMakeLists.txt new file mode 100644 index 0000000000..19c35f6660 --- /dev/null +++ b/src/platformsupport/devicediscovery/CMakeLists.txt @@ -0,0 +1,39 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: BSD-3-Clause + +##################################################################### +## DeviceDiscoverySupportPrivate Module: +##################################################################### + +qt_internal_add_module(DeviceDiscoverySupportPrivate + CONFIG_MODULE_NAME devicediscovery_support + STATIC + INTERNAL_MODULE + SOURCES + qdevicediscovery_p.h + DEFINES + QT_NO_CAST_FROM_ASCII + PUBLIC_LIBRARIES + Qt::CorePrivate + NO_GENERATE_CPP_EXPORTS +) + +## Scopes: +##################################################################### + +qt_internal_extend_target(DeviceDiscoverySupportPrivate CONDITION QT_FEATURE_libudev + SOURCES + qdevicediscovery_udev.cpp qdevicediscovery_udev_p.h + LIBRARIES + PkgConfig::Libudev +) + +qt_internal_extend_target(DeviceDiscoverySupportPrivate CONDITION QT_FEATURE_evdev AND NOT QT_FEATURE_libudev + SOURCES + qdevicediscovery_static.cpp qdevicediscovery_static_p.h +) + +qt_internal_extend_target(DeviceDiscoverySupportPrivate CONDITION NOT QT_FEATURE_evdev AND NOT QT_FEATURE_libudev + SOURCES + qdevicediscovery_dummy.cpp qdevicediscovery_dummy_p.h +) diff --git a/src/platformsupport/devicediscovery/devicediscovery.pro b/src/platformsupport/devicediscovery/devicediscovery.pro deleted file mode 100644 index 881ec4d41e..0000000000 --- a/src/platformsupport/devicediscovery/devicediscovery.pro +++ /dev/null @@ -1,24 +0,0 @@ -TARGET = QtDeviceDiscoverySupport -MODULE = devicediscovery_support - -QT = core-private -QT_FOR_CONFIG += gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII - -HEADERS += qdevicediscovery_p.h - -qtConfig(libudev) { - SOURCES += qdevicediscovery_udev.cpp - HEADERS += qdevicediscovery_udev_p.h - QMAKE_USE_PRIVATE += libudev -} else: qtConfig(evdev) { - SOURCES += qdevicediscovery_static.cpp - HEADERS += qdevicediscovery_static_p.h -} else { - SOURCES += qdevicediscovery_dummy.cpp - HEADERS += qdevicediscovery_dummy_p.h -} - -load(qt_module) diff --git a/src/platformsupport/devicediscovery/qdevicediscovery_dummy.cpp b/src/platformsupport/devicediscovery/qdevicediscovery_dummy.cpp index a04b91b438..f94f7be3b2 100644 --- a/src/platformsupport/devicediscovery/qdevicediscovery_dummy.cpp +++ b/src/platformsupport/devicediscovery/qdevicediscovery_dummy.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qdevicediscovery_dummy_p.h" diff --git a/src/platformsupport/devicediscovery/qdevicediscovery_dummy_p.h b/src/platformsupport/devicediscovery/qdevicediscovery_dummy_p.h index fe669c8dec..9ac6fbe921 100644 --- a/src/platformsupport/devicediscovery/qdevicediscovery_dummy_p.h +++ b/src/platformsupport/devicediscovery/qdevicediscovery_dummy_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QDEVICEDISCOVERY_DUMMY_H #define QDEVICEDISCOVERY_DUMMY_H @@ -60,7 +24,7 @@ class QDeviceDiscoveryDummy : public QDeviceDiscovery Q_OBJECT public: - QDeviceDiscoveryDummy(QDeviceTypes types, QObject *parent = 0); + QDeviceDiscoveryDummy(QDeviceTypes types, QObject *parent = nullptr); QStringList scanConnectedDevices() override; }; diff --git a/src/platformsupport/devicediscovery/qdevicediscovery_p.h b/src/platformsupport/devicediscovery/qdevicediscovery_p.h index e3c22b0b37..59ce3cd889 100644 --- a/src/platformsupport/devicediscovery/qdevicediscovery_p.h +++ b/src/platformsupport/devicediscovery/qdevicediscovery_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2018 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QDEVICEDISCOVERY_H #define QDEVICEDISCOVERY_H @@ -54,6 +18,7 @@ #include <QObject> #include <QSocketNotifier> #include <QStringList> +#include <private/qglobal_p.h> #define QT_EVDEV_DEVICE_PATH "/dev/input/" #define QT_EVDEV_DEVICE_PREFIX "event" @@ -86,7 +51,7 @@ public: Q_ENUM(QDeviceType) Q_DECLARE_FLAGS(QDeviceTypes, QDeviceType) - static QDeviceDiscovery *create(QDeviceTypes type, QObject *parent = 0); + static QDeviceDiscovery *create(QDeviceTypes type, QObject *parent = nullptr); virtual QStringList scanConnectedDevices() = 0; @@ -96,7 +61,7 @@ signals: protected: QDeviceDiscovery(QDeviceTypes types, QObject *parent) : QObject(parent), m_types(types) { } - Q_DISABLE_COPY(QDeviceDiscovery) + Q_DISABLE_COPY_MOVE(QDeviceDiscovery) QDeviceTypes m_types; }; diff --git a/src/platformsupport/devicediscovery/qdevicediscovery_static.cpp b/src/platformsupport/devicediscovery/qdevicediscovery_static.cpp index a1575677f5..03a77aaae7 100644 --- a/src/platformsupport/devicediscovery/qdevicediscovery_static.cpp +++ b/src/platformsupport/devicediscovery/qdevicediscovery_static.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qdevicediscovery_static_p.h" @@ -83,6 +47,8 @@ static bool testBit(long bit, const long *field) QT_BEGIN_NAMESPACE +using namespace Qt::StringLiterals; + Q_LOGGING_CATEGORY(lcDD, "qt.qpa.input") QDeviceDiscovery *QDeviceDiscovery::create(QDeviceTypes types, QObject *parent) @@ -107,7 +73,7 @@ QStringList QDeviceDiscoveryStatic::scanConnectedDevices() dir.setPath(QString::fromLatin1(QT_EVDEV_DEVICE_PATH)); const auto deviceFiles = dir.entryList(); for (const QString &deviceFile : deviceFiles) { - QString absoluteFilePath = dir.absolutePath() + QLatin1Char('/') + deviceFile; + QString absoluteFilePath = dir.absolutePath() + u'/' + deviceFile; if (checkDeviceType(absoluteFilePath)) devices << absoluteFilePath; } @@ -118,7 +84,7 @@ QStringList QDeviceDiscoveryStatic::scanConnectedDevices() dir.setPath(QString::fromLatin1(QT_DRM_DEVICE_PATH)); const auto deviceFiles = dir.entryList(); for (const QString &deviceFile : deviceFiles) { - QString absoluteFilePath = dir.absolutePath() + QLatin1Char('/') + deviceFile; + QString absoluteFilePath = dir.absolutePath() + u'/' + deviceFile; if (checkDeviceType(absoluteFilePath)) devices << absoluteFilePath; } @@ -139,7 +105,7 @@ bool QDeviceDiscoveryStatic::checkDeviceType(const QString &device) qCDebug(lcDD) << "doing static device discovery for " << device; - if ((m_types & Device_DRM) && device.contains(QLatin1String(QT_DRM_DEVICE_PREFIX))) { + if ((m_types & Device_DRM) && device.contains(QT_DRM_DEVICE_PREFIX ""_L1)) { QT_CLOSE(fd); return true; } diff --git a/src/platformsupport/devicediscovery/qdevicediscovery_static_p.h b/src/platformsupport/devicediscovery/qdevicediscovery_static_p.h index 93110c3c55..fb698c9022 100644 --- a/src/platformsupport/devicediscovery/qdevicediscovery_static_p.h +++ b/src/platformsupport/devicediscovery/qdevicediscovery_static_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QDEVICEDISCOVERY_STATIC_H #define QDEVICEDISCOVERY_STATIC_H @@ -60,7 +24,7 @@ class QDeviceDiscoveryStatic : public QDeviceDiscovery Q_OBJECT public: - QDeviceDiscoveryStatic(QDeviceTypes types, QObject *parent = 0); + QDeviceDiscoveryStatic(QDeviceTypes types, QObject *parent = nullptr); QStringList scanConnectedDevices() override; private: diff --git a/src/platformsupport/devicediscovery/qdevicediscovery_udev.cpp b/src/platformsupport/devicediscovery/qdevicediscovery_udev.cpp index f601a196ca..45043818a4 100644 --- a/src/platformsupport/devicediscovery/qdevicediscovery_udev.cpp +++ b/src/platformsupport/devicediscovery/qdevicediscovery_udev.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qdevicediscovery_udev_p.h" @@ -46,17 +10,23 @@ #include <QSocketNotifier> #include <QLoggingCategory> +#ifdef Q_OS_FREEBSD +#include <dev/evdev/input.h> +#else #include <linux/input.h> +#endif QT_BEGIN_NAMESPACE +using namespace Qt::StringLiterals; + Q_LOGGING_CATEGORY(lcDD, "qt.qpa.input") QDeviceDiscovery *QDeviceDiscovery::create(QDeviceTypes types, QObject *parent) { qCDebug(lcDD) << "udev device discovery for type" << types; - QDeviceDiscovery *helper = 0; + QDeviceDiscovery *helper = nullptr; struct udev *udev; udev = udev_new(); @@ -71,7 +41,7 @@ QDeviceDiscovery *QDeviceDiscovery::create(QDeviceTypes types, QObject *parent) QDeviceDiscoveryUDev::QDeviceDiscoveryUDev(QDeviceTypes types, struct udev *udev, QObject *parent) : QDeviceDiscovery(types, parent), - m_udev(udev), m_udevMonitor(0), m_udevMonitorFileDescriptor(-1), m_udevSocketNotifier(0) + m_udev(udev) { if (!m_udev) return; @@ -88,7 +58,7 @@ QDeviceDiscoveryUDev::QDeviceDiscoveryUDev(QDeviceTypes types, struct udev *udev m_udevMonitorFileDescriptor = udev_monitor_get_fd(m_udevMonitor); m_udevSocketNotifier = new QSocketNotifier(m_udevMonitorFileDescriptor, QSocketNotifier::Read, this); - connect(m_udevSocketNotifier, SIGNAL(activated(int)), this, SLOT(handleUDevNotification())); + connect(m_udevSocketNotifier, SIGNAL(activated(QSocketDescriptor)), this, SLOT(handleUDevNotification())); } QDeviceDiscoveryUDev::~QDeviceDiscoveryUDev() @@ -136,9 +106,9 @@ QStringList QDeviceDiscoveryUDev::scanConnectedDevices() const char *syspath = udev_list_entry_get_name(entry); udev_device *udevice = udev_device_new_from_syspath(m_udev, syspath); QString candidate = QString::fromUtf8(udev_device_get_devnode(udevice)); - if ((m_types & Device_InputMask) && candidate.startsWith(QLatin1String(QT_EVDEV_DEVICE))) + if ((m_types & Device_InputMask) && candidate.startsWith(QT_EVDEV_DEVICE ""_L1)) devices << candidate; - if ((m_types & Device_VideoMask) && candidate.startsWith(QLatin1String(QT_DRM_DEVICE))) { + if ((m_types & Device_VideoMask) && candidate.startsWith(QT_DRM_DEVICE ""_L1)) { if (m_types & Device_DRM_PrimaryGPU) { udev_device *pci = udev_device_get_parent_with_subsystem_devtype(udevice, "pci", 0); if (pci) { @@ -182,9 +152,9 @@ void QDeviceDiscoveryUDev::handleUDevNotification() const char *subsystem; devNode = QString::fromUtf8(str); - if (devNode.startsWith(QLatin1String(QT_EVDEV_DEVICE))) + if (devNode.startsWith(QT_EVDEV_DEVICE ""_L1)) subsystem = "input"; - else if (devNode.startsWith(QLatin1String(QT_DRM_DEVICE))) + else if (devNode.startsWith(QT_DRM_DEVICE ""_L1)) subsystem = "drm"; else goto cleanup; @@ -216,7 +186,7 @@ bool QDeviceDiscoveryUDev::checkDeviceType(udev_device *dev) if ((m_types & Device_Keyboard) && (qstrcmp(udev_device_get_property_value(dev, "ID_INPUT_KEYBOARD"), "1") == 0 )) { const QString capabilities_key = QString::fromUtf8(udev_device_get_sysattr_value(dev, "capabilities/key")); - const auto val = capabilities_key.splitRef(QLatin1Char(' '), QString::SkipEmptyParts); + const auto val = QStringView{capabilities_key}.split(u' ', Qt::SkipEmptyParts); if (!val.isEmpty()) { bool ok; unsigned long long keys = val.last().toULongLong(&ok, 16); @@ -254,3 +224,5 @@ bool QDeviceDiscoveryUDev::checkDeviceType(udev_device *dev) } QT_END_NAMESPACE + +#include "moc_qdevicediscovery_udev_p.cpp" diff --git a/src/platformsupport/devicediscovery/qdevicediscovery_udev_p.h b/src/platformsupport/devicediscovery/qdevicediscovery_udev_p.h index 28618d0b21..3074877b5a 100644 --- a/src/platformsupport/devicediscovery/qdevicediscovery_udev_p.h +++ b/src/platformsupport/devicediscovery/qdevicediscovery_udev_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QDEVICEDISCOVERY_UDEV_H #define QDEVICEDISCOVERY_UDEV_H @@ -61,23 +25,25 @@ class QDeviceDiscoveryUDev : public QDeviceDiscovery Q_OBJECT public: - QDeviceDiscoveryUDev(QDeviceTypes types, struct udev *udev, QObject *parent = 0); + QDeviceDiscoveryUDev(QDeviceTypes types, struct udev *udev, QObject *parent = nullptr); ~QDeviceDiscoveryUDev(); QStringList scanConnectedDevices() override; private slots: void handleUDevNotification(); +protected: + struct udev *m_udev; + private: bool checkDeviceType(struct udev_device *dev); void startWatching(); void stopWatching(); - struct udev *m_udev; - struct udev_monitor *m_udevMonitor; - int m_udevMonitorFileDescriptor; - QSocketNotifier *m_udevSocketNotifier; + struct udev_monitor *m_udevMonitor = nullptr; + int m_udevMonitorFileDescriptor = -1; + QSocketNotifier *m_udevSocketNotifier = nullptr; }; QT_END_NAMESPACE diff --git a/src/platformsupport/edid/edid.pro b/src/platformsupport/edid/edid.pro deleted file mode 100644 index 842a91170e..0000000000 --- a/src/platformsupport/edid/edid.pro +++ /dev/null @@ -1,13 +0,0 @@ -TARGET = QtEdidSupport -MODULE = edid_support - -QT = core-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII -PRECOMPILED_HEADER = ../../corelib/global/qt_pch.h - -HEADERS += qedidparser_p.h -SOURCES += qedidparser.cpp - -load(qt_module) diff --git a/src/platformsupport/edid/qedidparser.cpp b/src/platformsupport/edid/qedidparser.cpp deleted file mode 100644 index 06c8852825..0000000000 --- a/src/platformsupport/edid/qedidparser.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtCore/QFile> - -#include "qedidparser_p.h" -#include "qedidvendortable_p.h" - -#define ARRAY_LENGTH(a) (sizeof (a) / sizeof (a)[0]) - -#define EDID_DESCRIPTOR_ALPHANUMERIC_STRING 0xfe -#define EDID_DESCRIPTOR_PRODUCT_NAME 0xfc -#define EDID_DESCRIPTOR_SERIAL_NUMBER 0xff - -#define EDID_OFFSET_DATA_BLOCKS 0x36 -#define EDID_OFFSET_LAST_BLOCK 0x6c -#define EDID_OFFSET_PNP_ID 0x08 -#define EDID_OFFSET_SERIAL 0x0c -#define EDID_PHYSICAL_WIDTH 0x15 -#define EDID_OFFSET_PHYSICAL_HEIGHT 0x16 - -QT_BEGIN_NAMESPACE - -QEdidParser::QEdidParser() -{ - // Cache vendors list from pnp.ids - const QString fileName = QLatin1String("/usr/share/hwdata/pnp.ids"); - if (QFile::exists(fileName)) { - QFile file(fileName); - - if (file.open(QFile::ReadOnly)) { - while (!file.atEnd()) { - QString line = QString::fromUtf8(file.readLine()).trimmed(); - - if (line.startsWith(QLatin1Char('#'))) - continue; - - QStringList parts = line.split(QLatin1Char('\t')); - if (parts.count() > 1) { - QString pnpId = parts.at(0); - parts.removeFirst(); - m_vendorCache[pnpId] = parts.join(QLatin1Char(' ')); - } - } - - file.close(); - } - } -} - -bool QEdidParser::parse(const QByteArray &blob) -{ - const quint8 *data = reinterpret_cast<const quint8 *>(blob.constData()); - const size_t length = blob.length(); - - // Verify header - if (length < 128) - return false; - if (data[0] != 0x00 || data[1] != 0xff) - return false; - - /* Decode the PNP ID from three 5 bit words packed into 2 bytes - * /--08--\/--09--\ - * 7654321076543210 - * |\---/\---/\---/ - * R C1 C2 C3 */ - char pnpId[3]; - pnpId[0] = 'A' + ((data[EDID_OFFSET_PNP_ID] & 0x7c) / 4) - 1; - pnpId[1] = 'A' + ((data[EDID_OFFSET_PNP_ID] & 0x3) * 8) + ((data[EDID_OFFSET_PNP_ID + 1] & 0xe0) / 32) - 1; - pnpId[2] = 'A' + (data[EDID_OFFSET_PNP_ID + 1] & 0x1f) - 1; - QString pnpIdString = QString::fromLatin1(pnpId, 3); - - // Clear manufacturer - manufacturer = QString(); - - // Serial number, will be overwritten by an ASCII descriptor - // when and if it will be found - quint32 serial = data[EDID_OFFSET_SERIAL] - + (data[EDID_OFFSET_SERIAL + 1] << 8) - + (data[EDID_OFFSET_SERIAL + 2] << 16) - + (data[EDID_OFFSET_SERIAL + 3] << 24); - if (serial > 0) - serialNumber = QString::number(serial); - else - serialNumber = QString(); - - // Parse EDID data - for (int i = 0; i < 5; ++i) { - const uint offset = EDID_OFFSET_DATA_BLOCKS + i * 18; - - if (data[offset] != 0 || data[offset + 1] != 0 || data[offset + 2] != 0) - continue; - - if (data[offset + 3] == EDID_DESCRIPTOR_PRODUCT_NAME) - model = parseEdidString(&data[offset + 5]); - else if (data[offset + 3] == EDID_DESCRIPTOR_ALPHANUMERIC_STRING) - identifier = parseEdidString(&data[offset + 5]); - else if (data[offset + 3] == EDID_DESCRIPTOR_SERIAL_NUMBER) - serialNumber = parseEdidString(&data[offset + 5]); - } - - // Try to use cache first because it is potentially more updated - manufacturer = m_vendorCache.value(pnpIdString); - if (manufacturer.isEmpty()) { - // Find the manufacturer from the vendor lookup table - for (size_t i = 0; i < ARRAY_LENGTH(q_edidVendorTable); i++) { - if (strncmp(q_edidVendorTable[i].id, pnpId, 3) == 0) { - manufacturer = QString::fromUtf8(q_edidVendorTable[i].name); - break; - } - } - } - - // If we don't know the manufacturer, fallback to PNP ID - if (manufacturer.isEmpty()) - manufacturer = pnpIdString; - - // Physical size - physicalSize = QSizeF(data[EDID_PHYSICAL_WIDTH], data[EDID_OFFSET_PHYSICAL_HEIGHT]) * 10; - - return true; -} - -QString QEdidParser::parseEdidString(const quint8 *data) -{ - QByteArray buffer(reinterpret_cast<const char *>(data), 13); - - // Erase carriage return and line feed - buffer = buffer.replace('\r', '\0').replace('\n', '\0'); - - // Replace non-printable characters with dash - for (int i = 0; i < buffer.count(); ++i) { - if (buffer[i] < '\040' || buffer[i] > '\176') - buffer[i] = '-'; - } - - return QString::fromLatin1(buffer.trimmed()); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/edid/qedidparser_p.h b/src/platformsupport/edid/qedidparser_p.h deleted file mode 100644 index c436155258..0000000000 --- a/src/platformsupport/edid/qedidparser_p.h +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QEDIDPARSER_P_H -#define QEDIDPARSER_P_H - -#include <QtCore/QSize> -#include <QtCore/QMap> - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -QT_BEGIN_NAMESPACE - -class QEdidParser -{ -public: - QEdidParser(); - - bool parse(const QByteArray &blob); - - QString identifier; - QString manufacturer; - QString model; - QString serialNumber; - QSizeF physicalSize; - -private: - QMap<QString, QString> m_vendorCache; - - QString parseEdidString(const quint8 *data); -}; - -QT_END_NAMESPACE - -#endif // QEDIDPARSER_P_H diff --git a/src/platformsupport/edid/qedidvendortable_p.h b/src/platformsupport/edid/qedidvendortable_p.h deleted file mode 100644 index 5768dbe992..0000000000 --- a/src/platformsupport/edid/qedidvendortable_p.h +++ /dev/null @@ -1,2307 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/* - * This lookup table was generated from https://github.com/vcrhonek/hwdata/raw/master/pnp.ids - * - * Do not change this file directly, instead edit the - * qtbase/util/edid/qedidvendortable.py script and regenerate this file. - */ - -#ifndef QEDIDVENDORTABLE_P_H -#define QEDIDVENDORTABLE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -QT_BEGIN_NAMESPACE - -typedef struct VendorTable { - const char id[4]; - const char name[78]; -} VendorTable; - -static const struct VendorTable q_edidVendorTable[] = { - { "AAA", "Avolites Ltd" }, - { "AAE", "Anatek Electronics Inc." }, - { "AAT", "Ann Arbor Technologies" }, - { "ABA", "ABBAHOME INC." }, - { "ABC", "AboCom System Inc" }, - { "ABD", "Allen Bradley Company" }, - { "ABE", "Alcatel Bell" }, - { "ABO", "D-Link Systems Inc" }, - { "ABT", "Anchor Bay Technologies, Inc." }, - { "ABV", "Advanced Research Technology" }, - { "ACA", "Ariel Corporation" }, - { "ACB", "Aculab Ltd" }, - { "ACC", "Accton Technology Corporation" }, - { "ACD", "AWETA BV" }, - { "ACE", "Actek Engineering Pty Ltd" }, - { "ACG", "A&R Cambridge Ltd" }, - { "ACH", "Archtek Telecom Corporation" }, - { "ACI", "Ancor Communications Inc" }, - { "ACK", "Acksys" }, - { "ACL", "Apricot Computers" }, - { "ACM", "Acroloop Motion Control Systems Inc" }, - { "ACO", "Allion Computer Inc." }, - { "ACP", "Aspen Tech Inc" }, - { "ACR", "Acer Technologies" }, - { "ACS", "Altos Computer Systems" }, - { "ACT", "Applied Creative Technology" }, - { "ACU", "Acculogic" }, - { "ACV", "ActivCard S.A" }, - { "ADA", "Addi-Data GmbH" }, - { "ADB", "Aldebbaron" }, - { "ADC", "Acnhor Datacomm" }, - { "ADD", "Advanced Peripheral Devices Inc" }, - { "ADE", "Arithmos, Inc." }, - { "ADH", "Aerodata Holdings Ltd" }, - { "ADI", "ADI Systems Inc" }, - { "ADK", "Adtek System Science Company Ltd" }, - { "ADL", "ASTRA Security Products Ltd" }, - { "ADM", "Ad Lib MultiMedia Inc" }, - { "ADN", "Analog & Digital Devices Tel. Inc" }, - { "ADP", "Adaptec Inc" }, - { "ADR", "Nasa Ames Research Center" }, - { "ADS", "Analog Devices Inc" }, - { "ADT", "Aved Display Technologies" }, - { "ADV", "Advanced Micro Devices Inc" }, - { "ADX", "Adax Inc" }, - { "AEC", "Antex Electronics Corporation" }, - { "AED", "Advanced Electronic Designs, Inc." }, - { "AEI", "Actiontec Electric Inc" }, - { "AEJ", "Alpha Electronics Company" }, - { "AEM", "ASEM S.p.A." }, - { "AEN", "Avencall" }, - { "AEP", "Aetas Peripheral International" }, - { "AET", "Aethra Telecomunicazioni S.r.l." }, - { "AFA", "Alfa Inc" }, - { "AGC", "Beijing Aerospace Golden Card Electronic Engineering Co.,Ltd." }, - { "AGI", "Artish Graphics Inc" }, - { "AGL", "Argolis" }, - { "AGM", "Advan Int'l Corporation" }, - { "AGT", "Agilent Technologies" }, - { "AHC", "Advantech Co., Ltd." }, - { "AIC", "Arnos Insturments & Computer Systems" }, - { "AIE", "Altmann Industrieelektronik" }, - { "AII", "Amptron International Inc." }, - { "AIL", "Altos India Ltd" }, - { "AIM", "AIMS Lab Inc" }, - { "AIR", "Advanced Integ. Research Inc" }, - { "AIS", "Alien Internet Services" }, - { "AIW", "Aiwa Company Ltd" }, - { "AIX", "ALTINEX, INC." }, - { "AJA", "AJA Video Systems, Inc." }, - { "AKB", "Akebia Ltd" }, - { "AKE", "AKAMI Electric Co.,Ltd" }, - { "AKI", "AKIA Corporation" }, - { "AKL", "AMiT Ltd" }, - { "AKM", "Asahi Kasei Microsystems Company Ltd" }, - { "AKP", "Atom Komplex Prylad" }, - { "AKY", "Askey Computer Corporation" }, - { "ALA", "Alacron Inc" }, - { "ALC", "Altec Corporation" }, - { "ALD", "In4S Inc" }, - { "ALG", "Realtek Semiconductor Corp." }, - { "ALH", "AL Systems" }, - { "ALI", "Acer Labs" }, - { "ALJ", "Altec Lansing" }, - { "ALK", "Acrolink Inc" }, - { "ALL", "Alliance Semiconductor Corporation" }, - { "ALM", "Acutec Ltd." }, - { "ALN", "Alana Technologies" }, - { "ALO", "Algolith Inc." }, - { "ALP", "Alps Electric Company Ltd" }, - { "ALR", "Advanced Logic" }, - { "ALS", "Texas Advanced optoelectronics Solutions, Inc" }, - { "ALT", "Altra" }, - { "ALV", "AlphaView LCD" }, - { "ALX", "ALEXON Co.,Ltd." }, - { "AMA", "Asia Microelectronic Development Inc" }, - { "AMB", "Ambient Technologies, Inc." }, - { "AMC", "Attachmate Corporation" }, - { "AMD", "Amdek Corporation" }, - { "AMI", "American Megatrends Inc" }, - { "AML", "Anderson Multimedia Communications (HK) Limited" }, - { "AMN", "Amimon LTD." }, - { "AMO", "Amino Technologies PLC and Amino Communications Limited" }, - { "AMP", "AMP Inc" }, - { "AMS", "ARMSTEL, Inc." }, - { "AMT", "AMT International Industry" }, - { "AMX", "AMX LLC" }, - { "ANA", "Anakron" }, - { "ANC", "Ancot" }, - { "AND", "Adtran Inc" }, - { "ANI", "Anigma Inc" }, - { "ANK", "Anko Electronic Company Ltd" }, - { "ANL", "Analogix Semiconductor, Inc" }, - { "ANO", "Anorad Corporation" }, - { "ANP", "Andrew Network Production" }, - { "ANR", "ANR Ltd" }, - { "ANS", "Ansel Communication Company" }, - { "ANT", "Ace CAD Enterprise Company Ltd" }, - { "ANX", "Acer Netxus Inc" }, - { "AOA", "AOpen Inc." }, - { "AOE", "Advanced Optics Electronics, Inc." }, - { "AOL", "America OnLine" }, - { "AOT", "Alcatel" }, - { "APC", "American Power Conversion" }, - { "APD", "AppliAdata" }, - { "APE", "Alpine Electronics, Inc." }, - { "APG", "Horner Electric Inc" }, - { "API", "A Plus Info Corporation" }, - { "APL", "Aplicom Oy" }, - { "APM", "Applied Memory Tech" }, - { "APN", "Appian Tech Inc" }, - { "APP", "Apple Computer Inc" }, - { "APR", "Aprilia s.p.a." }, - { "APS", "Autologic Inc" }, - { "APT", "Audio Processing Technology Ltd" }, - { "APV", "A+V Link" }, - { "APX", "AP Designs Ltd" }, - { "ARC", "Alta Research Corporation" }, - { "ARE", "ICET S.p.A." }, - { "ARG", "Argus Electronics Co., LTD" }, - { "ARI", "Argosy Research Inc" }, - { "ARK", "Ark Logic Inc" }, - { "ARL", "Arlotto Comnet Inc" }, - { "ARM", "Arima" }, - { "ARO", "Poso International B.V." }, - { "ARS", "Arescom Inc" }, - { "ART", "Corion Industrial Corporation" }, - { "ASC", "Ascom Strategic Technology Unit" }, - { "ASD", "USC Information Sciences Institute" }, - { "ASE", "AseV Display Labs" }, - { "ASI", "Ahead Systems" }, - { "ASK", "Ask A/S" }, - { "ASL", "AccuScene Corporation Ltd" }, - { "ASM", "ASEM S.p.A." }, - { "ASN", "Asante Tech Inc" }, - { "ASP", "ASP Microelectronics Ltd" }, - { "AST", "AST Research Inc" }, - { "ASU", "Asuscom Network Inc" }, - { "ASX", "AudioScience" }, - { "ASY", "Rockwell Collins / Airshow Systems" }, - { "ATA", "Allied Telesyn International (Asia) Pte Ltd" }, - { "ATC", "Ably-Tech Corporation" }, - { "ATD", "Alpha Telecom Inc" }, - { "ATE", "Innovate Ltd" }, - { "ATH", "Athena Informatica S.R.L." }, - { "ATI", "Allied Telesis KK" }, - { "ATK", "Allied Telesyn Int'l" }, - { "ATL", "Arcus Technology Ltd" }, - { "ATM", "ATM Ltd" }, - { "ATN", "Athena Smartcard Solutions Ltd." }, - { "ATO", "ASTRO DESIGN, INC." }, - { "ATP", "Alpha-Top Corporation" }, - { "ATT", "AT&T" }, - { "ATV", "Office Depot, Inc." }, - { "ATX", "Athenix Corporation" }, - { "AUI", "Alps Electric Inc" }, - { "AUO", "AU Optronics" }, - { "AUR", "Aureal Semiconductor" }, - { "AUT", "Autotime Corporation" }, - { "AVA", "Avaya Communication" }, - { "AVC", "Auravision Corporation" }, - { "AVD", "Avid Electronics Corporation" }, - { "AVE", "Add Value Enterpises (Asia) Pte Ltd" }, - { "AVI", "Nippon Avionics Co.,Ltd" }, - { "AVL", "Avalue Technology Inc." }, - { "AVM", "AVM GmbH" }, - { "AVN", "Advance Computer Corporation" }, - { "AVO", "Avocent Corporation" }, - { "AVR", "AVer Information Inc." }, - { "AVT", "Avtek (Electronics) Pty Ltd" }, - { "AVV", "SBS Technologies (Canada), Inc. (was Avvida Systems, Inc.)" }, - { "AVX", "AVerMedia Technologies, Inc." }, - { "AWC", "Access Works Comm Inc" }, - { "AWL", "Aironet Wireless Communications, Inc" }, - { "AWS", "Wave Systems" }, - { "AXB", "Adrienne Electronics Corporation" }, - { "AXC", "AXIOMTEK CO., LTD." }, - { "AXE", "D-Link Systems Inc" }, - { "AXI", "American Magnetics" }, - { "AXL", "Axel" }, - { "AXO", "Axonic Labs LLC" }, - { "AXP", "American Express" }, - { "AXT", "Axtend Technologies Inc" }, - { "AXX", "Axxon Computer Corporation" }, - { "AXY", "AXYZ Automation Services, Inc" }, - { "AYD", "Aydin Displays" }, - { "AYR", "Airlib, Inc" }, - { "AZM", "AZ Middelheim - Radiotherapy" }, - { "AZT", "Aztech Systems Ltd" }, - { "BAC", "Biometric Access Corporation" }, - { "BAN", "Banyan" }, - { "BBB", "an-najah university" }, - { "BBH", "B&Bh" }, - { "BBL", "Brain Boxes Limited" }, - { "BCC", "Beaver Computer Corporaton" }, - { "BCD", "Barco GmbH" }, - { "BCM", "Broadcom" }, - { "BCQ", "Deutsche Telekom Berkom GmbH" }, - { "BCS", "Booria CAD/CAM systems" }, - { "BDO", "Brahler ICS" }, - { "BDR", "Blonder Tongue Labs, Inc." }, - { "BDS", "Barco Display Systems" }, - { "BEC", "Elektro Beckhoff GmbH" }, - { "BEI", "Beckworth Enterprises Inc" }, - { "BEK", "Beko Elektronik A.S." }, - { "BEL", "Beltronic Industrieelektronik GmbH" }, - { "BEO", "Baug & Olufsen" }, - { "BFE", "B.F. Engineering Corporation" }, - { "BGB", "Barco Graphics N.V" }, - { "BGT", "Budzetron Inc" }, - { "BHZ", "BitHeadz, Inc." }, - { "BIC", "Big Island Communications" }, - { "BII", "Boeckeler Instruments Inc" }, - { "BIL", "Billion Electric Company Ltd" }, - { "BIO", "BioLink Technologies International, Inc." }, - { "BIT", "Bit 3 Computer" }, - { "BLI", "Busicom" }, - { "BLN", "BioLink Technologies" }, - { "BLP", "Bloomberg L.P." }, - { "BMD", "Blackmagic Design" }, - { "BMI", "Benson Medical Instruments Company" }, - { "BML", "BIOMED Lab" }, - { "BMS", "BIOMEDISYS" }, - { "BNE", "Bull AB" }, - { "BNK", "Banksia Tech Pty Ltd" }, - { "BNO", "Bang & Olufsen" }, - { "BNS", "Boulder Nonlinear Systems" }, - { "BOB", "Rainy Orchard" }, - { "BOE", "BOE" }, - { "BOI", "NINGBO BOIGLE DIGITAL TECHNOLOGY CO.,LTD" }, - { "BOS", "BOS" }, - { "BPD", "Micro Solutions, Inc." }, - { "BPU", "Best Power" }, - { "BRA", "Braemac Pty Ltd" }, - { "BRC", "BARC" }, - { "BRG", "Bridge Information Co., Ltd" }, - { "BRI", "Boca Research Inc" }, - { "BRM", "Braemar Inc" }, - { "BRO", "BROTHER INDUSTRIES,LTD." }, - { "BSE", "Bose Corporation" }, - { "BSL", "Biomedical Systems Laboratory" }, - { "BSN", "BRIGHTSIGN, LLC" }, - { "BST", "BodySound Technologies, Inc." }, - { "BTC", "Bit 3 Computer" }, - { "BTE", "Brilliant Technology" }, - { "BTF", "Bitfield Oy" }, - { "BTI", "BusTech Inc" }, - { "BTO", "BioTao Ltd" }, - { "BUF", "Yasuhiko Shirai Melco Inc" }, - { "BUG", "B.U.G., Inc." }, - { "BUJ", "ATI Tech Inc" }, - { "BUL", "Bull" }, - { "BUR", "Bernecker & Rainer Ind-Eletronik GmbH" }, - { "BUS", "BusTek" }, - { "BUT", "21ST CENTURY ENTERTAINMENT" }, - { "BWK", "Bitworks Inc." }, - { "BXE", "Buxco Electronics" }, - { "BYD", "byd:sign corporation" }, - { "CAA", "Castles Automation Co., Ltd" }, - { "CAC", "CA & F Elettronica" }, - { "CAG", "CalComp" }, - { "CAI", "Canon Inc." }, - { "CAL", "Acon" }, - { "CAM", "Cambridge Audio" }, - { "CAN", "CORNEA" }, - { "CAR", "Cardinal Company Ltd" }, - { "CAS", "CASIO COMPUTER CO.,LTD" }, - { "CAT", "Consultancy in Advanced Technology" }, - { "CAV", "Cavium Networks, Inc" }, - { "CBI", "ComputerBoards Inc" }, - { "CBR", "Cebra Tech A/S" }, - { "CBT", "Cabletime Ltd" }, - { "CBX", "Cybex Computer Products Corporation" }, - { "CCC", "C-Cube Microsystems" }, - { "CCI", "Cache" }, - { "CCJ", "CONTEC CO.,LTD." }, - { "CCL", "CCL/ITRI" }, - { "CCP", "Capetronic USA Inc" }, - { "CDC", "Core Dynamics Corporation" }, - { "CDD", "Convergent Data Devices" }, - { "CDE", "Colin.de" }, - { "CDG", "Christie Digital Systems Inc" }, - { "CDI", "Concept Development Inc" }, - { "CDK", "Cray Communications" }, - { "CDN", "Codenoll Technical Corporation" }, - { "CDP", "CalComp" }, - { "CDS", "Computer Diagnostic Systems" }, - { "CDT", "IBM Corporation" }, - { "CDV", "Convergent Design Inc." }, - { "CEA", "Consumer Electronics Association" }, - { "CEC", "Chicony Electronics Company Ltd" }, - { "CED", "Cambridge Electronic Design Ltd" }, - { "CEF", "Cefar Digital Vision" }, - { "CEI", "Crestron Electronics, Inc." }, - { "CEM", "MEC Electronics GmbH" }, - { "CEN", "Centurion Technologies P/L" }, - { "CEP", "C-DAC" }, - { "CER", "Ceronix" }, - { "CET", "TEC CORPORATION" }, - { "CFG", "Atlantis" }, - { "CGA", "Chunghwa Picture Tubes, LTD" }, - { "CGS", "Chyron Corp" }, - { "CGT", "congatec AG" }, - { "CHA", "Chase Research PLC" }, - { "CHC", "Chic Technology Corp." }, - { "CHD", "ChangHong Electric Co.,Ltd" }, - { "CHE", "Acer Inc" }, - { "CHG", "Sichuan Changhong Electric CO, LTD." }, - { "CHI", "Chrontel Inc" }, - { "CHL", "Chloride-R&D" }, - { "CHM", "CHIC TECHNOLOGY CORP." }, - { "CHO", "Sichuang Changhong Corporation" }, - { "CHP", "CH Products" }, - { "CHS", "Agentur Chairos" }, - { "CHT", "Chunghwa Picture Tubes,LTD." }, - { "CHY", "Cherry GmbH" }, - { "CIC", "Comm. Intelligence Corporation" }, - { "CII", "Cromack Industries Inc" }, - { "CIL", "Citicom Infotech Private Limited" }, - { "CIN", "Citron GmbH" }, - { "CIP", "Ciprico Inc" }, - { "CIR", "Cirrus Logic Inc" }, - { "CIS", "Cisco Systems Inc" }, - { "CIT", "Citifax Limited" }, - { "CKC", "The Concept Keyboard Company Ltd" }, - { "CKJ", "Carina System Co., Ltd." }, - { "CLA", "Clarion Company Ltd" }, - { "CLD", "COMMAT L.t.d." }, - { "CLE", "Classe Audio" }, - { "CLG", "CoreLogic" }, - { "CLI", "Cirrus Logic Inc" }, - { "CLM", "CrystaLake Multimedia" }, - { "CLO", "Clone Computers" }, - { "CLT", "automated computer control systems" }, - { "CLV", "Clevo Company" }, - { "CLX", "CardLogix" }, - { "CMC", "CMC Ltd" }, - { "CMD", "Colorado MicroDisplay, Inc." }, - { "CMG", "Chenming Mold Ind. Corp." }, - { "CMI", "C-Media Electronics" }, - { "CMM", "Comtime GmbH" }, - { "CMN", "Chimei Innolux Corporation" }, - { "CMO", "Chi Mei Optoelectronics corp." }, - { "CMR", "Cambridge Research Systems Ltd" }, - { "CMS", "CompuMaster Srl" }, - { "CMX", "Comex Electronics AB" }, - { "CNB", "American Power Conversion" }, - { "CNC", "Alvedon Computers Ltd" }, - { "CNE", "Cine-tal" }, - { "CNI", "Connect Int'l A/S" }, - { "CNN", "Canon Inc" }, - { "CNT", "COINT Multimedia Systems" }, - { "COB", "COBY Electronics Co., Ltd" }, - { "COD", "CODAN Pty. Ltd." }, - { "COI", "Codec Inc." }, - { "COL", "Rockwell Collins, Inc." }, - { "COM", "Comtrol Corporation" }, - { "CON", "Contec Company Ltd" }, - { "COO", "coolux GmbH" }, - { "COR", "Corollary Inc" }, - { "COS", "CoStar Corporation" }, - { "COT", "Core Technology Inc" }, - { "COW", "Polycow Productions" }, - { "COX", "Comrex" }, - { "CPC", "Ciprico Inc" }, - { "CPD", "CompuAdd" }, - { "CPI", "Computer Peripherals Inc" }, - { "CPL", "Compal Electronics Inc" }, - { "CPM", "Capella Microsystems Inc." }, - { "CPQ", "Compaq Computer Company" }, - { "CPT", "cPATH" }, - { "CPX", "Powermatic Data Systems" }, - { "CRC", "CONRAC GmbH" }, - { "CRD", "Cardinal Technical Inc" }, - { "CRE", "Creative Labs Inc" }, - { "CRI", "Crio Inc." }, - { "CRL", "Creative Logic" }, - { "CRN", "Cornerstone Imaging" }, - { "CRO", "Extraordinary Technologies PTY Limited" }, - { "CRQ", "Cirque Corporation" }, - { "CRS", "Crescendo Communication Inc" }, - { "CRV", "Cerevo Inc." }, - { "CRX", "Cyrix Corporation" }, - { "CSB", "Transtex SA" }, - { "CSC", "Crystal Semiconductor" }, - { "CSD", "Cresta Systems Inc" }, - { "CSE", "Concept Solutions & Engineering" }, - { "CSI", "Cabletron System Inc" }, - { "CSM", "Cosmic Engineering Inc." }, - { "CSO", "California Institute of Technology" }, - { "CSS", "CSS Laboratories" }, - { "CST", "CSTI Inc" }, - { "CTA", "CoSystems Inc" }, - { "CTC", "CTC Communication Development Company Ltd" }, - { "CTE", "Chunghwa Telecom Co., Ltd." }, - { "CTL", "Creative Technology Ltd" }, - { "CTM", "Computerm Corporation" }, - { "CTN", "Computone Products" }, - { "CTP", "Computer Technology Corporation" }, - { "CTS", "Comtec Systems Co., Ltd." }, - { "CTX", "Creatix Polymedia GmbH" }, - { "CUB", "Cubix Corporation" }, - { "CUK", "Calibre UK Ltd" }, - { "CVA", "Covia Inc." }, - { "CVI", "Colorado Video, Inc." }, - { "CVS", "Clarity Visual Systems" }, - { "CWR", "Connectware Inc" }, - { "CXT", "Conexant Systems" }, - { "CYB", "CyberVision" }, - { "CYC", "Cylink Corporation" }, - { "CYD", "Cyclades Corporation" }, - { "CYL", "Cyberlabs" }, - { "CYT", "Cytechinfo Inc" }, - { "CYV", "Cyviz AS" }, - { "CYW", "Cyberware" }, - { "CYX", "Cyrix Corporation" }, - { "CZE", "Carl Zeiss AG" }, - { "DAC", "Digital Acoustics Corporation" }, - { "DAE", "Digatron Industrie Elektronik GmbH" }, - { "DAI", "DAIS SET Ltd." }, - { "DAK", "Daktronics" }, - { "DAL", "Digital Audio Labs Inc" }, - { "DAN", "Danelec Marine A/S" }, - { "DAS", "DAVIS AS" }, - { "DAT", "Datel Inc" }, - { "DAU", "Daou Tech Inc" }, - { "DAV", "Davicom Semiconductor Inc" }, - { "DAW", "DA2 Technologies Inc" }, - { "DAX", "Data Apex Ltd" }, - { "DBD", "Diebold Inc." }, - { "DBI", "DigiBoard Inc" }, - { "DBK", "Databook Inc" }, - { "DBL", "Doble Engineering Company" }, - { "DBN", "DB Networks Inc" }, - { "DCA", "Digital Communications Association" }, - { "DCC", "Dale Computer Corporation" }, - { "DCD", "Datacast LLC" }, - { "DCE", "dSPACE GmbH" }, - { "DCI", "Concepts Inc" }, - { "DCL", "Dynamic Controls Ltd" }, - { "DCM", "DCM Data Products" }, - { "DCO", "Dialogue Technology Corporation" }, - { "DCR", "Decros Ltd" }, - { "DCS", "Diamond Computer Systems Inc" }, - { "DCT", "Dancall Telecom A/S" }, - { "DCV", "Datatronics Technology Inc" }, - { "DDA", "DA2 Technologies Corporation" }, - { "DDD", "Danka Data Devices" }, - { "DDE", "Datasat Digital Entertainment" }, - { "DDI", "Data Display AG" }, - { "DDS", "Barco, n.v." }, - { "DDT", "Datadesk Technologies Inc" }, - { "DDV", "Delta Information Systems, Inc" }, - { "DEC", "Digital Equipment Corporation" }, - { "DEI", "Deico Electronics" }, - { "DEL", "Dell Inc." }, - { "DEN", "Densitron Computers Ltd" }, - { "DEX", "idex displays" }, - { "DFI", "DFI" }, - { "DFK", "SharkTec A/S" }, - { "DFT", "DEI Holdings dba Definitive Technology" }, - { "DGA", "Digiital Arts Inc" }, - { "DGC", "Data General Corporation" }, - { "DGI", "DIGI International" }, - { "DGK", "DugoTech Co., LTD" }, - { "DGP", "Digicorp European sales S.A." }, - { "DGS", "Diagsoft Inc" }, - { "DGT", "The Dearborn Group" }, - { "DHP", "DH Print" }, - { "DHQ", "Quadram" }, - { "DHT", "Projectavision Inc" }, - { "DIA", "Diadem" }, - { "DIG", "Digicom S.p.A." }, - { "DII", "Dataq Instruments Inc" }, - { "DIM", "dPict Imaging, Inc." }, - { "DIN", "Daintelecom Co., Ltd" }, - { "DIS", "Diseda S.A." }, - { "DIT", "Dragon Information Technology" }, - { "DJE", "Capstone Visual Product Development" }, - { "DJP", "Maygay Machines, Ltd" }, - { "DKY", "Datakey Inc" }, - { "DLB", "Dolby Laboratories Inc." }, - { "DLC", "Diamond Lane Comm. Corporation" }, - { "DLG", "Digital-Logic GmbH" }, - { "DLK", "D-Link Systems Inc" }, - { "DLL", "Dell Inc" }, - { "DLT", "Digitelec Informatique Park Cadera" }, - { "DMB", "Digicom Systems Inc" }, - { "DMC", "Dune Microsystems Corporation" }, - { "DMM", "Dimond Multimedia Systems Inc" }, - { "DMP", "D&M Holdings Inc, Professional Business Company" }, - { "DMS", "DOME imaging systems" }, - { "DMT", "Distributed Management Task Force, Inc. (DMTF)" }, - { "DMV", "NDS Ltd" }, - { "DNA", "DNA Enterprises, Inc." }, - { "DNG", "Apache Micro Peripherals Inc" }, - { "DNI", "Deterministic Networks Inc." }, - { "DNT", "Dr. Neuhous Telekommunikation GmbH" }, - { "DNV", "DiCon" }, - { "DOL", "Dolman Technologies Group Inc" }, - { "DOM", "Dome Imaging Systems" }, - { "DON", "DENON, Ltd." }, - { "DOT", "Dotronic Mikroelektronik GmbH" }, - { "DPA", "DigiTalk Pro AV" }, - { "DPC", "Delta Electronics Inc" }, - { "DPI", "DocuPoint" }, - { "DPL", "Digital Projection Limited" }, - { "DPM", "ADPM Synthesis sas" }, - { "DPS", "Digital Processing Systems" }, - { "DPT", "DPT" }, - { "DPX", "DpiX, Inc." }, - { "DQB", "Datacube Inc" }, - { "DRB", "Dr. Bott KG" }, - { "DRC", "Data Ray Corp." }, - { "DRD", "DIGITAL REFLECTION INC." }, - { "DRI", "Data Race Inc" }, - { "DRS", "DRS Defense Solutions, LLC" }, - { "DSD", "DS Multimedia Pte Ltd" }, - { "DSI", "Digitan Systems Inc" }, - { "DSM", "DSM Digital Services GmbH" }, - { "DSP", "Domain Technology Inc" }, - { "DTA", "DELTATEC" }, - { "DTC", "DTC Tech Corporation" }, - { "DTE", "Dimension Technologies, Inc." }, - { "DTI", "Diversified Technology, Inc." }, - { "DTK", "Dynax Electronics (HK) Ltd" }, - { "DTL", "e-Net Inc" }, - { "DTN", "Datang Telephone Co" }, - { "DTO", "Deutsche Thomson OHG" }, - { "DTT", "Design & Test Technology, Inc." }, - { "DTX", "Data Translation" }, - { "DUA", "Dosch & Amand GmbH & Company KG" }, - { "DUN", "NCR Corporation" }, - { "DVD", "Dictaphone Corporation" }, - { "DVL", "Devolo AG" }, - { "DVS", "Digital Video System" }, - { "DVT", "Data Video" }, - { "DWE", "Daewoo Electronics Company Ltd" }, - { "DXC", "Digipronix Control Systems" }, - { "DXD", "DECIMATOR DESIGN PTY LTD" }, - { "DXL", "Dextera Labs Inc" }, - { "DXP", "Data Expert Corporation" }, - { "DXS", "Signet" }, - { "DYC", "Dycam Inc" }, - { "DYM", "Dymo-CoStar Corporation" }, - { "DYN", "Askey Computer Corporation" }, - { "DYX", "Dynax Electronics (HK) Ltd" }, - { "EAS", "Evans and Sutherland Computer" }, - { "EBH", "Data Price Informatica" }, - { "EBT", "HUALONG TECHNOLOGY CO., LTD" }, - { "ECA", "Electro Cam Corp." }, - { "ECC", "ESSential Comm. Corporation" }, - { "ECI", "Enciris Technologies" }, - { "ECK", "Eugene Chukhlomin Sole Proprietorship, d.b.a." }, - { "ECL", "Excel Company Ltd" }, - { "ECM", "E-Cmos Tech Corporation" }, - { "ECO", "Echo Speech Corporation" }, - { "ECP", "Elecom Company Ltd" }, - { "ECS", "Elitegroup Computer Systems Company Ltd" }, - { "ECT", "Enciris Technologies" }, - { "EDC", "e.Digital Corporation" }, - { "EDG", "Electronic-Design GmbH" }, - { "EDI", "Edimax Tech. Company Ltd" }, - { "EDM", "EDMI" }, - { "EDT", "Emerging Display Technologies Corp" }, - { "EEE", "ET&T Technology Company Ltd" }, - { "EEH", "EEH Datalink GmbH" }, - { "EEP", "E.E.P.D. GmbH" }, - { "EES", "EE Solutions, Inc." }, - { "EGA", "Elgato Systems LLC" }, - { "EGD", "EIZO GmbH Display Technologies" }, - { "EGL", "Eagle Technology" }, - { "EGN", "Egenera, Inc." }, - { "EGO", "Ergo Electronics" }, - { "EHJ", "Epson Research" }, - { "EHN", "Enhansoft" }, - { "EIC", "Eicon Technology Corporation" }, - { "EKA", "MagTek Inc." }, - { "EKC", "Eastman Kodak Company" }, - { "EKS", "EKSEN YAZILIM" }, - { "ELA", "ELAD srl" }, - { "ELC", "Electro Scientific Ind" }, - { "ELE", "Elecom Company Ltd" }, - { "ELG", "Elmeg GmbH Kommunikationstechnik" }, - { "ELI", "Edsun Laboratories" }, - { "ELL", "Electrosonic Ltd" }, - { "ELM", "Elmic Systems Inc" }, - { "ELO", "Tyco Electronics" }, - { "ELS", "ELSA GmbH" }, - { "ELT", "Element Labs, Inc." }, - { "ELX", "Elonex PLC" }, - { "EMB", "Embedded computing inc ltd" }, - { "EMC", "eMicro Corporation" }, - { "EME", "EMiNE TECHNOLOGY COMPANY, LTD." }, - { "EMG", "EMG Consultants Inc" }, - { "EMI", "Ex Machina Inc" }, - { "EMK", "Emcore Corporation" }, - { "EMO", "ELMO COMPANY, LIMITED" }, - { "EMU", "Emulex Corporation" }, - { "ENC", "Eizo Nanao Corporation" }, - { "END", "ENIDAN Technologies Ltd" }, - { "ENE", "ENE Technology Inc." }, - { "ENI", "Efficient Networks" }, - { "ENS", "Ensoniq Corporation" }, - { "ENT", "Enterprise Comm. & Computing Inc" }, - { "EPC", "Empac" }, - { "EPH", "Epiphan Systems Inc." }, - { "EPI", "Envision Peripherals, Inc" }, - { "EPN", "EPiCON Inc." }, - { "EPS", "KEPS" }, - { "EQP", "Equipe Electronics Ltd." }, - { "EQX", "Equinox Systems Inc" }, - { "ERG", "Ergo System" }, - { "ERI", "Ericsson Mobile Communications AB" }, - { "ERN", "Ericsson, Inc." }, - { "ERP", "Euraplan GmbH" }, - { "ERT", "Escort Insturments Corporation" }, - { "ESA", "Elbit Systems of America" }, - { "ESC", "Eden Sistemas de Computacao S/A" }, - { "ESD", "Ensemble Designs, Inc" }, - { "ESG", "ELCON Systemtechnik GmbH" }, - { "ESI", "Extended Systems, Inc." }, - { "ESK", "ES&S" }, - { "ESL", "Esterline Technologies" }, - { "ESN", "eSATURNUS" }, - { "ESS", "ESS Technology Inc" }, - { "EST", "Embedded Solution Technology" }, - { "ESY", "E-Systems Inc" }, - { "ETC", "Everton Technology Company Ltd" }, - { "ETD", "ELAN MICROELECTRONICS CORPORATION" }, - { "ETH", "Etherboot Project" }, - { "ETI", "Eclipse Tech Inc" }, - { "ETK", "eTEK Labs Inc." }, - { "ETL", "Evertz Microsystems Ltd." }, - { "ETS", "Electronic Trade Solutions Ltd" }, - { "ETT", "E-Tech Inc" }, - { "EUT", "Ericsson Mobile Networks B.V." }, - { "EVE", "Advanced Micro Peripherals Ltd" }, - { "EVI", "eviateg GmbH" }, - { "EVX", "Everex" }, - { "EXA", "Exabyte" }, - { "EXC", "Excession Audio" }, - { "EXI", "Exide Electronics" }, - { "EXN", "RGB Systems, Inc. dba Extron Electronics" }, - { "EXP", "Data Export Corporation" }, - { "EXT", "Exatech Computadores & Servicos Ltda" }, - { "EXX", "Exxact GmbH" }, - { "EXY", "Exterity Ltd" }, - { "EYE", "eyevis GmbH" }, - { "EZE", "EzE Technologies" }, - { "EZP", "Storm Technology" }, - { "FAR", "Farallon Computing" }, - { "FBI", "Interface Corporation" }, - { "FCB", "Furukawa Electric Company Ltd" }, - { "FCG", "First International Computer Ltd" }, - { "FCS", "Focus Enhancements, Inc." }, - { "FDC", "Future Domain" }, - { "FDT", "Fujitsu Display Technologies Corp." }, - { "FEC", "FURUNO ELECTRIC CO., LTD." }, - { "FEL", "Fellowes & Questec" }, - { "FEN", "Fen Systems Ltd." }, - { "FER", "Ferranti Int'L" }, - { "FFC", "FUJIFILM Corporation" }, - { "FFI", "Fairfield Industries" }, - { "FGD", "Lisa Draexlmaier GmbH" }, - { "FGL", "Fujitsu General Limited." }, - { "FHL", "FHLP" }, - { "FIC", "Formosa Industrial Computing Inc" }, - { "FIL", "Forefront Int'l Ltd" }, - { "FIN", "Finecom Co., Ltd." }, - { "FIR", "Chaplet Systems Inc" }, - { "FIS", "FLY-IT Simulators" }, - { "FIT", "Feature Integration Technology Inc." }, - { "FJC", "Fujitsu Takamisawa Component Limited" }, - { "FJS", "Fujitsu Spain" }, - { "FJT", "F.J. Tieman BV" }, - { "FLE", "ADTI Media, Inc" }, - { "FLI", "Faroudja Laboratories" }, - { "FLY", "Butterfly Communications" }, - { "FMA", "Fast Multimedia AG" }, - { "FMC", "Ford Microelectronics Inc" }, - { "FMI", "Fujitsu Microelect Inc" }, - { "FML", "Fujitsu Microelect Ltd" }, - { "FMZ", "Formoza-Altair" }, - { "FNC", "Fanuc LTD" }, - { "FNI", "Funai Electric Co., Ltd." }, - { "FOA", "FOR-A Company Limited" }, - { "FOS", "Foss Tecator" }, - { "FOX", "HON HAI PRECISON IND.CO.,LTD." }, - { "FPE", "Fujitsu Peripherals Ltd" }, - { "FPS", "Deltec Corporation" }, - { "FPX", "Cirel Systemes" }, - { "FRC", "Force Computers" }, - { "FRD", "Freedom Scientific BLV" }, - { "FRE", "Forvus Research Inc" }, - { "FRI", "Fibernet Research Inc" }, - { "FRO", "FARO Technologies" }, - { "FRS", "South Mountain Technologies, LTD" }, - { "FSC", "Future Systems Consulting KK" }, - { "FSI", "Fore Systems Inc" }, - { "FST", "Modesto PC Inc" }, - { "FTC", "Futuretouch Corporation" }, - { "FTE", "Frontline Test Equipment Inc." }, - { "FTG", "FTG Data Systems" }, - { "FTI", "FastPoint Technologies, Inc." }, - { "FTL", "FUJITSU TEN LIMITED" }, - { "FTN", "Fountain Technologies Inc" }, - { "FTR", "Mediasonic" }, - { "FTW", "MindTribe Product Engineering, Inc." }, - { "FUJ", "Fujitsu Ltd" }, - { "FUN", "sisel muhendislik" }, - { "FUS", "Fujitsu Siemens Computers GmbH" }, - { "FVC", "First Virtual Corporation" }, - { "FVX", "C-C-C Group Plc" }, - { "FWA", "Attero Tech, LLC" }, - { "FWR", "Flat Connections Inc" }, - { "FXX", "Fuji Xerox" }, - { "FZC", "Founder Group Shenzhen Co." }, - { "FZI", "FZI Forschungszentrum Informatik" }, - { "GAG", "Gage Applied Sciences Inc" }, - { "GAL", "Galil Motion Control" }, - { "GAU", "Gaudi Co., Ltd." }, - { "GCC", "GCC Technologies Inc" }, - { "GCI", "Gateway Comm. Inc" }, - { "GCS", "Grey Cell Systems Ltd" }, - { "GDC", "General Datacom" }, - { "GDI", "G. Diehl ISDN GmbH" }, - { "GDS", "GDS" }, - { "GDT", "Vortex Computersysteme GmbH" }, - { "GED", "General Dynamics C4 Systems" }, - { "GEF", "GE Fanuc Embedded Systems" }, - { "GEH", "GE Intelligent Platforms - Huntsville" }, - { "GEM", "Gem Plus" }, - { "GEN", "Genesys ATE Inc" }, - { "GEO", "GEO Sense" }, - { "GER", "GERMANEERS GmbH" }, - { "GES", "GES Singapore Pte Ltd" }, - { "GET", "Getac Technology Corporation" }, - { "GFM", "GFMesstechnik GmbH" }, - { "GFN", "Gefen Inc." }, - { "GGL", "Google Inc." }, - { "GIC", "General Inst. Corporation" }, - { "GIM", "Guillemont International" }, - { "GIP", "GI Provision Ltd" }, - { "GIS", "AT&T Global Info Solutions" }, - { "GJN", "Grand Junction Networks" }, - { "GLD", "Goldmund - Digital Audio SA" }, - { "GLE", "AD electronics" }, - { "GLM", "Genesys Logic" }, - { "GLS", "Gadget Labs LLC" }, - { "GMK", "GMK Electronic Design GmbH" }, - { "GML", "General Information Systems" }, - { "GMM", "GMM Research Inc" }, - { "GMN", "GEMINI 2000 Ltd" }, - { "GMX", "GMX Inc" }, - { "GND", "Gennum Corporation" }, - { "GNN", "GN Nettest Inc" }, - { "GNZ", "Gunze Ltd" }, - { "GRA", "Graphica Computer" }, - { "GRE", "GOLD RAIN ENTERPRISES CORP." }, - { "GRH", "Granch Ltd" }, - { "GRM", "Garmin International" }, - { "GRV", "Advanced Gravis" }, - { "GRY", "Robert Gray Company" }, - { "GSB", "NIPPONDENCHI CO,.LTD" }, - { "GSC", "General Standards Corporation" }, - { "GSM", "LG Electronics" }, - { "GST", "Graphic SystemTechnology" }, - { "GSY", "Grossenbacher Systeme AG" }, - { "GTC", "Graphtec Corporation" }, - { "GTI", "Goldtouch" }, - { "GTK", "G-Tech Corporation" }, - { "GTM", "Garnet System Company Ltd" }, - { "GTS", "Geotest Marvin Test Systems Inc" }, - { "GTT", "General Touch Technology Co., Ltd." }, - { "GUD", "Guntermann & Drunck GmbH" }, - { "GUZ", "Guzik Technical Enterprises" }, - { "GVC", "GVC Corporation" }, - { "GVL", "Global Village Communication" }, - { "GWI", "GW Instruments" }, - { "GWY", "Gateway 2000" }, - { "GZE", "GUNZE Limited" }, - { "HAE", "Haider electronics" }, - { "HAI", "Haivision Systems Inc." }, - { "HAL", "Halberthal" }, - { "HAN", "Hanchang System Corporation" }, - { "HAR", "Harris Corporation" }, - { "HAY", "Hayes Microcomputer Products Inc" }, - { "HCA", "DAT" }, - { "HCE", "Hitachi Consumer Electronics Co., Ltd" }, - { "HCL", "HCL America Inc" }, - { "HCM", "HCL Peripherals" }, - { "HCP", "Hitachi Computer Products Inc" }, - { "HCW", "Hauppauge Computer Works Inc" }, - { "HDC", "HardCom Elektronik & Datateknik" }, - { "HDI", "HD-INFO d.o.o." }, - { "HDV", "Holografika kft." }, - { "HEC", "Hitachi Engineering Company Ltd" }, - { "HEL", "Hitachi Micro Systems Europe Ltd" }, - { "HER", "Ascom Business Systems" }, - { "HET", "HETEC Datensysteme GmbH" }, - { "HHC", "HIRAKAWA HEWTECH CORP." }, - { "HHI", "Fraunhofer Heinrich-Hertz-Institute" }, - { "HIB", "Hibino Corporation" }, - { "HIC", "Hitachi Information Technology Co., Ltd." }, - { "HIK", "Hikom Co., Ltd." }, - { "HIL", "Hilevel Technology" }, - { "HIQ", "Kaohsiung Opto Electronics Americas, Inc." }, - { "HIT", "Hitachi America Ltd" }, - { "HJI", "Harris & Jeffries Inc" }, - { "HKA", "HONKO MFG. CO., LTD." }, - { "HKG", "Josef Heim KG" }, - { "HMC", "Hualon Microelectric Corporation" }, - { "HMK", "hmk Daten-System-Technik BmbH" }, - { "HMX", "HUMAX Co., Ltd." }, - { "HNS", "Hughes Network Systems" }, - { "HOB", "HOB Electronic GmbH" }, - { "HOE", "Hosiden Corporation" }, - { "HOL", "Holoeye Photonics AG" }, - { "HON", "Sonitronix" }, - { "HPA", "Zytor Communications" }, - { "HPC", "Hewlett Packard Co." }, - { "HPD", "Hewlett Packard" }, - { "HPI", "Headplay, Inc." }, - { "HPK", "HAMAMATSU PHOTONICS K.K." }, - { "HPQ", "HP" }, - { "HPR", "H.P.R. Electronics GmbH" }, - { "HRC", "Hercules" }, - { "HRE", "Qingdao Haier Electronics Co., Ltd." }, - { "HRI", "Hall Research" }, - { "HRL", "Herolab GmbH" }, - { "HRS", "Harris Semiconductor" }, - { "HRT", "HERCULES" }, - { "HSC", "Hagiwara Sys-Com Company Ltd" }, - { "HSD", "HannStar Display Corp" }, - { "HSM", "AT&T Microelectronics" }, - { "HSP", "HannStar Display Corp" }, - { "HTC", "Hitachi Ltd" }, - { "HTI", "Hampshire Company, Inc." }, - { "HTK", "Holtek Microelectronics Inc" }, - { "HTX", "Hitex Systementwicklung GmbH" }, - { "HUB", "GAI-Tronics, A Hubbell Company" }, - { "HUM", "IMP Electronics Ltd." }, - { "HWA", "Harris Canada Inc" }, - { "HWC", "DBA Hans Wedemeyer" }, - { "HWD", "Highwater Designs Ltd" }, - { "HWP", "Hewlett Packard" }, - { "HXM", "Hexium Ltd." }, - { "HYC", "Hypercope Gmbh Aachen" }, - { "HYD", "Hydis Technologies.Co.,LTD" }, - { "HYO", "HYC CO., LTD." }, - { "HYP", "Hyphen Ltd" }, - { "HYR", "Hypertec Pty Ltd" }, - { "HYT", "Heng Yu Technology (HK) Limited" }, - { "HYV", "Hynix Semiconductor" }, - { "IAF", "Institut f r angewandte Funksystemtechnik GmbH" }, - { "IAI", "Integration Associates, Inc." }, - { "IAT", "IAT Germany GmbH" }, - { "IBC", "Integrated Business Systems" }, - { "IBI", "INBINE.CO.LTD" }, - { "IBM", "IBM France" }, - { "IBP", "IBP Instruments GmbH" }, - { "IBR", "IBR GmbH" }, - { "ICA", "ICA Inc" }, - { "ICC", "BICC Data Networks Ltd" }, - { "ICD", "ICD Inc" }, - { "ICE", "IC Ensemble" }, - { "ICI", "Infotek Communication Inc" }, - { "ICM", "Intracom SA" }, - { "ICN", "Sanyo Icon" }, - { "ICO", "Intel Corp" }, - { "ICP", "ICP Electronics, Inc./iEi Technology Corp." }, - { "ICS", "Integrated Circuit Systems" }, - { "ICV", "Inside Contactless" }, - { "ICX", "ICCC A/S" }, - { "IDC", "International Datacasting Corporation" }, - { "IDE", "IDE Associates" }, - { "IDK", "IDK Corporation" }, - { "IDN", "Idneo Technologies" }, - { "IDO", "IDEO Product Development" }, - { "IDP", "Integrated Device Technology, Inc." }, - { "IDS", "Interdigital Sistemas de Informacao" }, - { "IDT", "International Display Technology" }, - { "IDX", "IDEXX Labs" }, - { "IEC", "Interlace Engineering Corporation" }, - { "IEE", "IEE" }, - { "IEI", "Interlink Electronics" }, - { "IFS", "In Focus Systems Inc" }, - { "IFT", "Informtech" }, - { "IFX", "Infineon Technologies AG" }, - { "IFZ", "Infinite Z" }, - { "IGC", "Intergate Pty Ltd" }, - { "IGM", "IGM Communi" }, - { "IHE", "InHand Electronics" }, - { "IIC", "ISIC Innoscan Industrial Computers A/S" }, - { "III", "Intelligent Instrumentation" }, - { "IIN", "IINFRA Co., Ltd" }, - { "IKS", "Ikos Systems Inc" }, - { "ILC", "Image Logic Corporation" }, - { "ILS", "Innotech Corporation" }, - { "IMA", "Imagraph" }, - { "IMB", "ART s.r.l." }, - { "IMC", "IMC Networks" }, - { "IMD", "ImasDe Canarias S.A." }, - { "IME", "Imagraph" }, - { "IMG", "IMAGENICS Co., Ltd." }, - { "IMI", "International Microsystems Inc" }, - { "IMM", "Immersion Corporation" }, - { "IMN", "Impossible Production" }, - { "IMP", "Impression Products Incorporated" }, - { "IMT", "Inmax Technology Corporation" }, - { "INC", "Home Row Inc" }, - { "IND", "ILC" }, - { "INE", "Inventec Electronics (M) Sdn. Bhd." }, - { "INF", "Inframetrics Inc" }, - { "ING", "Integraph Corporation" }, - { "INI", "Initio Corporation" }, - { "INK", "Indtek Co., Ltd." }, - { "INL", "InnoLux Display Corporation" }, - { "INM", "InnoMedia Inc" }, - { "INN", "Innovent Systems, Inc." }, - { "INO", "Innolab Pte Ltd" }, - { "INP", "Interphase Corporation" }, - { "INS", "Ines GmbH" }, - { "INT", "Interphase Corporation" }, - { "INU", "Inovatec S.p.A." }, - { "INV", "Inviso, Inc." }, - { "INX", "Communications Supply Corporation (A division of WESCO)" }, - { "INZ", "Best Buy" }, - { "IOA", "CRE Technology Corporation" }, - { "IOD", "I-O Data Device Inc" }, - { "IOM", "Iomega" }, - { "ION", "Inside Out Networks" }, - { "IOS", "i-O Display System" }, - { "IOT", "I/OTech Inc" }, - { "IPC", "IPC Corporation" }, - { "IPD", "Industrial Products Design, Inc." }, - { "IPI", "Intelligent Platform Management Interface (IPMI) forum (Intel, HP, NEC, Dell)" }, - { "IPM", "IPM Industria Politecnica Meridionale SpA" }, - { "IPN", "Performance Technologies" }, - { "IPP", "IP Power Technologies GmbH" }, - { "IPR", "Ithaca Peripherals" }, - { "IPS", "IPS, Inc. (Intellectual Property Solutions, Inc.)" }, - { "IPT", "International Power Technologies" }, - { "IPW", "IPWireless, Inc" }, - { "IQI", "IneoQuest Technologies, Inc" }, - { "IQT", "IMAGEQUEST Co., Ltd" }, - { "IRD", "IRdata" }, - { "ISA", "Symbol Technologies" }, - { "ISC", "Id3 Semiconductors" }, - { "ISG", "Insignia Solutions Inc" }, - { "ISI", "Interface Solutions" }, - { "ISL", "Isolation Systems" }, - { "ISM", "Image Stream Medical" }, - { "ISP", "IntreSource Systems Pte Ltd" }, - { "ISR", "INSIS Co., LTD." }, - { "ISS", "ISS Inc" }, - { "IST", "Intersolve Technologies" }, - { "ISY", "International Integrated Systems,Inc.(IISI)" }, - { "ITA", "Itausa Export North America" }, - { "ITC", "Intercom Inc" }, - { "ITD", "Internet Technology Corporation" }, - { "ITE", "Integrated Tech Express Inc" }, - { "ITK", "ITK Telekommunikation AG" }, - { "ITL", "Inter-Tel" }, - { "ITM", "ITM inc." }, - { "ITN", "The NTI Group" }, - { "ITP", "IT-PRO Consulting und Systemhaus GmbH" }, - { "ITR", "Infotronic America, Inc." }, - { "ITS", "IDTECH" }, - { "ITT", "I&T Telecom." }, - { "ITX", "integrated Technology Express Inc" }, - { "IUC", "ICSL" }, - { "IVI", "Intervoice Inc" }, - { "IVM", "Iiyama North America" }, - { "IVS", "Intevac Photonics Inc." }, - { "IWR", "Icuiti Corporation" }, - { "IWX", "Intelliworxx, Inc." }, - { "IXD", "Intertex Data AB" }, - { "JAC", "Astec Inc" }, - { "JAE", "Japan Aviation Electronics Industry, Limited" }, - { "JAS", "Janz Automationssysteme AG" }, - { "JAT", "Jaton Corporation" }, - { "JAZ", "Carrera Computer Inc" }, - { "JCE", "Jace Tech Inc" }, - { "JDL", "Japan Digital Laboratory Co.,Ltd." }, - { "JEN", "N-Vision" }, - { "JET", "JET POWER TECHNOLOGY CO., LTD." }, - { "JFX", "Jones Futurex Inc" }, - { "JGD", "University College" }, - { "JIC", "Jaeik Information & Communication Co., Ltd." }, - { "JKC", "JVC KENWOOD Corporation" }, - { "JMT", "Micro Technical Company Ltd" }, - { "JPC", "JPC Technology Limited" }, - { "JPW", "Wallis Hamilton Industries" }, - { "JQE", "CNet Technical Inc" }, - { "JSD", "JS DigiTech, Inc" }, - { "JSI", "Jupiter Systems, Inc." }, - { "JSK", "SANKEN ELECTRIC CO., LTD" }, - { "JTS", "JS Motorsports" }, - { "JTY", "jetway security micro,inc" }, - { "JUK", "Janich & Klass Computertechnik GmbH" }, - { "JUP", "Jupiter Systems" }, - { "JVC", "JVC" }, - { "JWD", "Video International Inc." }, - { "JWL", "Jewell Instruments, LLC" }, - { "JWS", "JWSpencer & Co." }, - { "JWY", "Jetway Information Co., Ltd" }, - { "KAR", "Karna" }, - { "KBI", "Kidboard Inc" }, - { "KBL", "Kobil Systems GmbH" }, - { "KCD", "Chunichi Denshi Co.,LTD." }, - { "KCL", "Keycorp Ltd" }, - { "KDE", "KDE" }, - { "KDK", "Kodiak Tech" }, - { "KDM", "Korea Data Systems Co., Ltd." }, - { "KDS", "KDS USA" }, - { "KDT", "KDDI Technology Corporation" }, - { "KEC", "Kyushu Electronics Systems Inc" }, - { "KEM", "Kontron Embedded Modules GmbH" }, - { "KES", "Kesa Corporation" }, - { "KEY", "Key Tech Inc" }, - { "KFC", "SCD Tech" }, - { "KFE", "Komatsu Forest" }, - { "KFX", "Kofax Image Products" }, - { "KGL", "KEISOKU GIKEN Co.,Ltd." }, - { "KIS", "KiSS Technology A/S" }, - { "KMC", "Mitsumi Company Ltd" }, - { "KME", "KIMIN Electronics Co., Ltd." }, - { "KML", "Kensington Microware Ltd" }, - { "KNC", "Konica corporation" }, - { "KNX", "Nutech Marketing PTL" }, - { "KOB", "Kobil Systems GmbH" }, - { "KOD", "Eastman Kodak Company" }, - { "KOE", "KOLTER ELECTRONIC" }, - { "KOL", "Kollmorgen Motion Technologies Group" }, - { "KOU", "KOUZIRO Co.,Ltd." }, - { "KOW", "KOWA Company,LTD." }, - { "KPC", "King Phoenix Company" }, - { "KRL", "Krell Industries Inc." }, - { "KRM", "Kroma Telecom" }, - { "KRY", "Kroy LLC" }, - { "KSC", "Kinetic Systems Corporation" }, - { "KSL", "Karn Solutions Ltd." }, - { "KSX", "King Tester Corporation" }, - { "KTC", "Kingston Tech Corporation" }, - { "KTD", "Takahata Electronics Co.,Ltd." }, - { "KTE", "K-Tech" }, - { "KTG", "Kayser-Threde GmbH" }, - { "KTI", "Konica Technical Inc" }, - { "KTK", "Key Tronic Corporation" }, - { "KTN", "Katron Tech Inc" }, - { "KUR", "Kurta Corporation" }, - { "KVA", "Kvaser AB" }, - { "KVX", "KeyView" }, - { "KWD", "Kenwood Corporation" }, - { "KYC", "Kyocera Corporation" }, - { "KYE", "KYE Syst Corporation" }, - { "KYK", "Samsung Electronics America Inc" }, - { "KZI", "K-Zone International co. Ltd." }, - { "KZN", "K-Zone International" }, - { "LAB", "ACT Labs Ltd" }, - { "LAC", "LaCie" }, - { "LAF", "Microline" }, - { "LAG", "Laguna Systems" }, - { "LAN", "Sodeman Lancom Inc" }, - { "LAS", "LASAT Comm. A/S" }, - { "LAV", "Lava Computer MFG Inc" }, - { "LBO", "Lubosoft" }, - { "LCC", "LCI" }, - { "LCD", "Toshiba Matsushita Display Technology Co., Ltd" }, - { "LCE", "La Commande Electronique" }, - { "LCI", "Lite-On Communication Inc" }, - { "LCM", "Latitude Comm." }, - { "LCN", "LEXICON" }, - { "LCS", "Longshine Electronics Company" }, - { "LCT", "Labcal Technologies" }, - { "LDT", "LogiDataTech Electronic GmbH" }, - { "LEC", "Lectron Company Ltd" }, - { "LED", "Long Engineering Design Inc" }, - { "LEG", "Legerity, Inc" }, - { "LEN", "Lenovo Group Limited" }, - { "LEO", "First International Computer Inc" }, - { "LEX", "Lexical Ltd" }, - { "LGC", "Logic Ltd" }, - { "LGI", "Logitech Inc" }, - { "LGS", "LG Semicom Company Ltd" }, - { "LGX", "Lasergraphics, Inc." }, - { "LHA", "Lars Haagh ApS" }, - { "LHE", "Lung Hwa Electronics Company Ltd" }, - { "LHT", "Lighthouse Technologies Limited" }, - { "LIN", "Lenovo Beijing Co. Ltd." }, - { "LIP", "Linked IP GmbH" }, - { "LIT", "Lithics Silicon Technology" }, - { "LJX", "Datalogic Corporation" }, - { "LKM", "Likom Technology Sdn. Bhd." }, - { "LLL", "L-3 Communications" }, - { "LMG", "Lucent Technologies" }, - { "LMI", "Lexmark Int'l Inc" }, - { "LMP", "Leda Media Products" }, - { "LMT", "Laser Master" }, - { "LND", "Land Computer Company Ltd" }, - { "LNK", "Link Tech Inc" }, - { "LNR", "Linear Systems Ltd." }, - { "LNT", "LANETCO International" }, - { "LNV", "Lenovo" }, - { "LOC", "Locamation B.V." }, - { "LOE", "Loewe Opta GmbH" }, - { "LOG", "Logicode Technology Inc" }, - { "LOL", "Litelogic Operations Ltd" }, - { "LPE", "El-PUSK Co., Ltd." }, - { "LPI", "Design Technology" }, - { "LPL", "LG Philips" }, - { "LSC", "LifeSize Communications" }, - { "LSD", "Intersil Corporation" }, - { "LSI", "Loughborough Sound Images" }, - { "LSJ", "LSI Japan Company Ltd" }, - { "LSL", "Logical Solutions" }, - { "LSY", "LSI Systems Inc" }, - { "LTC", "Labtec Inc" }, - { "LTI", "Jongshine Tech Inc" }, - { "LTK", "Lucidity Technology Company Ltd" }, - { "LTN", "Litronic Inc" }, - { "LTS", "LTS Scale LLC" }, - { "LTV", "Leitch Technology International Inc." }, - { "LTW", "Lightware, Inc" }, - { "LUC", "Lucent Technologies" }, - { "LUM", "Lumagen, Inc." }, - { "LUX", "Luxxell Research Inc" }, - { "LVI", "LVI Low Vision International AB" }, - { "LWC", "Labway Corporation" }, - { "LWR", "Lightware Visual Engineering" }, - { "LWW", "Lanier Worldwide" }, - { "LXC", "LXCO Technologies AG" }, - { "LXN", "Luxeon" }, - { "LXS", "ELEA CardWare" }, - { "LZX", "Lightwell Company Ltd" }, - { "MAC", "MAC System Company Ltd" }, - { "MAD", "Xedia Corporation" }, - { "MAE", "Maestro Pty Ltd" }, - { "MAG", "MAG InnoVision" }, - { "MAI", "Mutoh America Inc" }, - { "MAL", "Meridian Audio Ltd" }, - { "MAN", "LGIC" }, - { "MAS", "Mass Inc." }, - { "MAT", "Matsushita Electric Ind. Company Ltd" }, - { "MAX", "Rogen Tech Distribution Inc" }, - { "MAY", "Maynard Electronics" }, - { "MAZ", "MAZeT GmbH" }, - { "MBC", "MBC" }, - { "MBD", "Microbus PLC" }, - { "MBM", "Marshall Electronics" }, - { "MBV", "Moreton Bay" }, - { "MCA", "American Nuclear Systems Inc" }, - { "MCC", "Micro Industries" }, - { "MCD", "McDATA Corporation" }, - { "MCE", "Metz-Werke GmbH & Co KG" }, - { "MCG", "Motorola Computer Group" }, - { "MCI", "Micronics Computers" }, - { "MCL", "Motorola Communications Israel" }, - { "MCM", "Metricom Inc" }, - { "MCN", "Micron Electronics Inc" }, - { "MCO", "Motion Computing Inc." }, - { "MCP", "Magni Systems Inc" }, - { "MCQ", "Mat's Computers" }, - { "MCR", "Marina Communicaitons" }, - { "MCS", "Micro Computer Systems" }, - { "MCT", "Microtec" }, - { "MDA", "Media4 Inc" }, - { "MDC", "Midori Electronics" }, - { "MDD", "MODIS" }, - { "MDG", "Madge Networks" }, - { "MDI", "Micro Design Inc" }, - { "MDK", "Mediatek Corporation" }, - { "MDO", "Panasonic" }, - { "MDR", "Medar Inc" }, - { "MDS", "Micro Display Systems Inc" }, - { "MDT", "Magus Data Tech" }, - { "MDV", "MET Development Inc" }, - { "MDX", "MicroDatec GmbH" }, - { "MDY", "Microdyne Inc" }, - { "MEC", "Mega System Technologies Inc" }, - { "MED", "Messeltronik Dresden GmbH" }, - { "MEE", "Mitsubishi Electric Engineering Co., Ltd." }, - { "MEG", "Abeam Tech Ltd" }, - { "MEI", "Panasonic Industry Company" }, - { "MEJ", "Mac-Eight Co., LTD." }, - { "MEL", "Mitsubishi Electric Corporation" }, - { "MEN", "MEN Mikroelectronik Nueruberg GmbH" }, - { "MEP", "Meld Technology" }, - { "MEQ", "Matelect Ltd." }, - { "MET", "Metheus Corporation" }, - { "MEX", "MSC Vertriebs GmbH" }, - { "MFG", "MicroField Graphics Inc" }, - { "MFI", "Micro Firmware" }, - { "MFR", "MediaFire Corp." }, - { "MGA", "Mega System Technologies, Inc." }, - { "MGC", "Mentor Graphics Corporation" }, - { "MGE", "Schneider Electric S.A." }, - { "MGL", "M-G Technology Ltd" }, - { "MGT", "Megatech R & D Company" }, - { "MIC", "Micom Communications Inc" }, - { "MID", "miro Displays" }, - { "MII", "Mitec Inc" }, - { "MIL", "Marconi Instruments Ltd" }, - { "MIM", "Mimio – A Newell Rubbermaid Company" }, - { "MIN", "Minicom Digital Signage" }, - { "MIP", "micronpc.com" }, - { "MIR", "Miro Computer Prod." }, - { "MIS", "Modular Industrial Solutions Inc" }, - { "MIT", "MCM Industrial Technology GmbH" }, - { "MJI", "MARANTZ JAPAN, INC." }, - { "MJS", "MJS Designs" }, - { "MKC", "Media Tek Inc." }, - { "MKT", "MICROTEK Inc." }, - { "MKV", "Trtheim Technology" }, - { "MLD", "Deep Video Imaging Ltd" }, - { "MLG", "Micrologica AG" }, - { "MLI", "McIntosh Laboratory Inc." }, - { "MLM", "Millennium Engineering Inc" }, - { "MLN", "Mark Levinson" }, - { "MLS", "Milestone EPE" }, - { "MLX", "Mylex Corporation" }, - { "MMA", "Micromedia AG" }, - { "MMD", "Micromed Biotecnologia Ltd" }, - { "MMF", "Minnesota Mining and Manufacturing" }, - { "MMI", "Multimax" }, - { "MMM", "Electronic Measurements" }, - { "MMN", "MiniMan Inc" }, - { "MMS", "MMS Electronics" }, - { "MNC", "Mini Micro Methods Ltd" }, - { "MNL", "Monorail Inc" }, - { "MNP", "Microcom" }, - { "MOD", "Modular Technology" }, - { "MOM", "Momentum Data Systems" }, - { "MOS", "Moses Corporation" }, - { "MOT", "Motorola UDS" }, - { "MPC", "M-Pact Inc" }, - { "MPI", "Mediatrix Peripherals Inc" }, - { "MPJ", "Microlab" }, - { "MPL", "Maple Research Inst. Company Ltd" }, - { "MPN", "Mainpine Limited" }, - { "MPS", "mps Software GmbH" }, - { "MPX", "Micropix Technologies, Ltd." }, - { "MQP", "MultiQ Products AB" }, - { "MRA", "Miranda Technologies Inc" }, - { "MRC", "Marconi Simulation & Ty-Coch Way Training" }, - { "MRD", "MicroDisplay Corporation" }, - { "MRK", "Maruko & Company Ltd" }, - { "MRL", "Miratel" }, - { "MRO", "Medikro Oy" }, - { "MRT", "Merging Technologies" }, - { "MSA", "Micro Systemation AB" }, - { "MSC", "Mouse Systems Corporation" }, - { "MSD", "Datenerfassungs- und Informationssysteme" }, - { "MSF", "M-Systems Flash Disk Pioneers" }, - { "MSG", "MSI GmbH" }, - { "MSH", "Microsoft" }, - { "MSI", "Microstep" }, - { "MSK", "Megasoft Inc" }, - { "MSL", "MicroSlate Inc." }, - { "MSM", "Advanced Digital Systems" }, - { "MSP", "Mistral Solutions [P] Ltd." }, - { "MSR", "MASPRO DENKOH Corp." }, - { "MST", "MS Telematica" }, - { "MSU", "motorola" }, - { "MSV", "Mosgi Corporation" }, - { "MSX", "Micomsoft Co., Ltd." }, - { "MSY", "MicroTouch Systems Inc" }, - { "MTB", "Media Technologies Ltd." }, - { "MTC", "Mars-Tech Corporation" }, - { "MTD", "MindTech Display Co. Ltd" }, - { "MTE", "MediaTec GmbH" }, - { "MTH", "Micro-Tech Hearing Instruments" }, - { "MTI", "Motorola Inc." }, - { "MTK", "Microtek International Inc." }, - { "MTL", "Mitel Corporation" }, - { "MTM", "Motium" }, - { "MTN", "Mtron Storage Technology Co., Ltd." }, - { "MTR", "Mitron computer Inc" }, - { "MTS", "Multi-Tech Systems" }, - { "MTU", "Mark of the Unicorn Inc" }, - { "MTX", "Matrox" }, - { "MUD", "Multi-Dimension Institute" }, - { "MUK", "mainpine limited" }, - { "MVD", "Microvitec PLC" }, - { "MVI", "Media Vision Inc" }, - { "MVM", "SOBO VISION" }, - { "MVS", "Microvision" }, - { "MVX", "COM 1" }, - { "MWI", "Multiwave Innovation Pte Ltd" }, - { "MWR", "mware" }, - { "MWY", "Microway Inc" }, - { "MXD", "MaxData Computer GmbH & Co.KG" }, - { "MXI", "Macronix Inc" }, - { "MXL", "Hitachi Maxell, Ltd." }, - { "MXP", "Maxpeed Corporation" }, - { "MXT", "Maxtech Corporation" }, - { "MXV", "MaxVision Corporation" }, - { "MYA", "Monydata" }, - { "MYR", "Myriad Solutions Ltd" }, - { "MYX", "Micronyx Inc" }, - { "NAC", "Ncast Corporation" }, - { "NAD", "NAD Electronics" }, - { "NAK", "Nakano Engineering Co.,Ltd." }, - { "NAL", "Network Alchemy" }, - { "NAT", "NaturalPoint Inc." }, - { "NAV", "Navigation Corporation" }, - { "NAX", "Naxos Tecnologia" }, - { "NBL", "N*Able Technologies Inc" }, - { "NBS", "National Key Lab. on ISN" }, - { "NBT", "NingBo Bestwinning Technology CO., Ltd" }, - { "NCA", "Nixdorf Company" }, - { "NCC", "NCR Corporation" }, - { "NCE", "Norcent Technology, Inc." }, - { "NCI", "NewCom Inc" }, - { "NCL", "NetComm Ltd" }, - { "NCR", "NCR Electronics" }, - { "NCS", "Northgate Computer Systems" }, - { "NCT", "NEC CustomTechnica, Ltd." }, - { "NDC", "National DataComm Corporaiton" }, - { "NDI", "National Display Systems" }, - { "NDK", "Naitoh Densei CO., LTD." }, - { "NDL", "Network Designers" }, - { "NDS", "Nokia Data" }, - { "NEC", "NEC Corporation" }, - { "NEO", "NEO TELECOM CO.,LTD." }, - { "NET", "Mettler Toledo" }, - { "NEU", "NEUROTEC - EMPRESA DE PESQUISA E DESENVOLVIMENTO EM BIOMEDICINA" }, - { "NEX", "Nexgen Mediatech Inc.," }, - { "NFC", "BTC Korea Co., Ltd" }, - { "NFS", "Number Five Software" }, - { "NGC", "Network General" }, - { "NGS", "A D S Exports" }, - { "NHT", "Vinci Labs" }, - { "NIC", "National Instruments Corporation" }, - { "NIS", "Nissei Electric Company" }, - { "NIT", "Network Info Technology" }, - { "NIX", "Seanix Technology Inc" }, - { "NLC", "Next Level Communications" }, - { "NME", "Navico, Inc." }, - { "NMP", "Nokia Mobile Phones" }, - { "NMS", "Natural Micro System" }, - { "NMV", "NEC-Mitsubishi Electric Visual Systems Corporation" }, - { "NMX", "Neomagic" }, - { "NNC", "NNC" }, - { "NOE", "NordicEye AB" }, - { "NOI", "North Invent A/S" }, - { "NOK", "Nokia Display Products" }, - { "NOR", "Norand Corporation" }, - { "NOT", "Not Limited Inc" }, - { "NPI", "Network Peripherals Inc" }, - { "NRL", "U.S. Naval Research Lab" }, - { "NRT", "Beijing Northern Radiantelecom Co." }, - { "NRV", "Taugagreining hf" }, - { "NSC", "National Semiconductor Corporation" }, - { "NSI", "NISSEI ELECTRIC CO.,LTD" }, - { "NSP", "Nspire System Inc." }, - { "NSS", "Newport Systems Solutions" }, - { "NST", "Network Security Technology Co" }, - { "NTC", "NeoTech S.R.L" }, - { "NTI", "New Tech Int'l Company" }, - { "NTL", "National Transcomm. Ltd" }, - { "NTN", "Nuvoton Technology Corporation" }, - { "NTR", "N-trig Innovative Technologies, Inc." }, - { "NTS", "Nits Technology Inc." }, - { "NTT", "NTT Advanced Technology Corporation" }, - { "NTW", "Networth Inc" }, - { "NTX", "Netaccess Inc" }, - { "NUG", "NU Technology, Inc." }, - { "NUI", "NU Inc." }, - { "NVC", "NetVision Corporation" }, - { "NVD", "Nvidia" }, - { "NVI", "NuVision US, Inc." }, - { "NVL", "Novell Inc" }, - { "NVT", "Navatek Engineering Corporation" }, - { "NWC", "NW Computer Engineering" }, - { "NWP", "NovaWeb Technologies Inc" }, - { "NWS", "Newisys, Inc." }, - { "NXC", "NextCom K.K." }, - { "NXG", "Nexgen" }, - { "NXP", "NXP Semiconductors bv." }, - { "NXQ", "Nexiq Technologies, Inc." }, - { "NXS", "Technology Nexus Secure Open Systems AB" }, - { "NYC", "nakayo telecommunications,inc." }, - { "OAK", "Oak Tech Inc" }, - { "OAS", "Oasys Technology Company" }, - { "OBS", "Optibase Technologies" }, - { "OCD", "Macraigor Systems Inc" }, - { "OCN", "Olfan" }, - { "OCS", "Open Connect Solutions" }, - { "ODM", "ODME Inc." }, - { "ODR", "Odrac" }, - { "OEC", "ORION ELECTRIC CO.,LTD" }, - { "OEI", "Optum Engineering Inc." }, - { "OIC", "Option Industrial Computers" }, - { "OIM", "Option International" }, - { "OIN", "Option International" }, - { "OKI", "OKI Electric Industrial Company Ltd" }, - { "OLC", "Olicom A/S" }, - { "OLD", "Olidata S.p.A." }, - { "OLI", "Olivetti" }, - { "OLT", "Olitec S.A." }, - { "OLV", "Olitec S.A." }, - { "OLY", "OLYMPUS CORPORATION" }, - { "OMC", "OBJIX Multimedia Corporation" }, - { "OMN", "Omnitel" }, - { "OMR", "Omron Corporation" }, - { "ONE", "Oneac Corporation" }, - { "ONK", "ONKYO Corporation" }, - { "ONL", "OnLive, Inc" }, - { "ONS", "On Systems Inc" }, - { "ONW", "OPEN Networks Ltd" }, - { "ONX", "SOMELEC Z.I. Du Vert Galanta" }, - { "OOS", "OSRAM" }, - { "OPC", "Opcode Inc" }, - { "OPI", "D.N.S. Corporation" }, - { "OPP", "OPPO Digital, Inc." }, - { "OPT", "OPTi Inc" }, - { "OPV", "Optivision Inc" }, - { "OQI", "Oksori Company Ltd" }, - { "ORG", "ORGA Kartensysteme GmbH" }, - { "ORI", "OSR Open Systems Resources, Inc." }, - { "ORN", "ORION ELECTRIC CO., LTD." }, - { "OSA", "OSAKA Micro Computer, Inc." }, - { "OSP", "OPTI-UPS Corporation" }, - { "OSR", "Oksori Company Ltd" }, - { "OTB", "outsidetheboxstuff.com" }, - { "OTI", "Orchid Technology" }, - { "OTM", "Optoma Corporation" }, - { "OTT", "OPTO22, Inc." }, - { "OUK", "OUK Company Ltd" }, - { "OVR", "Oculus VR, Inc." }, - { "OWL", "Mediacom Technologies Pte Ltd" }, - { "OXU", "Oxus Research S.A." }, - { "OYO", "Shadow Systems" }, - { "OZC", "OZ Corporation" }, - { "OZO", "Tribe Computer Works Inc" }, - { "PAC", "Pacific Avionics Corporation" }, - { "PAD", "Promotion and Display Technology Ltd." }, - { "PAK", "Many CNC System Co., Ltd." }, - { "PAM", "Peter Antesberger Messtechnik" }, - { "PAN", "The Panda Project" }, - { "PAR", "Parallan Comp Inc" }, - { "PBI", "Pitney Bowes" }, - { "PBL", "Packard Bell Electronics" }, - { "PBN", "Packard Bell NEC" }, - { "PBV", "Pitney Bowes" }, - { "PCA", "Philips BU Add On Card" }, - { "PCB", "OCTAL S.A." }, - { "PCC", "PowerCom Technology Company Ltd" }, - { "PCG", "First Industrial Computer Inc" }, - { "PCI", "Pioneer Computer Inc" }, - { "PCK", "PCBANK21" }, - { "PCL", "pentel.co.,ltd" }, - { "PCM", "PCM Systems Corporation" }, - { "PCO", "Performance Concepts Inc.," }, - { "PCP", "Procomp USA Inc" }, - { "PCS", "TOSHIBA PERSONAL COMPUTER SYSTEM CORPRATION" }, - { "PCT", "PC-Tel Inc" }, - { "PCW", "Pacific CommWare Inc" }, - { "PCX", "PC Xperten" }, - { "PDM", "Psion Dacom Plc." }, - { "PDN", "AT&T Paradyne" }, - { "PDR", "Pure Data Inc" }, - { "PDS", "PD Systems International Ltd" }, - { "PDT", "PDTS - Prozessdatentechnik und Systeme" }, - { "PDV", "Prodrive B.V." }, - { "PEC", "POTRANS Electrical Corp." }, - { "PEI", "PEI Electronics Inc" }, - { "PEL", "Primax Electric Ltd" }, - { "PEN", "Interactive Computer Products Inc" }, - { "PEP", "Peppercon AG" }, - { "PER", "Perceptive Signal Technologies" }, - { "PET", "Practical Electronic Tools" }, - { "PFT", "Telia ProSoft AB" }, - { "PGI", "PACSGEAR, Inc." }, - { "PGM", "Paradigm Advanced Research Centre" }, - { "PGP", "propagamma kommunikation" }, - { "PGS", "Princeton Graphic Systems" }, - { "PHC", "Pijnenburg Beheer N.V." }, - { "PHE", "Philips Medical Systems Boeblingen GmbH" }, - { "PHI", "DO NOT USE - PHI" }, - { "PHL", "Philips Consumer Electronics Company" }, - { "PHO", "Photonics Systems Inc." }, - { "PHS", "Philips Communication Systems" }, - { "PHY", "Phylon Communications" }, - { "PIE", "Pacific Image Electronics Company Ltd" }, - { "PIM", "Prism, LLC" }, - { "PIO", "Pioneer Electronic Corporation" }, - { "PIX", "Pixie Tech Inc" }, - { "PJA", "Projecta" }, - { "PJD", "Projectiondesign AS" }, - { "PJT", "Pan Jit International Inc." }, - { "PKA", "Acco UK ltd." }, - { "PLC", "Pro-Log Corporation" }, - { "PLF", "Panasonic Avionics Corporation" }, - { "PLM", "PROLINK Microsystems Corp." }, - { "PLT", "PT Hartono Istana Teknologi" }, - { "PLV", "PLUS Vision Corp." }, - { "PLX", "Parallax Graphics" }, - { "PLY", "Polycom Inc." }, - { "PMC", "PMC Consumer Electronics Ltd" }, - { "PMD", "TDK USA Corporation" }, - { "PMM", "Point Multimedia System" }, - { "PMT", "Promate Electronic Co., Ltd." }, - { "PMX", "Photomatrix" }, - { "PNG", "P.I. Engineering Inc" }, - { "PNL", "Panelview, Inc." }, - { "PNP", "Microsoft" }, - { "PNR", "Planar Systems, Inc." }, - { "PNS", "PanaScope" }, - { "PNX", "Phoenix Technologies, Ltd." }, - { "POL", "PolyComp (PTY) Ltd." }, - { "PON", "Perpetual Technologies, LLC" }, - { "POR", "Portalis LC" }, - { "PPC", "Phoenixtec Power Company Ltd" }, - { "PPD", "MEPhI" }, - { "PPI", "Practical Peripherals" }, - { "PPM", "Clinton Electronics Corp." }, - { "PPP", "Purup Prepress AS" }, - { "PPR", "PicPro" }, - { "PPX", "Perceptive Pixel Inc." }, - { "PQI", "Pixel Qi" }, - { "PRA", "PRO/AUTOMATION" }, - { "PRC", "PerComm" }, - { "PRD", "Praim S.R.L." }, - { "PRF", "Digital Electronics Corporation" }, - { "PRG", "The Phoenix Research Group Inc" }, - { "PRI", "Priva Hortimation BV" }, - { "PRM", "Prometheus" }, - { "PRO", "Proteon" }, - { "PRS", "Leutron Vision" }, - { "PRT", "Parade Technologies, Ltd." }, - { "PRX", "Proxima Corporation" }, - { "PSA", "Advanced Signal Processing Technologies" }, - { "PSC", "Philips Semiconductors" }, - { "PSD", "Peus-Systems GmbH" }, - { "PSE", "Practical Solutions Pte., Ltd." }, - { "PSI", "PSI-Perceptive Solutions Inc" }, - { "PSL", "Perle Systems Limited" }, - { "PSM", "Prosum" }, - { "PST", "Global Data SA" }, - { "PSY", "Prodea Systems Inc." }, - { "PTA", "PAR Tech Inc." }, - { "PTC", "PS Technology Corporation" }, - { "PTG", "Cipher Systems Inc" }, - { "PTH", "Pathlight Technology Inc" }, - { "PTI", "Promise Technology Inc" }, - { "PTL", "Pantel Inc" }, - { "PTS", "Plain Tree Systems Inc" }, - { "PTW", "DO NOT USE - PTW" }, - { "PUL", "Pulse-Eight Ltd" }, - { "PVC", "DO NOT USE - PVC" }, - { "PVG", "Proview Global Co., Ltd" }, - { "PVI", "Prime view international Co., Ltd" }, - { "PVM", "Penta Studiotechnik GmbH" }, - { "PVN", "Pixel Vision" }, - { "PVP", "Klos Technologies, Inc." }, - { "PXC", "Phoenix Contact" }, - { "PXE", "PIXELA CORPORATION" }, - { "PXL", "The Moving Pixel Company" }, - { "PXM", "Proxim Inc" }, - { "QCC", "QuakeCom Company Ltd" }, - { "QCH", "Metronics Inc" }, - { "QCI", "Quanta Computer Inc" }, - { "QCK", "Quick Corporation" }, - { "QCL", "Quadrant Components Inc" }, - { "QCP", "Qualcomm Inc" }, - { "QDI", "Quantum Data Incorporated" }, - { "QDM", "Quadram" }, - { "QDS", "Quanta Display Inc." }, - { "QFF", "Padix Co., Inc." }, - { "QFI", "Quickflex, Inc" }, - { "QLC", "Q-Logic" }, - { "QQQ", "Chuomusen Co., Ltd." }, - { "QSI", "Quantum Solutions, Inc." }, - { "QTD", "Quantum 3D Inc" }, - { "QTH", "Questech Ltd" }, - { "QTI", "Quicknet Technologies Inc" }, - { "QTM", "Quantum" }, - { "QTR", "Qtronix Corporation" }, - { "QUA", "Quatographic AG" }, - { "QUE", "Questra Consulting" }, - { "QVU", "Quartics" }, - { "RAC", "Racore Computer Products Inc" }, - { "RAD", "Radisys Corporation" }, - { "RAI", "Rockwell Automation/Intecolor" }, - { "RAN", "Rancho Tech Inc" }, - { "RAR", "Raritan, Inc." }, - { "RAS", "RAScom Inc" }, - { "RAT", "Rent-A-Tech" }, - { "RAY", "Raylar Design, Inc." }, - { "RCE", "Parc d'Activite des Bellevues" }, - { "RCH", "Reach Technology Inc" }, - { "RCI", "RC International" }, - { "RCN", "Radio Consult SRL" }, - { "RCO", "Rockwell Collins" }, - { "RDI", "Rainbow Displays, Inc." }, - { "RDM", "Tremon Enterprises Company Ltd" }, - { "RDN", "RADIODATA GmbH" }, - { "RDS", "Radius Inc" }, - { "REA", "Real D" }, - { "REC", "ReCom" }, - { "RED", "Research Electronics Development Inc" }, - { "REF", "Reflectivity, Inc." }, - { "REH", "Rehan Electronics Ltd." }, - { "REL", "Reliance Electric Ind Corporation" }, - { "REM", "SCI Systems Inc." }, - { "REN", "Renesas Technology Corp." }, - { "RES", "ResMed Pty Ltd" }, - { "RET", "Resonance Technology, Inc." }, - { "REX", "RATOC Systems, Inc." }, - { "RGB", "RGB Spectrum" }, - { "RGL", "Robertson Geologging Ltd" }, - { "RHD", "RightHand Technologies" }, - { "RHM", "Rohm Company Ltd" }, - { "RHT", "Red Hat, Inc." }, - { "RIC", "RICOH COMPANY, LTD." }, - { "RII", "Racal Interlan Inc" }, - { "RIO", "Rios Systems Company Ltd" }, - { "RIT", "Ritech Inc" }, - { "RIV", "Rivulet Communications" }, - { "RJA", "Roland Corporation" }, - { "RJS", "Advanced Engineering" }, - { "RKC", "Reakin Technolohy Corporation" }, - { "RLD", "MEPCO" }, - { "RLN", "RadioLAN Inc" }, - { "RMC", "Raritan Computer, Inc" }, - { "RMP", "Research Machines" }, - { "RMT", "Roper Mobile" }, - { "RNB", "Rainbow Technologies" }, - { "ROB", "Robust Electronics GmbH" }, - { "ROH", "Rohm Co., Ltd." }, - { "ROK", "Rockwell International" }, - { "ROP", "Roper International Ltd" }, - { "ROS", "Rohde & Schwarz" }, - { "RPI", "RoomPro Technologies" }, - { "RPT", "R.P.T.Intergroups" }, - { "RRI", "Radicom Research Inc" }, - { "RSC", "PhotoTelesis" }, - { "RSH", "ADC-Centre" }, - { "RSI", "Rampage Systems Inc" }, - { "RSN", "Radiospire Networks, Inc." }, - { "RSQ", "R Squared" }, - { "RSS", "Rockwell Semiconductor Systems" }, - { "RSV", "Ross Video Ltd" }, - { "RSX", "Rapid Tech Corporation" }, - { "RTC", "Relia Technologies" }, - { "RTI", "Rancho Tech Inc" }, - { "RTK", "DO NOT USE - RTK" }, - { "RTL", "Realtek Semiconductor Company Ltd" }, - { "RTS", "Raintree Systems" }, - { "RUN", "RUNCO International" }, - { "RUP", "Ups Manufactoring s.r.l." }, - { "RVC", "RSI Systems Inc" }, - { "RVI", "Realvision Inc" }, - { "RVL", "Reveal Computer Prod" }, - { "RWC", "Red Wing Corporation" }, - { "RXT", "Tectona SoftSolutions (P) Ltd.," }, - { "SAA", "Sanritz Automation Co.,Ltd." }, - { "SAE", "Saab Aerotech" }, - { "SAG", "Sedlbauer" }, - { "SAI", "Sage Inc" }, - { "SAK", "Saitek Ltd" }, - { "SAM", "Samsung Electric Company" }, - { "SAN", "Sanyo Electric Co.,Ltd." }, - { "SAS", "Stores Automated Systems Inc" }, - { "SAT", "Shuttle Tech" }, - { "SBC", "Shanghai Bell Telephone Equip Mfg Co" }, - { "SBD", "Softbed - Consulting & Development Ltd" }, - { "SBI", "SMART Technologies Inc." }, - { "SBS", "SBS-or Industrial Computers GmbH" }, - { "SBT", "Senseboard Technologies AB" }, - { "SCB", "SeeCubic B.V." }, - { "SCC", "SORD Computer Corporation" }, - { "SCD", "Sanyo Electric Company Ltd" }, - { "SCE", "Sun Corporation" }, - { "SCH", "Schlumberger Cards" }, - { "SCI", "System Craft" }, - { "SCL", "Sigmacom Co., Ltd." }, - { "SCM", "SCM Microsystems Inc" }, - { "SCN", "Scanport, Inc." }, - { "SCO", "SORCUS Computer GmbH" }, - { "SCP", "Scriptel Corporation" }, - { "SCR", "Systran Corporation" }, - { "SCS", "Nanomach Anstalt" }, - { "SCT", "Smart Card Technology" }, - { "SDA", "SAT (Societe Anonyme)" }, - { "SDD", "Intrada-SDD Ltd" }, - { "SDE", "Sherwood Digital Electronics Corporation" }, - { "SDF", "SODIFF E&T CO., Ltd." }, - { "SDH", "Communications Specialies, Inc." }, - { "SDI", "Samtron Displays Inc" }, - { "SDK", "SAIT-Devlonics" }, - { "SDR", "SDR Systems" }, - { "SDS", "SunRiver Data System" }, - { "SDT", "Siemens AG" }, - { "SDX", "SDX Business Systems Ltd" }, - { "SEA", "Seanix Technology Inc." }, - { "SEB", "system elektronik GmbH" }, - { "SEC", "Seiko Epson Corporation" }, - { "SEE", "SeeColor Corporation" }, - { "SEG", "DO NOT USE - SEG" }, - { "SEI", "Seitz & Associates Inc" }, - { "SEL", "Way2Call Communications" }, - { "SEM", "Samsung Electronics Company Ltd" }, - { "SEN", "Sencore" }, - { "SEO", "SEOS Ltd" }, - { "SEP", "SEP Eletronica Ltda." }, - { "SER", "Sony Ericsson Mobile Communications Inc." }, - { "SES", "Session Control LLC" }, - { "SET", "SendTek Corporation" }, - { "SFM", "TORNADO Company" }, - { "SFT", "Mikroforum Ring 3" }, - { "SGC", "Spectragraphics Corporation" }, - { "SGD", "Sigma Designs, Inc." }, - { "SGE", "Kansai Electric Company Ltd" }, - { "SGI", "Scan Group Ltd" }, - { "SGL", "Super Gate Technology Company Ltd" }, - { "SGM", "SAGEM" }, - { "SGO", "Logos Design A/S" }, - { "SGT", "Stargate Technology" }, - { "SGW", "Shanghai Guowei Science and Technology Co., Ltd." }, - { "SGX", "Silicon Graphics Inc" }, - { "SGZ", "Systec Computer GmbH" }, - { "SHC", "ShibaSoku Co., Ltd." }, - { "SHG", "Soft & Hardware development Goldammer GmbH" }, - { "SHI", "Jiangsu Shinco Electronic Group Co., Ltd" }, - { "SHP", "Sharp Corporation" }, - { "SHR", "Digital Discovery" }, - { "SHT", "Shin Ho Tech" }, - { "SIA", "SIEMENS AG" }, - { "SIB", "Sanyo Electric Company Ltd" }, - { "SIC", "Sysmate Corporation" }, - { "SID", "Seiko Instruments Information Devices Inc" }, - { "SIE", "Siemens" }, - { "SIG", "Sigma Designs Inc" }, - { "SII", "Silicon Image, Inc." }, - { "SIL", "Silicon Laboratories, Inc" }, - { "SIM", "S3 Inc" }, - { "SIN", "Singular Technology Co., Ltd." }, - { "SIR", "Sirius Technologies Pty Ltd" }, - { "SIS", "Silicon Integrated Systems Corporation" }, - { "SIT", "Sitintel" }, - { "SIU", "Seiko Instruments USA Inc" }, - { "SIX", "Zuniq Data Corporation" }, - { "SJE", "Sejin Electron Inc" }, - { "SKD", "Schneider & Koch" }, - { "SKT", "Samsung Electro-Mechanics Company Ltd" }, - { "SKY", "SKYDATA S.P.A." }, - { "SLA", "Systeme Lauer GmbH&Co KG" }, - { "SLB", "Shlumberger Ltd" }, - { "SLC", "Syslogic Datentechnik AG" }, - { "SLF", "StarLeaf" }, - { "SLH", "Silicon Library Inc." }, - { "SLI", "Symbios Logic Inc" }, - { "SLK", "Silitek Corporation" }, - { "SLM", "Solomon Technology Corporation" }, - { "SLR", "Schlumberger Technology Corporate" }, - { "SLS", "Schnick-Schnack-Systems GmbH" }, - { "SLT", "Salt Internatioinal Corp." }, - { "SLX", "Specialix" }, - { "SMA", "SMART Modular Technologies" }, - { "SMB", "Schlumberger" }, - { "SMC", "Standard Microsystems Corporation" }, - { "SME", "Sysmate Company" }, - { "SMI", "SpaceLabs Medical Inc" }, - { "SMK", "SMK CORPORATION" }, - { "SML", "Sumitomo Metal Industries, Ltd." }, - { "SMM", "Shark Multimedia Inc" }, - { "SMO", "STMicroelectronics" }, - { "SMP", "Simple Computing" }, - { "SMR", "B.& V. s.r.l." }, - { "SMS", "Silicom Multimedia Systems Inc" }, - { "SMT", "Silcom Manufacturing Tech Inc" }, - { "SNC", "Sentronic International Corp." }, - { "SNI", "Siemens Microdesign GmbH" }, - { "SNK", "S&K Electronics" }, - { "SNO", "SINOSUN TECHNOLOGY CO., LTD" }, - { "SNP", "Siemens Nixdorf Info Systems" }, - { "SNS", "Cirtech (UK) Ltd" }, - { "SNT", "SuperNet Inc" }, - { "SNW", "Snell & Wilcox" }, - { "SNX", "Sonix Comm. Ltd" }, - { "SNY", "Sony" }, - { "SOI", "Silicon Optix Corporation" }, - { "SOL", "Solitron Technologies Inc" }, - { "SON", "Sony" }, - { "SOR", "Sorcus Computer GmbH" }, - { "SOT", "Sotec Company Ltd" }, - { "SOY", "SOYO Group, Inc" }, - { "SPC", "SpinCore Technologies, Inc" }, - { "SPE", "SPEA Software AG" }, - { "SPH", "G&W Instruments GmbH" }, - { "SPI", "SPACE-I Co., Ltd." }, - { "SPK", "SpeakerCraft" }, - { "SPL", "Smart Silicon Systems Pty Ltd" }, - { "SPN", "Sapience Corporation" }, - { "SPR", "pmns GmbH" }, - { "SPS", "Synopsys Inc" }, - { "SPT", "Sceptre Tech Inc" }, - { "SPU", "SIM2 Multimedia S.P.A." }, - { "SPX", "Simplex Time Recorder Co." }, - { "SQT", "Sequent Computer Systems Inc" }, - { "SRC", "Integrated Tech Express Inc" }, - { "SRD", "Setred" }, - { "SRF", "Surf Communication Solutions Ltd" }, - { "SRG", "Intuitive Surgical, Inc." }, - { "SRS", "SR-Systems e.K." }, - { "SRT", "SeeReal Technologies GmbH" }, - { "SSC", "Sierra Semiconductor Inc" }, - { "SSD", "FlightSafety International" }, - { "SSE", "Samsung Electronic Co." }, - { "SSI", "S-S Technology Inc" }, - { "SSJ", "Sankyo Seiki Mfg.co., Ltd" }, - { "SSP", "Spectrum Signal Proecessing Inc" }, - { "SSS", "S3 Inc" }, - { "SST", "SystemSoft Corporation" }, - { "STA", "ST Electronics Systems Assembly Pte Ltd" }, - { "STB", "STB Systems Inc" }, - { "STC", "STAC Electronics" }, - { "STD", "STD Computer Inc" }, - { "STE", "SII Ido-Tsushin Inc" }, - { "STF", "Starflight Electronics" }, - { "STG", "StereoGraphics Corp." }, - { "STH", "Semtech Corporation" }, - { "STI", "Smart Tech Inc" }, - { "STK", "SANTAK CORP." }, - { "STL", "SigmaTel Inc" }, - { "STM", "SGS Thomson Microelectronics" }, - { "STN", "Samsung Electronics America" }, - { "STO", "Stollmann E+V GmbH" }, - { "STP", "StreamPlay Ltd" }, - { "STR", "Starlight Networks Inc" }, - { "STS", "SITECSYSTEM CO., LTD." }, - { "STT", "Star Paging Telecom Tech (Shenzhen) Co. Ltd." }, - { "STU", "Sentelic Corporation" }, - { "STW", "Starwin Inc." }, - { "STX", "ST-Ericsson" }, - { "STY", "SDS Technologies" }, - { "SUB", "Subspace Comm. Inc" }, - { "SUM", "Summagraphics Corporation" }, - { "SUN", "Sun Electronics Corporation" }, - { "SUP", "Supra Corporation" }, - { "SUR", "Surenam Computer Corporation" }, - { "SVA", "SGEG" }, - { "SVC", "Intellix Corp." }, - { "SVD", "SVD Computer" }, - { "SVI", "Sun Microsystems" }, - { "SVS", "SVSI" }, - { "SVT", "SEVIT Co., Ltd." }, - { "SWC", "Software Café" }, - { "SWI", "Sierra Wireless Inc." }, - { "SWL", "Sharedware Ltd" }, - { "SWS", "Static" }, - { "SWT", "Software Technologies Group,Inc." }, - { "SXB", "Syntax-Brillian" }, - { "SXD", "Silex technology, Inc." }, - { "SXG", "SELEX GALILEO" }, - { "SXL", "SolutionInside" }, - { "SXT", "SHARP TAKAYA ELECTRONIC INDUSTRY CO.,LTD." }, - { "SYC", "Sysmic" }, - { "SYE", "SY Electronics Ltd" }, - { "SYK", "Stryker Communications" }, - { "SYL", "Sylvania Computer Products" }, - { "SYM", "Symicron Computer Communications Ltd." }, - { "SYN", "Synaptics Inc" }, - { "SYP", "SYPRO Co Ltd" }, - { "SYS", "Sysgration Ltd" }, - { "SYT", "Seyeon Tech Company Ltd" }, - { "SYV", "SYVAX Inc" }, - { "SYX", "Prime Systems, Inc." }, - { "TAA", "Tandberg" }, - { "TAB", "Todos Data System AB" }, - { "TAG", "Teles AG" }, - { "TAI", "Toshiba America Info Systems Inc" }, - { "TAM", "Tamura Seisakusyo Ltd" }, - { "TAS", "Taskit Rechnertechnik GmbH" }, - { "TAT", "Teleliaison Inc" }, - { "TAX", "Taxan (Europe) Ltd" }, - { "TBB", "Triple S Engineering Inc" }, - { "TBC", "Turbo Communication, Inc" }, - { "TBS", "Turtle Beach System" }, - { "TCC", "Tandon Corporation" }, - { "TCD", "Taicom Data Systems Co., Ltd." }, - { "TCE", "Century Corporation" }, - { "TCH", "Interaction Systems, Inc" }, - { "TCI", "Tulip Computers Int'l B.V." }, - { "TCJ", "TEAC America Inc" }, - { "TCL", "Technical Concepts Ltd" }, - { "TCM", "3Com Corporation" }, - { "TCN", "Tecnetics (PTY) Ltd" }, - { "TCO", "Thomas-Conrad Corporation" }, - { "TCR", "Thomson Consumer Electronics" }, - { "TCS", "Tatung Company of America Inc" }, - { "TCT", "Telecom Technology Centre Co. Ltd." }, - { "TCX", "FREEMARS Heavy Industries" }, - { "TDC", "Teradici" }, - { "TDD", "Tandberg Data Display AS" }, - { "TDK", "TDK USA Corporation" }, - { "TDM", "Tandem Computer Europe Inc" }, - { "TDP", "3D Perception" }, - { "TDS", "Tri-Data Systems Inc" }, - { "TDT", "TDT" }, - { "TDV", "TDVision Systems, Inc." }, - { "TDY", "Tandy Electronics" }, - { "TEA", "TEAC System Corporation" }, - { "TEC", "Tecmar Inc" }, - { "TEK", "Tektronix Inc" }, - { "TEL", "Promotion and Display Technology Ltd." }, - { "TER", "TerraTec Electronic GmbH" }, - { "TGC", "Toshiba Global Commerce Solutions, Inc." }, - { "TGI", "TriGem Computer Inc" }, - { "TGM", "TriGem Computer,Inc." }, - { "TGS", "Torus Systems Ltd" }, - { "TGV", "Grass Valley Germany GmbH" }, - { "THN", "Thundercom Holdings Sdn. Bhd." }, - { "TIC", "Trigem KinfoComm" }, - { "TIP", "TIPTEL AG" }, - { "TIV", "OOO Technoinvest" }, - { "TIX", "Tixi.Com GmbH" }, - { "TKC", "Taiko Electric Works.LTD" }, - { "TKN", "Teknor Microsystem Inc" }, - { "TKO", "TouchKo, Inc." }, - { "TKS", "TimeKeeping Systems, Inc." }, - { "TLA", "Ferrari Electronic GmbH" }, - { "TLD", "Telindus" }, - { "TLF", "Teleforce.,co,ltd" }, - { "TLI", "TOSHIBA TELI CORPORATION" }, - { "TLK", "Telelink AG" }, - { "TLS", "Teleste Educational OY" }, - { "TLT", "Dai Telecom S.p.A." }, - { "TLV", "S3 Inc" }, - { "TLX", "Telxon Corporation" }, - { "TMC", "Techmedia Computer Systems Corporation" }, - { "TME", "AT&T Microelectronics" }, - { "TMI", "Texas Microsystem" }, - { "TMM", "Time Management, Inc." }, - { "TMR", "Taicom International Inc" }, - { "TMS", "Trident Microsystems Ltd" }, - { "TMT", "T-Metrics Inc." }, - { "TMX", "Thermotrex Corporation" }, - { "TNC", "TNC Industrial Company Ltd" }, - { "TNJ", "DO NOT USE - TNJ" }, - { "TNM", "TECNIMAGEN SA" }, - { "TNY", "Tennyson Tech Pty Ltd" }, - { "TOE", "TOEI Electronics Co., Ltd." }, - { "TOG", "The OPEN Group" }, - { "TON", "TONNA" }, - { "TOP", "Orion Communications Co., Ltd." }, - { "TOS", "Toshiba Corporation" }, - { "TOU", "Touchstone Technology" }, - { "TPC", "Touch Panel Systems Corporation" }, - { "TPE", "Technology Power Enterprises Inc" }, - { "TPJ", "Junnila" }, - { "TPK", "TOPRE CORPORATION" }, - { "TPR", "Topro Technology Inc" }, - { "TPS", "Teleprocessing Systeme GmbH" }, - { "TPT", "Thruput Ltd" }, - { "TPV", "Top Victory Electronics ( Fujian ) Company Ltd" }, - { "TPZ", "Ypoaz Systems Inc" }, - { "TRA", "TriTech Microelectronics International" }, - { "TRC", "Trioc AB" }, - { "TRD", "Trident Microsystem Inc" }, - { "TRE", "Tremetrics" }, - { "TRI", "Tricord Systems" }, - { "TRL", "Royal Information" }, - { "TRM", "Tekram Technology Company Ltd" }, - { "TRN", "Datacommunicatie Tron B.V." }, - { "TRS", "Torus Systems Ltd" }, - { "TRT", "Tritec Electronic AG" }, - { "TRU", "Aashima Technology B.V." }, - { "TRV", "Trivisio Prototyping GmbH" }, - { "TRX", "Trex Enterprises" }, - { "TSB", "Toshiba America Info Systems Inc" }, - { "TSC", "Sanyo Electric Company Ltd" }, - { "TSD", "TechniSat Digital GmbH" }, - { "TSE", "Tottori Sanyo Electric" }, - { "TSF", "Racal-Airtech Software Forge Ltd" }, - { "TSG", "The Software Group Ltd" }, - { "TSI", "TeleVideo Systems" }, - { "TSL", "Tottori SANYO Electric Co., Ltd." }, - { "TSP", "U.S. Navy" }, - { "TST", "Transtream Inc" }, - { "TSV", "TRANSVIDEO" }, - { "TSY", "TouchSystems" }, - { "TTA", "Topson Technology Co., Ltd." }, - { "TTB", "National Semiconductor Japan Ltd" }, - { "TTC", "Telecommunications Techniques Corporation" }, - { "TTE", "TTE, Inc." }, - { "TTI", "Trenton Terminals Inc" }, - { "TTK", "Totoku Electric Company Ltd" }, - { "TTL", "2-Tel B.V." }, - { "TTS", "TechnoTrend Systemtechnik GmbH" }, - { "TTY", "TRIDELITY Display Solutions GmbH" }, - { "TUA", "T+A elektroakustik GmbH" }, - { "TUT", "Tut Systems" }, - { "TVD", "Tecnovision" }, - { "TVI", "Truevision" }, - { "TVM", "Taiwan Video & Monitor Corporation" }, - { "TVO", "TV One Ltd" }, - { "TVR", "TV Interactive Corporation" }, - { "TVS", "TVS Electronics Limited" }, - { "TVV", "TV1 GmbH" }, - { "TWA", "Tidewater Association" }, - { "TWE", "Kontron Electronik" }, - { "TWH", "Twinhead International Corporation" }, - { "TWI", "Easytel oy" }, - { "TWK", "TOWITOKO electronics GmbH" }, - { "TWX", "TEKWorx Limited" }, - { "TXL", "Trixel Ltd" }, - { "TXN", "Texas Insturments" }, - { "TXT", "Textron Defense System" }, - { "TYN", "Tyan Computer Corporation" }, - { "UAS", "Ultima Associates Pte Ltd" }, - { "UBI", "Ungermann-Bass Inc" }, - { "UBL", "Ubinetics Ltd." }, - { "UDN", "Uniden Corporation" }, - { "UEC", "Ultima Electronics Corporation" }, - { "UEG", "Elitegroup Computer Systems Company Ltd" }, - { "UEI", "Universal Electronics Inc" }, - { "UET", "Universal Empowering Technologies" }, - { "UFG", "UNIGRAF-USA" }, - { "UFO", "UFO Systems Inc" }, - { "UHB", "XOCECO" }, - { "UIC", "Uniform Industrial Corporation" }, - { "UJR", "Ueda Japan Radio Co., Ltd." }, - { "ULT", "Ultra Network Tech" }, - { "UMC", "United Microelectr Corporation" }, - { "UMG", "Umezawa Giken Co.,Ltd" }, - { "UMM", "Universal Multimedia" }, - { "UNA", "Unisys DSD" }, - { "UNB", "Unisys Corporation" }, - { "UNC", "Unisys Corporation" }, - { "UND", "Unisys Corporation" }, - { "UNE", "Unisys Corporation" }, - { "UNF", "Unisys Corporation" }, - { "UNI", "Unisys Corporation" }, - { "UNM", "Unisys Corporation" }, - { "UNO", "Unisys Corporation" }, - { "UNP", "Unitop" }, - { "UNS", "Unisys Corporation" }, - { "UNT", "Unisys Corporation" }, - { "UNY", "Unicate" }, - { "UPP", "UPPI" }, - { "UPS", "Systems Enhancement" }, - { "URD", "Video Computer S.p.A." }, - { "USA", "Utimaco Safeware AG" }, - { "USD", "U.S. Digital Corporation" }, - { "USI", "Universal Scientific Industrial Co., Ltd." }, - { "USR", "U.S. Robotics Inc" }, - { "UTD", "Up to Date Tech" }, - { "UWC", "Uniwill Computer Corp." }, - { "VAD", "Vaddio, LLC" }, - { "VAL", "Valence Computing Corporation" }, - { "VAR", "Varian Australia Pty Ltd" }, - { "VBR", "VBrick Systems Inc." }, - { "VBT", "Valley Board Ltda" }, - { "VCC", "Virtual Computer Corporation" }, - { "VCI", "VistaCom Inc" }, - { "VCJ", "Victor Company of Japan, Limited" }, - { "VCM", "Vector Magnetics, LLC" }, - { "VCX", "VCONEX" }, - { "VDA", "Victor Data Systems" }, - { "VDC", "VDC Display Systems" }, - { "VDM", "Vadem" }, - { "VDO", "Video & Display Oriented Corporation" }, - { "VDS", "Vidisys GmbH & Company" }, - { "VDT", "Viditec, Inc." }, - { "VEC", "Vector Informatik GmbH" }, - { "VEK", "Vektrex" }, - { "VES", "Vestel Elektronik Sanayi ve Ticaret A. S." }, - { "VFI", "VeriFone Inc" }, - { "VHI", "Macrocad Development Inc." }, - { "VIA", "VIA Tech Inc" }, - { "VIB", "Tatung UK Ltd" }, - { "VIC", "Victron B.V." }, - { "VID", "Ingram Macrotron Germany" }, - { "VIK", "Viking Connectors" }, - { "VIM", "Via Mons Ltd." }, - { "VIN", "Vine Micros Ltd" }, - { "VIR", "Visual Interface, Inc" }, - { "VIS", "Visioneer" }, - { "VIT", "Visitech AS" }, - { "VIZ", "VIZIO, Inc" }, - { "VLB", "ValleyBoard Ltda." }, - { "VLK", "Vislink International Ltd" }, - { "VLT", "VideoLan Technologies" }, - { "VMI", "Vermont Microsystems" }, - { "VML", "Vine Micros Limited" }, - { "VMW", "VMware Inc.," }, - { "VNC", "Vinca Corporation" }, - { "VOB", "MaxData Computer AG" }, - { "VPI", "Video Products Inc" }, - { "VPR", "Best Buy" }, - { "VQ@", "Vision Quest" }, - { "VRC", "Virtual Resources Corporation" }, - { "VSC", "ViewSonic Corporation" }, - { "VSD", "3M" }, - { "VSI", "VideoServer" }, - { "VSN", "Ingram Macrotron" }, - { "VSP", "Vision Systems GmbH" }, - { "VSR", "V-Star Electronics Inc." }, - { "VTC", "VTel Corporation" }, - { "VTG", "Voice Technologies Group Inc" }, - { "VTI", "VLSI Tech Inc" }, - { "VTK", "Viewteck Co., Ltd." }, - { "VTL", "Vivid Technology Pte Ltd" }, - { "VTM", "Miltope Corporation" }, - { "VTN", "VIDEOTRON CORP." }, - { "VTS", "VTech Computers Ltd" }, - { "VTV", "VATIV Technologies" }, - { "VTX", "Vestax Corporation" }, - { "VUT", "Vutrix (UK) Ltd" }, - { "VWB", "Vweb Corp." }, - { "WAC", "Wacom Tech" }, - { "WAL", "Wave Access" }, - { "WAN", "DO NOT USE - WAN" }, - { "WAV", "Wavephore" }, - { "WBN", "MicroSoftWare" }, - { "WBS", "WB Systemtechnik GmbH" }, - { "WCI", "Wisecom Inc" }, - { "WCS", "Woodwind Communications Systems Inc" }, - { "WDC", "Western Digital" }, - { "WDE", "Westinghouse Digital Electronics" }, - { "WEB", "WebGear Inc" }, - { "WEC", "Winbond Electronics Corporation" }, - { "WEL", "W-DEV" }, - { "WEY", "WEY Design AG" }, - { "WHI", "Whistle Communications" }, - { "WII", "Innoware Inc" }, - { "WIL", "WIPRO Information Technology Ltd" }, - { "WIN", "Wintop Technology Inc" }, - { "WIP", "Wipro Infotech" }, - { "WKH", "Uni-Take Int'l Inc." }, - { "WLD", "Wildfire Communications Inc" }, - { "WML", "Wolfson Microelectronics Ltd" }, - { "WMO", "Westermo Teleindustri AB" }, - { "WMT", "Winmate Communication Inc" }, - { "WNI", "WillNet Inc." }, - { "WNV", "Winnov L.P." }, - { "WNX", "Wincor Nixdorf International GmbH" }, - { "WPA", "Matsushita Communication Industrial Co., Ltd." }, - { "WPI", "Wearnes Peripherals International (Pte) Ltd" }, - { "WRC", "WiNRADiO Communications" }, - { "WSC", "CIS Technology Inc" }, - { "WSP", "Wireless And Smart Products Inc." }, - { "WST", "Wistron Corporation" }, - { "WTC", "ACC Microelectronics" }, - { "WTI", "WorkStation Tech" }, - { "WTK", "Wearnes Thakral Pte" }, - { "WTS", "Restek Electric Company Ltd" }, - { "WVM", "Wave Systems Corporation" }, - { "WVV", "WolfVision GmbH" }, - { "WWV", "World Wide Video, Inc." }, - { "WXT", "Woxter Technology Co. Ltd" }, - { "WYS", "Wyse Technology" }, - { "WYT", "Wooyoung Image & Information Co.,Ltd." }, - { "XAC", "XAC Automation Corp" }, - { "XAD", "Alpha Data" }, - { "XDM", "XDM Ltd." }, - { "XER", "DO NOT USE - XER" }, - { "XFG", "Jan Strapko - FOTO" }, - { "XFO", "EXFO Electro Optical Engineering" }, - { "XIN", "Xinex Networks Inc" }, - { "XIO", "Xiotech Corporation" }, - { "XIR", "Xirocm Inc" }, - { "XIT", "Xitel Pty ltd" }, - { "XLX", "Xilinx, Inc." }, - { "XMM", "C3PO S.L." }, - { "XNT", "XN Technologies, Inc." }, - { "XOC", "DO NOT USE - XOC" }, - { "XQU", "SHANGHAI SVA-DAV ELECTRONICS CO., LTD" }, - { "XRC", "Xircom Inc" }, - { "XRO", "XORO ELECTRONICS (CHENGDU) LIMITED" }, - { "XSN", "Xscreen AS" }, - { "XST", "XS Technologies Inc" }, - { "XSY", "XSYS" }, - { "XTD", "Icuiti Corporation" }, - { "XTE", "X2E GmbH" }, - { "XTL", "Crystal Computer" }, - { "XTN", "X-10 (USA) Inc" }, - { "XYC", "Xycotec Computer GmbH" }, - { "YED", "Y-E Data Inc" }, - { "YHQ", "Yokogawa Electric Corporation" }, - { "YHW", "Exacom SA" }, - { "YMH", "Yamaha Corporation" }, - { "YOW", "American Biometric Company" }, - { "ZAN", "Zandar Technologies plc" }, - { "ZAX", "Zefiro Acoustics" }, - { "ZAZ", "Zazzle Technologies" }, - { "ZBR", "Zebra Technologies International, LLC" }, - { "ZCT", "ZeitControl cardsystems GmbH" }, - { "ZDS", "Zenith Data Systems" }, - { "ZGT", "Zenith Data Systems" }, - { "ZIC", "Nationz Technologies Inc." }, - { "ZMT", "Zalman Tech Co., Ltd." }, - { "ZMZ", "Z Microsystems" }, - { "ZNI", "Zetinet Inc" }, - { "ZNX", "Znyx Adv. Systems" }, - { "ZOW", "Zowie Intertainment, Inc" }, - { "ZRN", "Zoran Corporation" }, - { "ZSE", "Zenith Data Systems" }, - { "ZTC", "ZyDAS Technology Corporation" }, - { "ZTE", "ZTE Corporation" }, - { "ZTI", "Zoom Telephonics Inc" }, - { "ZTM", "ZT Group Int'l Inc." }, - { "ZTT", "Z3 Technology" }, - { "ZYD", "Zydacron Inc" }, - { "ZYP", "Zypcom Inc" }, - { "ZYT", "Zytex Computers" }, - { "ZYX", "Zyxel" }, - { "ZZZ", "Boca Research Inc" }, -}; - -QT_END_NAMESPACE - -#endif // QEDIDVENDORTABLE_P_H diff --git a/src/platformsupport/eglconvenience/eglconvenience.pro b/src/platformsupport/eglconvenience/eglconvenience.pro deleted file mode 100644 index df21f14697..0000000000 --- a/src/platformsupport/eglconvenience/eglconvenience.pro +++ /dev/null @@ -1,43 +0,0 @@ -TARGET = QtEglSupport -MODULE = egl_support - -QT = core-private gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII -PRECOMPILED_HEADER = ../../corelib/global/qt_pch.h - -HEADERS += \ - qeglconvenience_p.h \ - qeglstreamconvenience_p.h \ - qt_egl_p.h - -SOURCES += \ - qeglconvenience.cpp \ - qeglstreamconvenience.cpp - -qtConfig(opengl) { - HEADERS += \ - qeglplatformcontext_p.h \ - qeglpbuffer_p.h - - SOURCES += \ - qeglplatformcontext.cpp \ - qeglpbuffer.cpp -} - -qtConfig(egl_x11) { - HEADERS += \ - qxlibeglintegration_p.h - SOURCES += \ - qxlibeglintegration.cpp - QMAKE_USE_PRIVATE += xlib -} else { - # Avoid X11 header collision, use generic EGL native types - DEFINES += QT_EGL_NO_X11 -} -CONFIG += egl - -qtConfig(dlopen): QMAKE_USE += libdl - -load(qt_module) diff --git a/src/platformsupport/eglconvenience/qeglconvenience.cpp b/src/platformsupport/eglconvenience/qeglconvenience.cpp deleted file mode 100644 index 5ee4773b70..0000000000 --- a/src/platformsupport/eglconvenience/qeglconvenience.cpp +++ /dev/null @@ -1,627 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QByteArray> -#include <QOpenGLContext> - -#ifdef Q_OS_LINUX -#include <sys/ioctl.h> -#include <linux/fb.h> -#endif -#include <private/qmath_p.h> - -#include "qeglconvenience_p.h" - -#ifndef EGL_OPENGL_ES3_BIT_KHR -#define EGL_OPENGL_ES3_BIT_KHR 0x0040 -#endif - -QT_BEGIN_NAMESPACE - -QVector<EGLint> q_createConfigAttributesFromFormat(const QSurfaceFormat &format) -{ - int redSize = format.redBufferSize(); - int greenSize = format.greenBufferSize(); - int blueSize = format.blueBufferSize(); - int alphaSize = format.alphaBufferSize(); - int depthSize = format.depthBufferSize(); - int stencilSize = format.stencilBufferSize(); - int sampleCount = format.samples(); - - QVector<EGLint> configAttributes; - - // Map default, unspecified values (-1) to 0. This is important due to sorting rule #3 - // in section 3.4.1 of the spec and allows picking a potentially faster 16-bit config - // over 32-bit ones when there is no explicit request for the color channel sizes: - // - // The red/green/blue sizes have a sort priority of 3, so they are sorted by - // first. (unless a caveat like SLOW or NON_CONFORMANT is present) The sort order is - // Special and described as "by larger _total_ number of color bits.". So EGL will put - // 32-bit configs in the list before the 16-bit configs. However, the spec also goes - // on to say "If the requested number of bits in attrib_list for a particular - // component is 0, then the number of bits for that component is not considered". This - // part of the spec also seems to imply that setting the red/green/blue bits to zero - // means none of the components are considered and EGL disregards the entire sorting - // rule. It then looks to the next highest priority rule, which is - // EGL_BUFFER_SIZE. Despite the selection criteria being "AtLeast" for - // EGL_BUFFER_SIZE, it's sort order is "smaller" meaning 16-bit configs are put in the - // list before 32-bit configs. - // - // This also means that explicitly specifying a size like 565 will still result in - // having larger (888) configs first in the returned list. We need to handle this - // ourselves later by manually filtering the list, instead of just blindly taking the - // first config from it. - - configAttributes.append(EGL_RED_SIZE); - configAttributes.append(redSize > 0 ? redSize : 0); - - configAttributes.append(EGL_GREEN_SIZE); - configAttributes.append(greenSize > 0 ? greenSize : 0); - - configAttributes.append(EGL_BLUE_SIZE); - configAttributes.append(blueSize > 0 ? blueSize : 0); - - configAttributes.append(EGL_ALPHA_SIZE); - configAttributes.append(alphaSize > 0 ? alphaSize : 0); - - configAttributes.append(EGL_SAMPLES); - configAttributes.append(sampleCount > 0 ? sampleCount : 0); - - configAttributes.append(EGL_SAMPLE_BUFFERS); - configAttributes.append(sampleCount > 0); - - if (format.renderableType() != QSurfaceFormat::OpenVG) { - configAttributes.append(EGL_DEPTH_SIZE); - configAttributes.append(depthSize > 0 ? depthSize : 0); - - configAttributes.append(EGL_STENCIL_SIZE); - configAttributes.append(stencilSize > 0 ? stencilSize : 0); - } else { - // OpenVG needs alpha mask for clipping - configAttributes.append(EGL_ALPHA_MASK_SIZE); - configAttributes.append(8); - } - - return configAttributes; -} - -bool q_reduceConfigAttributes(QVector<EGLint> *configAttributes) -{ - int i = -1; - // Reduce the complexity of a configuration request to ask for less - // because the previous request did not result in success. Returns - // true if the complexity was reduced, or false if no further - // reductions in complexity are possible. - - i = configAttributes->indexOf(EGL_SWAP_BEHAVIOR); - if (i >= 0) { - configAttributes->remove(i,2); - } - -#ifdef EGL_VG_ALPHA_FORMAT_PRE_BIT - // For OpenVG, we sometimes try to create a surface using a pre-multiplied format. If we can't - // find a config which supports pre-multiplied formats, remove the flag on the surface type: - - i = configAttributes->indexOf(EGL_SURFACE_TYPE); - if (i >= 0) { - EGLint surfaceType = configAttributes->at(i +1); - if (surfaceType & EGL_VG_ALPHA_FORMAT_PRE_BIT) { - surfaceType ^= EGL_VG_ALPHA_FORMAT_PRE_BIT; - configAttributes->replace(i+1,surfaceType); - return true; - } - } -#endif - - // EGL chooses configs with the highest color depth over - // those with smaller (but faster) lower color depths. One - // way around this is to set EGL_BUFFER_SIZE to 16, which - // trumps the others. Of course, there may not be a 16-bit - // config available, so it's the first restraint we remove. - i = configAttributes->indexOf(EGL_BUFFER_SIZE); - if (i >= 0) { - if (configAttributes->at(i+1) == 16) { - configAttributes->remove(i,2); - return true; - } - } - - i = configAttributes->indexOf(EGL_SAMPLES); - if (i >= 0) { - EGLint value = configAttributes->value(i+1, 0); - if (value > 1) - configAttributes->replace(i+1, qMin(EGLint(16), value / 2)); - else - configAttributes->remove(i, 2); - return true; - } - - i = configAttributes->indexOf(EGL_SAMPLE_BUFFERS); - if (i >= 0) { - configAttributes->remove(i,2); - return true; - } - - i = configAttributes->indexOf(EGL_DEPTH_SIZE); - if (i >= 0) { - if (configAttributes->at(i + 1) >= 32) - configAttributes->replace(i + 1, 24); - else if (configAttributes->at(i + 1) > 1) - configAttributes->replace(i + 1, 1); - else - configAttributes->remove(i, 2); - return true; - } - - i = configAttributes->indexOf(EGL_ALPHA_SIZE); - if (i >= 0) { - configAttributes->remove(i,2); -#if defined(EGL_BIND_TO_TEXTURE_RGBA) && defined(EGL_BIND_TO_TEXTURE_RGB) - i = configAttributes->indexOf(EGL_BIND_TO_TEXTURE_RGBA); - if (i >= 0) { - configAttributes->replace(i,EGL_BIND_TO_TEXTURE_RGB); - configAttributes->replace(i+1,true); - - } -#endif - return true; - } - - i = configAttributes->indexOf(EGL_STENCIL_SIZE); - if (i >= 0) { - if (configAttributes->at(i + 1) > 1) - configAttributes->replace(i + 1, 1); - else - configAttributes->remove(i, 2); - return true; - } - -#ifdef EGL_BIND_TO_TEXTURE_RGB - i = configAttributes->indexOf(EGL_BIND_TO_TEXTURE_RGB); - if (i >= 0) { - configAttributes->remove(i,2); - return true; - } -#endif - - return false; -} - -QEglConfigChooser::QEglConfigChooser(EGLDisplay display) - : m_display(display) - , m_surfaceType(EGL_WINDOW_BIT) - , m_ignore(false) - , m_confAttrRed(0) - , m_confAttrGreen(0) - , m_confAttrBlue(0) - , m_confAttrAlpha(0) -{ -} - -QEglConfigChooser::~QEglConfigChooser() -{ -} - -EGLConfig QEglConfigChooser::chooseConfig() -{ - QVector<EGLint> configureAttributes = q_createConfigAttributesFromFormat(m_format); - configureAttributes.append(EGL_SURFACE_TYPE); - configureAttributes.append(surfaceType()); - - configureAttributes.append(EGL_RENDERABLE_TYPE); - bool needsES2Plus = false; - switch (m_format.renderableType()) { - case QSurfaceFormat::OpenVG: - configureAttributes.append(EGL_OPENVG_BIT); - break; -#ifdef EGL_VERSION_1_4 - case QSurfaceFormat::DefaultRenderableType: -#ifndef QT_NO_OPENGL - if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL) - configureAttributes.append(EGL_OPENGL_BIT); - else -#endif // QT_NO_OPENGL - needsES2Plus = true; - break; - case QSurfaceFormat::OpenGL: - configureAttributes.append(EGL_OPENGL_BIT); - break; -#endif - case QSurfaceFormat::OpenGLES: - if (m_format.majorVersion() == 1) { - configureAttributes.append(EGL_OPENGL_ES_BIT); - break; - } - Q_FALLTHROUGH(); - default: - needsES2Plus = true; - break; - } - if (needsES2Plus) { - if (m_format.majorVersion() >= 3 && q_hasEglExtension(display(), "EGL_KHR_create_context")) - configureAttributes.append(EGL_OPENGL_ES3_BIT_KHR); - else - configureAttributes.append(EGL_OPENGL_ES2_BIT); - } - configureAttributes.append(EGL_NONE); - - EGLConfig cfg = 0; - do { - // Get the number of matching configurations for this set of properties. - EGLint matching = 0; - if (!eglChooseConfig(display(), configureAttributes.constData(), 0, 0, &matching) || !matching) - continue; - - // Fetch all of the matching configurations and find the - // first that matches the pixel format we wanted. - int i = configureAttributes.indexOf(EGL_RED_SIZE); - m_confAttrRed = configureAttributes.at(i+1); - i = configureAttributes.indexOf(EGL_GREEN_SIZE); - m_confAttrGreen = configureAttributes.at(i+1); - i = configureAttributes.indexOf(EGL_BLUE_SIZE); - m_confAttrBlue = configureAttributes.at(i+1); - i = configureAttributes.indexOf(EGL_ALPHA_SIZE); - m_confAttrAlpha = i == -1 ? 0 : configureAttributes.at(i+1); - - QVector<EGLConfig> configs(matching); - eglChooseConfig(display(), configureAttributes.constData(), configs.data(), configs.size(), &matching); - if (!cfg && matching > 0) - cfg = configs.first(); - - // Filter the list. Due to the EGL sorting rules configs with higher depth are - // placed first when the minimum color channel sizes have been specified (i.e. the - // QSurfaceFormat contains color sizes > 0). To prevent returning a 888 config - // when the QSurfaceFormat explicitly asked for 565, go through the returned - // configs and look for one that exactly matches the requested sizes. When no - // sizes have been given, take the first, which will be a config with the smaller - // (e.g. 16-bit) depth. - for (int i = 0; i < configs.size(); ++i) { - if (filterConfig(configs[i])) - return configs.at(i); - } - } while (q_reduceConfigAttributes(&configureAttributes)); - - if (!cfg) - qWarning("Cannot find EGLConfig, returning null config"); - return cfg; -} - -bool QEglConfigChooser::filterConfig(EGLConfig config) const -{ - // If we are fine with the highest depth (e.g. RGB888 configs) even when something - // smaller (565) was explicitly requested, do nothing. - if (m_ignore) - return true; - - EGLint red = 0; - EGLint green = 0; - EGLint blue = 0; - EGLint alpha = 0; - - // Compare only if a size was given. Otherwise just accept. - if (m_confAttrRed) - eglGetConfigAttrib(display(), config, EGL_RED_SIZE, &red); - if (m_confAttrGreen) - eglGetConfigAttrib(display(), config, EGL_GREEN_SIZE, &green); - if (m_confAttrBlue) - eglGetConfigAttrib(display(), config, EGL_BLUE_SIZE, &blue); - if (m_confAttrAlpha) - eglGetConfigAttrib(display(), config, EGL_ALPHA_SIZE, &alpha); - - return red == m_confAttrRed && green == m_confAttrGreen - && blue == m_confAttrBlue && alpha == m_confAttrAlpha; -} - -EGLConfig q_configFromGLFormat(EGLDisplay display, const QSurfaceFormat &format, bool highestPixelFormat, int surfaceType) -{ - QEglConfigChooser chooser(display); - chooser.setSurfaceFormat(format); - chooser.setSurfaceType(surfaceType); - chooser.setIgnoreColorChannels(highestPixelFormat); - - return chooser.chooseConfig(); -} - -QSurfaceFormat q_glFormatFromConfig(EGLDisplay display, const EGLConfig config, const QSurfaceFormat &referenceFormat) -{ - QSurfaceFormat format; - EGLint redSize = 0; - EGLint greenSize = 0; - EGLint blueSize = 0; - EGLint alphaSize = 0; - EGLint depthSize = 0; - EGLint stencilSize = 0; - EGLint sampleCount = 0; - EGLint renderableType = 0; - - eglGetConfigAttrib(display, config, EGL_RED_SIZE, &redSize); - eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &greenSize); - eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &blueSize); - eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &alphaSize); - eglGetConfigAttrib(display, config, EGL_DEPTH_SIZE, &depthSize); - eglGetConfigAttrib(display, config, EGL_STENCIL_SIZE, &stencilSize); - eglGetConfigAttrib(display, config, EGL_SAMPLES, &sampleCount); - eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType); - - if (referenceFormat.renderableType() == QSurfaceFormat::OpenVG && (renderableType & EGL_OPENVG_BIT)) - format.setRenderableType(QSurfaceFormat::OpenVG); -#ifdef EGL_VERSION_1_4 - else if (referenceFormat.renderableType() == QSurfaceFormat::OpenGL - && (renderableType & EGL_OPENGL_BIT)) - format.setRenderableType(QSurfaceFormat::OpenGL); - else if (referenceFormat.renderableType() == QSurfaceFormat::DefaultRenderableType -#ifndef QT_NO_OPENGL - && QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL -#endif - && (renderableType & EGL_OPENGL_BIT)) - format.setRenderableType(QSurfaceFormat::OpenGL); -#endif - else - format.setRenderableType(QSurfaceFormat::OpenGLES); - - format.setRedBufferSize(redSize); - format.setGreenBufferSize(greenSize); - format.setBlueBufferSize(blueSize); - format.setAlphaBufferSize(alphaSize); - format.setDepthBufferSize(depthSize); - format.setStencilBufferSize(stencilSize); - format.setSamples(sampleCount); - format.setStereo(false); // EGL doesn't support stereo buffers - format.setSwapInterval(referenceFormat.swapInterval()); - - // Clear the EGL error state because some of the above may - // have errored out because the attribute is not applicable - // to the surface type. Such errors don't matter. - eglGetError(); - - return format; -} - -bool q_hasEglExtension(EGLDisplay display, const char* extensionName) -{ - QList<QByteArray> extensions = - QByteArray(reinterpret_cast<const char *> - (eglQueryString(display, EGL_EXTENSIONS))).split(' '); - return extensions.contains(extensionName); -} - -struct AttrInfo { EGLint attr; const char *name; }; -static struct AttrInfo attrs[] = { - {EGL_BUFFER_SIZE, "EGL_BUFFER_SIZE"}, - {EGL_ALPHA_SIZE, "EGL_ALPHA_SIZE"}, - {EGL_BLUE_SIZE, "EGL_BLUE_SIZE"}, - {EGL_GREEN_SIZE, "EGL_GREEN_SIZE"}, - {EGL_RED_SIZE, "EGL_RED_SIZE"}, - {EGL_DEPTH_SIZE, "EGL_DEPTH_SIZE"}, - {EGL_STENCIL_SIZE, "EGL_STENCIL_SIZE"}, - {EGL_CONFIG_CAVEAT, "EGL_CONFIG_CAVEAT"}, - {EGL_CONFIG_ID, "EGL_CONFIG_ID"}, - {EGL_LEVEL, "EGL_LEVEL"}, - {EGL_MAX_PBUFFER_HEIGHT, "EGL_MAX_PBUFFER_HEIGHT"}, - {EGL_MAX_PBUFFER_PIXELS, "EGL_MAX_PBUFFER_PIXELS"}, - {EGL_MAX_PBUFFER_WIDTH, "EGL_MAX_PBUFFER_WIDTH"}, - {EGL_NATIVE_RENDERABLE, "EGL_NATIVE_RENDERABLE"}, - {EGL_NATIVE_VISUAL_ID, "EGL_NATIVE_VISUAL_ID"}, - {EGL_NATIVE_VISUAL_TYPE, "EGL_NATIVE_VISUAL_TYPE"}, - {EGL_SAMPLES, "EGL_SAMPLES"}, - {EGL_SAMPLE_BUFFERS, "EGL_SAMPLE_BUFFERS"}, - {EGL_SURFACE_TYPE, "EGL_SURFACE_TYPE"}, - {EGL_TRANSPARENT_TYPE, "EGL_TRANSPARENT_TYPE"}, - {EGL_TRANSPARENT_BLUE_VALUE, "EGL_TRANSPARENT_BLUE_VALUE"}, - {EGL_TRANSPARENT_GREEN_VALUE, "EGL_TRANSPARENT_GREEN_VALUE"}, - {EGL_TRANSPARENT_RED_VALUE, "EGL_TRANSPARENT_RED_VALUE"}, - {EGL_BIND_TO_TEXTURE_RGB, "EGL_BIND_TO_TEXTURE_RGB"}, - {EGL_BIND_TO_TEXTURE_RGBA, "EGL_BIND_TO_TEXTURE_RGBA"}, - {EGL_MIN_SWAP_INTERVAL, "EGL_MIN_SWAP_INTERVAL"}, - {EGL_MAX_SWAP_INTERVAL, "EGL_MAX_SWAP_INTERVAL"}, - {-1, 0}}; - -void q_printEglConfig(EGLDisplay display, EGLConfig config) -{ - EGLint index; - for (index = 0; attrs[index].attr != -1; ++index) { - EGLint value; - if (eglGetConfigAttrib(display, config, attrs[index].attr, &value)) { - qDebug("\t%s: %d", attrs[index].name, (int)value); - } - } -} - -#ifdef Q_OS_UNIX - -QSizeF q_physicalScreenSizeFromFb(int framebufferDevice, const QSize &screenSize) -{ -#ifndef Q_OS_LINUX - Q_UNUSED(framebufferDevice) -#endif - const int defaultPhysicalDpi = 100; - static QSizeF size; - - if (size.isEmpty()) { - // Note: in millimeters - int width = qEnvironmentVariableIntValue("QT_QPA_EGLFS_PHYSICAL_WIDTH"); - int height = qEnvironmentVariableIntValue("QT_QPA_EGLFS_PHYSICAL_HEIGHT"); - - if (width && height) { - size.setWidth(width); - size.setHeight(height); - return size; - } - - int w = -1; - int h = -1; - QSize screenResolution; -#ifdef Q_OS_LINUX - struct fb_var_screeninfo vinfo; - - if (framebufferDevice != -1) { - if (ioctl(framebufferDevice, FBIOGET_VSCREENINFO, &vinfo) == -1) { - qWarning("eglconvenience: Could not query screen info"); - } else { - w = vinfo.width; - h = vinfo.height; - screenResolution = QSize(vinfo.xres, vinfo.yres); - } - } else -#endif - { - // Use the provided screen size, when available, since some platforms may have their own - // specific way to query it. Otherwise try querying it from the framebuffer. - screenResolution = screenSize.isEmpty() ? q_screenSizeFromFb(framebufferDevice) : screenSize; - } - - size.setWidth(w <= 0 ? screenResolution.width() * Q_MM_PER_INCH / defaultPhysicalDpi : qreal(w)); - size.setHeight(h <= 0 ? screenResolution.height() * Q_MM_PER_INCH / defaultPhysicalDpi : qreal(h)); - - if (w <= 0 || h <= 0) - qWarning("Unable to query physical screen size, defaulting to %d dpi.\n" - "To override, set QT_QPA_EGLFS_PHYSICAL_WIDTH " - "and QT_QPA_EGLFS_PHYSICAL_HEIGHT (in millimeters).", defaultPhysicalDpi); - } - - return size; -} - -QSize q_screenSizeFromFb(int framebufferDevice) -{ -#ifndef Q_OS_LINUX - Q_UNUSED(framebufferDevice) -#endif - const int defaultWidth = 800; - const int defaultHeight = 600; - static QSize size; - - if (size.isEmpty()) { - int width = qEnvironmentVariableIntValue("QT_QPA_EGLFS_WIDTH"); - int height = qEnvironmentVariableIntValue("QT_QPA_EGLFS_HEIGHT"); - - if (width && height) { - size.setWidth(width); - size.setHeight(height); - return size; - } - -#ifdef Q_OS_LINUX - struct fb_var_screeninfo vinfo; - int xres = -1; - int yres = -1; - - if (framebufferDevice != -1) { - if (ioctl(framebufferDevice, FBIOGET_VSCREENINFO, &vinfo) == -1) { - qWarning("eglconvenience: Could not read screen info"); - } else { - xres = vinfo.xres; - yres = vinfo.yres; - } - } - - size.setWidth(xres <= 0 ? defaultWidth : xres); - size.setHeight(yres <= 0 ? defaultHeight : yres); -#else - size.setWidth(defaultWidth); - size.setHeight(defaultHeight); -#endif - } - - return size; -} - -int q_screenDepthFromFb(int framebufferDevice) -{ -#ifndef Q_OS_LINUX - Q_UNUSED(framebufferDevice) -#endif - const int defaultDepth = 32; - static int depth = qEnvironmentVariableIntValue("QT_QPA_EGLFS_DEPTH"); - - if (depth == 0) { -#ifdef Q_OS_LINUX - struct fb_var_screeninfo vinfo; - - if (framebufferDevice != -1) { - if (ioctl(framebufferDevice, FBIOGET_VSCREENINFO, &vinfo) == -1) - qWarning("eglconvenience: Could not query screen info"); - else - depth = vinfo.bits_per_pixel; - } - - if (depth <= 0) - depth = defaultDepth; -#else - depth = defaultDepth; -#endif - } - - return depth; -} - -qreal q_refreshRateFromFb(int framebufferDevice) -{ -#ifndef Q_OS_LINUX - Q_UNUSED(framebufferDevice) -#endif - - static qreal rate = 0; - -#ifdef Q_OS_LINUX - if (rate == 0) { - if (framebufferDevice != -1) { - struct fb_var_screeninfo vinfo; - if (ioctl(framebufferDevice, FBIOGET_VSCREENINFO, &vinfo) != -1) { - const quint64 quot = quint64(vinfo.left_margin + vinfo.right_margin + vinfo.xres + vinfo.hsync_len) - * quint64(vinfo.upper_margin + vinfo.lower_margin + vinfo.yres + vinfo.vsync_len) - * vinfo.pixclock; - if (quot) - rate = 1000000000000LLU / quot; - } else { - qWarning("eglconvenience: Could not query screen info"); - } - } - } -#endif - - if (rate == 0) - rate = 60; - - return rate; -} - -#endif // Q_OS_UNIX - -QT_END_NAMESPACE diff --git a/src/platformsupport/eglconvenience/qeglconvenience_p.h b/src/platformsupport/eglconvenience/qeglconvenience_p.h deleted file mode 100644 index ab2b813515..0000000000 --- a/src/platformsupport/eglconvenience/qeglconvenience_p.h +++ /dev/null @@ -1,111 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QEGLCONVENIENCE_H -#define QEGLCONVENIENCE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/QSurfaceFormat> -#include <QtCore/QVector> -#include <QtCore/QSizeF> -#include <QtEglSupport/private/qt_egl_p.h> - -QT_BEGIN_NAMESPACE - -QVector<EGLint> q_createConfigAttributesFromFormat(const QSurfaceFormat &format); -bool q_reduceConfigAttributes(QVector<EGLint> *configAttributes); -EGLConfig q_configFromGLFormat(EGLDisplay display, const QSurfaceFormat &format, bool highestPixelFormat = false, int surfaceType = EGL_WINDOW_BIT); -QSurfaceFormat q_glFormatFromConfig(EGLDisplay display, const EGLConfig config, const QSurfaceFormat &referenceFormat = QSurfaceFormat()); -bool q_hasEglExtension(EGLDisplay display,const char* extensionName); -void q_printEglConfig(EGLDisplay display, EGLConfig config); - -#ifdef Q_OS_UNIX -QSizeF q_physicalScreenSizeFromFb(int framebufferDevice, const QSize &screenSize = QSize()); -QSize q_screenSizeFromFb(int framebufferDevice); -int q_screenDepthFromFb(int framebufferDevice); -qreal q_refreshRateFromFb(int framebufferDevice); -#endif - -class QEglConfigChooser -{ -public: - QEglConfigChooser(EGLDisplay display); - virtual ~QEglConfigChooser(); - - EGLDisplay display() const { return m_display; } - - void setSurfaceType(EGLint surfaceType) { m_surfaceType = surfaceType; } - EGLint surfaceType() const { return m_surfaceType; } - - void setSurfaceFormat(const QSurfaceFormat &format) { m_format = format; } - QSurfaceFormat surfaceFormat() const { return m_format; } - - void setIgnoreColorChannels(bool ignore) { m_ignore = ignore; } - bool ignoreColorChannels() const { return m_ignore; } - - EGLConfig chooseConfig(); - -protected: - virtual bool filterConfig(EGLConfig config) const; - - QSurfaceFormat m_format; - EGLDisplay m_display; - EGLint m_surfaceType; - bool m_ignore; - - int m_confAttrRed; - int m_confAttrGreen; - int m_confAttrBlue; - int m_confAttrAlpha; -}; - - -QT_END_NAMESPACE - -#endif //QEGLCONVENIENCE_H diff --git a/src/platformsupport/eglconvenience/qeglpbuffer.cpp b/src/platformsupport/eglconvenience/qeglpbuffer.cpp deleted file mode 100644 index 15fc089778..0000000000 --- a/src/platformsupport/eglconvenience/qeglpbuffer.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtGui/QOffscreenSurface> -#include "qeglpbuffer_p.h" -#include "qeglconvenience_p.h" - -QT_BEGIN_NAMESPACE - -/*! - \class QEGLPbuffer - \brief A pbuffer-based implementation of QPlatformOffscreenSurface for EGL. - \since 5.2 - \internal - \ingroup qpa - - To use this implementation in the platform plugin simply - reimplement QPlatformIntegration::createPlatformOffscreenSurface() - and return a new instance of this class. -*/ - -QEGLPbuffer::QEGLPbuffer(EGLDisplay display, const QSurfaceFormat &format, QOffscreenSurface *offscreenSurface, - QEGLPlatformContext::Flags flags) - : QPlatformOffscreenSurface(offscreenSurface) - , m_format(format) - , m_display(display) - , m_pbuffer(EGL_NO_SURFACE) -{ - m_hasSurfaceless = !flags.testFlag(QEGLPlatformContext::NoSurfaceless) - && q_hasEglExtension(display, "EGL_KHR_surfaceless_context"); - - // Disable surfaceless contexts on Mesa for now. As of 10.6.0 and Intel at least, some - // operations (glReadPixels) are unable to work without a surface since they at some - // point temporarily unbind the current FBO and then later blow up in some seemingly - // safe operations, like setting the viewport, that apparently need access to the - // read/draw surface in the Intel backend. - const char *vendor = eglQueryString(display, EGL_VENDOR); // hard to check for GL_ strings here, so blacklist all Mesa - if (vendor && strstr(vendor, "Mesa")) - m_hasSurfaceless = false; - - if (m_hasSurfaceless) - return; - - EGLConfig config = q_configFromGLFormat(m_display, m_format, false, EGL_PBUFFER_BIT); - - if (config) { - const EGLint attributes[] = { - EGL_WIDTH, offscreenSurface->size().width(), - EGL_HEIGHT, offscreenSurface->size().height(), - EGL_LARGEST_PBUFFER, EGL_FALSE, - EGL_NONE - }; - - m_pbuffer = eglCreatePbufferSurface(m_display, config, attributes); - - if (m_pbuffer != EGL_NO_SURFACE) - m_format = q_glFormatFromConfig(m_display, config); - } -} - -QEGLPbuffer::~QEGLPbuffer() -{ - if (m_pbuffer != EGL_NO_SURFACE) - eglDestroySurface(m_display, m_pbuffer); -} - -bool QEGLPbuffer::isValid() const -{ - return m_pbuffer != EGL_NO_SURFACE || m_hasSurfaceless; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/eglconvenience/qeglpbuffer_p.h b/src/platformsupport/eglconvenience/qeglpbuffer_p.h deleted file mode 100644 index 0285e067a6..0000000000 --- a/src/platformsupport/eglconvenience/qeglpbuffer_p.h +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QEGLPBUFFER_H -#define QEGLPBUFFER_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <qpa/qplatformoffscreensurface.h> -#include <QtEglSupport/private/qeglplatformcontext_p.h> - -QT_BEGIN_NAMESPACE - -class QEGLPbuffer : public QPlatformOffscreenSurface -{ -public: - QEGLPbuffer(EGLDisplay display, const QSurfaceFormat &format, QOffscreenSurface *offscreenSurface, - QEGLPlatformContext::Flags flags = 0); - ~QEGLPbuffer(); - - QSurfaceFormat format() const override { return m_format; } - bool isValid() const override; - - EGLSurface pbuffer() const { return m_pbuffer; } - -private: - QSurfaceFormat m_format; - EGLDisplay m_display; - EGLSurface m_pbuffer; - bool m_hasSurfaceless; -}; - -QT_END_NAMESPACE - -#endif // QEGLPBUFFER_H diff --git a/src/platformsupport/eglconvenience/qeglplatformcontext.cpp b/src/platformsupport/eglconvenience/qeglplatformcontext.cpp deleted file mode 100644 index e44918823b..0000000000 --- a/src/platformsupport/eglconvenience/qeglplatformcontext.cpp +++ /dev/null @@ -1,882 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qeglplatformcontext_p.h" -#include "qeglconvenience_p.h" -#include "qeglpbuffer_p.h" -#include <qpa/qplatformwindow.h> -#include <QOpenGLContext> -#include <QtPlatformHeaders/QEGLNativeContext> -#include <QDebug> - -#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_EMBEDDED) -#include <QtCore/private/qjnihelpers_p.h> -#endif -#ifndef Q_OS_WIN -#include <dlfcn.h> -#endif - -QT_BEGIN_NAMESPACE - -/*! - \class QEGLPlatformContext - \brief An EGL context implementation. - \since 5.2 - \internal - \ingroup qpa - - Implement QPlatformOpenGLContext using EGL. To use it in platform - plugins a subclass must be created since - eglSurfaceForPlatformSurface() has to be reimplemented. This - function is used for mapping platform surfaces (windows) to EGL - surfaces and is necessary since different platform plugins may - have different ways of handling native windows (for example, a - plugin may choose not to back every platform window by a real EGL - surface). Other than that, no further customization is necessary. - */ - -// Constants from EGL_KHR_create_context -#ifndef EGL_CONTEXT_MINOR_VERSION_KHR -#define EGL_CONTEXT_MINOR_VERSION_KHR 0x30FB -#endif -#ifndef EGL_CONTEXT_FLAGS_KHR -#define EGL_CONTEXT_FLAGS_KHR 0x30FC -#endif -#ifndef EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR -#define EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR 0x30FD -#endif -#ifndef EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR -#define EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR 0x00000001 -#endif -#ifndef EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR -#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR 0x00000002 -#endif -#ifndef EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR -#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR 0x00000001 -#endif -#ifndef EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR -#define EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR 0x00000002 -#endif - -// Constants for OpenGL which are not available in the ES headers. -#ifndef GL_CONTEXT_FLAGS -#define GL_CONTEXT_FLAGS 0x821E -#endif -#ifndef GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT -#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x0001 -#endif -#ifndef GL_CONTEXT_FLAG_DEBUG_BIT -#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 -#endif -#ifndef GL_CONTEXT_PROFILE_MASK -#define GL_CONTEXT_PROFILE_MASK 0x9126 -#endif -#ifndef GL_CONTEXT_CORE_PROFILE_BIT -#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 -#endif -#ifndef GL_CONTEXT_COMPATIBILITY_PROFILE_BIT -#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 -#endif - -QEGLPlatformContext::QEGLPlatformContext(const QSurfaceFormat &format, QPlatformOpenGLContext *share, EGLDisplay display, - EGLConfig *config, const QVariant &nativeHandle, Flags flags) - : m_eglDisplay(display) - , m_swapInterval(-1) - , m_swapIntervalEnvChecked(false) - , m_swapIntervalFromEnv(-1) - , m_flags(flags) -{ - if (nativeHandle.isNull()) { - m_eglConfig = config ? *config : q_configFromGLFormat(display, format); - m_ownsContext = true; - init(format, share); - } else { - m_ownsContext = false; - adopt(nativeHandle, share); - } -} - -void QEGLPlatformContext::init(const QSurfaceFormat &format, QPlatformOpenGLContext *share) -{ - m_format = q_glFormatFromConfig(m_eglDisplay, m_eglConfig, format); - // m_format now has the renderableType() resolved (it cannot be Default anymore) - // but does not yet contain version, profile, options. - m_shareContext = share ? static_cast<QEGLPlatformContext *>(share)->m_eglContext : 0; - - QVector<EGLint> contextAttrs; - contextAttrs.append(EGL_CONTEXT_CLIENT_VERSION); - contextAttrs.append(format.majorVersion()); - const bool hasKHRCreateContext = q_hasEglExtension(m_eglDisplay, "EGL_KHR_create_context"); - if (hasKHRCreateContext) { - contextAttrs.append(EGL_CONTEXT_MINOR_VERSION_KHR); - contextAttrs.append(format.minorVersion()); - int flags = 0; - // The debug bit is supported both for OpenGL and OpenGL ES. - if (format.testOption(QSurfaceFormat::DebugContext)) - flags |= EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR; - // The fwdcompat bit is only for OpenGL 3.0+. - if (m_format.renderableType() == QSurfaceFormat::OpenGL - && format.majorVersion() >= 3 - && !format.testOption(QSurfaceFormat::DeprecatedFunctions)) - flags |= EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR; - if (flags) { - contextAttrs.append(EGL_CONTEXT_FLAGS_KHR); - contextAttrs.append(flags); - } - // Profiles are OpenGL only and mandatory in 3.2+. The value is silently ignored for < 3.2. - if (m_format.renderableType() == QSurfaceFormat::OpenGL) { - contextAttrs.append(EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR); - contextAttrs.append(format.profile() == QSurfaceFormat::CoreProfile - ? EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR - : EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR); - } - } - - // Special Options for OpenVG surfaces - if (m_format.renderableType() == QSurfaceFormat::OpenVG) { - contextAttrs.append(EGL_ALPHA_MASK_SIZE); - contextAttrs.append(8); - } - - contextAttrs.append(EGL_NONE); - m_contextAttrs = contextAttrs; - - switch (m_format.renderableType()) { - case QSurfaceFormat::OpenVG: - m_api = EGL_OPENVG_API; - break; -#ifdef EGL_VERSION_1_4 - case QSurfaceFormat::OpenGL: - m_api = EGL_OPENGL_API; - break; -#endif // EGL_VERSION_1_4 - default: - m_api = EGL_OPENGL_ES_API; - break; - } - - eglBindAPI(m_api); - m_eglContext = eglCreateContext(m_eglDisplay, m_eglConfig, m_shareContext, contextAttrs.constData()); - if (m_eglContext == EGL_NO_CONTEXT && m_shareContext != EGL_NO_CONTEXT) { - m_shareContext = 0; - m_eglContext = eglCreateContext(m_eglDisplay, m_eglConfig, 0, contextAttrs.constData()); - } - - if (m_eglContext == EGL_NO_CONTEXT) { - qWarning("QEGLPlatformContext: Failed to create context: %x", eglGetError()); - return; - } - - static const bool printConfig = qEnvironmentVariableIntValue("QT_QPA_EGLFS_DEBUG"); - if (printConfig) { - qDebug() << "Created context for format" << format << "with config:"; - q_printEglConfig(m_eglDisplay, m_eglConfig); - } - - // Cannot just call updateFormatFromGL() since it relies on virtuals. Defer it to initialize(). -} - -void QEGLPlatformContext::adopt(const QVariant &nativeHandle, QPlatformOpenGLContext *share) -{ - if (!nativeHandle.canConvert<QEGLNativeContext>()) { - qWarning("QEGLPlatformContext: Requires a QEGLNativeContext"); - return; - } - QEGLNativeContext handle = nativeHandle.value<QEGLNativeContext>(); - EGLContext context = handle.context(); - if (!context) { - qWarning("QEGLPlatformContext: No EGLContext given"); - return; - } - - // A context belonging to a given EGLDisplay cannot be used with another one. - if (handle.display() != m_eglDisplay) { - qWarning("QEGLPlatformContext: Cannot adopt context from different display"); - return; - } - - // Figure out the EGLConfig. - EGLint value = 0; - eglQueryContext(m_eglDisplay, context, EGL_CONFIG_ID, &value); - EGLint n = 0; - EGLConfig cfg; - const EGLint attribs[] = { EGL_CONFIG_ID, value, EGL_NONE }; - if (eglChooseConfig(m_eglDisplay, attribs, &cfg, 1, &n) && n == 1) { - m_eglConfig = cfg; - m_format = q_glFormatFromConfig(m_eglDisplay, m_eglConfig); - } else { - qWarning("QEGLPlatformContext: Failed to get framebuffer configuration for context"); - } - - // Fetch client API type. - value = 0; - eglQueryContext(m_eglDisplay, context, EGL_CONTEXT_CLIENT_TYPE, &value); - if (value == EGL_OPENGL_API || value == EGL_OPENGL_ES_API) { - // if EGL config supports both OpenGL and OpenGL ES render type, - // q_glFormatFromConfig() with the default "referenceFormat" parameter - // will always figure it out as OpenGL render type. - // We can override it to match user's real render type. - if (value == EGL_OPENGL_ES_API) - m_format.setRenderableType(QSurfaceFormat::OpenGLES); - m_api = value; - eglBindAPI(m_api); - } else { - qWarning("QEGLPlatformContext: Failed to get client API type"); - m_api = EGL_OPENGL_ES_API; - } - - m_eglContext = context; - m_shareContext = share ? static_cast<QEGLPlatformContext *>(share)->m_eglContext : 0; - updateFormatFromGL(); -} - -void QEGLPlatformContext::initialize() -{ - if (m_eglContext != EGL_NO_CONTEXT) - updateFormatFromGL(); -} - -// Base implementation for pbuffers. Subclasses will handle the specialized cases for -// platforms without pbuffers. -EGLSurface QEGLPlatformContext::createTemporaryOffscreenSurface() -{ - // Make the context current to ensure the GL version query works. This needs a surface too. - const EGLint pbufferAttributes[] = { - EGL_WIDTH, 1, - EGL_HEIGHT, 1, - EGL_LARGEST_PBUFFER, EGL_FALSE, - EGL_NONE - }; - - // Cannot just pass m_eglConfig because it may not be suitable for pbuffers. Instead, - // do what QEGLPbuffer would do: request a config with the same attributes but with - // PBUFFER_BIT set. - EGLConfig config = q_configFromGLFormat(m_eglDisplay, m_format, false, EGL_PBUFFER_BIT); - - return eglCreatePbufferSurface(m_eglDisplay, config, pbufferAttributes); -} - -void QEGLPlatformContext::destroyTemporaryOffscreenSurface(EGLSurface surface) -{ - eglDestroySurface(m_eglDisplay, surface); -} - -void QEGLPlatformContext::runGLChecks() -{ - // Nothing to do here, subclasses may override in order to perform OpenGL - // queries needing a context. -} - -void QEGLPlatformContext::updateFormatFromGL() -{ -#ifndef QT_NO_OPENGL - // Have to save & restore to prevent QOpenGLContext::currentContext() from becoming - // inconsistent after QOpenGLContext::create(). - EGLDisplay prevDisplay = eglGetCurrentDisplay(); - if (prevDisplay == EGL_NO_DISPLAY) // when no context is current - prevDisplay = m_eglDisplay; - EGLContext prevContext = eglGetCurrentContext(); - EGLSurface prevSurfaceDraw = eglGetCurrentSurface(EGL_DRAW); - EGLSurface prevSurfaceRead = eglGetCurrentSurface(EGL_READ); - - // Rely on the surfaceless extension, if available. This is beneficial since we can - // avoid creating an extra pbuffer surface which is apparently troublesome with some - // drivers (Mesa) when certain attributes are present (multisampling). - EGLSurface tempSurface = EGL_NO_SURFACE; - EGLContext tempContext = EGL_NO_CONTEXT; - if (m_flags.testFlag(NoSurfaceless) || !q_hasEglExtension(m_eglDisplay, "EGL_KHR_surfaceless_context")) - tempSurface = createTemporaryOffscreenSurface(); - - EGLBoolean ok = eglMakeCurrent(m_eglDisplay, tempSurface, tempSurface, m_eglContext); - if (!ok) { - EGLConfig config = q_configFromGLFormat(m_eglDisplay, m_format, false, EGL_PBUFFER_BIT); - tempContext = eglCreateContext(m_eglDisplay, config, 0, m_contextAttrs.constData()); - if (tempContext != EGL_NO_CONTEXT) - ok = eglMakeCurrent(m_eglDisplay, tempSurface, tempSurface, tempContext); - } - if (ok) { - if (m_format.renderableType() == QSurfaceFormat::OpenGL - || m_format.renderableType() == QSurfaceFormat::OpenGLES) { - const GLubyte *s = glGetString(GL_VERSION); - if (s) { - QByteArray version = QByteArray(reinterpret_cast<const char *>(s)); - int major, minor; - if (QPlatformOpenGLContext::parseOpenGLVersion(version, major, minor)) { -#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_EMBEDDED) - // Some Android 4.2.2 devices report OpenGL ES 3.0 without the functions being available. - static int apiLevel = QtAndroidPrivate::androidSdkVersion(); - if (apiLevel <= 17 && major >= 3) { - major = 2; - minor = 0; - } -#endif - m_format.setMajorVersion(major); - m_format.setMinorVersion(minor); - } - } - m_format.setProfile(QSurfaceFormat::NoProfile); - m_format.setOptions(QSurfaceFormat::FormatOptions()); - if (m_format.renderableType() == QSurfaceFormat::OpenGL) { - // Check profile and options. - if (m_format.majorVersion() < 3) { - m_format.setOption(QSurfaceFormat::DeprecatedFunctions); - } else { - GLint value = 0; - glGetIntegerv(GL_CONTEXT_FLAGS, &value); - if (!(value & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT)) - m_format.setOption(QSurfaceFormat::DeprecatedFunctions); - if (value & GL_CONTEXT_FLAG_DEBUG_BIT) - m_format.setOption(QSurfaceFormat::DebugContext); - if (m_format.version() >= qMakePair(3, 2)) { - value = 0; - glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &value); - if (value & GL_CONTEXT_CORE_PROFILE_BIT) - m_format.setProfile(QSurfaceFormat::CoreProfile); - else if (value & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) - m_format.setProfile(QSurfaceFormat::CompatibilityProfile); - } - } - } - } - runGLChecks(); - eglMakeCurrent(prevDisplay, prevSurfaceDraw, prevSurfaceRead, prevContext); - } else { - qWarning("QEGLPlatformContext: Failed to make temporary surface current, format not updated (%x)", eglGetError()); - } - if (tempSurface != EGL_NO_SURFACE) - destroyTemporaryOffscreenSurface(tempSurface); - if (tempContext != EGL_NO_CONTEXT) - eglDestroyContext(m_eglDisplay, tempContext); -#endif // QT_NO_OPENGL -} - -bool QEGLPlatformContext::makeCurrent(QPlatformSurface *surface) -{ - Q_ASSERT(surface->surface()->supportsOpenGL()); - - eglBindAPI(m_api); - - EGLSurface eglSurface = eglSurfaceForPlatformSurface(surface); - - // shortcut: on some GPUs, eglMakeCurrent is not a cheap operation - if (eglGetCurrentContext() == m_eglContext && - eglGetCurrentDisplay() == m_eglDisplay && - eglGetCurrentSurface(EGL_READ) == eglSurface && - eglGetCurrentSurface(EGL_DRAW) == eglSurface) { - return true; - } - - const bool ok = eglMakeCurrent(m_eglDisplay, eglSurface, eglSurface, m_eglContext); - if (ok) { - if (!m_swapIntervalEnvChecked) { - m_swapIntervalEnvChecked = true; - if (qEnvironmentVariableIsSet("QT_QPA_EGLFS_SWAPINTERVAL")) { - QByteArray swapIntervalString = qgetenv("QT_QPA_EGLFS_SWAPINTERVAL"); - bool intervalOk; - const int swapInterval = swapIntervalString.toInt(&intervalOk); - if (intervalOk) - m_swapIntervalFromEnv = swapInterval; - } - } - const int requestedSwapInterval = m_swapIntervalFromEnv >= 0 - ? m_swapIntervalFromEnv - : surface->format().swapInterval(); - if (requestedSwapInterval >= 0 && m_swapInterval != requestedSwapInterval) { - m_swapInterval = requestedSwapInterval; - if (eglSurface != EGL_NO_SURFACE) // skip if using surfaceless context - eglSwapInterval(eglDisplay(), m_swapInterval); - } - } else { - qWarning("QEGLPlatformContext: eglMakeCurrent failed: %x", eglGetError()); - } - - return ok; -} - -QEGLPlatformContext::~QEGLPlatformContext() -{ - if (m_ownsContext && m_eglContext != EGL_NO_CONTEXT) - eglDestroyContext(m_eglDisplay, m_eglContext); - - m_eglContext = EGL_NO_CONTEXT; -} - -void QEGLPlatformContext::doneCurrent() -{ - eglBindAPI(m_api); - bool ok = eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - if (!ok) - qWarning("QEGLPlatformContext: eglMakeCurrent failed: %x", eglGetError()); -} - -void QEGLPlatformContext::swapBuffers(QPlatformSurface *surface) -{ - eglBindAPI(m_api); - EGLSurface eglSurface = eglSurfaceForPlatformSurface(surface); - if (eglSurface != EGL_NO_SURFACE) { // skip if using surfaceless context - bool ok = eglSwapBuffers(m_eglDisplay, eglSurface); - if (!ok) - qWarning("QEGLPlatformContext: eglSwapBuffers failed: %x", eglGetError()); - } -} - -QFunctionPointer QEGLPlatformContext::getProcAddress(const char *procName) -{ - eglBindAPI(m_api); - QFunctionPointer proc = (QFunctionPointer) eglGetProcAddress(procName); -#if !defined(Q_OS_WIN) && !defined(Q_OS_INTEGRITY) - if (!proc) - proc = (QFunctionPointer) dlsym(RTLD_DEFAULT, procName); -#elif !defined(QT_OPENGL_DYNAMIC) - // On systems without KHR_get_all_proc_addresses and without - // dynamic linking there still has to be a way to access the - // standard GLES functions. QOpenGL(Extra)Functions never makes - // direct GL API calls since Qt 5.7, so all such workarounds are - // expected to be handled in the platform plugin. - if (!proc) { - static struct StdFunc { - const char *name; - QFunctionPointer func; - } standardFuncs[] = { -#ifdef QT_OPENGL_ES_2 - { "glBindTexture", (QFunctionPointer) ::glBindTexture }, - { "glBlendFunc", (QFunctionPointer) ::glBlendFunc }, - { "glClear", (QFunctionPointer) ::glClear }, - { "glClearColor", (QFunctionPointer) ::glClearColor }, - { "glClearStencil", (QFunctionPointer) ::glClearStencil }, - { "glColorMask", (QFunctionPointer) ::glColorMask }, - { "glCopyTexImage2D", (QFunctionPointer) ::glCopyTexImage2D }, - { "glCopyTexSubImage2D", (QFunctionPointer) ::glCopyTexSubImage2D }, - { "glCullFace", (QFunctionPointer) ::glCullFace }, - { "glDeleteTextures", (QFunctionPointer) ::glDeleteTextures }, - { "glDepthFunc", (QFunctionPointer) ::glDepthFunc }, - { "glDepthMask", (QFunctionPointer) ::glDepthMask }, - { "glDisable", (QFunctionPointer) ::glDisable }, - { "glDrawArrays", (QFunctionPointer) ::glDrawArrays }, - { "glDrawElements", (QFunctionPointer) ::glDrawElements }, - { "glEnable", (QFunctionPointer) ::glEnable }, - { "glFinish", (QFunctionPointer) ::glFinish }, - { "glFlush", (QFunctionPointer) ::glFlush }, - { "glFrontFace", (QFunctionPointer) ::glFrontFace }, - { "glGenTextures", (QFunctionPointer) ::glGenTextures }, - { "glGetBooleanv", (QFunctionPointer) ::glGetBooleanv }, - { "glGetError", (QFunctionPointer) ::glGetError }, - { "glGetFloatv", (QFunctionPointer) ::glGetFloatv }, - { "glGetIntegerv", (QFunctionPointer) ::glGetIntegerv }, - { "glGetString", (QFunctionPointer) ::glGetString }, - { "glGetTexParameterfv", (QFunctionPointer) ::glGetTexParameterfv }, - { "glGetTexParameteriv", (QFunctionPointer) ::glGetTexParameteriv }, - { "glHint", (QFunctionPointer) ::glHint }, - { "glIsEnabled", (QFunctionPointer) ::glIsEnabled }, - { "glIsTexture", (QFunctionPointer) ::glIsTexture }, - { "glLineWidth", (QFunctionPointer) ::glLineWidth }, - { "glPixelStorei", (QFunctionPointer) ::glPixelStorei }, - { "glPolygonOffset", (QFunctionPointer) ::glPolygonOffset }, - { "glReadPixels", (QFunctionPointer) ::glReadPixels }, - { "glScissor", (QFunctionPointer) ::glScissor }, - { "glStencilFunc", (QFunctionPointer) ::glStencilFunc }, - { "glStencilMask", (QFunctionPointer) ::glStencilMask }, - { "glStencilOp", (QFunctionPointer) ::glStencilOp }, - { "glTexImage2D", (QFunctionPointer) ::glTexImage2D }, - { "glTexParameterf", (QFunctionPointer) ::glTexParameterf }, - { "glTexParameterfv", (QFunctionPointer) ::glTexParameterfv }, - { "glTexParameteri", (QFunctionPointer) ::glTexParameteri }, - { "glTexParameteriv", (QFunctionPointer) ::glTexParameteriv }, - { "glTexSubImage2D", (QFunctionPointer) ::glTexSubImage2D }, - { "glViewport", (QFunctionPointer) ::glViewport }, - - { "glActiveTexture", (QFunctionPointer) ::glActiveTexture }, - { "glAttachShader", (QFunctionPointer) ::glAttachShader }, - { "glBindAttribLocation", (QFunctionPointer) ::glBindAttribLocation }, - { "glBindBuffer", (QFunctionPointer) ::glBindBuffer }, - { "glBindFramebuffer", (QFunctionPointer) ::glBindFramebuffer }, - { "glBindRenderbuffer", (QFunctionPointer) ::glBindRenderbuffer }, - { "glBlendColor", (QFunctionPointer) ::glBlendColor }, - { "glBlendEquation", (QFunctionPointer) ::glBlendEquation }, - { "glBlendEquationSeparate", (QFunctionPointer) ::glBlendEquationSeparate }, - { "glBlendFuncSeparate", (QFunctionPointer) ::glBlendFuncSeparate }, - { "glBufferData", (QFunctionPointer) ::glBufferData }, - { "glBufferSubData", (QFunctionPointer) ::glBufferSubData }, - { "glCheckFramebufferStatus", (QFunctionPointer) ::glCheckFramebufferStatus }, - { "glCompileShader", (QFunctionPointer) ::glCompileShader }, - { "glCompressedTexImage2D", (QFunctionPointer) ::glCompressedTexImage2D }, - { "glCompressedTexSubImage2D", (QFunctionPointer) ::glCompressedTexSubImage2D }, - { "glCreateProgram", (QFunctionPointer) ::glCreateProgram }, - { "glCreateShader", (QFunctionPointer) ::glCreateShader }, - { "glDeleteBuffers", (QFunctionPointer) ::glDeleteBuffers }, - { "glDeleteFramebuffers", (QFunctionPointer) ::glDeleteFramebuffers }, - { "glDeleteProgram", (QFunctionPointer) ::glDeleteProgram }, - { "glDeleteRenderbuffers", (QFunctionPointer) ::glDeleteRenderbuffers }, - { "glDeleteShader", (QFunctionPointer) ::glDeleteShader }, - { "glDetachShader", (QFunctionPointer) ::glDetachShader }, - { "glDisableVertexAttribArray", (QFunctionPointer) ::glDisableVertexAttribArray }, - { "glEnableVertexAttribArray", (QFunctionPointer) ::glEnableVertexAttribArray }, - { "glFramebufferRenderbuffer", (QFunctionPointer) ::glFramebufferRenderbuffer }, - { "glFramebufferTexture2D", (QFunctionPointer) ::glFramebufferTexture2D }, - { "glGenBuffers", (QFunctionPointer) ::glGenBuffers }, - { "glGenerateMipmap", (QFunctionPointer) ::glGenerateMipmap }, - { "glGenFramebuffers", (QFunctionPointer) ::glGenFramebuffers }, - { "glGenRenderbuffers", (QFunctionPointer) ::glGenRenderbuffers }, - { "glGetActiveAttrib", (QFunctionPointer) ::glGetActiveAttrib }, - { "glGetActiveUniform", (QFunctionPointer) ::glGetActiveUniform }, - { "glGetAttachedShaders", (QFunctionPointer) ::glGetAttachedShaders }, - { "glGetAttribLocation", (QFunctionPointer) ::glGetAttribLocation }, - { "glGetBufferParameteriv", (QFunctionPointer) ::glGetBufferParameteriv }, - { "glGetFramebufferAttachmentParameteriv", (QFunctionPointer) ::glGetFramebufferAttachmentParameteriv }, - { "glGetProgramiv", (QFunctionPointer) ::glGetProgramiv }, - { "glGetProgramInfoLog", (QFunctionPointer) ::glGetProgramInfoLog }, - { "glGetRenderbufferParameteriv", (QFunctionPointer) ::glGetRenderbufferParameteriv }, - { "glGetShaderiv", (QFunctionPointer) ::glGetShaderiv }, - { "glGetShaderInfoLog", (QFunctionPointer) ::glGetShaderInfoLog }, - { "glGetShaderPrecisionFormat", (QFunctionPointer) ::glGetShaderPrecisionFormat }, - { "glGetShaderSource", (QFunctionPointer) ::glGetShaderSource }, - { "glGetUniformfv", (QFunctionPointer) ::glGetUniformfv }, - { "glGetUniformiv", (QFunctionPointer) ::glGetUniformiv }, - { "glGetUniformLocation", (QFunctionPointer) ::glGetUniformLocation }, - { "glGetVertexAttribfv", (QFunctionPointer) ::glGetVertexAttribfv }, - { "glGetVertexAttribiv", (QFunctionPointer) ::glGetVertexAttribiv }, - { "glGetVertexAttribPointerv", (QFunctionPointer) ::glGetVertexAttribPointerv }, - { "glIsBuffer", (QFunctionPointer) ::glIsBuffer }, - { "glIsFramebuffer", (QFunctionPointer) ::glIsFramebuffer }, - { "glIsProgram", (QFunctionPointer) ::glIsProgram }, - { "glIsRenderbuffer", (QFunctionPointer) ::glIsRenderbuffer }, - { "glIsShader", (QFunctionPointer) ::glIsShader }, - { "glLinkProgram", (QFunctionPointer) ::glLinkProgram }, - { "glReleaseShaderCompiler", (QFunctionPointer) ::glReleaseShaderCompiler }, - { "glRenderbufferStorage", (QFunctionPointer) ::glRenderbufferStorage }, - { "glSampleCoverage", (QFunctionPointer) ::glSampleCoverage }, - { "glShaderBinary", (QFunctionPointer) ::glShaderBinary }, - { "glShaderSource", (QFunctionPointer) ::glShaderSource }, - { "glStencilFuncSeparate", (QFunctionPointer) ::glStencilFuncSeparate }, - { "glStencilMaskSeparate", (QFunctionPointer) ::glStencilMaskSeparate }, - { "glStencilOpSeparate", (QFunctionPointer) ::glStencilOpSeparate }, - { "glUniform1f", (QFunctionPointer) ::glUniform1f }, - { "glUniform1fv", (QFunctionPointer) ::glUniform1fv }, - { "glUniform1i", (QFunctionPointer) ::glUniform1i }, - { "glUniform1iv", (QFunctionPointer) ::glUniform1iv }, - { "glUniform2f", (QFunctionPointer) ::glUniform2f }, - { "glUniform2fv", (QFunctionPointer) ::glUniform2fv }, - { "glUniform2i", (QFunctionPointer) ::glUniform2i }, - { "glUniform2iv", (QFunctionPointer) ::glUniform2iv }, - { "glUniform3f", (QFunctionPointer) ::glUniform3f }, - { "glUniform3fv", (QFunctionPointer) ::glUniform3fv }, - { "glUniform3i", (QFunctionPointer) ::glUniform3i }, - { "glUniform3iv", (QFunctionPointer) ::glUniform3iv }, - { "glUniform4f", (QFunctionPointer) ::glUniform4f }, - { "glUniform4fv", (QFunctionPointer) ::glUniform4fv }, - { "glUniform4i", (QFunctionPointer) ::glUniform4i }, - { "glUniform4iv", (QFunctionPointer) ::glUniform4iv }, - { "glUniformMatrix2fv", (QFunctionPointer) ::glUniformMatrix2fv }, - { "glUniformMatrix3fv", (QFunctionPointer) ::glUniformMatrix3fv }, - { "glUniformMatrix4fv", (QFunctionPointer) ::glUniformMatrix4fv }, - { "glUseProgram", (QFunctionPointer) ::glUseProgram }, - { "glValidateProgram", (QFunctionPointer) ::glValidateProgram }, - { "glVertexAttrib1f", (QFunctionPointer) ::glVertexAttrib1f }, - { "glVertexAttrib1fv", (QFunctionPointer) ::glVertexAttrib1fv }, - { "glVertexAttrib2f", (QFunctionPointer) ::glVertexAttrib2f }, - { "glVertexAttrib2fv", (QFunctionPointer) ::glVertexAttrib2fv }, - { "glVertexAttrib3f", (QFunctionPointer) ::glVertexAttrib3f }, - { "glVertexAttrib3fv", (QFunctionPointer) ::glVertexAttrib3fv }, - { "glVertexAttrib4f", (QFunctionPointer) ::glVertexAttrib4f }, - { "glVertexAttrib4fv", (QFunctionPointer) ::glVertexAttrib4fv }, - { "glVertexAttribPointer", (QFunctionPointer) ::glVertexAttribPointer }, - - { "glClearDepthf", (QFunctionPointer) ::glClearDepthf }, - { "glDepthRangef", (QFunctionPointer) ::glDepthRangef }, -#endif // QT_OPENGL_ES_2 - -#ifdef QT_OPENGL_ES_3 - { "glBeginQuery", (QFunctionPointer) ::glBeginQuery }, - { "glBeginTransformFeedback", (QFunctionPointer) ::glBeginTransformFeedback }, - { "glBindBufferBase", (QFunctionPointer) ::glBindBufferBase }, - { "glBindBufferRange", (QFunctionPointer) ::glBindBufferRange }, - { "glBindSampler", (QFunctionPointer) ::glBindSampler }, - { "glBindTransformFeedback", (QFunctionPointer) ::glBindTransformFeedback }, - { "glBindVertexArray", (QFunctionPointer) ::glBindVertexArray }, - { "glBlitFramebuffer", (QFunctionPointer) ::glBlitFramebuffer }, - { "glClearBufferfi", (QFunctionPointer) ::glClearBufferfi }, - { "glClearBufferfv", (QFunctionPointer) ::glClearBufferfv }, - { "glClearBufferiv", (QFunctionPointer) ::glClearBufferiv }, - { "glClearBufferuiv", (QFunctionPointer) ::glClearBufferuiv }, - { "glClientWaitSync", (QFunctionPointer) ::glClientWaitSync }, - { "glCompressedTexImage3D", (QFunctionPointer) ::glCompressedTexImage3D }, - { "glCompressedTexSubImage3D", (QFunctionPointer) ::glCompressedTexSubImage3D }, - { "glCopyBufferSubData", (QFunctionPointer) ::glCopyBufferSubData }, - { "glCopyTexSubImage3D", (QFunctionPointer) ::glCopyTexSubImage3D }, - { "glDeleteQueries", (QFunctionPointer) ::glDeleteQueries }, - { "glDeleteSamplers", (QFunctionPointer) ::glDeleteSamplers }, - { "glDeleteSync", (QFunctionPointer) ::glDeleteSync }, - { "glDeleteTransformFeedbacks", (QFunctionPointer) ::glDeleteTransformFeedbacks }, - { "glDeleteVertexArrays", (QFunctionPointer) ::glDeleteVertexArrays }, - { "glDrawArraysInstanced", (QFunctionPointer) ::glDrawArraysInstanced }, - { "glDrawBuffers", (QFunctionPointer) ::glDrawBuffers }, - { "glDrawElementsInstanced", (QFunctionPointer) ::glDrawElementsInstanced }, - { "glDrawRangeElements", (QFunctionPointer) ::glDrawRangeElements }, - { "glEndQuery", (QFunctionPointer) ::glEndQuery }, - { "glEndTransformFeedback", (QFunctionPointer) ::glEndTransformFeedback }, - { "glFenceSync", (QFunctionPointer) ::glFenceSync }, - { "glFlushMappedBufferRange", (QFunctionPointer) ::glFlushMappedBufferRange }, - { "glFramebufferTextureLayer", (QFunctionPointer) ::glFramebufferTextureLayer }, - { "glGenQueries", (QFunctionPointer) ::glGenQueries }, - { "glGenSamplers", (QFunctionPointer) ::glGenSamplers }, - { "glGenTransformFeedbacks", (QFunctionPointer) ::glGenTransformFeedbacks }, - { "glGenVertexArrays", (QFunctionPointer) ::glGenVertexArrays }, - { "glGetActiveUniformBlockName", (QFunctionPointer) ::glGetActiveUniformBlockName }, - { "glGetActiveUniformBlockiv", (QFunctionPointer) ::glGetActiveUniformBlockiv }, - { "glGetActiveUniformsiv", (QFunctionPointer) ::glGetActiveUniformsiv }, - { "glGetBufferParameteri64v", (QFunctionPointer) ::glGetBufferParameteri64v }, - { "glGetBufferPointerv", (QFunctionPointer) ::glGetBufferPointerv }, - { "glGetFragDataLocation", (QFunctionPointer) ::glGetFragDataLocation }, - { "glGetInteger64i_v", (QFunctionPointer) ::glGetInteger64i_v }, - { "glGetInteger64v", (QFunctionPointer) ::glGetInteger64v }, - { "glGetIntegeri_v", (QFunctionPointer) ::glGetIntegeri_v }, - { "glGetInternalformativ", (QFunctionPointer) ::glGetInternalformativ }, - { "glGetProgramBinary", (QFunctionPointer) ::glGetProgramBinary }, - { "glGetQueryObjectuiv", (QFunctionPointer) ::glGetQueryObjectuiv }, - { "glGetQueryiv", (QFunctionPointer) ::glGetQueryiv }, - { "glGetSamplerParameterfv", (QFunctionPointer) ::glGetSamplerParameterfv }, - { "glGetSamplerParameteriv", (QFunctionPointer) ::glGetSamplerParameteriv }, - { "glGetStringi", (QFunctionPointer) ::glGetStringi }, - { "glGetSynciv", (QFunctionPointer) ::glGetSynciv }, - { "glGetTransformFeedbackVarying", (QFunctionPointer) ::glGetTransformFeedbackVarying }, - { "glGetUniformBlockIndex", (QFunctionPointer) ::glGetUniformBlockIndex }, - { "glGetUniformIndices", (QFunctionPointer) ::glGetUniformIndices }, - { "glGetUniformuiv", (QFunctionPointer) ::glGetUniformuiv }, - { "glGetVertexAttribIiv", (QFunctionPointer) ::glGetVertexAttribIiv }, - { "glGetVertexAttribIuiv", (QFunctionPointer) ::glGetVertexAttribIuiv }, - { "glInvalidateFramebuffer", (QFunctionPointer) ::glInvalidateFramebuffer }, - { "glInvalidateSubFramebuffer", (QFunctionPointer) ::glInvalidateSubFramebuffer }, - { "glIsQuery", (QFunctionPointer) ::glIsQuery }, - { "glIsSampler", (QFunctionPointer) ::glIsSampler }, - { "glIsSync", (QFunctionPointer) ::glIsSync }, - { "glIsTransformFeedback", (QFunctionPointer) ::glIsTransformFeedback }, - { "glIsVertexArray", (QFunctionPointer) ::glIsVertexArray }, - { "glMapBufferRange", (QFunctionPointer) ::glMapBufferRange }, - { "glPauseTransformFeedback", (QFunctionPointer) ::glPauseTransformFeedback }, - { "glProgramBinary", (QFunctionPointer) ::glProgramBinary }, - { "glProgramParameteri", (QFunctionPointer) ::glProgramParameteri }, - { "glReadBuffer", (QFunctionPointer) ::glReadBuffer }, - { "glRenderbufferStorageMultisample", (QFunctionPointer) ::glRenderbufferStorageMultisample }, - { "glResumeTransformFeedback", (QFunctionPointer) ::glResumeTransformFeedback }, - { "glSamplerParameterf", (QFunctionPointer) ::glSamplerParameterf }, - { "glSamplerParameterfv", (QFunctionPointer) ::glSamplerParameterfv }, - { "glSamplerParameteri", (QFunctionPointer) ::glSamplerParameteri }, - { "glSamplerParameteriv", (QFunctionPointer) ::glSamplerParameteriv }, - { "glTexImage3D", (QFunctionPointer) ::glTexImage3D }, - { "glTexStorage2D", (QFunctionPointer) ::glTexStorage2D }, - { "glTexStorage3D", (QFunctionPointer) ::glTexStorage3D }, - { "glTexSubImage3D", (QFunctionPointer) ::glTexSubImage3D }, - { "glTransformFeedbackVaryings", (QFunctionPointer) ::glTransformFeedbackVaryings }, - { "glUniform1ui", (QFunctionPointer) ::glUniform1ui }, - { "glUniform1uiv", (QFunctionPointer) ::glUniform1uiv }, - { "glUniform2ui", (QFunctionPointer) ::glUniform2ui }, - { "glUniform2uiv", (QFunctionPointer) ::glUniform2uiv }, - { "glUniform3ui", (QFunctionPointer) ::glUniform3ui }, - { "glUniform3uiv", (QFunctionPointer) ::glUniform3uiv }, - { "glUniform4ui", (QFunctionPointer) ::glUniform4ui }, - { "glUniform4uiv", (QFunctionPointer) ::glUniform4uiv }, - { "glUniformBlockBinding", (QFunctionPointer) ::glUniformBlockBinding }, - { "glUniformMatrix2x3fv", (QFunctionPointer) ::glUniformMatrix2x3fv }, - { "glUniformMatrix2x4fv", (QFunctionPointer) ::glUniformMatrix2x4fv }, - { "glUniformMatrix3x2fv", (QFunctionPointer) ::glUniformMatrix3x2fv }, - { "glUniformMatrix3x4fv", (QFunctionPointer) ::glUniformMatrix3x4fv }, - { "glUniformMatrix4x2fv", (QFunctionPointer) ::glUniformMatrix4x2fv }, - { "glUniformMatrix4x3fv", (QFunctionPointer) ::glUniformMatrix4x3fv }, - { "glUnmapBuffer", (QFunctionPointer) ::glUnmapBuffer }, - { "glVertexAttribDivisor", (QFunctionPointer) ::glVertexAttribDivisor }, - { "glVertexAttribI4i", (QFunctionPointer) ::glVertexAttribI4i }, - { "glVertexAttribI4iv", (QFunctionPointer) ::glVertexAttribI4iv }, - { "glVertexAttribI4ui", (QFunctionPointer) ::glVertexAttribI4ui }, - { "glVertexAttribI4uiv", (QFunctionPointer) ::glVertexAttribI4uiv }, - { "glVertexAttribIPointer", (QFunctionPointer) ::glVertexAttribIPointer }, - { "glWaitSync", (QFunctionPointer) ::glWaitSync }, -#endif // QT_OPENGL_ES_3 - -#ifdef QT_OPENGL_ES_3_1 - { "glActiveShaderProgram", (QFunctionPointer) ::glActiveShaderProgram }, - { "glBindImageTexture", (QFunctionPointer) ::glBindImageTexture }, - { "glBindProgramPipeline", (QFunctionPointer) ::glBindProgramPipeline }, - { "glBindVertexBuffer", (QFunctionPointer) ::glBindVertexBuffer }, - { "glCreateShaderProgramv", (QFunctionPointer) ::glCreateShaderProgramv }, - { "glDeleteProgramPipelines", (QFunctionPointer) ::glDeleteProgramPipelines }, - { "glDispatchCompute", (QFunctionPointer) ::glDispatchCompute }, - { "glDispatchComputeIndirect", (QFunctionPointer) ::glDispatchComputeIndirect }, - { "glDrawArraysIndirect", (QFunctionPointer) ::glDrawArraysIndirect }, - { "glDrawElementsIndirect", (QFunctionPointer) ::glDrawElementsIndirect }, - { "glFramebufferParameteri", (QFunctionPointer) ::glFramebufferParameteri }, - { "glGenProgramPipelines", (QFunctionPointer) ::glGenProgramPipelines }, - { "glGetBooleani_v", (QFunctionPointer) ::glGetBooleani_v }, - { "glGetFramebufferParameteriv", (QFunctionPointer) ::glGetFramebufferParameteriv }, - { "glGetMultisamplefv", (QFunctionPointer) ::glGetMultisamplefv }, - { "glGetProgramInterfaceiv", (QFunctionPointer) ::glGetProgramInterfaceiv }, - { "glGetProgramPipelineInfoLog", (QFunctionPointer) ::glGetProgramPipelineInfoLog }, - { "glGetProgramPipelineiv", (QFunctionPointer) ::glGetProgramPipelineiv }, - { "glGetProgramResourceIndex", (QFunctionPointer) ::glGetProgramResourceIndex }, - { "glGetProgramResourceLocation", (QFunctionPointer) ::glGetProgramResourceLocation }, - { "glGetProgramResourceName", (QFunctionPointer) ::glGetProgramResourceName }, - { "glGetProgramResourceiv", (QFunctionPointer) ::glGetProgramResourceiv }, - { "glGetTexLevelParameterfv", (QFunctionPointer) ::glGetTexLevelParameterfv }, - { "glGetTexLevelParameteriv", (QFunctionPointer) ::glGetTexLevelParameteriv }, - { "glIsProgramPipeline", (QFunctionPointer) ::glIsProgramPipeline }, - { "glMemoryBarrier", (QFunctionPointer) ::glMemoryBarrier }, - { "glMemoryBarrierByRegion", (QFunctionPointer) ::glMemoryBarrierByRegion }, - { "glProgramUniform1f", (QFunctionPointer) ::glProgramUniform1f }, - { "glProgramUniform1fv", (QFunctionPointer) ::glProgramUniform1fv }, - { "glProgramUniform1i", (QFunctionPointer) ::glProgramUniform1i }, - { "glProgramUniform1iv", (QFunctionPointer) ::glProgramUniform1iv }, - { "glProgramUniform1ui", (QFunctionPointer) ::glProgramUniform1ui }, - { "glProgramUniform1uiv", (QFunctionPointer) ::glProgramUniform1uiv }, - { "glProgramUniform2f", (QFunctionPointer) ::glProgramUniform2f }, - { "glProgramUniform2fv", (QFunctionPointer) ::glProgramUniform2fv }, - { "glProgramUniform2i", (QFunctionPointer) ::glProgramUniform2i }, - { "glProgramUniform2iv", (QFunctionPointer) ::glProgramUniform2iv }, - { "glProgramUniform2ui", (QFunctionPointer) ::glProgramUniform2ui }, - { "glProgramUniform2uiv", (QFunctionPointer) ::glProgramUniform2uiv }, - { "glProgramUniform3f", (QFunctionPointer) ::glProgramUniform3f }, - { "glProgramUniform3fv", (QFunctionPointer) ::glProgramUniform3fv }, - { "glProgramUniform3i", (QFunctionPointer) ::glProgramUniform3i }, - { "glProgramUniform3iv", (QFunctionPointer) ::glProgramUniform3iv }, - { "glProgramUniform3ui", (QFunctionPointer) ::glProgramUniform3ui }, - { "glProgramUniform3uiv", (QFunctionPointer) ::glProgramUniform3uiv }, - { "glProgramUniform4f", (QFunctionPointer) ::glProgramUniform4f }, - { "glProgramUniform4fv", (QFunctionPointer) ::glProgramUniform4fv }, - { "glProgramUniform4i", (QFunctionPointer) ::glProgramUniform4i }, - { "glProgramUniform4iv", (QFunctionPointer) ::glProgramUniform4iv }, - { "glProgramUniform4ui", (QFunctionPointer) ::glProgramUniform4ui }, - { "glProgramUniform4uiv", (QFunctionPointer) ::glProgramUniform4uiv }, - { "glProgramUniformMatrix2fv", (QFunctionPointer) ::glProgramUniformMatrix2fv }, - { "glProgramUniformMatrix2x3fv", (QFunctionPointer) ::glProgramUniformMatrix2x3fv }, - { "glProgramUniformMatrix2x4fv", (QFunctionPointer) ::glProgramUniformMatrix2x4fv }, - { "glProgramUniformMatrix3fv", (QFunctionPointer) ::glProgramUniformMatrix3fv }, - { "glProgramUniformMatrix3x2fv", (QFunctionPointer) ::glProgramUniformMatrix3x2fv }, - { "glProgramUniformMatrix3x4fv", (QFunctionPointer) ::glProgramUniformMatrix3x4fv }, - { "glProgramUniformMatrix4fv", (QFunctionPointer) ::glProgramUniformMatrix4fv }, - { "glProgramUniformMatrix4x2fv", (QFunctionPointer) ::glProgramUniformMatrix4x2fv }, - { "glProgramUniformMatrix4x3fv", (QFunctionPointer) ::glProgramUniformMatrix4x3fv }, - { "glSampleMaski", (QFunctionPointer) ::glSampleMaski }, - { "glTexStorage2DMultisample", (QFunctionPointer) ::glTexStorage2DMultisample }, - { "glUseProgramStages", (QFunctionPointer) ::glUseProgramStages }, - { "glValidateProgramPipeline", (QFunctionPointer) ::glValidateProgramPipeline }, - { "glVertexAttribBinding", (QFunctionPointer) ::glVertexAttribBinding }, - { "glVertexAttribFormat", (QFunctionPointer) ::glVertexAttribFormat }, - { "glVertexAttribIFormat", (QFunctionPointer) ::glVertexAttribIFormat }, - { "glVertexBindingDivisor", (QFunctionPointer) ::glVertexBindingDivisor }, -#endif // QT_OPENGL_ES_3_1 - -#ifdef QT_OPENGL_ES_3_2 - { "glBlendBarrier", (QFunctionPointer) ::glBlendBarrier }, - { "glCopyImageSubData", (QFunctionPointer) ::glCopyImageSubData }, - { "glDebugMessageControl", (QFunctionPointer) ::glDebugMessageControl }, - { "glDebugMessageInsert", (QFunctionPointer) ::glDebugMessageInsert }, - { "glDebugMessageCallback", (QFunctionPointer) ::glDebugMessageCallback }, - { "glGetDebugMessageLog", (QFunctionPointer) ::glGetDebugMessageLog }, - { "glPushDebugGroup", (QFunctionPointer) ::glPushDebugGroup }, - { "glPopDebugGroup", (QFunctionPointer) ::glPopDebugGroup }, - { "glObjectLabel", (QFunctionPointer) ::glObjectLabel }, - { "glGetObjectLabel", (QFunctionPointer) ::glGetObjectLabel }, - { "glObjectPtrLabel", (QFunctionPointer) ::glObjectPtrLabel }, - { "glGetObjectPtrLabel", (QFunctionPointer) ::glGetObjectPtrLabel }, - { "glGetPointerv", (QFunctionPointer) ::glGetPointerv }, - { "glEnablei", (QFunctionPointer) ::glEnablei }, - { "glDisablei", (QFunctionPointer) ::glDisablei }, - { "glBlendEquationi", (QFunctionPointer) ::glBlendEquationi }, - { "glBlendEquationSeparatei", (QFunctionPointer) ::glBlendEquationSeparatei }, - { "glBlendFunci", (QFunctionPointer) ::glBlendFunci }, - { "glBlendFuncSeparatei", (QFunctionPointer) ::glBlendFuncSeparatei }, - { "glColorMaski", (QFunctionPointer) ::glColorMaski }, - { "glIsEnabledi", (QFunctionPointer) ::glIsEnabledi }, - { "glDrawElementsBaseVertex", (QFunctionPointer) ::glDrawElementsBaseVertex }, - { "glDrawRangeElementsBaseVertex", (QFunctionPointer) ::glDrawRangeElementsBaseVertex }, - { "glDrawElementsInstancedBaseVertex", (QFunctionPointer) ::glDrawElementsInstancedBaseVertex }, - { "glFramebufferTexture", (QFunctionPointer) ::glFramebufferTexture }, - { "glPrimitiveBoundingBox", (QFunctionPointer) ::glPrimitiveBoundingBox }, - { "glGetGraphicsResetStatus", (QFunctionPointer) ::glGetGraphicsResetStatus }, - { "glReadnPixels", (QFunctionPointer) ::glReadnPixels }, - { "glGetnUniformfv", (QFunctionPointer) ::glGetnUniformfv }, - { "glGetnUniformiv", (QFunctionPointer) ::glGetnUniformiv }, - { "glGetnUniformuiv", (QFunctionPointer) ::glGetnUniformuiv }, - { "glMinSampleShading", (QFunctionPointer) ::glMinSampleShading }, - { "glPatchParameteri", (QFunctionPointer) ::glPatchParameteri }, - { "glTexParameterIiv", (QFunctionPointer) ::glTexParameterIiv }, - { "glTexParameterIuiv", (QFunctionPointer) ::glTexParameterIuiv }, - { "glGetTexParameterIiv", (QFunctionPointer) ::glGetTexParameterIiv }, - { "glGetTexParameterIuiv", (QFunctionPointer) ::glGetTexParameterIuiv }, - { "glSamplerParameterIiv", (QFunctionPointer) ::glSamplerParameterIiv }, - { "glSamplerParameterIuiv", (QFunctionPointer) ::glSamplerParameterIuiv }, - { "glGetSamplerParameterIiv", (QFunctionPointer) ::glGetSamplerParameterIiv }, - { "glGetSamplerParameterIuiv", (QFunctionPointer) ::glGetSamplerParameterIuiv }, - { "glTexBuffer", (QFunctionPointer) ::glTexBuffer }, - { "glTexBufferRange", (QFunctionPointer) ::glTexBufferRange }, - { "glTexStorage3DMultisample", (QFunctionPointer) ::glTexStorage3DMultisample }, -#endif // QT_OPENGL_ES_3_2 - }; - - for (size_t i = 0; i < sizeof(standardFuncs) / sizeof(StdFunc); ++i) { - if (!qstrcmp(procName, standardFuncs[i].name)) { - proc = standardFuncs[i].func; - break; - } - } - } -#endif - - return proc; -} - -QSurfaceFormat QEGLPlatformContext::format() const -{ - return m_format; -} - -EGLContext QEGLPlatformContext::eglContext() const -{ - return m_eglContext; -} - -EGLDisplay QEGLPlatformContext::eglDisplay() const -{ - return m_eglDisplay; -} - -EGLConfig QEGLPlatformContext::eglConfig() const -{ - return m_eglConfig; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/eglconvenience/qeglplatformcontext_p.h b/src/platformsupport/eglconvenience/qeglplatformcontext_p.h deleted file mode 100644 index d6cbbe4131..0000000000 --- a/src/platformsupport/eglconvenience/qeglplatformcontext_p.h +++ /dev/null @@ -1,118 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QEGLPLATFORMCONTEXT_H -#define QEGLPLATFORMCONTEXT_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/qtextstream.h> -#include <qpa/qplatformwindow.h> -#include <qpa/qplatformopenglcontext.h> -#include <QtCore/QVariant> -#include <QtEglSupport/private/qt_egl_p.h> - -QT_BEGIN_NAMESPACE - -class QEGLPlatformContext : public QPlatformOpenGLContext -{ -public: - enum Flag { - NoSurfaceless = 0x01 - }; - Q_DECLARE_FLAGS(Flags, Flag) - - QEGLPlatformContext(const QSurfaceFormat &format, QPlatformOpenGLContext *share, EGLDisplay display, - EGLConfig *config = 0, const QVariant &nativeHandle = QVariant(), - Flags flags = 0); - ~QEGLPlatformContext(); - - void initialize() override; - bool makeCurrent(QPlatformSurface *surface) override; - void doneCurrent() override; - void swapBuffers(QPlatformSurface *surface) override; - QFunctionPointer getProcAddress(const char *procName) override; - - QSurfaceFormat format() const override; - bool isSharing() const override { return m_shareContext != EGL_NO_CONTEXT; } - bool isValid() const override { return m_eglContext != EGL_NO_CONTEXT; } - - EGLContext eglContext() const; - EGLDisplay eglDisplay() const; - EGLConfig eglConfig() const; - -protected: - virtual EGLSurface eglSurfaceForPlatformSurface(QPlatformSurface *surface) = 0; - virtual EGLSurface createTemporaryOffscreenSurface(); - virtual void destroyTemporaryOffscreenSurface(EGLSurface surface); - virtual void runGLChecks(); - -private: - void init(const QSurfaceFormat &format, QPlatformOpenGLContext *share); - void adopt(const QVariant &nativeHandle, QPlatformOpenGLContext *share); - void updateFormatFromGL(); - - EGLContext m_eglContext; - EGLContext m_shareContext; - EGLDisplay m_eglDisplay; - EGLConfig m_eglConfig; - QSurfaceFormat m_format; - EGLenum m_api; - int m_swapInterval; - bool m_swapIntervalEnvChecked; - int m_swapIntervalFromEnv; - Flags m_flags; - bool m_ownsContext; - QVector<EGLint> m_contextAttrs; -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(QEGLPlatformContext::Flags) - -QT_END_NAMESPACE - -#endif //QEGLPLATFORMCONTEXT_H diff --git a/src/platformsupport/eglconvenience/qeglstreamconvenience.cpp b/src/platformsupport/eglconvenience/qeglstreamconvenience.cpp deleted file mode 100644 index 5c336f0553..0000000000 --- a/src/platformsupport/eglconvenience/qeglstreamconvenience.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qeglstreamconvenience_p.h" -#include <string.h> - -QT_BEGIN_NAMESPACE - -QEGLStreamConvenience::QEGLStreamConvenience() - : initialized(false), - has_egl_platform_device(false), - has_egl_device_base(false), - has_egl_stream(false), - has_egl_stream_producer_eglsurface(false), - has_egl_stream_consumer_egloutput(false), - has_egl_output_drm(false), - has_egl_output_base(false), - has_egl_stream_cross_process_fd(false), - has_egl_stream_consumer_gltexture(false) -{ - const char *extensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); - if (!extensions) { - qWarning("Failed to query EGL extensions"); - return; - } - - query_devices = reinterpret_cast<PFNEGLQUERYDEVICESEXTPROC>(eglGetProcAddress("eglQueryDevicesEXT")); - query_device_string = reinterpret_cast<PFNEGLQUERYDEVICESTRINGEXTPROC>(eglGetProcAddress("eglQueryDeviceStringEXT")); - get_platform_display = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT")); - - has_egl_device_base = strstr(extensions, "EGL_EXT_device_base"); - has_egl_platform_device = strstr(extensions, "EGL_EXT_platform_device"); -} - -void QEGLStreamConvenience::initialize(EGLDisplay dpy) -{ - if (initialized) - return; - - if (!eglBindAPI(EGL_OPENGL_ES_API)) { - qWarning("Failed to bind OpenGL ES API"); - return; - } - - const char *extensions = eglQueryString(dpy, EGL_EXTENSIONS); - if (!extensions) { - qWarning("Failed to query EGL extensions"); - return; - } - - create_stream = reinterpret_cast<PFNEGLCREATESTREAMKHRPROC>(eglGetProcAddress("eglCreateStreamKHR")); - destroy_stream = reinterpret_cast<PFNEGLDESTROYSTREAMKHRPROC>(eglGetProcAddress("eglDestroyStreamKHR")); - stream_attrib = reinterpret_cast<PFNEGLSTREAMATTRIBKHRPROC>(eglGetProcAddress("eglStreamAttribKHR")); - query_stream = reinterpret_cast<PFNEGLQUERYSTREAMKHRPROC>(eglGetProcAddress("eglQueryStreamKHR")); - query_stream_u64 = reinterpret_cast<PFNEGLQUERYSTREAMU64KHRPROC>(eglGetProcAddress("eglQueryStreamu64KHR")); - create_stream_producer_surface = reinterpret_cast<PFNEGLCREATESTREAMPRODUCERSURFACEKHRPROC>(eglGetProcAddress("eglCreateStreamProducerSurfaceKHR")); - stream_consumer_output = reinterpret_cast<PFNEGLSTREAMCONSUMEROUTPUTEXTPROC>(eglGetProcAddress("eglStreamConsumerOutputEXT")); - get_output_layers = reinterpret_cast<PFNEGLGETOUTPUTLAYERSEXTPROC>(eglGetProcAddress("eglGetOutputLayersEXT")); - get_output_ports = reinterpret_cast<PFNEGLGETOUTPUTPORTSEXTPROC>(eglGetProcAddress("eglGetOutputPortsEXT")); - output_layer_attrib = reinterpret_cast<PFNEGLOUTPUTLAYERATTRIBEXTPROC>(eglGetProcAddress("eglOutputLayerAttribEXT")); - query_output_layer_attrib = reinterpret_cast<PFNEGLQUERYOUTPUTLAYERATTRIBEXTPROC>(eglGetProcAddress("eglQueryOutputLayerAttribEXT")); - query_output_layer_string = reinterpret_cast<PFNEGLQUERYOUTPUTLAYERSTRINGEXTPROC>(eglGetProcAddress("eglQueryOutputLayerStringEXT")); - query_output_port_attrib = reinterpret_cast<PFNEGLQUERYOUTPUTPORTATTRIBEXTPROC>(eglGetProcAddress("eglQueryOutputPortAttribEXT")); - query_output_port_string = reinterpret_cast<PFNEGLQUERYOUTPUTPORTSTRINGEXTPROC>(eglGetProcAddress("eglQueryOutputPortStringEXT")); - get_stream_file_descriptor = reinterpret_cast<PFNEGLGETSTREAMFILEDESCRIPTORKHRPROC>(eglGetProcAddress("eglGetStreamFileDescriptorKHR")); - create_stream_from_file_descriptor = reinterpret_cast<PFNEGLCREATESTREAMFROMFILEDESCRIPTORKHRPROC>(eglGetProcAddress("eglCreateStreamFromFileDescriptorKHR")); - stream_consumer_gltexture = reinterpret_cast<PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALKHRPROC>(eglGetProcAddress("eglStreamConsumerGLTextureExternalKHR")); - stream_consumer_acquire = reinterpret_cast<PFNEGLSTREAMCONSUMERACQUIREKHRPROC>(eglGetProcAddress("eglStreamConsumerAcquireKHR")); - stream_consumer_release = reinterpret_cast<PFNEGLSTREAMCONSUMERRELEASEKHRPROC>(eglGetProcAddress("eglStreamConsumerReleaseKHR")); - create_stream_attrib_nv = reinterpret_cast<PFNEGLCREATESTREAMATTRIBNVPROC>(eglGetProcAddress("eglCreateStreamAttribNV")); - set_stream_attrib_nv = reinterpret_cast<PFNEGLSETSTREAMATTRIBNVPROC>(eglGetProcAddress("eglSetStreamAttribNV")); - query_stream_attrib_nv = reinterpret_cast<PFNEGLQUERYSTREAMATTRIBNVPROC>(eglGetProcAddress("eglQueryStreamAttribNV")); - acquire_stream_attrib_nv = reinterpret_cast<PFNEGLSTREAMCONSUMERACQUIREATTRIBNVPROC>(eglGetProcAddress("eglStreamConsumerAcquireAttribNV")); - release_stream_attrib_nv = reinterpret_cast<PFNEGLSTREAMCONSUMERRELEASEATTRIBNVPROC>(eglGetProcAddress("eglStreamConsumerReleaseAttribNV")); - - has_egl_stream = strstr(extensions, "EGL_KHR_stream"); - has_egl_stream_producer_eglsurface = strstr(extensions, "EGL_KHR_stream_producer_eglsurface"); - has_egl_stream_consumer_egloutput = strstr(extensions, "EGL_EXT_stream_consumer_egloutput"); - has_egl_output_drm = strstr(extensions, "EGL_EXT_output_drm"); - has_egl_output_base = strstr(extensions, "EGL_EXT_output_base"); - has_egl_stream_cross_process_fd = strstr(extensions, "EGL_KHR_stream_cross_process_fd"); - has_egl_stream_consumer_gltexture = strstr(extensions, "EGL_KHR_stream_consumer_gltexture"); - - initialized = true; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/eglconvenience/qeglstreamconvenience_p.h b/src/platformsupport/eglconvenience/qeglstreamconvenience_p.h deleted file mode 100644 index c3d3070210..0000000000 --- a/src/platformsupport/eglconvenience/qeglstreamconvenience_p.h +++ /dev/null @@ -1,210 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QEGLSTREAMCONVENIENCE_H -#define QEGLSTREAMCONVENIENCE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <qglobal.h> -#include <QtEglSupport/private/qt_egl_p.h> - -// This provides runtime EGLDevice/Output/Stream support even when eglext.h in -// the sysroot is not up-to-date. - -#ifndef EGL_VERSION_1_5 -typedef intptr_t EGLAttrib; -#endif - -#ifndef EGL_EXT_platform_base -typedef EGLDisplay (EGLAPIENTRYP PFNEGLGETPLATFORMDISPLAYEXTPROC) (EGLenum platform, void *native_display, const EGLint *attrib_list); -#endif - -#ifndef EGL_EXT_device_base -typedef void *EGLDeviceEXT; -#define EGL_NO_DEVICE_EXT ((EGLDeviceEXT)(0)) -typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDEVICESEXTPROC) (EGLint max_devices, EGLDeviceEXT *devices, EGLint *num_devices); -typedef const char *(EGLAPIENTRYP PFNEGLQUERYDEVICESTRINGEXTPROC) (EGLDeviceEXT device, EGLint name); -#endif - -#ifndef EGL_EXT_output_base -typedef void *EGLOutputLayerEXT; -typedef void *EGLOutputPortEXT; -#define EGL_NO_OUTPUT_LAYER_EXT ((EGLOutputLayerEXT)0) -typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETOUTPUTLAYERSEXTPROC) (EGLDisplay dpy, const EGLAttrib *attrib_list, EGLOutputLayerEXT *layers, EGLint max_layers, EGLint *num_layers); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETOUTPUTPORTSEXTPROC) (EGLDisplay dpy, const EGLAttrib *attrib_list, EGLOutputPortEXT *ports, EGLint max_ports, EGLint *num_ports); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLOUTPUTLAYERATTRIBEXTPROC) (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint attribute, EGLAttrib value); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYOUTPUTLAYERATTRIBEXTPROC) (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint attribute, EGLAttrib *value); -typedef const char *(EGLAPIENTRYP PFNEGLQUERYOUTPUTLAYERSTRINGEXTPROC) (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint name); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYOUTPUTPORTATTRIBEXTPROC) (EGLDisplay dpy, EGLOutputPortEXT port, EGLint attribute, EGLAttrib *value); -typedef const char *(EGLAPIENTRYP PFNEGLQUERYOUTPUTPORTSTRINGEXTPROC) (EGLDisplay dpy, EGLOutputPortEXT port, EGLint name); -#endif - -#ifndef EGL_KHR_stream -typedef void *EGLStreamKHR; -typedef quint64 EGLuint64KHR; -#define EGL_NO_STREAM_KHR ((EGLStreamKHR)0) -#define EGL_STREAM_STATE_KHR 0x3214 -#define EGL_STREAM_STATE_CREATED_KHR 0x3215 -#define EGL_STREAM_STATE_CONNECTING_KHR 0x3216 -#define EGL_STREAM_STATE_EMPTY_KHR 0x3217 -#define EGL_STREAM_STATE_NEW_FRAME_AVAILABLE_KHR 0x3218 -#define EGL_STREAM_STATE_OLD_FRAME_AVAILABLE_KHR 0x3219 -#define EGL_STREAM_STATE_DISCONNECTED_KHR 0x321A -#define EGL_BAD_STREAM_KHR 0x321B -#define EGL_BAD_STATE_KHR 0x321C -typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMKHRPROC) (EGLDisplay dpy, const EGLint *attrib_list); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSTREAMKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMATTRIBKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint value); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint *value); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMU64KHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLuint64KHR *value); -#endif - -#ifndef EGL_KHR_stream_fifo -#define EGL_STREAM_FIFO_LENGTH_KHR 0x31FC -#endif - -#ifndef EGL_KHR_stream_producer_eglsurface -#define EGL_STREAM_BIT_KHR 0x0800 -typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATESTREAMPRODUCERSURFACEKHRPROC) (EGLDisplay dpy, EGLConfig config, EGLStreamKHR stream, const EGLint *attrib_list); -#endif - -#ifndef EGL_KHR_stream_cross_process_fd -typedef int EGLNativeFileDescriptorKHR; -#define EGL_NO_FILE_DESCRIPTOR_KHR ((EGLNativeFileDescriptorKHR)(-1)) -typedef EGLNativeFileDescriptorKHR (EGLAPIENTRYP PFNEGLGETSTREAMFILEDESCRIPTORKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream); -typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMFROMFILEDESCRIPTORKHRPROC) (EGLDisplay dpy, EGLNativeFileDescriptorKHR file_descriptor); -#endif - -#ifndef EGL_KHR_stream_consumer_gltexture -typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERACQUIREKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERRELEASEKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream); -#endif - -#ifndef EGL_EXT_stream_consumer_egloutput -typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMEROUTPUTEXTPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLOutputLayerEXT layer); -#endif - -#ifndef EGL_EXT_platform_device -#define EGL_PLATFORM_DEVICE_EXT 0x313F -#endif - -#ifndef EGL_EXT_device_drm -#define EGL_DRM_DEVICE_FILE_EXT 0x3233 -#endif - -#ifndef EGL_EXT_output_drm -#define EGL_DRM_CRTC_EXT 0x3234 -#define EGL_DRM_PLANE_EXT 0x3235 -#endif - -#ifndef EGL_PLATFORM_X11_KHR -#define EGL_PLATFORM_X11_KHR 0x31D5 -#endif - -#ifndef EGL_NV_stream_attrib -typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMATTRIBNVPROC) (EGLDisplay dpy, const EGLAttrib *attrib_list); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLSETSTREAMATTRIBNVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib value); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMATTRIBNVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib *value); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERACQUIREATTRIBNVPROC) (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list); -typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERRELEASEATTRIBNVPROC) (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list); -#endif - -QT_BEGIN_NAMESPACE - -class QEGLStreamConvenience -{ -public: - QEGLStreamConvenience(); - void initialize(EGLDisplay dpy); - - PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display; - PFNEGLQUERYDEVICESEXTPROC query_devices; - PFNEGLQUERYDEVICESTRINGEXTPROC query_device_string; - PFNEGLCREATESTREAMKHRPROC create_stream; - PFNEGLCREATESTREAMATTRIBNVPROC create_stream_attrib_nv; - PFNEGLSETSTREAMATTRIBNVPROC set_stream_attrib_nv; - PFNEGLQUERYSTREAMATTRIBNVPROC query_stream_attrib_nv; - PFNEGLSTREAMCONSUMERACQUIREATTRIBNVPROC acquire_stream_attrib_nv; - PFNEGLSTREAMCONSUMERRELEASEATTRIBNVPROC release_stream_attrib_nv; - PFNEGLDESTROYSTREAMKHRPROC destroy_stream; - PFNEGLSTREAMATTRIBKHRPROC stream_attrib; - PFNEGLQUERYSTREAMKHRPROC query_stream; - PFNEGLQUERYSTREAMU64KHRPROC query_stream_u64; - PFNEGLCREATESTREAMPRODUCERSURFACEKHRPROC create_stream_producer_surface; - PFNEGLSTREAMCONSUMEROUTPUTEXTPROC stream_consumer_output; - PFNEGLGETOUTPUTLAYERSEXTPROC get_output_layers; - PFNEGLGETOUTPUTPORTSEXTPROC get_output_ports; - PFNEGLOUTPUTLAYERATTRIBEXTPROC output_layer_attrib; - PFNEGLQUERYOUTPUTLAYERATTRIBEXTPROC query_output_layer_attrib; - PFNEGLQUERYOUTPUTLAYERSTRINGEXTPROC query_output_layer_string; - PFNEGLQUERYOUTPUTPORTATTRIBEXTPROC query_output_port_attrib; - PFNEGLQUERYOUTPUTPORTSTRINGEXTPROC query_output_port_string; - PFNEGLGETSTREAMFILEDESCRIPTORKHRPROC get_stream_file_descriptor; - PFNEGLCREATESTREAMFROMFILEDESCRIPTORKHRPROC create_stream_from_file_descriptor; - PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALKHRPROC stream_consumer_gltexture; - PFNEGLSTREAMCONSUMERACQUIREKHRPROC stream_consumer_acquire; - PFNEGLSTREAMCONSUMERRELEASEKHRPROC stream_consumer_release; - - bool initialized; - - bool has_egl_platform_device; - bool has_egl_device_base; - bool has_egl_stream; - bool has_egl_stream_producer_eglsurface; - bool has_egl_stream_consumer_egloutput; - bool has_egl_output_drm; - bool has_egl_output_base; - bool has_egl_stream_cross_process_fd; - bool has_egl_stream_consumer_gltexture; -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/platformsupport/eglconvenience/qt_egl_p.h b/src/platformsupport/eglconvenience/qt_egl_p.h deleted file mode 100644 index ea554927de..0000000000 --- a/src/platformsupport/eglconvenience/qt_egl_p.h +++ /dev/null @@ -1,121 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT_EGL_P_H -#define QT_EGL_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#ifdef QT_EGL_NO_X11 -# ifndef MESA_EGL_NO_X11_HEADERS -# define MESA_EGL_NO_X11_HEADERS // MESA -# endif -# if !defined(Q_OS_INTEGRITY) -# define WIN_INTERFACE_CUSTOM // NV -# endif // Q_OS_INTEGRITY -#endif // QT_EGL_NO_X11 - -#ifdef QT_EGL_WAYLAND -# define WAYLAND // NV -#endif // QT_EGL_WAYLAND - -#include <EGL/egl.h> -#include <EGL/eglext.h> - -#include <stdint.h> - -QT_BEGIN_NAMESPACE - -namespace QtInternal { - -template <class FromType, class ToType> -struct QtEglConverter -{ - static inline ToType convert(FromType v) - { return v; } -}; - -template <> -struct QtEglConverter<uint32_t, uintptr_t> -{ - static inline uintptr_t convert(uint32_t v) - { return v; } -}; - -#if QT_POINTER_SIZE > 4 -template <> -struct QtEglConverter<uintptr_t, uint32_t> -{ - static inline uint32_t convert(uintptr_t v) - { return uint32_t(v); } -}; -#endif - -template <> -struct QtEglConverter<uint32_t, void *> -{ - static inline void *convert(uint32_t v) - { return reinterpret_cast<void *>(uintptr_t(v)); } -}; - -template <> -struct QtEglConverter<void *, uint32_t> -{ - static inline uint32_t convert(void *v) - { return uintptr_t(v); } -}; - -} // QtInternal - -template <class ToType, class FromType> -static inline ToType qt_egl_cast(FromType from) -{ return QtInternal::QtEglConverter<FromType, ToType>::convert(from); } - -QT_END_NAMESPACE - -#endif // QT_EGL_P_H diff --git a/src/platformsupport/eglconvenience/qxlibeglintegration.cpp b/src/platformsupport/eglconvenience/qxlibeglintegration.cpp deleted file mode 100644 index ac743e1e38..0000000000 --- a/src/platformsupport/eglconvenience/qxlibeglintegration.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QLoggingCategory> -#include "qxlibeglintegration_p.h" - -Q_LOGGING_CATEGORY(lcXlibEglDebug, "qt.egl.xlib.debug") - -VisualID QXlibEglIntegration::getCompatibleVisualId(Display *display, EGLDisplay eglDisplay, EGLConfig config) -{ - VisualID visualId = 0; - EGLint eglValue = 0; - - EGLint configRedSize = 0; - eglGetConfigAttrib(eglDisplay, config, EGL_RED_SIZE, &configRedSize); - - EGLint configGreenSize = 0; - eglGetConfigAttrib(eglDisplay, config, EGL_GREEN_SIZE, &configGreenSize); - - EGLint configBlueSize = 0; - eglGetConfigAttrib(eglDisplay, config, EGL_BLUE_SIZE, &configBlueSize); - - EGLint configAlphaSize = 0; - eglGetConfigAttrib(eglDisplay, config, EGL_ALPHA_SIZE, &configAlphaSize); - - eglGetConfigAttrib(eglDisplay, config, EGL_CONFIG_ID, &eglValue); - int configId = eglValue; - - // See if EGL provided a valid VisualID: - eglGetConfigAttrib(eglDisplay, config, EGL_NATIVE_VISUAL_ID, &eglValue); - visualId = (VisualID)eglValue; - if (visualId) { - // EGL has suggested a visual id, so get the rest of the visual info for that id: - XVisualInfo visualInfoTemplate; - memset(&visualInfoTemplate, 0, sizeof(XVisualInfo)); - visualInfoTemplate.visualid = visualId; - - XVisualInfo *chosenVisualInfo; - int matchingCount = 0; - chosenVisualInfo = XGetVisualInfo(display, VisualIDMask, &visualInfoTemplate, &matchingCount); - if (chosenVisualInfo) { - // Skip size checks if implementation supports non-matching visual - // and config (QTBUG-9444). - if (q_hasEglExtension(eglDisplay,"EGL_NV_post_convert_rounding")) { - XFree(chosenVisualInfo); - return visualId; - } - // Skip also for i.MX6 where 565 visuals are suggested for the default 444 configs and it works just fine. - const char *vendor = eglQueryString(eglDisplay, EGL_VENDOR); - if (vendor && strstr(vendor, "Vivante")) { - XFree(chosenVisualInfo); - return visualId; - } - - int visualRedSize = qPopulationCount(chosenVisualInfo->red_mask); - int visualGreenSize = qPopulationCount(chosenVisualInfo->green_mask); - int visualBlueSize = qPopulationCount(chosenVisualInfo->blue_mask); - int visualAlphaSize = chosenVisualInfo->depth - visualRedSize - visualBlueSize - visualGreenSize; - - const bool visualMatchesConfig = visualRedSize >= configRedSize - && visualGreenSize >= configGreenSize - && visualBlueSize >= configBlueSize - && visualAlphaSize >= configAlphaSize; - - // In some cases EGL tends to suggest a 24-bit visual for 8888 - // configs. In such a case we have to fall back to XGetVisualInfo. - if (!visualMatchesConfig) { - visualId = 0; - qCDebug(lcXlibEglDebug, - "EGL suggested using X Visual ID %d (%d %d %d %d depth %d) for EGL config %d" - "(%d %d %d %d), but this is incompatible", - (int)visualId, visualRedSize, visualGreenSize, visualBlueSize, visualAlphaSize, chosenVisualInfo->depth, - configId, configRedSize, configGreenSize, configBlueSize, configAlphaSize); - } - } else { - qCDebug(lcXlibEglDebug, "EGL suggested using X Visual ID %d for EGL config %d, but that isn't a valid ID", - (int)visualId, configId); - visualId = 0; - } - XFree(chosenVisualInfo); - } - else - qCDebug(lcXlibEglDebug, "EGL did not suggest a VisualID (EGL_NATIVE_VISUAL_ID was zero) for EGLConfig %d", configId); - - if (visualId) { - qCDebug(lcXlibEglDebug, configAlphaSize > 0 - ? "Using ARGB Visual ID %d provided by EGL for config %d" - : "Using Opaque Visual ID %d provided by EGL for config %d", (int)visualId, configId); - return visualId; - } - - // Finally, try to use XGetVisualInfo and only use the bit depths to match on: - if (!visualId) { - XVisualInfo visualInfoTemplate; - memset(&visualInfoTemplate, 0, sizeof(XVisualInfo)); - XVisualInfo *matchingVisuals; - int matchingCount = 0; - - visualInfoTemplate.depth = configRedSize + configGreenSize + configBlueSize + configAlphaSize; - matchingVisuals = XGetVisualInfo(display, - VisualDepthMask, - &visualInfoTemplate, - &matchingCount); - if (!matchingVisuals) { - // Try again without taking the alpha channel into account: - visualInfoTemplate.depth = configRedSize + configGreenSize + configBlueSize; - matchingVisuals = XGetVisualInfo(display, - VisualDepthMask, - &visualInfoTemplate, - &matchingCount); - } - - if (matchingVisuals) { - visualId = matchingVisuals[0].visualid; - XFree(matchingVisuals); - } - } - - if (visualId) { - qCDebug(lcXlibEglDebug, "Using Visual ID %d provided by XGetVisualInfo for EGL config %d", (int)visualId, configId); - return visualId; - } - - qWarning("Unable to find an X11 visual which matches EGL config %d", configId); - return (VisualID)0; -} diff --git a/src/platformsupport/eglconvenience/qxlibeglintegration_p.h b/src/platformsupport/eglconvenience/qxlibeglintegration_p.h deleted file mode 100644 index 899b217146..0000000000 --- a/src/platformsupport/eglconvenience/qxlibeglintegration_p.h +++ /dev/null @@ -1,65 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QTESTLITEEGLINTEGRATION_H -#define QTESTLITEEGLINTEGRATION_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qeglconvenience_p.h" -#include <X11/X.h> -#include <X11/Xlib.h> -#include <X11/Xutil.h> - -class QXlibEglIntegration -{ -public: - static VisualID getCompatibleVisualId(Display *display, EGLDisplay eglDisplay, EGLConfig config); -}; - -#endif // QTESTLITEEGLINTEGRATION_H diff --git a/src/platformsupport/eventdispatchers/eventdispatchers.pro b/src/platformsupport/eventdispatchers/eventdispatchers.pro deleted file mode 100644 index 9d3ac4bbc6..0000000000 --- a/src/platformsupport/eventdispatchers/eventdispatchers.pro +++ /dev/null @@ -1,32 +0,0 @@ -TARGET = QtEventDispatcherSupport -MODULE = eventdispatcher_support - -QT = core-private gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII -PRECOMPILED_HEADER = ../../corelib/global/qt_pch.h - -unix { - SOURCES += \ - qunixeventdispatcher.cpp \ - qgenericunixeventdispatcher.cpp - - HEADERS += \ - qunixeventdispatcher_qpa_p.h \ - qgenericunixeventdispatcher_p.h -} else { - SOURCES += \ - qwindowsguieventdispatcher.cpp - - HEADERS += \ - qwindowsguieventdispatcher_p.h -} - -qtConfig(glib) { - SOURCES += qeventdispatcher_glib.cpp - HEADERS += qeventdispatcher_glib_p.h - QMAKE_USE_PRIVATE += glib -} - -load(qt_module) diff --git a/src/platformsupport/eventdispatchers/qeventdispatcher_glib.cpp b/src/platformsupport/eventdispatchers/qeventdispatcher_glib.cpp deleted file mode 100644 index 0ccbf01e80..0000000000 --- a/src/platformsupport/eventdispatchers/qeventdispatcher_glib.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qeventdispatcher_glib_p.h" - -#include "qguiapplication.h" - -#include "qplatformdefs.h" - -#include <glib.h> -#include "private/qguiapplication_p.h" - -QT_BEGIN_NAMESPACE - -struct GUserEventSource -{ - GSource source; - QPAEventDispatcherGlib *q; - QPAEventDispatcherGlibPrivate *d; -}; - -static gboolean userEventSourcePrepare(GSource *source, gint *timeout) -{ - Q_UNUSED(timeout) - GUserEventSource *userEventSource = reinterpret_cast<GUserEventSource *>(source); - return userEventSource->d->wakeUpCalled; -} - -static gboolean userEventSourceCheck(GSource *source) -{ - return userEventSourcePrepare(source, 0); -} - -static gboolean userEventSourceDispatch(GSource *source, GSourceFunc, gpointer) -{ - GUserEventSource *userEventSource = reinterpret_cast<GUserEventSource *>(source); - QPAEventDispatcherGlib *dispatcher = userEventSource->q; - QWindowSystemInterface::sendWindowSystemEvents(dispatcher->m_flags); - return true; -} - -static GSourceFuncs userEventSourceFuncs = { - userEventSourcePrepare, - userEventSourceCheck, - userEventSourceDispatch, - NULL, - NULL, - NULL -}; - -QPAEventDispatcherGlibPrivate::QPAEventDispatcherGlibPrivate(GMainContext *context) - : QEventDispatcherGlibPrivate(context) -{ - Q_Q(QPAEventDispatcherGlib); - userEventSource = reinterpret_cast<GUserEventSource *>(g_source_new(&userEventSourceFuncs, - sizeof(GUserEventSource))); - userEventSource->q = q; - userEventSource->d = this; - g_source_set_can_recurse(&userEventSource->source, true); - g_source_attach(&userEventSource->source, mainContext); -} - - -QPAEventDispatcherGlib::QPAEventDispatcherGlib(QObject *parent) - : QEventDispatcherGlib(*new QPAEventDispatcherGlibPrivate, parent) - , m_flags(QEventLoop::AllEvents) -{ - Q_D(QPAEventDispatcherGlib); - d->userEventSource->q = this; -} - -QPAEventDispatcherGlib::~QPAEventDispatcherGlib() -{ - Q_D(QPAEventDispatcherGlib); - - g_source_destroy(&d->userEventSource->source); - g_source_unref(&d->userEventSource->source); - d->userEventSource = 0; -} - -bool QPAEventDispatcherGlib::processEvents(QEventLoop::ProcessEventsFlags flags) -{ - m_flags = flags; - return QEventDispatcherGlib::processEvents(m_flags); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/eventdispatchers/qeventdispatcher_glib_p.h b/src/platformsupport/eventdispatchers/qeventdispatcher_glib_p.h deleted file mode 100644 index 085a1c52f3..0000000000 --- a/src/platformsupport/eventdispatchers/qeventdispatcher_glib_p.h +++ /dev/null @@ -1,87 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QEVENTDISPATCHER_GLIB_QPA_P_H -#define QEVENTDISPATCHER_GLIB_QPA_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/private/qeventdispatcher_glib_p.h> - -typedef struct _GMainContext GMainContext; - -QT_BEGIN_NAMESPACE -class QPAEventDispatcherGlibPrivate; - -class QPAEventDispatcherGlib : public QEventDispatcherGlib -{ - Q_OBJECT - Q_DECLARE_PRIVATE(QPAEventDispatcherGlib) - -public: - explicit QPAEventDispatcherGlib(QObject *parent = 0); - ~QPAEventDispatcherGlib(); - - bool processEvents(QEventLoop::ProcessEventsFlags flags) override; - QEventLoop::ProcessEventsFlags m_flags; -}; - -struct GUserEventSource; - -class QPAEventDispatcherGlibPrivate : public QEventDispatcherGlibPrivate -{ - Q_DECLARE_PUBLIC(QPAEventDispatcherGlib) -public: - QPAEventDispatcherGlibPrivate(GMainContext *context = 0); - GUserEventSource *userEventSource; -}; - - -QT_END_NAMESPACE - -#endif // QEVENTDISPATCHER_GLIB_QPA_P_H diff --git a/src/platformsupport/eventdispatchers/qgenericunixeventdispatcher.cpp b/src/platformsupport/eventdispatchers/qgenericunixeventdispatcher.cpp deleted file mode 100644 index 2e1d81a181..0000000000 --- a/src/platformsupport/eventdispatchers/qgenericunixeventdispatcher.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qgenericunixeventdispatcher_p.h" -#include "qunixeventdispatcher_qpa_p.h" -#include "qeventdispatcher_glib_p.h" - -QT_BEGIN_NAMESPACE - -class QAbstractEventDispatcher *QtGenericUnixDispatcher::createUnixEventDispatcher() -{ -#if !defined(QT_NO_GLIB) && !defined(Q_OS_WIN) - if (qEnvironmentVariableIsEmpty("QT_NO_GLIB") && QEventDispatcherGlib::versionSupported()) - return new QPAEventDispatcherGlib(); - else -#endif - return new QUnixEventDispatcherQPA(); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/eventdispatchers/qgenericunixeventdispatcher_p.h b/src/platformsupport/eventdispatchers/qgenericunixeventdispatcher_p.h deleted file mode 100644 index 61b4d0515c..0000000000 --- a/src/platformsupport/eventdispatchers/qgenericunixeventdispatcher_p.h +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#ifndef QGENERICUNIXEVENTDISPATCHER_P_H -#define QGENERICUNIXEVENTDISPATCHER_P_H - -#include <qglobal.h> - -QT_BEGIN_NAMESPACE - -class QAbstractEventDispatcher; -namespace QtGenericUnixDispatcher { -QAbstractEventDispatcher* createUnixEventDispatcher(); -} -using QtGenericUnixDispatcher::createUnixEventDispatcher; - -QT_END_NAMESPACE - -#endif // QGENERICUNIXEVENTDISPATCHER_P_H diff --git a/src/platformsupport/eventdispatchers/qunixeventdispatcher.cpp b/src/platformsupport/eventdispatchers/qunixeventdispatcher.cpp deleted file mode 100644 index 44258538ec..0000000000 --- a/src/platformsupport/eventdispatchers/qunixeventdispatcher.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qplatformdefs.h" -#include "qcoreapplication.h" -#include "qunixeventdispatcher_qpa_p.h" -#include "private/qguiapplication_p.h" - -#include <qpa/qwindowsysteminterface.h> - -#include <QtCore/QDebug> - -QT_BEGIN_NAMESPACE - -QT_USE_NAMESPACE - - -QUnixEventDispatcherQPA::QUnixEventDispatcherQPA(QObject *parent) - : QEventDispatcherUNIX(parent) -{ } - -QUnixEventDispatcherQPA::~QUnixEventDispatcherQPA() -{ } - -bool QUnixEventDispatcherQPA::processEvents(QEventLoop::ProcessEventsFlags flags) -{ - const bool didSendEvents = QEventDispatcherUNIX::processEvents(flags); - return QWindowSystemInterface::sendWindowSystemEvents(flags) || didSendEvents; -} - -bool QUnixEventDispatcherQPA::hasPendingEvents() -{ - extern uint qGlobalPostedEventsCount(); // from qapplication.cpp - return qGlobalPostedEventsCount() || QWindowSystemInterface::windowSystemEventsQueued(); -} - -void QUnixEventDispatcherQPA::flush() -{ - if(qApp) - qApp->sendPostedEvents(); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/eventdispatchers/qunixeventdispatcher_qpa_p.h b/src/platformsupport/eventdispatchers/qunixeventdispatcher_qpa_p.h deleted file mode 100644 index 7f775b73ee..0000000000 --- a/src/platformsupport/eventdispatchers/qunixeventdispatcher_qpa_p.h +++ /dev/null @@ -1,75 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QUNIXEVENTDISPATCHER_QPA_H -#define QUNIXEVENTDISPATCHER_QPA_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/qglobal.h> -#include <QtCore/private/qeventdispatcher_unix_p.h> - -QT_BEGIN_NAMESPACE - -class QUnixEventDispatcherQPA : public QEventDispatcherUNIX -{ - Q_OBJECT - -public: - explicit QUnixEventDispatcherQPA(QObject *parent = 0); - ~QUnixEventDispatcherQPA(); - - bool processEvents(QEventLoop::ProcessEventsFlags flags); - bool hasPendingEvents(); - - void flush(); -}; - -QT_END_NAMESPACE - -#endif // QUNIXEVENTDISPATCHER_QPA_H diff --git a/src/platformsupport/eventdispatchers/qwindowsguieventdispatcher.cpp b/src/platformsupport/eventdispatchers/qwindowsguieventdispatcher.cpp deleted file mode 100644 index a37547f513..0000000000 --- a/src/platformsupport/eventdispatchers/qwindowsguieventdispatcher.cpp +++ /dev/null @@ -1,231 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Samuel Gaist <samuel.gaist@edeltech.ch> -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qwindowsguieventdispatcher_p.h" - -#include <qpa/qwindowsysteminterface.h> - -#include <QtCore/QCoreApplication> -#include <QtCore/QDebug> - -QT_BEGIN_NAMESPACE - -/*! - \class QWindowsGuiEventDispatcher - \brief Event dispatcher for Windows - - Maintains a global stack storing the current event dispatcher and - its processing flags for access from the Windows procedure - qWindowsWndProc. Handling the Lighthouse gui events should be done - from within the qWindowsWndProc to ensure correct processing of messages. - - \internal - \ingroup qt-lighthouse-win -*/ - -QWindowsGuiEventDispatcher::QWindowsGuiEventDispatcher(QObject *parent) : - QEventDispatcherWin32(parent), m_flags(0) -{ - setObjectName(QStringLiteral("QWindowsGuiEventDispatcher")); - createInternalHwnd(); // QTBUG-40881: Do not delay registering timers, etc. for QtMfc. -} - -bool QWindowsGuiEventDispatcher::processEvents(QEventLoop::ProcessEventsFlags flags) -{ - const QEventLoop::ProcessEventsFlags oldFlags = m_flags; - m_flags = flags; - const bool rc = QEventDispatcherWin32::processEvents(flags); - m_flags = oldFlags; - return rc; -} - -void QWindowsGuiEventDispatcher::sendPostedEvents() -{ - QEventDispatcherWin32::sendPostedEvents(); - QWindowSystemInterface::sendWindowSystemEvents(m_flags); -} - -// Helpers for printing debug output for WM_* messages. -struct MessageDebugEntry -{ - UINT message; - const char *description; - bool interesting; -}; - -static const MessageDebugEntry -messageDebugEntries[] = { - {WM_CREATE, "WM_CREATE", true}, - {WM_PAINT, "WM_PAINT", true}, - {WM_CLOSE, "WM_CLOSE", true}, - {WM_DESTROY, "WM_DESTROY", true}, - {WM_MOVE, "WM_MOVE", true}, - {WM_SIZE, "WM_SIZE", true}, - {WM_GETICON, "WM_GETICON", false}, - {WM_KEYDOWN, "WM_KEYDOWN", true}, - {WM_SYSKEYDOWN, "WM_SYSKEYDOWN", true}, - {WM_SYSCOMMAND, "WM_SYSCOMMAND", true}, - {WM_KEYUP, "WM_KEYUP", true}, - {WM_SYSKEYUP, "WM_SYSKEYUP", true}, -#if defined(WM_APPCOMMAND) - {WM_APPCOMMAND, "WM_APPCOMMAND", true}, -#endif - {WM_IME_CHAR, "WM_IMECHAR", true}, - {WM_IME_KEYDOWN, "WM_IMECHAR", true}, - {WM_CANCELMODE, "WM_CANCELMODE", true}, - {WM_CHAR, "WM_CHAR", true}, - {WM_DEADCHAR, "WM_DEADCHAR", true}, - {WM_ACTIVATE, "WM_ACTIVATE", true}, - {WM_SETFOCUS, "WM_SETFOCUS", true}, - {WM_KILLFOCUS, "WM_KILLFOCUS", true}, - {WM_ENABLE, "WM_ENABLE", true}, - {WM_SHOWWINDOW, "WM_SHOWWINDOW", true}, - {WM_WINDOWPOSCHANGED, "WM_WINDOWPOSCHANGED", true}, - {WM_SETCURSOR, "WM_SETCURSOR", false}, - {WM_GETFONT, "WM_GETFONT", true}, - {WM_LBUTTONDOWN, "WM_LBUTTONDOWN", true}, - {WM_LBUTTONUP, "WM_LBUTTONUP", true}, - {WM_LBUTTONDBLCLK, "WM_LBUTTONDBLCLK", true}, - {WM_RBUTTONDOWN, "WM_RBUTTONDOWN", true}, - {WM_RBUTTONUP, "WM_RBUTTONUP", true}, - {WM_RBUTTONDBLCLK, "WM_RBUTTONDBLCLK", true}, - {WM_MBUTTONDOWN, "WM_MBUTTONDOWN", true}, - {WM_MBUTTONUP, "WM_MBUTTONUP", true}, - {WM_MBUTTONDBLCLK, "WM_MBUTTONDBLCLK", true}, - {WM_MOUSEWHEEL, "WM_MOUSEWHEEL", true}, - {WM_XBUTTONDOWN, "WM_XBUTTONDOWN", true}, - {WM_XBUTTONUP, "WM_XBUTTONUP", true}, - {WM_XBUTTONDBLCLK, "WM_XBUTTONDBLCLK", true}, - {WM_MOUSEHWHEEL, "WM_MOUSEHWHEEL", true}, - {WM_GETOBJECT, "WM_GETOBJECT", true}, - {WM_IME_SETCONTEXT, "WM_IME_SETCONTEXT", true}, - {WM_INPUTLANGCHANGE, "WM_INPUTLANGCHANGE", true}, - {WM_IME_NOTIFY, "WM_IME_NOTIFY", true}, -#if defined(WM_DWMNCRENDERINGCHANGED) - {WM_DWMNCRENDERINGCHANGED, "WM_DWMNCRENDERINGCHANGED", true}, -#endif - {WM_IME_SETCONTEXT, "WM_IME_SETCONTEXT", true}, - {WM_IME_NOTIFY, "WM_IME_NOTIFY", true}, - {WM_RENDERFORMAT, "WM_RENDERFORMAT", true}, - {WM_RENDERALLFORMATS, "WM_RENDERALLFORMATS", true}, - {WM_DESTROYCLIPBOARD, "WM_DESTROYCLIPBOARD", true}, - {WM_CAPTURECHANGED, "WM_CAPTURECHANGED", true}, - {WM_IME_STARTCOMPOSITION, "WM_IME_STARTCOMPOSITION", true}, - {WM_IME_COMPOSITION, "WM_IME_COMPOSITION", true}, - {WM_IME_ENDCOMPOSITION, "WM_IME_ENDCOMPOSITION", true}, - {WM_IME_NOTIFY, "WM_IME_NOTIFY", true}, - {WM_IME_REQUEST, "WM_IME_REQUEST", true}, -#if !defined(QT_NO_SESSIONMANAGER) - {WM_QUERYENDSESSION, "WM_QUERYENDSESSION", true}, - {WM_ENDSESSION, "WM_ENDSESSION", true}, -#endif - {WM_MOUSEACTIVATE,"WM_MOUSEACTIVATE", true}, - {WM_CHILDACTIVATE, "WM_CHILDACTIVATE", true}, - {WM_PARENTNOTIFY, "WM_PARENTNOTIFY", true}, - {WM_ENTERIDLE, "WM_ENTERIDLE", false}, - {WM_GETMINMAXINFO, "WM_GETMINMAXINFO", true}, - {WM_WINDOWPOSCHANGING, "WM_WINDOWPOSCHANGING", true}, - {WM_NCCREATE, "WM_NCCREATE", true}, - {WM_NCDESTROY, "WM_NCDESTROY", true}, - {WM_NCCALCSIZE, "WM_NCCALCSIZE", true}, - {WM_NCACTIVATE, "WM_NCACTIVATE", true}, - {WM_NCMOUSEMOVE, "WM_NCMOUSEMOVE", true}, - {WM_NCMOUSELEAVE, "WM_NCMOUSELEAVE", true}, - {WM_NCLBUTTONDOWN, "WM_NCLBUTTONDOWN", true}, - {WM_NCLBUTTONUP, "WM_NCLBUTTONUP", true}, - {WM_ACTIVATEAPP, "WM_ACTIVATEAPP", true}, - {WM_NCPAINT, "WM_NCPAINT", true}, - {WM_ERASEBKGND, "WM_ERASEBKGND", true}, - {WM_MOUSEMOVE, "WM_MOUSEMOVE", true}, - {WM_MOUSELEAVE, "WM_MOUSELEAVE", true}, - {WM_NCHITTEST, "WM_NCHITTEST", false}, -#ifdef WM_TOUCH - {WM_TOUCH, "WM_TOUCH", true}, -#endif - {WM_CHANGECBCHAIN, "WM_CHANGECBCHAIN", true}, - {WM_DISPLAYCHANGE, "WM_DISPLAYCHANGE", true}, - {WM_DRAWCLIPBOARD, "WM_DRAWCLIPBOARD", true}, - {WM_THEMECHANGED, "WM_THEMECHANGED", true}, - {0x90, "WM_UAHDESTROYWINDOW", true}, - {0x272, "WM_UNREGISTER_WINDOW_SERVICES", true}, -#ifdef WM_POINTERUPDATE - {WM_POINTERDEVICECHANGE, "WM_POINTERDEVICECHANGE", true}, - {WM_POINTERDEVICEINRANGE, "WM_POINTERDEVICEINRANGE", true}, - {WM_POINTERDEVICEOUTOFRANGE, "WM_POINTERDEVICEOUTOFRANGE", true}, - {WM_NCPOINTERUPDATE, "WM_NCPOINTERUPDATE", true}, - {WM_NCPOINTERDOWN, "WM_NCPOINTERDOWN", true}, - {WM_NCPOINTERUP, "WM_NCPOINTERUP", true}, - {WM_POINTERUPDATE, "WM_POINTERUPDATE", true}, - {WM_POINTERDOWN, "WM_POINTERDOWN", true}, - {WM_POINTERUP, "WM_POINTERUP", true}, - {WM_POINTERENTER, "WM_POINTERENTER", true}, - {WM_POINTERLEAVE, "WM_POINTERLEAVE", true}, - {WM_POINTERACTIVATE, "WM_POINTERACTIVATE", true}, - {WM_POINTERCAPTURECHANGED, "WM_POINTERCAPTURECHANGED", true}, - {WM_TOUCHHITTESTING, "WM_TOUCHHITTESTING", true}, - {WM_POINTERWHEEL, "WM_POINTERWHEEL", true}, - {WM_POINTERHWHEEL, "WM_POINTERHWHEEL", true}, -#endif // WM_POINTERUPDATE -#ifdef DM_POINTERHITTEST - {DM_POINTERHITTEST, "DM_POINTERHITTEST", true}, -#endif // DM_POINTERHITTEST -#ifdef WM_POINTERROUTEDTO - {WM_POINTERROUTEDTO, "WM_POINTERROUTEDTO", true}, - {WM_POINTERROUTEDAWAY, "WM_POINTERROUTEDAWAY", true}, - {WM_POINTERROUTEDRELEASED, "WM_POINTERROUTEDRELEASED", true}, -#endif // WM_POINTERROUTEDTO -}; - -static inline const MessageDebugEntry *messageDebugEntry(UINT msg) -{ - for (size_t i = 0; i < sizeof(messageDebugEntries)/sizeof(MessageDebugEntry); i++) - if (messageDebugEntries[i].message == msg) - return messageDebugEntries + i; - return 0; -} - -const char *QWindowsGuiEventDispatcher::windowsMessageName(UINT msg) -{ - if (const MessageDebugEntry *e = messageDebugEntry(msg)) - return e->description; - return "Unknown"; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/eventdispatchers/qwindowsguieventdispatcher_p.h b/src/platformsupport/eventdispatchers/qwindowsguieventdispatcher_p.h deleted file mode 100644 index 4ff047a60e..0000000000 --- a/src/platformsupport/eventdispatchers/qwindowsguieventdispatcher_p.h +++ /dev/null @@ -1,75 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QWINDOWSGUIEVENTDISPATCHER_H -#define QWINDOWSGUIEVENTDISPATCHER_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/private/qeventdispatcher_win_p.h> - -QT_BEGIN_NAMESPACE - -class QWindowsGuiEventDispatcher : public QEventDispatcherWin32 -{ - Q_OBJECT -public: - explicit QWindowsGuiEventDispatcher(QObject *parent = 0); - - static const char *windowsMessageName(UINT msg); - - bool QT_ENSURE_STACK_ALIGNED_FOR_SSE processEvents(QEventLoop::ProcessEventsFlags flags) override; - void sendPostedEvents() override; - -private: - QEventLoop::ProcessEventsFlags m_flags; -}; - -QT_END_NAMESPACE - -#endif // QWINDOWSGUIEVENTDISPATCHER_H diff --git a/src/platformsupport/fbconvenience/CMakeLists.txt b/src/platformsupport/fbconvenience/CMakeLists.txt new file mode 100644 index 0000000000..7bd7daec0d --- /dev/null +++ b/src/platformsupport/fbconvenience/CMakeLists.txt @@ -0,0 +1,26 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: BSD-3-Clause + +##################################################################### +## FbSupportPrivate Module: +##################################################################### + +qt_internal_add_module(FbSupportPrivate + CONFIG_MODULE_NAME fb_support + STATIC + INTERNAL_MODULE + SOURCES + qfbbackingstore.cpp qfbbackingstore_p.h + qfbcursor.cpp qfbcursor_p.h + qfbscreen.cpp qfbscreen_p.h + qfbvthandler.cpp qfbvthandler_p.h + qfbwindow.cpp qfbwindow_p.h + DEFINES + QT_NO_CAST_FROM_ASCII + PUBLIC_LIBRARIES + Qt::CorePrivate + Qt::GuiPrivate + PRECOMPILED_HEADER + "../../corelib/global/qt_pch.h" + NO_GENERATE_CPP_EXPORTS +) diff --git a/src/platformsupport/fbconvenience/fbconvenience.pro b/src/platformsupport/fbconvenience/fbconvenience.pro deleted file mode 100644 index 3775906470..0000000000 --- a/src/platformsupport/fbconvenience/fbconvenience.pro +++ /dev/null @@ -1,24 +0,0 @@ -TARGET = QtFbSupport -MODULE = fb_support - -QT = core-private gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII -PRECOMPILED_HEADER = ../../corelib/global/qt_pch.h - -SOURCES += \ - qfbscreen.cpp \ - qfbbackingstore.cpp \ - qfbwindow.cpp \ - qfbcursor.cpp \ - qfbvthandler.cpp - -HEADERS += \ - qfbscreen_p.h \ - qfbbackingstore_p.h \ - qfbwindow_p.h \ - qfbcursor_p.h \ - qfbvthandler_p.h - -load(qt_module) diff --git a/src/platformsupport/fbconvenience/qfbbackingstore.cpp b/src/platformsupport/fbconvenience/qfbbackingstore.cpp index e2d94406a4..8443c77dd3 100644 --- a/src/platformsupport/fbconvenience/qfbbackingstore.cpp +++ b/src/platformsupport/fbconvenience/qfbbackingstore.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qfbbackingstore_p.h" #include "qfbwindow_p.h" diff --git a/src/platformsupport/fbconvenience/qfbbackingstore_p.h b/src/platformsupport/fbconvenience/qfbbackingstore_p.h index c4762c9327..ead06bf55f 100644 --- a/src/platformsupport/fbconvenience/qfbbackingstore_p.h +++ b/src/platformsupport/fbconvenience/qfbbackingstore_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QFBBACKINGSTORE_P_H #define QFBBACKINGSTORE_P_H @@ -53,6 +17,7 @@ #include <qpa/qplatformbackingstore.h> #include <QtCore/QMutex> +#include <QtCore/private/qglobal_p.h> QT_BEGIN_NAMESPACE diff --git a/src/platformsupport/fbconvenience/qfbcursor.cpp b/src/platformsupport/fbconvenience/qfbcursor.cpp index e0f6b69e77..9f7e964760 100644 --- a/src/platformsupport/fbconvenience/qfbcursor.cpp +++ b/src/platformsupport/fbconvenience/qfbcursor.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qfbcursor_p.h" #include "qfbscreen_p.h" @@ -69,7 +33,7 @@ QFbCursor::QFbCursor(QFbScreen *screen) if (!mVisible) return; - mCursorImage = new QPlatformCursorImage(0, 0, 0, 0, 0, 0); + mCursorImage.reset(new QPlatformCursorImage(0, 0, 0, 0, 0, 0)); setCursor(Qt::ArrowCursor); mDeviceListener = new QFbCursorDeviceListener(this); @@ -113,7 +77,7 @@ void QFbCursor::pointerEvent(const QMouseEvent &e) { if (e.type() != QEvent::MouseMove) return; - m_pos = e.screenPos().toPoint(); + m_pos = e.globalPosition().toPoint(); if (!mVisible) return; mCurrentRect = getCurrentRect(); @@ -210,3 +174,5 @@ void QFbCursor::updateMouseStatus() } QT_END_NAMESPACE + +#include "moc_qfbcursor_p.cpp" diff --git a/src/platformsupport/fbconvenience/qfbcursor_p.h b/src/platformsupport/fbconvenience/qfbcursor_p.h index cc36a2411b..a118440ac9 100644 --- a/src/platformsupport/fbconvenience/qfbcursor_p.h +++ b/src/platformsupport/fbconvenience/qfbcursor_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QFBCURSOR_P_H #define QFBCURSOR_P_H @@ -113,7 +77,7 @@ private: QRect mPrevRect; // last place the cursor was drawn bool mDirty; bool mOnScreen; - QPlatformCursorImage *mCursorImage; + QScopedPointer<QPlatformCursorImage> mCursorImage; QFbCursorDeviceListener *mDeviceListener; QPoint m_pos; }; diff --git a/src/platformsupport/fbconvenience/qfbscreen.cpp b/src/platformsupport/fbconvenience/qfbscreen.cpp index c42fd879f8..85e2f57198 100644 --- a/src/platformsupport/fbconvenience/qfbscreen.cpp +++ b/src/platformsupport/fbconvenience/qfbscreen.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qfbscreen_p.h" #include "qfbcursor_p.h" @@ -99,7 +63,7 @@ void QFbScreen::addWindow(QFbWindow *window) } setDirty(window->geometry()); QWindow *w = topWindow(); - QWindowSystemInterface::handleWindowActivated(w); + QWindowSystemInterface::handleFocusWindowChanged(w); topWindowChanged(w); } @@ -108,7 +72,7 @@ void QFbScreen::removeWindow(QFbWindow *window) mWindowStack.removeOne(window); setDirty(window->geometry()); QWindow *w = topWindow(); - QWindowSystemInterface::handleWindowActivated(w); + QWindowSystemInterface::handleFocusWindowChanged(w); topWindowChanged(w); } @@ -120,7 +84,7 @@ void QFbScreen::raise(QFbWindow *window) mWindowStack.move(index, 0); setDirty(window->geometry()); QWindow *w = topWindow(); - QWindowSystemInterface::handleWindowActivated(w); + QWindowSystemInterface::handleFocusWindowChanged(w); topWindowChanged(w); } @@ -132,7 +96,7 @@ void QFbScreen::lower(QFbWindow *window) mWindowStack.move(index, mWindowStack.size() - 1); setDirty(window->geometry()); QWindow *w = topWindow(); - QWindowSystemInterface::handleWindowActivated(w); + QWindowSystemInterface::handleFocusWindowChanged(w); topWindowChanged(w); } @@ -156,7 +120,7 @@ QWindow *QFbScreen::topLevelAt(const QPoint & p) const int QFbScreen::windowCount() const { - return mWindowStack.count(); + return mWindowStack.size(); } void QFbScreen::setDirty(const QRect &rect) @@ -246,7 +210,7 @@ QRegion QFbScreen::doRedraw() QFbWindow *QFbScreen::windowForId(WId wid) const { - for (int i = 0; i < mWindowStack.count(); ++i) { + for (int i = 0; i < mWindowStack.size(); ++i) { if (mWindowStack[i]->winId() == wid) return mWindowStack[i]; } @@ -255,7 +219,9 @@ QFbWindow *QFbScreen::windowForId(WId wid) const QFbScreen::Flags QFbScreen::flags() const { - return 0; + return { }; } QT_END_NAMESPACE + +#include "moc_qfbscreen_p.cpp" diff --git a/src/platformsupport/fbconvenience/qfbscreen_p.h b/src/platformsupport/fbconvenience/qfbscreen_p.h index eed615de36..82dd98fcf6 100644 --- a/src/platformsupport/fbconvenience/qfbscreen_p.h +++ b/src/platformsupport/fbconvenience/qfbscreen_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QFBSCREEN_P_H #define QFBSCREEN_P_H diff --git a/src/platformsupport/fbconvenience/qfbvthandler.cpp b/src/platformsupport/fbconvenience/qfbvthandler.cpp index 7bb9e28ac2..0d835331d6 100644 --- a/src/platformsupport/fbconvenience/qfbvthandler.cpp +++ b/src/platformsupport/fbconvenience/qfbvthandler.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qfbvthandler_p.h" #include <QtCore/QSocketNotifier> @@ -70,6 +34,10 @@ QT_BEGIN_NAMESPACE #ifdef VTH_ENABLED static void setTTYCursor(bool enable) { + static bool ignore = qEnvironmentVariableIntValue("QT_QPA_PRESERVE_CONSOLE_STATE"); + if (ignore) + return; + const char * const devs[] = { "/dev/tty0", "/dev/tty", "/dev/console", 0 }; int fd = -1; for (const char * const *dev = devs; *dev; ++dev) { @@ -206,3 +174,5 @@ void QFbVtHandler::handleInt() } QT_END_NAMESPACE + +#include "moc_qfbvthandler_p.cpp" diff --git a/src/platformsupport/fbconvenience/qfbvthandler_p.h b/src/platformsupport/fbconvenience/qfbvthandler_p.h index 17d07317b2..8a1fb37a67 100644 --- a/src/platformsupport/fbconvenience/qfbvthandler_p.h +++ b/src/platformsupport/fbconvenience/qfbvthandler_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QFBVTHANDLER_H #define QFBVTHANDLER_H @@ -63,7 +27,7 @@ class QFbVtHandler : public QObject Q_OBJECT public: - QFbVtHandler(QObject *parent = 0); + QFbVtHandler(QObject *parent = nullptr); ~QFbVtHandler(); signals: diff --git a/src/platformsupport/fbconvenience/qfbwindow.cpp b/src/platformsupport/fbconvenience/qfbwindow.cpp index 36f92b8cea..54716cc497 100644 --- a/src/platformsupport/fbconvenience/qfbwindow.cpp +++ b/src/platformsupport/fbconvenience/qfbwindow.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qfbwindow_p.h" #include "qfbscreen_p.h" @@ -45,11 +9,12 @@ QT_BEGIN_NAMESPACE +Q_CONSTINIT static QBasicAtomicInt winIdGenerator = Q_BASIC_ATOMIC_INITIALIZER(0); + QFbWindow::QFbWindow(QWindow *window) : QPlatformWindow(window), mBackingStore(0), mWindowState(Qt::WindowNoState) { - static QAtomicInt winIdGenerator(1); - mWindowId = winIdGenerator.fetchAndAddRelaxed(1); + mWindowId = winIdGenerator.fetchAndAddRelaxed(1) + 1; } QFbWindow::~QFbWindow() @@ -137,14 +102,14 @@ void QFbWindow::lower() void QFbWindow::repaint(const QRegion ®ion) { const QRect currentGeometry = geometry(); - const QRect dirtyClient = region.boundingRect(); - const QRect dirtyRegion = dirtyClient.translated(currentGeometry.topLeft()); const QRect oldGeometryLocal = mOldGeometry; mOldGeometry = currentGeometry; // If this is a move, redraw the previous location if (oldGeometryLocal != currentGeometry) platformScreen()->setDirty(oldGeometryLocal); - platformScreen()->setDirty(dirtyRegion); + auto topLeft = currentGeometry.topLeft(); + for (auto rect : region) + platformScreen()->setDirty(rect.translated(topLeft)); } QT_END_NAMESPACE diff --git a/src/platformsupport/fbconvenience/qfbwindow_p.h b/src/platformsupport/fbconvenience/qfbwindow_p.h index 76b34ce041..8367a10bce 100644 --- a/src/platformsupport/fbconvenience/qfbwindow_p.h +++ b/src/platformsupport/fbconvenience/qfbwindow_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QFBWINDOW_P_H #define QFBWINDOW_P_H @@ -52,6 +16,7 @@ // #include <qpa/qplatformwindow.h> +#include <private/qglobal_p.h> QT_BEGIN_NAMESPACE diff --git a/src/platformsupport/fontdatabases/fontconfig/fontconfig.pri b/src/platformsupport/fontdatabases/fontconfig/fontconfig.pri deleted file mode 100644 index 671d6be237..0000000000 --- a/src/platformsupport/fontdatabases/fontconfig/fontconfig.pri +++ /dev/null @@ -1,6 +0,0 @@ -HEADERS += $$PWD/qfontconfigdatabase_p.h \ - $$PWD/qfontenginemultifontconfig_p.h -SOURCES += $$PWD/qfontconfigdatabase.cpp \ - $$PWD/qfontenginemultifontconfig.cpp - -QMAKE_USE_PRIVATE += fontconfig diff --git a/src/platformsupport/fontdatabases/fontconfig/qfontconfigdatabase.cpp b/src/platformsupport/fontdatabases/fontconfig/qfontconfigdatabase.cpp deleted file mode 100644 index e545d54ec2..0000000000 --- a/src/platformsupport/fontdatabases/fontconfig/qfontconfigdatabase.cpp +++ /dev/null @@ -1,1002 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qfontconfigdatabase_p.h" -#include "qfontenginemultifontconfig_p.h" - -#include <QtFontDatabaseSupport/private/qfontengine_ft_p.h> - -#include <QtCore/QList> -#include <QtCore/QElapsedTimer> -#include <QtCore/QFile> - -#include <qpa/qplatformnativeinterface.h> -#include <qpa/qplatformscreen.h> -#include <qpa/qplatformintegration.h> -#include <qpa/qplatformservices.h> - -#include <QtGui/private/qguiapplication_p.h> -#include <QtGui/private/qhighdpiscaling_p.h> - -#include <QtGui/qguiapplication.h> - -#include <fontconfig/fontconfig.h> -#if FC_VERSION >= 20402 -#include <fontconfig/fcfreetype.h> -#endif - -QT_BEGIN_NAMESPACE - -static const int maxWeight = 99; - -static inline int mapToQtWeightForRange(int fcweight, int fcLower, int fcUpper, int qtLower, int qtUpper) -{ - return qtLower + ((fcweight - fcLower) * (qtUpper - qtLower)) / (fcUpper - fcLower); -} - -static inline int weightFromFcWeight(int fcweight) -{ - // Font Config uses weights from 0 to 215 (the highest enum value) while QFont ranges from - // 0 to 99. The spacing between the values for the enums are uneven so a linear mapping from - // Font Config values to Qt would give surprising results. So, we do a piecewise linear - // mapping. This ensures that where there is a corresponding enum on both sides (for example - // FC_WEIGHT_DEMIBOLD and QFont::DemiBold) we map one to the other but other values map - // to intermediate Qt weights. - - if (fcweight <= FC_WEIGHT_THIN) - return QFont::Thin; - if (fcweight <= FC_WEIGHT_ULTRALIGHT) - return mapToQtWeightForRange(fcweight, FC_WEIGHT_THIN, FC_WEIGHT_ULTRALIGHT, QFont::Thin, QFont::ExtraLight); - if (fcweight <= FC_WEIGHT_LIGHT) - return mapToQtWeightForRange(fcweight, FC_WEIGHT_ULTRALIGHT, FC_WEIGHT_LIGHT, QFont::ExtraLight, QFont::Light); - if (fcweight <= FC_WEIGHT_NORMAL) - return mapToQtWeightForRange(fcweight, FC_WEIGHT_LIGHT, FC_WEIGHT_NORMAL, QFont::Light, QFont::Normal); - if (fcweight <= FC_WEIGHT_MEDIUM) - return mapToQtWeightForRange(fcweight, FC_WEIGHT_NORMAL, FC_WEIGHT_MEDIUM, QFont::Normal, QFont::Medium); - if (fcweight <= FC_WEIGHT_DEMIBOLD) - return mapToQtWeightForRange(fcweight, FC_WEIGHT_MEDIUM, FC_WEIGHT_DEMIBOLD, QFont::Medium, QFont::DemiBold); - if (fcweight <= FC_WEIGHT_BOLD) - return mapToQtWeightForRange(fcweight, FC_WEIGHT_DEMIBOLD, FC_WEIGHT_BOLD, QFont::DemiBold, QFont::Bold); - if (fcweight <= FC_WEIGHT_ULTRABOLD) - return mapToQtWeightForRange(fcweight, FC_WEIGHT_BOLD, FC_WEIGHT_ULTRABOLD, QFont::Bold, QFont::ExtraBold); - if (fcweight <= FC_WEIGHT_BLACK) - return mapToQtWeightForRange(fcweight, FC_WEIGHT_ULTRABOLD, FC_WEIGHT_BLACK, QFont::ExtraBold, QFont::Black); - if (fcweight <= FC_WEIGHT_ULTRABLACK) - return mapToQtWeightForRange(fcweight, FC_WEIGHT_BLACK, FC_WEIGHT_ULTRABLACK, QFont::Black, maxWeight); - return maxWeight; -} - -static inline int stretchFromFcWidth(int fcwidth) -{ - // Font Config enums for width match pretty closely with those used by Qt so just use - // Font Config values directly while enforcing the same limits imposed by QFont. - const int maxStretch = 4000; - int qtstretch; - if (fcwidth < 1) - qtstretch = 1; - else if (fcwidth > maxStretch) - qtstretch = maxStretch; - else - qtstretch = fcwidth; - - return qtstretch; -} - -static const char specialLanguages[][6] = { - "", // Unknown - "", // Inherited - "", // Common - "en", // Latin - "el", // Greek - "ru", // Cyrillic - "hy", // Armenian - "he", // Hebrew - "ar", // Arabic - "syr", // Syriac - "dv", // Thaana - "hi", // Devanagari - "bn", // Bengali - "pa", // Gurmukhi - "gu", // Gujarati - "or", // Oriya - "ta", // Tamil - "te", // Telugu - "kn", // Kannada - "ml", // Malayalam - "si", // Sinhala - "th", // Thai - "lo", // Lao - "bo", // Tibetan - "my", // Myanmar - "ka", // Georgian - "ko", // Hangul - "am", // Ethiopic - "chr", // Cherokee - "cr", // CanadianAboriginal - "sga", // Ogham - "non", // Runic - "km", // Khmer - "mn", // Mongolian - "ja", // Hiragana - "ja", // Katakana - "zh-TW", // Bopomofo - "", // Han - "ii", // Yi - "ett", // OldItalic - "got", // Gothic - "en", // Deseret - "fil", // Tagalog - "hnn", // Hanunoo - "bku", // Buhid - "tbw", // Tagbanwa - "cop", // Coptic - "lif", // Limbu - "tdd", // TaiLe - "grc", // LinearB - "uga", // Ugaritic - "en", // Shavian - "so", // Osmanya - "grc", // Cypriot - "", // Braille - "bug", // Buginese - "khb", // NewTaiLue - "cu", // Glagolitic - "shi", // Tifinagh - "syl", // SylotiNagri - "peo", // OldPersian - "pra", // Kharoshthi - "ban", // Balinese - "akk", // Cuneiform - "phn", // Phoenician - "lzh", // PhagsPa - "man", // Nko - "su", // Sundanese - "lep", // Lepcha - "sat", // OlChiki - "vai", // Vai - "saz", // Saurashtra - "eky", // KayahLi - "rej", // Rejang - "xlc", // Lycian - "xcr", // Carian - "xld", // Lydian - "cjm", // Cham - "nod", // TaiTham - "blt", // TaiViet - "ae", // Avestan - "egy", // EgyptianHieroglyphs - "smp", // Samaritan - "lis", // Lisu - "bax", // Bamum - "jv", // Javanese - "mni", // MeeteiMayek - "arc", // ImperialAramaic - "xsa", // OldSouthArabian - "xpr", // InscriptionalParthian - "pal", // InscriptionalPahlavi - "otk", // OldTurkic - "bh", // Kaithi - "bbc", // Batak - "pra", // Brahmi - "myz", // Mandaic - "ccp", // Chakma - "xmr", // MeroiticCursive - "xmr", // MeroiticHieroglyphs - "hmd", // Miao - "sa", // Sharada - "srb", // SoraSompeng - "doi", // Takri - "lez", // CaucasianAlbanian - "bsq", // BassaVah - "fr", // Duployan - "sq", // Elbasan - "sa", // Grantha - "hnj", // PahawhHmong - "sd", // Khojki - "lab", // LinearA - "hi", // Mahajani - "xmn", // Manichaean - "men", // MendeKikakui - "mr", // Modi - "mru", // Mro - "xna", // OldNorthArabian - "arc", // Nabataean - "arc", // Palmyrene - "ctd", // PauCinHau - "kv", // OldPermic - "pal", // PsalterPahlavi - "sa", // Siddham - "sd", // Khudawadi - "mai", // Tirhuta - "hoc", // WarangCiti - "", // Ahom - "", // AnatolianHieroglyphs - "", // Hatran - "", // Multani - "", // OldHungarian - "", // SignWriting - "", // Adlam - "", // Bhaiksuki - "", // Marchen - "", // Newa - "", // Osage - "", // Tangut - "", // MasaramGondi - "", // Nushu - "", // Soyombo - "" // ZanabazarSquare -}; -Q_STATIC_ASSERT(sizeof specialLanguages / sizeof *specialLanguages == QChar::ScriptCount); - -// this could become a list of all languages used for each writing -// system, instead of using the single most common language. -static const char languageForWritingSystem[][6] = { - "", // Any - "en", // Latin - "el", // Greek - "ru", // Cyrillic - "hy", // Armenian - "he", // Hebrew - "ar", // Arabic - "syr", // Syriac - "div", // Thaana - "hi", // Devanagari - "bn", // Bengali - "pa", // Gurmukhi - "gu", // Gujarati - "or", // Oriya - "ta", // Tamil - "te", // Telugu - "kn", // Kannada - "ml", // Malayalam - "si", // Sinhala - "th", // Thai - "lo", // Lao - "bo", // Tibetan - "my", // Myanmar - "ka", // Georgian - "km", // Khmer - "zh-cn", // SimplifiedChinese - "zh-tw", // TraditionalChinese - "ja", // Japanese - "ko", // Korean - "vi", // Vietnamese - "", // Symbol - "sga", // Ogham - "non", // Runic - "man" // N'Ko -}; -Q_STATIC_ASSERT(sizeof languageForWritingSystem / sizeof *languageForWritingSystem == QFontDatabase::WritingSystemsCount); - -#if FC_VERSION >= 20297 -// Newer FontConfig let's us sort out fonts that report certain scripts support, -// but no open type tables for handling them correctly. -// Check the reported script presence in the FC_CAPABILITY's "otlayout:" section. -static const char capabilityForWritingSystem[][5] = { - "", // Any - "", // Latin - "", // Greek - "", // Cyrillic - "", // Armenian - "", // Hebrew - "", // Arabic - "syrc", // Syriac - "thaa", // Thaana - "deva", // Devanagari - "beng", // Bengali - "guru", // Gurmukhi - "gujr", // Gujarati - "orya", // Oriya - "taml", // Tamil - "telu", // Telugu - "knda", // Kannada - "mlym", // Malayalam - "sinh", // Sinhala - "", // Thai - "", // Lao - "tibt", // Tibetan - "mymr", // Myanmar - "", // Georgian - "khmr", // Khmer - "", // SimplifiedChinese - "", // TraditionalChinese - "", // Japanese - "", // Korean - "", // Vietnamese - "", // Symbol - "", // Ogham - "", // Runic - "nko " // N'Ko -}; -Q_STATIC_ASSERT(sizeof(capabilityForWritingSystem) / sizeof(*capabilityForWritingSystem) == QFontDatabase::WritingSystemsCount); -#endif - -static const char *getFcFamilyForStyleHint(const QFont::StyleHint style) -{ - const char *stylehint = 0; - switch (style) { - case QFont::SansSerif: - stylehint = "sans-serif"; - break; - case QFont::Serif: - stylehint = "serif"; - break; - case QFont::TypeWriter: - case QFont::Monospace: - stylehint = "monospace"; - break; - case QFont::Cursive: - stylehint = "cursive"; - break; - case QFont::Fantasy: - stylehint = "fantasy"; - break; - default: - break; - } - return stylehint; -} - -static inline bool requiresOpenType(int writingSystem) -{ - return ((writingSystem >= QFontDatabase::Syriac && writingSystem <= QFontDatabase::Sinhala) - || writingSystem == QFontDatabase::Khmer || writingSystem == QFontDatabase::Nko); -} - -static void populateFromPattern(FcPattern *pattern) -{ - QString familyName; - QString familyNameLang; - FcChar8 *value = 0; - int weight_value; - int slant_value; - int spacing_value; - int width_value; - FcChar8 *file_value; - int indexValue; - FcChar8 *foundry_value; - FcChar8 *style_value; - FcBool scalable; - FcBool antialias; - - if (FcPatternGetString(pattern, FC_FAMILY, 0, &value) != FcResultMatch) - return; - - familyName = QString::fromUtf8((const char *)value); - - if (FcPatternGetString(pattern, FC_FAMILYLANG, 0, &value) == FcResultMatch) - familyNameLang = QString::fromUtf8((const char *)value); - - slant_value = FC_SLANT_ROMAN; - weight_value = FC_WEIGHT_REGULAR; - spacing_value = FC_PROPORTIONAL; - file_value = 0; - indexValue = 0; - scalable = FcTrue; - - - if (FcPatternGetInteger(pattern, FC_SLANT, 0, &slant_value) != FcResultMatch) - slant_value = FC_SLANT_ROMAN; - if (FcPatternGetInteger(pattern, FC_WEIGHT, 0, &weight_value) != FcResultMatch) - weight_value = FC_WEIGHT_REGULAR; - if (FcPatternGetInteger(pattern, FC_WIDTH, 0, &width_value) != FcResultMatch) - width_value = FC_WIDTH_NORMAL; - if (FcPatternGetInteger(pattern, FC_SPACING, 0, &spacing_value) != FcResultMatch) - spacing_value = FC_PROPORTIONAL; - if (FcPatternGetString(pattern, FC_FILE, 0, &file_value) != FcResultMatch) - file_value = 0; - if (FcPatternGetInteger(pattern, FC_INDEX, 0, &indexValue) != FcResultMatch) - indexValue = 0; - if (FcPatternGetBool(pattern, FC_SCALABLE, 0, &scalable) != FcResultMatch) - scalable = FcTrue; - if (FcPatternGetString(pattern, FC_FOUNDRY, 0, &foundry_value) != FcResultMatch) - foundry_value = 0; - if (FcPatternGetString(pattern, FC_STYLE, 0, &style_value) != FcResultMatch) - style_value = 0; - if (FcPatternGetBool(pattern,FC_ANTIALIAS,0,&antialias) != FcResultMatch) - antialias = true; - - QSupportedWritingSystems writingSystems; - FcLangSet *langset = 0; - FcResult res = FcPatternGetLangSet(pattern, FC_LANG, 0, &langset); - if (res == FcResultMatch) { - bool hasLang = false; -#if FC_VERSION >= 20297 - FcChar8 *cap = nullptr; - FcResult capRes = FcResultNoMatch; -#endif - for (int j = 1; j < QFontDatabase::WritingSystemsCount; ++j) { - const FcChar8 *lang = (const FcChar8*) languageForWritingSystem[j]; - if (lang) { - FcLangResult langRes = FcLangSetHasLang(langset, lang); - if (langRes != FcLangDifferentLang) { -#if FC_VERSION >= 20297 - if (*capabilityForWritingSystem[j] && requiresOpenType(j)) { - if (cap == nullptr) - capRes = FcPatternGetString(pattern, FC_CAPABILITY, 0, &cap); - if (capRes == FcResultMatch && strstr(reinterpret_cast<const char *>(cap), capabilityForWritingSystem[j]) == 0) - continue; - } -#endif - writingSystems.setSupported(QFontDatabase::WritingSystem(j)); - hasLang = true; - } - } - } - if (!hasLang) - // none of our known languages, add it to the other set - writingSystems.setSupported(QFontDatabase::Other); - } else { - // we set Other to supported for symbol fonts. It makes no - // sense to merge these with other ones, as they are - // special in a way. - writingSystems.setSupported(QFontDatabase::Other); - } - - FontFile *fontFile = new FontFile; - fontFile->fileName = QString::fromLocal8Bit((const char *)file_value); - fontFile->indexValue = indexValue; - - QFont::Style style = (slant_value == FC_SLANT_ITALIC) - ? QFont::StyleItalic - : ((slant_value == FC_SLANT_OBLIQUE) - ? QFont::StyleOblique - : QFont::StyleNormal); - // Note: weight should really be an int but registerFont incorrectly uses an enum - QFont::Weight weight = QFont::Weight(weightFromFcWeight(weight_value)); - - double pixel_size = 0; - if (!scalable) - FcPatternGetDouble (pattern, FC_PIXEL_SIZE, 0, &pixel_size); - - bool fixedPitch = spacing_value >= FC_MONO; - // Note: stretch should really be an int but registerFont incorrectly uses an enum - QFont::Stretch stretch = QFont::Stretch(stretchFromFcWidth(width_value)); - QString styleName = style_value ? QString::fromUtf8((const char *) style_value) : QString(); - QPlatformFontDatabase::registerFont(familyName,styleName,QLatin1String((const char *)foundry_value),weight,style,stretch,antialias,scalable,pixel_size,fixedPitch,writingSystems,fontFile); -// qDebug() << familyName << (const char *)foundry_value << weight << style << &writingSystems << scalable << true << pixel_size; - - for (int k = 1; FcPatternGetString(pattern, FC_FAMILY, k, &value) == FcResultMatch; ++k) { - const QString altFamilyName = QString::fromUtf8((const char *)value); - // Extra family names can be aliases or subfamilies. - // If it is a subfamily, register it as a separate font, so only members of the subfamily are - // matched when the subfamily is requested. - QString altStyleName; - if (FcPatternGetString(pattern, FC_STYLE, k, &value) == FcResultMatch) - altStyleName = QString::fromUtf8((const char *)value); - else - altStyleName = styleName; - - QString altFamilyNameLang; - if (FcPatternGetString(pattern, FC_FAMILYLANG, k, &value) == FcResultMatch) - altFamilyNameLang = QString::fromUtf8((const char *)value); - else - altFamilyNameLang = familyNameLang; - - if (familyNameLang == altFamilyNameLang && altStyleName != styleName) { - FontFile *altFontFile = new FontFile(*fontFile); - QPlatformFontDatabase::registerFont(altFamilyName, altStyleName, QLatin1String((const char *)foundry_value),weight,style,stretch,antialias,scalable,pixel_size,fixedPitch,writingSystems,altFontFile); - } else { - QPlatformFontDatabase::registerAliasToFontFamily(familyName, altFamilyName); - } - } - -} - -void QFontconfigDatabase::populateFontDatabase() -{ - FcInit(); - FcFontSet *fonts; - - { - FcObjectSet *os = FcObjectSetCreate(); - FcPattern *pattern = FcPatternCreate(); - const char *properties [] = { - FC_FAMILY, FC_STYLE, FC_WEIGHT, FC_SLANT, - FC_SPACING, FC_FILE, FC_INDEX, - FC_LANG, FC_CHARSET, FC_FOUNDRY, FC_SCALABLE, FC_PIXEL_SIZE, - FC_WIDTH, FC_FAMILYLANG, -#if FC_VERSION >= 20297 - FC_CAPABILITY, -#endif - (const char *)0 - }; - const char **p = properties; - while (*p) { - FcObjectSetAdd(os, *p); - ++p; - } - fonts = FcFontList(0, pattern, os); - FcObjectSetDestroy(os); - FcPatternDestroy(pattern); - } - - for (int i = 0; i < fonts->nfont; i++) - populateFromPattern(fonts->fonts[i]); - - FcFontSetDestroy (fonts); - - struct FcDefaultFont { - const char *qtname; - const char *rawname; - bool fixed; - }; - const FcDefaultFont defaults[] = { - { "Serif", "serif", false }, - { "Sans Serif", "sans-serif", false }, - { "Monospace", "monospace", true }, - { 0, 0, false } - }; - const FcDefaultFont *f = defaults; - // aliases only make sense for 'common', not for any of the specials - QSupportedWritingSystems ws; - ws.setSupported(QFontDatabase::Latin); - - while (f->qtname) { - QString familyQtName = QString::fromLatin1(f->qtname); - registerFont(familyQtName,QString(),QString(),QFont::Normal,QFont::StyleNormal,QFont::Unstretched,true,true,0,f->fixed,ws,0); - registerFont(familyQtName,QString(),QString(),QFont::Normal,QFont::StyleItalic,QFont::Unstretched,true,true,0,f->fixed,ws,0); - registerFont(familyQtName,QString(),QString(),QFont::Normal,QFont::StyleOblique,QFont::Unstretched,true,true,0,f->fixed,ws,0); - ++f; - } - - //Lighthouse has very lazy population of the font db. We want it to be initialized when - //QApplication is constructed, so that the population procedure can do something like this to - //set the default font -// const FcDefaultFont *s = defaults; -// QFont font("Sans Serif"); -// font.setPointSize(9); -// QApplication::setFont(font); -} - -void QFontconfigDatabase::invalidate() -{ - // Clear app fonts. - FcConfigAppFontClear(0); -} - -QFontEngineMulti *QFontconfigDatabase::fontEngineMulti(QFontEngine *fontEngine, QChar::Script script) -{ - return new QFontEngineMultiFontConfig(fontEngine, script); -} - -namespace { -QFontEngine::HintStyle defaultHintStyleFromMatch(QFont::HintingPreference hintingPreference, FcPattern *match, bool useXftConf) -{ - switch (hintingPreference) { - case QFont::PreferNoHinting: - return QFontEngine::HintNone; - case QFont::PreferVerticalHinting: - return QFontEngine::HintLight; - case QFont::PreferFullHinting: - return QFontEngine::HintFull; - case QFont::PreferDefaultHinting: - break; - } - - if (QHighDpiScaling::isActive()) - return QFontEngine::HintNone; - - int hint_style = 0; - if (FcPatternGetInteger (match, FC_HINT_STYLE, 0, &hint_style) == FcResultMatch) { - switch (hint_style) { - case FC_HINT_NONE: - return QFontEngine::HintNone; - case FC_HINT_SLIGHT: - return QFontEngine::HintLight; - case FC_HINT_MEDIUM: - return QFontEngine::HintMedium; - case FC_HINT_FULL: - return QFontEngine::HintFull; - default: - Q_UNREACHABLE(); - break; - } - } - - if (useXftConf) { - void *hintStyleResource = - QGuiApplication::platformNativeInterface()->nativeResourceForScreen("hintstyle", - QGuiApplication::primaryScreen()); - int hintStyle = int(reinterpret_cast<qintptr>(hintStyleResource)); - if (hintStyle > 0) - return QFontEngine::HintStyle(hintStyle - 1); - } - - return QFontEngine::HintFull; -} - -QFontEngine::SubpixelAntialiasingType subpixelTypeFromMatch(FcPattern *match, bool useXftConf) -{ - int subpixel = FC_RGBA_UNKNOWN; - if (FcPatternGetInteger(match, FC_RGBA, 0, &subpixel) == FcResultMatch) { - switch (subpixel) { - case FC_RGBA_UNKNOWN: - case FC_RGBA_NONE: - return QFontEngine::Subpixel_None; - case FC_RGBA_RGB: - return QFontEngine::Subpixel_RGB; - case FC_RGBA_BGR: - return QFontEngine::Subpixel_BGR; - case FC_RGBA_VRGB: - return QFontEngine::Subpixel_VRGB; - case FC_RGBA_VBGR: - return QFontEngine::Subpixel_VBGR; - default: - Q_UNREACHABLE(); - break; - } - } - - if (useXftConf) { - void *subpixelTypeResource = - QGuiApplication::platformNativeInterface()->nativeResourceForScreen("subpixeltype", - QGuiApplication::primaryScreen()); - int subpixelType = int(reinterpret_cast<qintptr>(subpixelTypeResource)); - if (subpixelType > 0) - return QFontEngine::SubpixelAntialiasingType(subpixelType - 1); - } - - return QFontEngine::Subpixel_None; -} -} // namespace - -QFontEngine *QFontconfigDatabase::fontEngine(const QFontDef &f, void *usrPtr) -{ - if (!usrPtr) - return 0; - - FontFile *fontfile = static_cast<FontFile *> (usrPtr); - QFontEngine::FaceId fid; - fid.filename = QFile::encodeName(fontfile->fileName); - fid.index = fontfile->indexValue; - - // FIXME: Unify with logic in QFontEngineFT::create() - QFontEngineFT *engine = new QFontEngineFT(f); - engine->face_id = fid; - - setupFontEngine(engine, f); - - if (!engine->init(fid, engine->antialias, engine->defaultFormat) || engine->invalid()) { - delete engine; - engine = 0; - } - - return engine; -} - -QFontEngine *QFontconfigDatabase::fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference) -{ - QFontEngineFT *engine = static_cast<QFontEngineFT*>(QFreeTypeFontDatabase::fontEngine(fontData, pixelSize, hintingPreference)); - if (engine == 0) - return 0; - - setupFontEngine(engine, engine->fontDef); - - return engine; -} - -QStringList QFontconfigDatabase::fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const -{ - QStringList fallbackFamilies; - FcPattern *pattern = FcPatternCreate(); - if (!pattern) - return fallbackFamilies; - - FcValue value; - value.type = FcTypeString; - QByteArray cs = family.toUtf8(); - value.u.s = (const FcChar8 *)cs.data(); - FcPatternAdd(pattern,FC_FAMILY,value,true); - - int slant_value = FC_SLANT_ROMAN; - if (style == QFont::StyleItalic) - slant_value = FC_SLANT_ITALIC; - else if (style == QFont::StyleOblique) - slant_value = FC_SLANT_OBLIQUE; - FcPatternAddInteger(pattern, FC_SLANT, slant_value); - - Q_ASSERT(uint(script) < QChar::ScriptCount); - if (*specialLanguages[script] != '\0') { - FcLangSet *ls = FcLangSetCreate(); - FcLangSetAdd(ls, (const FcChar8*)specialLanguages[script]); - FcPatternAddLangSet(pattern, FC_LANG, ls); - FcLangSetDestroy(ls); - } else if (!family.isEmpty()) { - // If script is Common or Han, then it may include languages like CJK, - // we should attach system default language set to the pattern - // to obtain correct font fallback list (i.e. if LANG=zh_CN - // then we normally want to use a Chinese font for CJK text; - // while a Japanese font should be used for that if LANG=ja) - FcPattern *dummy = FcPatternCreate(); - FcDefaultSubstitute(dummy); - FcChar8 *lang = 0; - FcResult res = FcPatternGetString(dummy, FC_LANG, 0, &lang); - if (res == FcResultMatch) - FcPatternAddString(pattern, FC_LANG, lang); - FcPatternDestroy(dummy); - } - - const char *stylehint = getFcFamilyForStyleHint(styleHint); - if (stylehint) { - value.u.s = (const FcChar8 *)stylehint; - FcPatternAddWeak(pattern, FC_FAMILY, value, FcTrue); - } - - FcConfigSubstitute(0, pattern, FcMatchPattern); - FcDefaultSubstitute(pattern); - - FcResult result = FcResultMatch; - FcFontSet *fontSet = FcFontSort(0,pattern,FcFalse,0,&result); - FcPatternDestroy(pattern); - - if (fontSet) { - QSet<QString> duplicates; - duplicates.reserve(fontSet->nfont + 1); - duplicates.insert(family.toCaseFolded()); - for (int i = 0; i < fontSet->nfont; i++) { - FcChar8 *value = 0; - if (FcPatternGetString(fontSet->fonts[i], FC_FAMILY, 0, &value) != FcResultMatch) - continue; - // capitalize(value); - const QString familyName = QString::fromUtf8((const char *)value); - const QString familyNameCF = familyName.toCaseFolded(); - if (!duplicates.contains(familyNameCF)) { - fallbackFamilies << familyName; - duplicates.insert(familyNameCF); - } - } - FcFontSetDestroy(fontSet); - } -// qDebug() << "fallbackFamilies for:" << family << style << styleHint << script << fallbackFamilies; - - return fallbackFamilies; -} - -static FcPattern *queryFont(const FcChar8 *file, const QByteArray &data, int id, FcBlanks *blanks, int *count) -{ -#if FC_VERSION < 20402 - Q_UNUSED(data) - return FcFreeTypeQuery(file, id, blanks, count); -#else - if (data.isEmpty()) - return FcFreeTypeQuery(file, id, blanks, count); - - FT_Library lib = qt_getFreetype(); - - FcPattern *pattern = 0; - - FT_Face face; - if (!FT_New_Memory_Face(lib, (const FT_Byte *)data.constData(), data.size(), id, &face)) { - *count = face->num_faces; - - pattern = FcFreeTypeQueryFace(face, file, id, blanks); - - FT_Done_Face(face); - } - - return pattern; -#endif -} - -QStringList QFontconfigDatabase::addApplicationFont(const QByteArray &fontData, const QString &fileName) -{ - QStringList families; - - FcFontSet *set = FcConfigGetFonts(0, FcSetApplication); - if (!set) { - FcConfigAppFontAddFile(0, (const FcChar8 *)":/non-existent"); - set = FcConfigGetFonts(0, FcSetApplication); // try again - if (!set) - return families; - } - - int id = 0; - FcBlanks *blanks = FcConfigGetBlanks(0); - int count = 0; - - FcPattern *pattern; - do { - pattern = queryFont((const FcChar8 *)QFile::encodeName(fileName).constData(), - fontData, id, blanks, &count); - if (!pattern) - return families; - - FcChar8 *fam = 0; - if (FcPatternGetString(pattern, FC_FAMILY, 0, &fam) == FcResultMatch) { - QString family = QString::fromUtf8(reinterpret_cast<const char *>(fam)); - families << family; - } - populateFromPattern(pattern); - - FcFontSetAdd(set, pattern); - - ++id; - } while (id < count); - - return families; -} - -QString QFontconfigDatabase::resolveFontFamilyAlias(const QString &family) const -{ - QString resolved = QFreeTypeFontDatabase::resolveFontFamilyAlias(family); - if (!resolved.isEmpty() && resolved != family) - return resolved; - FcPattern *pattern = FcPatternCreate(); - if (!pattern) - return family; - - if (!family.isEmpty()) { - QByteArray cs = family.toUtf8(); - FcPatternAddString(pattern, FC_FAMILY, (const FcChar8 *) cs.constData()); - } - FcConfigSubstitute(0, pattern, FcMatchPattern); - FcDefaultSubstitute(pattern); - - FcChar8 *familyAfterSubstitution = 0; - FcPatternGetString(pattern, FC_FAMILY, 0, &familyAfterSubstitution); - resolved = QString::fromUtf8((const char *) familyAfterSubstitution); - FcPatternDestroy(pattern); - - return resolved; -} - -QFont QFontconfigDatabase::defaultFont() const -{ - // Hack to get system default language until FcGetDefaultLangs() - // is exported (https://bugs.freedesktop.org/show_bug.cgi?id=32853) - // or https://bugs.freedesktop.org/show_bug.cgi?id=35482 is fixed - FcPattern *dummy = FcPatternCreate(); - FcDefaultSubstitute(dummy); - FcChar8 *lang = 0; - FcResult res = FcPatternGetString(dummy, FC_LANG, 0, &lang); - - FcPattern *pattern = FcPatternCreate(); - if (res == FcResultMatch) { - // Make defaultFont pattern matching locale language aware, because - // certain FC_LANG based custom rules may happen in FcConfigSubstitute() - FcPatternAddString(pattern, FC_LANG, lang); - } - FcConfigSubstitute(0, pattern, FcMatchPattern); - FcDefaultSubstitute(pattern); - - FcChar8 *familyAfterSubstitution = 0; - FcPatternGetString(pattern, FC_FAMILY, 0, &familyAfterSubstitution); - QString resolved = QString::fromUtf8((const char *) familyAfterSubstitution); - FcPatternDestroy(pattern); - FcPatternDestroy(dummy); - - return QFont(resolved); -} - -void QFontconfigDatabase::setupFontEngine(QFontEngineFT *engine, const QFontDef &fontDef) const -{ - bool antialias = !(fontDef.styleStrategy & QFont::NoAntialias); - bool forcedAntialiasSetting = !antialias || QHighDpiScaling::isActive(); - - const QPlatformServices *services = QGuiApplicationPrivate::platformIntegration()->services(); - bool useXftConf = false; - - if (services) { - const QList<QByteArray> desktopEnv = services->desktopEnvironment().split(':'); - useXftConf = desktopEnv.contains("GNOME") || desktopEnv.contains("UNITY") || desktopEnv.contains("XFCE"); - } - - if (useXftConf && !forcedAntialiasSetting) { - void *antialiasResource = - QGuiApplication::platformNativeInterface()->nativeResourceForScreen("antialiasingEnabled", - QGuiApplication::primaryScreen()); - int antialiasingEnabled = int(reinterpret_cast<qintptr>(antialiasResource)); - if (antialiasingEnabled > 0) - antialias = antialiasingEnabled - 1; - } - - QFontEngine::GlyphFormat format; - // try and get the pattern - FcPattern *pattern = FcPatternCreate(); - - FcValue value; - value.type = FcTypeString; - QByteArray cs = fontDef.family.toUtf8(); - value.u.s = (const FcChar8 *)cs.data(); - FcPatternAdd(pattern,FC_FAMILY,value,true); - - QFontEngine::FaceId fid = engine->faceId(); - - if (!fid.filename.isEmpty()) { - value.u.s = (const FcChar8 *)fid.filename.data(); - FcPatternAdd(pattern,FC_FILE,value,true); - - value.type = FcTypeInteger; - value.u.i = fid.index; - FcPatternAdd(pattern,FC_INDEX,value,true); - } - - if (fontDef.pixelSize > 0.1) - FcPatternAddDouble(pattern, FC_PIXEL_SIZE, fontDef.pixelSize); - - FcResult result; - - FcConfigSubstitute(0, pattern, FcMatchPattern); - FcDefaultSubstitute(pattern); - - FcPattern *match = FcFontMatch(0, pattern, &result); - if (match) { - engine->setDefaultHintStyle(defaultHintStyleFromMatch((QFont::HintingPreference)fontDef.hintingPreference, match, useXftConf)); - - FcBool fc_autohint; - if (FcPatternGetBool(match, FC_AUTOHINT,0, &fc_autohint) == FcResultMatch) - engine->forceAutoHint = fc_autohint; - -#if defined(FT_LCD_FILTER_H) - int lcdFilter; - if (FcPatternGetInteger(match, FC_LCD_FILTER, 0, &lcdFilter) == FcResultMatch) - engine->lcdFilterType = lcdFilter; -#endif - - if (!forcedAntialiasSetting) { - FcBool fc_antialias; - if (FcPatternGetBool(match, FC_ANTIALIAS,0, &fc_antialias) == FcResultMatch) - antialias = fc_antialias; - } - - if (antialias) { - QFontEngine::SubpixelAntialiasingType subpixelType = QFontEngine::Subpixel_None; - if (!(fontDef.styleStrategy & QFont::NoSubpixelAntialias)) - subpixelType = subpixelTypeFromMatch(match, useXftConf); - engine->subpixelType = subpixelType; - - format = (subpixelType == QFontEngine::Subpixel_None) - ? QFontEngine::Format_A8 - : QFontEngine::Format_A32; - } else - format = QFontEngine::Format_Mono; - - FcPatternDestroy(match); - } else - format = antialias ? QFontEngine::Format_A8 : QFontEngine::Format_Mono; - - FcPatternDestroy(pattern); - - engine->antialias = antialias; - engine->defaultFormat = format; - engine->glyphFormat = format; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/fontdatabases/fontconfig/qfontconfigdatabase_p.h b/src/platformsupport/fontdatabases/fontconfig/qfontconfigdatabase_p.h deleted file mode 100644 index a7257c2f98..0000000000 --- a/src/platformsupport/fontdatabases/fontconfig/qfontconfigdatabase_p.h +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QFONTCONFIGDATABASE_H -#define QFONTCONFIGDATABASE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <qpa/qplatformfontdatabase.h> -#include <QtFontDatabaseSupport/private/qfreetypefontdatabase_p.h> - -QT_BEGIN_NAMESPACE - -class QFontEngineFT; - -class QFontconfigDatabase : public QFreeTypeFontDatabase -{ -public: - void populateFontDatabase() override; - void invalidate() override; - QFontEngineMulti *fontEngineMulti(QFontEngine *fontEngine, QChar::Script script) override; - QFontEngine *fontEngine(const QFontDef &fontDef, void *handle) override; - QFontEngine *fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference) override; - QStringList fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const override; - QStringList addApplicationFont(const QByteArray &fontData, const QString &fileName) override; - QString resolveFontFamilyAlias(const QString &family) const override; - QFont defaultFont() const override; - -private: - void setupFontEngine(QFontEngineFT *engine, const QFontDef &fontDef) const; -}; - -QT_END_NAMESPACE - -#endif // QFONTCONFIGDATABASE_H diff --git a/src/platformsupport/fontdatabases/fontconfig/qfontenginemultifontconfig.cpp b/src/platformsupport/fontdatabases/fontconfig/qfontenginemultifontconfig.cpp deleted file mode 100644 index 2fbcb6216e..0000000000 --- a/src/platformsupport/fontdatabases/fontconfig/qfontenginemultifontconfig.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qfontenginemultifontconfig_p.h" - -#include <QtFontDatabaseSupport/private/qfontengine_ft_p.h> - -QT_BEGIN_NAMESPACE - -QFontEngineMultiFontConfig::QFontEngineMultiFontConfig(QFontEngine *fe, int script) - : QFontEngineMulti(fe, script) -{ -} - -QFontEngineMultiFontConfig::~QFontEngineMultiFontConfig() -{ - for (FcPattern *pattern : qAsConst(cachedMatchPatterns)) { - if (pattern) - FcPatternDestroy(pattern); - } -} - -bool QFontEngineMultiFontConfig::shouldLoadFontEngineForCharacter(int at, uint ucs4) const -{ - bool charSetHasChar = true; - FcPattern *matchPattern = getMatchPatternForFallback(at - 1); - if (matchPattern != 0) { - FcCharSet *charSet; - FcPatternGetCharSet(matchPattern, FC_CHARSET, 0, &charSet); - charSetHasChar = FcCharSetHasChar(charSet, ucs4); - } - - return charSetHasChar; -} - - -FcPattern * QFontEngineMultiFontConfig::getMatchPatternForFallback(int fallBackIndex) const -{ - Q_ASSERT(fallBackIndex < fallbackFamilyCount()); - if (fallbackFamilyCount() > cachedMatchPatterns.size()) - cachedMatchPatterns.resize(fallbackFamilyCount()); - FcPattern *ret = cachedMatchPatterns.at(fallBackIndex); - if (ret) - return ret; - FcPattern *requestPattern = FcPatternCreate(); - FcValue value; - value.type = FcTypeString; - QByteArray cs = fallbackFamilyAt(fallBackIndex).toUtf8(); - value.u.s = reinterpret_cast<const FcChar8 *>(cs.data()); - FcPatternAdd(requestPattern, FC_FAMILY, value, true); - FcResult result; - ret = FcFontMatch(0, requestPattern, &result); - cachedMatchPatterns.insert(fallBackIndex, ret); - FcPatternDestroy(requestPattern); - return ret; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/fontdatabases/fontconfig/qfontenginemultifontconfig_p.h b/src/platformsupport/fontdatabases/fontconfig/qfontenginemultifontconfig_p.h deleted file mode 100644 index 7f560c2d05..0000000000 --- a/src/platformsupport/fontdatabases/fontconfig/qfontenginemultifontconfig_p.h +++ /dev/null @@ -1,75 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QFONTENGINEMULTIFONTCONFIG_H -#define QFONTENGINEMULTIFONTCONFIG_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qfontengine_p.h> -#include <fontconfig/fontconfig.h> - -QT_BEGIN_NAMESPACE - -class QFontEngineMultiFontConfig : public QFontEngineMulti -{ -public: - explicit QFontEngineMultiFontConfig(QFontEngine *fe, int script); - - ~QFontEngineMultiFontConfig(); - - bool shouldLoadFontEngineForCharacter(int at, uint ucs4) const override; -private: - FcPattern* getMatchPatternForFallback(int at) const; - - mutable QVector<FcPattern*> cachedMatchPatterns; -}; - -QT_END_NAMESPACE - -#endif // QFONTENGINEMULTIFONTCONFIG_H diff --git a/src/platformsupport/fontdatabases/fontdatabases.pro b/src/platformsupport/fontdatabases/fontdatabases.pro deleted file mode 100644 index f2bac9ab94..0000000000 --- a/src/platformsupport/fontdatabases/fontdatabases.pro +++ /dev/null @@ -1,33 +0,0 @@ -TARGET = QtFontDatabaseSupport -MODULE = fontdatabase_support - -QT = core-private gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII -PRECOMPILED_HEADER = ../../corelib/global/qt_pch.h - -darwin { - include($$PWD/mac/coretext.pri) -} - -qtConfig(freetype) { - include($$PWD/freetype/freetype.pri) -} - -unix { - include($$PWD/genericunix/genericunix.pri) - qtConfig(fontconfig) { - include($$PWD/fontconfig/fontconfig.pri) - } -} - -win32:!winrt { - include($$PWD/windows/windows.pri) -} - -winrt { - include($$PWD/winrt/winrt.pri) -} - -load(qt_module) diff --git a/src/platformsupport/fontdatabases/freetype/freetype.pri b/src/platformsupport/fontdatabases/freetype/freetype.pri deleted file mode 100644 index 7bda687ef4..0000000000 --- a/src/platformsupport/fontdatabases/freetype/freetype.pri +++ /dev/null @@ -1,9 +0,0 @@ -HEADERS += \ - $$PWD/qfreetypefontdatabase_p.h \ - $$PWD/qfontengine_ft_p.h - -SOURCES += \ - $$PWD/qfreetypefontdatabase.cpp \ - $$PWD/qfontengine_ft.cpp - -QMAKE_USE_PRIVATE += freetype diff --git a/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp b/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp deleted file mode 100644 index e132442e37..0000000000 --- a/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp +++ /dev/null @@ -1,2267 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qdir.h" -#include "qmetatype.h" -#include "qtextstream.h" -#include "qvariant.h" -#include "qfontengine_ft_p.h" -#include "private/qimage_p.h" -#include <private/qstringiterator_p.h> -#include <qguiapplication.h> -#include <qscreen.h> -#include <qpa/qplatformscreen.h> -#include <QtCore/QUuid> - -#ifndef QT_NO_FREETYPE - -#include "qfile.h" -#include "qfileinfo.h" -#include <qscopedvaluerollback.h> -#include "qthreadstorage.h" -#include <qmath.h> -#include <qendian.h> - -#include <ft2build.h> -#include FT_FREETYPE_H -#include FT_OUTLINE_H -#include FT_SYNTHESIS_H -#include FT_TRUETYPE_TABLES_H -#include FT_TYPE1_TABLES_H -#include FT_GLYPH_H -#include FT_MODULE_H -#include FT_LCD_FILTER_H - -#if defined(FT_CONFIG_OPTIONS_H) -#include FT_CONFIG_OPTIONS_H -#endif - -#if defined(FT_FONT_FORMATS_H) -#include FT_FONT_FORMATS_H -#endif - -#ifdef QT_LINUXBASE -#include FT_ERRORS_H -#endif - -#if !defined(QT_MAX_CACHED_GLYPH_SIZE) -# define QT_MAX_CACHED_GLYPH_SIZE 64 -#endif - -QT_BEGIN_NAMESPACE - -#define FLOOR(x) ((x) & -64) -#define CEIL(x) (((x)+63) & -64) -#define TRUNC(x) ((x) >> 6) -#define ROUND(x) (((x)+32) & -64) - -static bool ft_getSfntTable(void *user_data, uint tag, uchar *buffer, uint *length) -{ - FT_Face face = (FT_Face)user_data; - - bool result = false; - if (FT_IS_SFNT(face)) { - FT_ULong len = *length; - result = FT_Load_Sfnt_Table(face, tag, 0, buffer, &len) == FT_Err_Ok; - *length = len; - Q_ASSERT(!result || int(*length) > 0); - } - - return result; -} - -static QFontEngineFT::Glyph emptyGlyph; - -static const QFontEngine::HintStyle ftInitialDefaultHintStyle = -#ifdef Q_OS_WIN - QFontEngineFT::HintFull; -#else - QFontEngineFT::HintNone; -#endif - -// -------------------------- Freetype support ------------------------------ - -class QtFreetypeData -{ -public: - QtFreetypeData() - : library(0), hasPatentFreeLcdRendering(false) - { } - ~QtFreetypeData(); - - FT_Library library; - QHash<QFontEngine::FaceId, QFreetypeFace *> faces; - bool hasPatentFreeLcdRendering; -}; - -QtFreetypeData::~QtFreetypeData() -{ - for (QHash<QFontEngine::FaceId, QFreetypeFace *>::ConstIterator iter = faces.cbegin(); iter != faces.cend(); ++iter) - iter.value()->cleanup(); - faces.clear(); - FT_Done_FreeType(library); - library = 0; -} - -Q_GLOBAL_STATIC(QThreadStorage<QtFreetypeData *>, theFreetypeData) - -QtFreetypeData *qt_getFreetypeData() -{ - QtFreetypeData *&freetypeData = theFreetypeData()->localData(); - if (!freetypeData) - freetypeData = new QtFreetypeData; - if (!freetypeData->library) { - FT_Init_FreeType(&freetypeData->library); -#if defined(FT_FONT_FORMATS_H) - // Freetype defaults to disabling stem-darkening on CFF, we re-enable it. - FT_Bool no_darkening = false; - FT_Property_Set(freetypeData->library, "cff", "no-stem-darkening", &no_darkening); -#endif - // FreeType has since 2.8.1 a patent free alternative to LCD-filtering. - FT_Int amajor, aminor = 0, apatch = 0; - FT_Library_Version(freetypeData->library, &amajor, &aminor, &apatch); - if (QT_VERSION_CHECK(amajor, aminor, apatch) >= QT_VERSION_CHECK(2, 8, 1)) - freetypeData->hasPatentFreeLcdRendering = true; - } - return freetypeData; -} - -FT_Library qt_getFreetype() -{ - QtFreetypeData *freetypeData = qt_getFreetypeData(); - Q_ASSERT(freetypeData->library); - return freetypeData->library; -} - -int QFreetypeFace::fsType() const -{ - int fsType = 0; - TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(face, ft_sfnt_os2); - if (os2) - fsType = os2->fsType; - return fsType; -} - -int QFreetypeFace::getPointInOutline(glyph_t glyph, int flags, quint32 point, QFixed *xpos, QFixed *ypos, quint32 *nPoints) -{ - if (int error = FT_Load_Glyph(face, glyph, flags)) - return error; - - if (face->glyph->format != FT_GLYPH_FORMAT_OUTLINE) - return Err_Invalid_SubTable; - - *nPoints = face->glyph->outline.n_points; - if (!(*nPoints)) - return Err_Ok; - - if (point > *nPoints) - return Err_Invalid_SubTable; - - *xpos = QFixed::fromFixed(face->glyph->outline.points[point].x); - *ypos = QFixed::fromFixed(face->glyph->outline.points[point].y); - - return Err_Ok; -} - -bool QFreetypeFace::isScalableBitmap() const -{ -#ifdef FT_HAS_COLOR - return !FT_IS_SCALABLE(face) && FT_HAS_COLOR(face); -#else - return false; -#endif -} - -extern QByteArray qt_fontdata_from_index(int); - -/* - * One font file can contain more than one font (bold/italic for example) - * find the right one and return it. - * - * Returns the freetype face or 0 in case of an empty file or any other problems - * (like not being able to open the file) - */ -QFreetypeFace *QFreetypeFace::getFace(const QFontEngine::FaceId &face_id, - const QByteArray &fontData) -{ - if (face_id.filename.isEmpty() && fontData.isEmpty()) - return 0; - - QtFreetypeData *freetypeData = qt_getFreetypeData(); - - QFreetypeFace *freetype = freetypeData->faces.value(face_id, 0); - if (freetype) { - freetype->ref.ref(); - } else { - QScopedPointer<QFreetypeFace> newFreetype(new QFreetypeFace); - FT_Face face; - if (!face_id.filename.isEmpty()) { - QString fileName = QFile::decodeName(face_id.filename); - if (face_id.filename.startsWith(":qmemoryfonts/")) { - // from qfontdatabase.cpp - QByteArray idx = face_id.filename; - idx.remove(0, 14); // remove ':qmemoryfonts/' - bool ok = false; - newFreetype->fontData = qt_fontdata_from_index(idx.toInt(&ok)); - if (!ok) - newFreetype->fontData = QByteArray(); - } else if (!QFileInfo(fileName).isNativePath()) { - QFile file(fileName); - if (!file.open(QIODevice::ReadOnly)) { - return 0; - } - newFreetype->fontData = file.readAll(); - } - } else { - newFreetype->fontData = fontData; - } - if (!newFreetype->fontData.isEmpty()) { - if (FT_New_Memory_Face(freetypeData->library, (const FT_Byte *)newFreetype->fontData.constData(), newFreetype->fontData.size(), face_id.index, &face)) { - return 0; - } - } else if (FT_New_Face(freetypeData->library, face_id.filename, face_id.index, &face)) { - return 0; - } - newFreetype->face = face; - - newFreetype->ref.store(1); - newFreetype->xsize = 0; - newFreetype->ysize = 0; - newFreetype->matrix.xx = 0x10000; - newFreetype->matrix.yy = 0x10000; - newFreetype->matrix.xy = 0; - newFreetype->matrix.yx = 0; - newFreetype->unicode_map = 0; - newFreetype->symbol_map = 0; - - memset(newFreetype->cmapCache, 0, sizeof(newFreetype->cmapCache)); - - for (int i = 0; i < newFreetype->face->num_charmaps; ++i) { - FT_CharMap cm = newFreetype->face->charmaps[i]; - switch(cm->encoding) { - case FT_ENCODING_UNICODE: - newFreetype->unicode_map = cm; - break; - case FT_ENCODING_APPLE_ROMAN: - case FT_ENCODING_ADOBE_LATIN_1: - if (!newFreetype->unicode_map || newFreetype->unicode_map->encoding != FT_ENCODING_UNICODE) - newFreetype->unicode_map = cm; - break; - case FT_ENCODING_ADOBE_CUSTOM: - case FT_ENCODING_MS_SYMBOL: - if (!newFreetype->symbol_map) - newFreetype->symbol_map = cm; - break; - default: - break; - } - } - - if (!FT_IS_SCALABLE(newFreetype->face) && newFreetype->face->num_fixed_sizes == 1) - FT_Set_Char_Size(face, newFreetype->face->available_sizes[0].x_ppem, newFreetype->face->available_sizes[0].y_ppem, 0, 0); - - FT_Set_Charmap(newFreetype->face, newFreetype->unicode_map); - QT_TRY { - freetypeData->faces.insert(face_id, newFreetype.data()); - } QT_CATCH(...) { - newFreetype.take()->release(face_id); - // we could return null in principle instead of throwing - QT_RETHROW; - } - freetype = newFreetype.take(); - } - return freetype; -} - -void QFreetypeFace::cleanup() -{ - hbFace.reset(); - FT_Done_Face(face); - face = 0; -} - -void QFreetypeFace::release(const QFontEngine::FaceId &face_id) -{ - if (!ref.deref()) { - if (face) { - QtFreetypeData *freetypeData = qt_getFreetypeData(); - - cleanup(); - - auto it = freetypeData->faces.constFind(face_id); - if (it != freetypeData->faces.constEnd()) - freetypeData->faces.erase(it); - - if (freetypeData->faces.isEmpty()) { - FT_Done_FreeType(freetypeData->library); - freetypeData->library = 0; - } - } - - delete this; - } -} - - -void QFreetypeFace::computeSize(const QFontDef &fontDef, int *xsize, int *ysize, bool *outline_drawing, QFixed *scalableBitmapScaleFactor) -{ - *ysize = qRound(fontDef.pixelSize * 64); - *xsize = *ysize * fontDef.stretch / 100; - *scalableBitmapScaleFactor = 1; - *outline_drawing = false; - - if (!(face->face_flags & FT_FACE_FLAG_SCALABLE)) { - int best = 0; - if (!isScalableBitmap()) { - /* - * Bitmap only faces must match exactly, so find the closest - * one (height dominant search) - */ - for (int i = 1; i < face->num_fixed_sizes; i++) { - if (qAbs(*ysize - face->available_sizes[i].y_ppem) < - qAbs(*ysize - face->available_sizes[best].y_ppem) || - (qAbs(*ysize - face->available_sizes[i].y_ppem) == - qAbs(*ysize - face->available_sizes[best].y_ppem) && - qAbs(*xsize - face->available_sizes[i].x_ppem) < - qAbs(*xsize - face->available_sizes[best].x_ppem))) { - best = i; - } - } - } else { - // Select the shortest bitmap strike whose height is larger than the desired height - for (int i = 1; i < face->num_fixed_sizes; i++) { - if (face->available_sizes[i].y_ppem < *ysize) { - if (face->available_sizes[i].y_ppem > face->available_sizes[best].y_ppem) - best = i; - } else if (face->available_sizes[best].y_ppem < *ysize) { - best = i; - } else if (face->available_sizes[i].y_ppem < face->available_sizes[best].y_ppem) { - best = i; - } - } - } - - // According to freetype documentation we must use FT_Select_Size - // to make sure we can select the desired bitmap strike index - if (FT_Select_Size(face, best) == 0) { - if (isScalableBitmap()) - *scalableBitmapScaleFactor = QFixed::fromReal((qreal)fontDef.pixelSize / face->available_sizes[best].height); - *xsize = face->available_sizes[best].x_ppem; - *ysize = face->available_sizes[best].y_ppem; - } else { - *xsize = *ysize = 0; - } - } else { - *outline_drawing = (*xsize > (QT_MAX_CACHED_GLYPH_SIZE<<6) || *ysize > (QT_MAX_CACHED_GLYPH_SIZE<<6)); - } -} - -QFontEngine::Properties QFreetypeFace::properties() const -{ - QFontEngine::Properties p; - p.postscriptName = FT_Get_Postscript_Name(face); - PS_FontInfoRec font_info; - if (FT_Get_PS_Font_Info(face, &font_info) == 0) - p.copyright = font_info.notice; - if (FT_IS_SCALABLE(face)) { - p.ascent = face->ascender; - p.descent = -face->descender; - p.leading = face->height - face->ascender + face->descender; - p.emSquare = face->units_per_EM; - p.boundingBox = QRectF(face->bbox.xMin, -face->bbox.yMax, - face->bbox.xMax - face->bbox.xMin, - face->bbox.yMax - face->bbox.yMin); - } else { - p.ascent = QFixed::fromFixed(face->size->metrics.ascender); - p.descent = QFixed::fromFixed(-face->size->metrics.descender); - p.leading = QFixed::fromFixed(face->size->metrics.height - face->size->metrics.ascender + face->size->metrics.descender); - p.emSquare = face->size->metrics.y_ppem; -// p.boundingBox = QRectF(-p.ascent.toReal(), 0, (p.ascent + p.descent).toReal(), face->size->metrics.max_advance/64.); - p.boundingBox = QRectF(0, -p.ascent.toReal(), - face->size->metrics.max_advance/64, (p.ascent + p.descent).toReal() ); - } - p.italicAngle = 0; - p.capHeight = p.ascent; - p.lineWidth = face->underline_thickness; - - return p; -} - -bool QFreetypeFace::getSfntTable(uint tag, uchar *buffer, uint *length) const -{ - return ft_getSfntTable(face, tag, buffer, length); -} - -/* Some fonts (such as MingLiu rely on hinting to scale different - components to their correct sizes. While this is really broken (it - should be done in the component glyph itself, not the hinter) we - will have to live with it. - - This means we can not use FT_LOAD_NO_HINTING to get the glyph - outline. All we can do is to load the unscaled glyph and scale it - down manually when required. -*/ -static void scaleOutline(FT_Face face, FT_GlyphSlot g, FT_Fixed x_scale, FT_Fixed y_scale) -{ - x_scale = FT_MulDiv(x_scale, 1 << 10, face->units_per_EM); - y_scale = FT_MulDiv(y_scale, 1 << 10, face->units_per_EM); - FT_Vector *p = g->outline.points; - const FT_Vector *e = p + g->outline.n_points; - while (p < e) { - p->x = FT_MulFix(p->x, x_scale); - p->y = FT_MulFix(p->y, y_scale); - ++p; - } -} - -#define GLYPH2PATH_DEBUG QT_NO_QDEBUG_MACRO // qDebug -void QFreetypeFace::addGlyphToPath(FT_Face face, FT_GlyphSlot g, const QFixedPoint &point, QPainterPath *path, FT_Fixed x_scale, FT_Fixed y_scale) -{ - const qreal factor = 1/64.; - scaleOutline(face, g, x_scale, y_scale); - - QPointF cp = point.toPointF(); - - // convert the outline to a painter path - int i = 0; - for (int j = 0; j < g->outline.n_contours; ++j) { - int last_point = g->outline.contours[j]; - GLYPH2PATH_DEBUG() << "contour:" << i << "to" << last_point; - QPointF start = QPointF(g->outline.points[i].x*factor, -g->outline.points[i].y*factor); - if (!(g->outline.tags[i] & 1)) { // start point is not on curve: - if (!(g->outline.tags[last_point] & 1)) { // end point is not on curve: - GLYPH2PATH_DEBUG() << " start and end point are not on curve"; - start = (QPointF(g->outline.points[last_point].x*factor, - -g->outline.points[last_point].y*factor) + start) / 2.0; - } else { - GLYPH2PATH_DEBUG() << " end point is on curve, start is not"; - start = QPointF(g->outline.points[last_point].x*factor, - -g->outline.points[last_point].y*factor); - } - --i; // to use original start point as control point below - } - start += cp; - GLYPH2PATH_DEBUG() << " start at" << start; - - path->moveTo(start); - QPointF c[4]; - c[0] = start; - int n = 1; - while (i < last_point) { - ++i; - c[n] = cp + QPointF(g->outline.points[i].x*factor, -g->outline.points[i].y*factor); - GLYPH2PATH_DEBUG() << " " << i << c[n] << "tag =" << (int)g->outline.tags[i] - << ": on curve =" << (bool)(g->outline.tags[i] & 1); - ++n; - switch (g->outline.tags[i] & 3) { - case 2: - // cubic bezier element - if (n < 4) - continue; - c[3] = (c[3] + c[2])/2; - --i; - break; - case 0: - // quadratic bezier element - if (n < 3) - continue; - c[3] = (c[1] + c[2])/2; - c[2] = (2*c[1] + c[3])/3; - c[1] = (2*c[1] + c[0])/3; - --i; - break; - case 1: - case 3: - if (n == 2) { - GLYPH2PATH_DEBUG() << " lineTo" << c[1]; - path->lineTo(c[1]); - c[0] = c[1]; - n = 1; - continue; - } else if (n == 3) { - c[3] = c[2]; - c[2] = (2*c[1] + c[3])/3; - c[1] = (2*c[1] + c[0])/3; - } - break; - } - GLYPH2PATH_DEBUG() << " cubicTo" << c[1] << c[2] << c[3]; - path->cubicTo(c[1], c[2], c[3]); - c[0] = c[3]; - n = 1; - } - - if (n == 1) { - GLYPH2PATH_DEBUG() << " closeSubpath"; - path->closeSubpath(); - } else { - c[3] = start; - if (n == 2) { - c[2] = (2*c[1] + c[3])/3; - c[1] = (2*c[1] + c[0])/3; - } - GLYPH2PATH_DEBUG() << " close cubicTo" << c[1] << c[2] << c[3]; - path->cubicTo(c[1], c[2], c[3]); - } - ++i; - } -} - -extern void qt_addBitmapToPath(qreal x0, qreal y0, const uchar *image_data, int bpl, int w, int h, QPainterPath *path); - -void QFreetypeFace::addBitmapToPath(FT_GlyphSlot slot, const QFixedPoint &point, QPainterPath *path) -{ - if (slot->format != FT_GLYPH_FORMAT_BITMAP - || slot->bitmap.pixel_mode != FT_PIXEL_MODE_MONO) - return; - - QPointF cp = point.toPointF(); - qt_addBitmapToPath(cp.x() + TRUNC(slot->metrics.horiBearingX), cp.y() - TRUNC(slot->metrics.horiBearingY), - slot->bitmap.buffer, slot->bitmap.pitch, slot->bitmap.width, slot->bitmap.rows, path); -} - -struct LcdFilterDummy -{ - static inline void filterPixel(uchar &, uchar &, uchar &) - {} -}; - -struct LcdFilterLegacy -{ - static inline void filterPixel(uchar &red, uchar &green, uchar &blue) - { - uint r = red, g = green, b = blue; - // intra-pixel filter used by the legacy filter (adopted from _ft_lcd_filter_legacy) - red = (r * uint(65538 * 9/13) + g * uint(65538 * 1/6) + b * uint(65538 * 1/13)) / 65536; - green = (r * uint(65538 * 3/13) + g * uint(65538 * 4/6) + b * uint(65538 * 3/13)) / 65536; - blue = (r * uint(65538 * 1/13) + g * uint(65538 * 1/6) + b * uint(65538 * 9/13)) / 65536; - } -}; - -template <typename LcdFilter> -static void convertRGBToARGB_helper(const uchar *src, uint *dst, int width, int height, int src_pitch, bool bgr) -{ - const int offs = bgr ? -1 : 1; - const int w = width * 3; - while (height--) { - uint *dd = dst; - for (int x = 0; x < w; x += 3) { - uchar red = src[x + 1 - offs]; - uchar green = src[x + 1]; - uchar blue = src[x + 1 + offs]; - LcdFilter::filterPixel(red, green, blue); - *dd++ = (0xFFU << 24) | (red << 16) | (green << 8) | blue; - } - dst += width; - src += src_pitch; - } -} - -static inline void convertRGBToARGB(const uchar *src, uint *dst, int width, int height, int src_pitch, bool bgr, bool legacyFilter) -{ - if (!legacyFilter) - convertRGBToARGB_helper<LcdFilterDummy>(src, dst, width, height, src_pitch, bgr); - else - convertRGBToARGB_helper<LcdFilterLegacy>(src, dst, width, height, src_pitch, bgr); -} - -template <typename LcdFilter> -static void convertRGBToARGB_V_helper(const uchar *src, uint *dst, int width, int height, int src_pitch, bool bgr) -{ - const int offs = bgr ? -src_pitch : src_pitch; - while (height--) { - for (int x = 0; x < width; x++) { - uchar red = src[x + src_pitch - offs]; - uchar green = src[x + src_pitch]; - uchar blue = src[x + src_pitch + offs]; - LcdFilter::filterPixel(red, green, blue); - *dst++ = (0XFFU << 24) | (red << 16) | (green << 8) | blue; - } - src += 3*src_pitch; - } -} - -static inline void convertRGBToARGB_V(const uchar *src, uint *dst, int width, int height, int src_pitch, bool bgr, bool legacyFilter) -{ - if (!legacyFilter) - convertRGBToARGB_V_helper<LcdFilterDummy>(src, dst, width, height, src_pitch, bgr); - else - convertRGBToARGB_V_helper<LcdFilterLegacy>(src, dst, width, height, src_pitch, bgr); -} - -static inline void convertGRAYToARGB(const uchar *src, uint *dst, int width, int height, int src_pitch) -{ - while (height--) { - const uchar *p = src; - const uchar * const e = p + width; - while (p < e) { - uchar gray = *p++; - *dst++ = (0xFFU << 24) | (gray << 16) | (gray << 8) | gray; - } - src += src_pitch; - } -} - -static void convoluteBitmap(const uchar *src, uchar *dst, int width, int height, int pitch) -{ - // convolute the bitmap with a triangle filter to get rid of color fringes - // If we take account for a gamma value of 2, we end up with - // weights of 1, 4, 9, 4, 1. We use an approximation of 1, 3, 8, 3, 1 here, - // as this nicely sums up to 16 :) - int h = height; - while (h--) { - dst[0] = dst[1] = 0; - // - for (int x = 2; x < width - 2; ++x) { - uint sum = src[x-2] + 3*src[x-1] + 8*src[x] + 3*src[x+1] + src[x+2]; - dst[x] = (uchar) (sum >> 4); - } - dst[width - 2] = dst[width - 1] = 0; - src += pitch; - dst += pitch; - } -} - -static QFontEngine::SubpixelAntialiasingType subpixelAntialiasingTypeHint() -{ - static int type = -1; - if (type == -1) { - if (QScreen *screen = QGuiApplication::primaryScreen()) - type = screen->handle()->subpixelAntialiasingTypeHint(); - } - return static_cast<QFontEngine::SubpixelAntialiasingType>(type); -} - -QFontEngineFT *QFontEngineFT::create(const QFontDef &fontDef, FaceId faceId, const QByteArray &fontData) -{ - QScopedPointer<QFontEngineFT> engine(new QFontEngineFT(fontDef)); - - QFontEngineFT::GlyphFormat format = QFontEngineFT::Format_Mono; - const bool antialias = !(fontDef.styleStrategy & QFont::NoAntialias); - - if (antialias) { - QFontEngine::SubpixelAntialiasingType subpixelType = subpixelAntialiasingTypeHint(); - if (subpixelType == QFontEngine::Subpixel_None || (fontDef.styleStrategy & QFont::NoSubpixelAntialias)) { - format = QFontEngineFT::Format_A8; - engine->subpixelType = QFontEngine::Subpixel_None; - } else { - format = QFontEngineFT::Format_A32; - engine->subpixelType = subpixelType; - } - } - - if (!engine->init(faceId, antialias, format, fontData) || engine->invalid()) { - qWarning("QFontEngineFT: Failed to create FreeType font engine"); - return nullptr; - } - - engine->setQtDefaultHintStyle(static_cast<QFont::HintingPreference>(fontDef.hintingPreference)); - return engine.take(); -} - -namespace { - class QFontEngineFTRawData: public QFontEngineFT - { - public: - QFontEngineFTRawData(const QFontDef &fontDef) : QFontEngineFT(fontDef) - { - } - - void updateFamilyNameAndStyle() - { - fontDef.family = QString::fromLatin1(freetype->face->family_name); - - if (freetype->face->style_flags & FT_STYLE_FLAG_ITALIC) - fontDef.style = QFont::StyleItalic; - - if (freetype->face->style_flags & FT_STYLE_FLAG_BOLD) - fontDef.weight = QFont::Bold; - } - - bool initFromData(const QByteArray &fontData) - { - FaceId faceId; - faceId.filename = ""; - faceId.index = 0; - faceId.uuid = QUuid::createUuid().toByteArray(); - - return init(faceId, true, Format_None, fontData); - } - }; -} - -QFontEngineFT *QFontEngineFT::create(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference) -{ - QFontDef fontDef; - fontDef.pixelSize = pixelSize; - fontDef.stretch = QFont::Unstretched; - fontDef.hintingPreference = hintingPreference; - - QFontEngineFTRawData *fe = new QFontEngineFTRawData(fontDef); - if (!fe->initFromData(fontData)) { - delete fe; - return 0; - } - - fe->updateFamilyNameAndStyle(); - fe->setQtDefaultHintStyle(static_cast<QFont::HintingPreference>(fontDef.hintingPreference)); - - return fe; -} - -QFontEngineFT::QFontEngineFT(const QFontDef &fd) - : QFontEngine(Freetype) -{ - fontDef = fd; - matrix.xx = 0x10000; - matrix.yy = 0x10000; - matrix.xy = 0; - matrix.yx = 0; - cache_cost = 100 * 1024; - kerning_pairs_loaded = false; - transform = false; - embolden = false; - obliquen = false; - antialias = true; - freetype = 0; - default_load_flags = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH; - default_hint_style = ftInitialDefaultHintStyle; - subpixelType = Subpixel_None; - lcdFilterType = (int)((quintptr) FT_LCD_FILTER_DEFAULT); - defaultFormat = Format_None; - embeddedbitmap = false; - const QByteArray env = qgetenv("QT_NO_FT_CACHE"); - cacheEnabled = env.isEmpty() || env.toInt() == 0; - m_subPixelPositionCount = 4; - forceAutoHint = false; - stemDarkeningDriver = false; -} - -QFontEngineFT::~QFontEngineFT() -{ - if (freetype) - freetype->release(face_id); -} - -bool QFontEngineFT::init(FaceId faceId, bool antialias, GlyphFormat format, - const QByteArray &fontData) -{ - return init(faceId, antialias, format, QFreetypeFace::getFace(faceId, fontData)); -} - -static void dont_delete(void*) {} - -bool QFontEngineFT::init(FaceId faceId, bool antialias, GlyphFormat format, - QFreetypeFace *freetypeFace) -{ - freetype = freetypeFace; - if (!freetype) { - xsize = 0; - ysize = 0; - return false; - } - defaultFormat = format; - this->antialias = antialias; - - if (!antialias) - glyphFormat = QFontEngine::Format_Mono; - else - glyphFormat = defaultFormat; - - face_id = faceId; - - symbol = freetype->symbol_map != 0; - PS_FontInfoRec psrec; - // don't assume that type1 fonts are symbol fonts by default - if (FT_Get_PS_Font_Info(freetype->face, &psrec) == FT_Err_Ok) { - symbol = bool(fontDef.family.contains(QLatin1String("symbol"), Qt::CaseInsensitive)); - } - - freetype->computeSize(fontDef, &xsize, &ysize, &defaultGlyphSet.outline_drawing, &scalableBitmapScaleFactor); - - FT_Face face = lockFace(); - - if (FT_IS_SCALABLE(face)) { - bool fake_oblique = (fontDef.style != QFont::StyleNormal) && !(face->style_flags & FT_STYLE_FLAG_ITALIC); - if (fake_oblique) - obliquen = true; - FT_Set_Transform(face, &matrix, 0); - freetype->matrix = matrix; - // fake bold - if ((fontDef.weight >= QFont::Bold) && !(face->style_flags & FT_STYLE_FLAG_BOLD) && !FT_IS_FIXED_WIDTH(face)) { - if (const TT_OS2 *os2 = reinterpret_cast<const TT_OS2 *>(FT_Get_Sfnt_Table(face, ft_sfnt_os2))) { - if (os2->usWeightClass < 750) - embolden = true; - } - } - // underline metrics - line_thickness = QFixed::fromFixed(FT_MulFix(face->underline_thickness, face->size->metrics.y_scale)); - underline_position = QFixed::fromFixed(-FT_MulFix(face->underline_position, face->size->metrics.y_scale)); - } else { - // ad hoc algorithm - int score = fontDef.weight * fontDef.pixelSize; - line_thickness = score / 700; - // looks better with thicker line for small pointsizes - if (line_thickness < 2 && score >= 1050) - line_thickness = 2; - underline_position = ((line_thickness * 2) + 3) / 6; - - if (isScalableBitmap()) { - glyphFormat = defaultFormat = GlyphFormat::Format_ARGB; - cacheEnabled = false; - } - } - if (line_thickness < 1) - line_thickness = 1; - - metrics = face->size->metrics; - - /* - TrueType fonts with embedded bitmaps may have a bitmap font specific - ascent/descent in the EBLC table. There is no direct public API - to extract those values. The only way we've found is to trick freetype - into thinking that it's not a scalable font in FT_SelectSize so that - the metrics are retrieved from the bitmap strikes. - */ - if (FT_IS_SCALABLE(face)) { - for (int i = 0; i < face->num_fixed_sizes; ++i) { - if (xsize == face->available_sizes[i].x_ppem && ysize == face->available_sizes[i].y_ppem) { - face->face_flags &= ~FT_FACE_FLAG_SCALABLE; - - FT_Select_Size(face, i); - if (face->size->metrics.ascender + face->size->metrics.descender > 0) { - FT_Pos leading = metrics.height - metrics.ascender + metrics.descender; - metrics.ascender = face->size->metrics.ascender; - metrics.descender = face->size->metrics.descender; - if (metrics.descender > 0 - && QString::fromUtf8(face->family_name) == QLatin1String("Courier New")) { - metrics.descender *= -1; - } - metrics.height = metrics.ascender - metrics.descender + leading; - } - FT_Set_Char_Size(face, xsize, ysize, 0, 0); - - face->face_flags |= FT_FACE_FLAG_SCALABLE; - break; - } - } - } -#if defined(FT_FONT_FORMATS_H) - const char *fmt = FT_Get_Font_Format(face); - if (fmt && qstrncmp(fmt, "CFF", 4) == 0) { - FT_Bool no_stem_darkening = true; - FT_Error err = FT_Property_Get(qt_getFreetype(), "cff", "no-stem-darkening", &no_stem_darkening); - if (err == FT_Err_Ok) - stemDarkeningDriver = !no_stem_darkening; - else - stemDarkeningDriver = false; - } -#endif - - fontDef.styleName = QString::fromUtf8(face->style_name); - - if (!freetype->hbFace) { - faceData.user_data = face; - faceData.get_font_table = ft_getSfntTable; - (void)harfbuzzFace(); // populates face_ - freetype->hbFace = std::move(face_); - } else { - Q_ASSERT(!face_); - } - // we share the HB face in QFreeTypeFace, so do not let ~QFontEngine() destroy it - face_ = Holder(freetype->hbFace.get(), dont_delete); - - unlockFace(); - - fsType = freetype->fsType(); - return true; -} - -void QFontEngineFT::setQtDefaultHintStyle(QFont::HintingPreference hintingPreference) -{ - switch (hintingPreference) { - case QFont::PreferNoHinting: - setDefaultHintStyle(HintNone); - break; - case QFont::PreferFullHinting: - setDefaultHintStyle(HintFull); - break; - case QFont::PreferVerticalHinting: - setDefaultHintStyle(HintLight); - break; - case QFont::PreferDefaultHinting: - setDefaultHintStyle(ftInitialDefaultHintStyle); - break; - } -} - -void QFontEngineFT::setDefaultHintStyle(HintStyle style) -{ - default_hint_style = style; -} - -bool QFontEngineFT::expectsGammaCorrectedBlending() const -{ - return stemDarkeningDriver; -} - -int QFontEngineFT::loadFlags(QGlyphSet *set, GlyphFormat format, int flags, - bool &hsubpixel, int &vfactor) const -{ - int load_flags = FT_LOAD_DEFAULT | default_load_flags; - int load_target = default_hint_style == HintLight - ? FT_LOAD_TARGET_LIGHT - : FT_LOAD_TARGET_NORMAL; - - if (format == Format_Mono) { - load_target = FT_LOAD_TARGET_MONO; - } else if (format == Format_A32) { - if (subpixelType == Subpixel_RGB || subpixelType == Subpixel_BGR) - hsubpixel = true; - else if (subpixelType == Subpixel_VRGB || subpixelType == Subpixel_VBGR) - vfactor = 3; - } else if (format == Format_ARGB) { -#ifdef FT_LOAD_COLOR - load_flags |= FT_LOAD_COLOR; -#endif - } - - if (set && set->outline_drawing) - load_flags |= FT_LOAD_NO_BITMAP; - - if (default_hint_style == HintNone || (flags & DesignMetrics) || (set && set->outline_drawing)) - load_flags |= FT_LOAD_NO_HINTING; - else - load_flags |= load_target; - - if (forceAutoHint) - load_flags |= FT_LOAD_FORCE_AUTOHINT; - - return load_flags; -} - -static inline bool areMetricsTooLarge(const QFontEngineFT::GlyphInfo &info) -{ - // false if exceeds QFontEngineFT::Glyph metrics - return info.width > 0xFF || info.height > 0xFF; -} - -static inline void transformBoundingBox(int *left, int *top, int *right, int *bottom, FT_Matrix *matrix) -{ - int l, r, t, b; - FT_Vector vector; - vector.x = *left; - vector.y = *top; - FT_Vector_Transform(&vector, matrix); - l = r = vector.x; - t = b = vector.y; - vector.x = *right; - vector.y = *top; - FT_Vector_Transform(&vector, matrix); - if (l > vector.x) l = vector.x; - if (r < vector.x) r = vector.x; - if (t < vector.y) t = vector.y; - if (b > vector.y) b = vector.y; - vector.x = *right; - vector.y = *bottom; - FT_Vector_Transform(&vector, matrix); - if (l > vector.x) l = vector.x; - if (r < vector.x) r = vector.x; - if (t < vector.y) t = vector.y; - if (b > vector.y) b = vector.y; - vector.x = *left; - vector.y = *bottom; - FT_Vector_Transform(&vector, matrix); - if (l > vector.x) l = vector.x; - if (r < vector.x) r = vector.x; - if (t < vector.y) t = vector.y; - if (b > vector.y) b = vector.y; - *left = l; - *right = r; - *top = t; - *bottom = b; -} - -QFontEngineFT::Glyph *QFontEngineFT::loadGlyph(QGlyphSet *set, uint glyph, - QFixed subPixelPosition, - GlyphFormat format, - bool fetchMetricsOnly, - bool disableOutlineDrawing) const -{ -// Q_ASSERT(freetype->lock == 1); - - if (format == Format_None) - format = defaultFormat != Format_None ? defaultFormat : Format_Mono; - Q_ASSERT(format != Format_None); - - Glyph *g = set ? set->getGlyph(glyph, subPixelPosition) : 0; - if (g && g->format == format && (fetchMetricsOnly || g->data)) - return g; - - if (!g && set && set->isGlyphMissing(glyph)) - return &emptyGlyph; - - - FT_Face face = freetype->face; - - FT_Matrix matrix = freetype->matrix; - - FT_Vector v; - v.x = format == Format_Mono ? 0 : FT_Pos(subPixelPosition.value()); - v.y = 0; - FT_Set_Transform(face, &matrix, &v); - - bool hsubpixel = false; - int vfactor = 1; - int load_flags = loadFlags(set, format, 0, hsubpixel, vfactor); - - bool transform = matrix.xx != 0x10000 - || matrix.yy != 0x10000 - || matrix.xy != 0 - || matrix.yx != 0; - - if (transform || obliquen || (format != Format_Mono && !isScalableBitmap())) - load_flags |= FT_LOAD_NO_BITMAP; - - FT_Error err = FT_Load_Glyph(face, glyph, load_flags); - if (err && (load_flags & FT_LOAD_NO_BITMAP)) { - load_flags &= ~FT_LOAD_NO_BITMAP; - err = FT_Load_Glyph(face, glyph, load_flags); - } - if (err == FT_Err_Too_Few_Arguments) { - // this is an error in the bytecode interpreter, just try to run without it - load_flags |= FT_LOAD_FORCE_AUTOHINT; - err = FT_Load_Glyph(face, glyph, load_flags); - } else if (err == FT_Err_Execution_Too_Long) { - // This is an error in the bytecode, probably a web font made by someone who - // didn't test bytecode hinting at all so disable for it for all glyphs. - qWarning("load glyph failed due to broken hinting bytecode in font, switching to auto hinting"); - default_load_flags |= FT_LOAD_FORCE_AUTOHINT; - load_flags |= FT_LOAD_FORCE_AUTOHINT; - err = FT_Load_Glyph(face, glyph, load_flags); - } - if (err != FT_Err_Ok) { - qWarning("load glyph failed err=%x face=%p, glyph=%d", err, face, glyph); - if (set) - set->setGlyphMissing(glyph); - return &emptyGlyph; - } - - FT_GlyphSlot slot = face->glyph; - - if (embolden) - FT_GlyphSlot_Embolden(slot); - if (obliquen) { - FT_GlyphSlot_Oblique(slot); - - // While Embolden alters the metrics of the slot, oblique does not, so we need - // to fix this ourselves. - transform = true; - FT_Matrix m; - m.xx = 0x10000; - m.yx = 0x0; - m.xy = 0x6000; - m.yy = 0x10000; - - FT_Matrix_Multiply(&m, &matrix); - } - - GlyphInfo info; - info.linearAdvance = slot->linearHoriAdvance >> 10; - info.xOff = TRUNC(ROUND(slot->advance.x)); - info.yOff = 0; - - if ((set && set->outline_drawing && !disableOutlineDrawing) || fetchMetricsOnly) { - int left = slot->metrics.horiBearingX; - int right = slot->metrics.horiBearingX + slot->metrics.width; - int top = slot->metrics.horiBearingY; - int bottom = slot->metrics.horiBearingY - slot->metrics.height; - - if (transform && slot->format != FT_GLYPH_FORMAT_BITMAP) - transformBoundingBox(&left, &top, &right, &bottom, &matrix); - - left = FLOOR(left); - right = CEIL(right); - bottom = FLOOR(bottom); - top = CEIL(top); - - info.x = TRUNC(left); - info.y = TRUNC(top); - info.width = TRUNC(right - left); - info.height = TRUNC(top - bottom); - - // If any of the metrics are too large to fit, don't cache them - if (areMetricsTooLarge(info)) - return 0; - - g = new Glyph; - g->data = 0; - g->linearAdvance = info.linearAdvance; - g->width = info.width; - g->height = info.height; - g->x = info.x; - g->y = info.y; - g->advance = info.xOff; - g->format = format; - - if (set) - set->setGlyph(glyph, subPixelPosition, g); - - return g; - } - - int glyph_buffer_size = 0; - QScopedArrayPointer<uchar> glyph_buffer; - bool useFreetypeRenderGlyph = false; - if (slot->format == FT_GLYPH_FORMAT_OUTLINE && (hsubpixel || vfactor != 1)) { - err = FT_Library_SetLcdFilter(slot->library, (FT_LcdFilter)lcdFilterType); - // We use FT_Render_Glyph if freetype has support for lcd-filtering - // or is version 2.8.1 or higher and can do without. - if (err == FT_Err_Ok || qt_getFreetypeData()->hasPatentFreeLcdRendering) - useFreetypeRenderGlyph = true; - } - if (useFreetypeRenderGlyph) { - err = FT_Render_Glyph(slot, hsubpixel ? FT_RENDER_MODE_LCD : FT_RENDER_MODE_LCD_V); - - if (err != FT_Err_Ok) - qWarning("render glyph failed err=%x face=%p, glyph=%d", err, face, glyph); - - FT_Library_SetLcdFilter(slot->library, FT_LCD_FILTER_NONE); - - info.height = slot->bitmap.rows / vfactor; - info.width = hsubpixel ? slot->bitmap.width / 3 : slot->bitmap.width; - info.x = slot->bitmap_left; - info.y = slot->bitmap_top; - - glyph_buffer_size = info.width * info.height * 4; - glyph_buffer.reset(new uchar[glyph_buffer_size]); - - if (hsubpixel) - convertRGBToARGB(slot->bitmap.buffer, (uint *)glyph_buffer.data(), info.width, info.height, slot->bitmap.pitch, subpixelType != Subpixel_RGB, false); - else if (vfactor != 1) - convertRGBToARGB_V(slot->bitmap.buffer, (uint *)glyph_buffer.data(), info.width, info.height, slot->bitmap.pitch, subpixelType != Subpixel_VRGB, false); - } else { - int left = slot->metrics.horiBearingX; - int right = slot->metrics.horiBearingX + slot->metrics.width; - int top = slot->metrics.horiBearingY; - int bottom = slot->metrics.horiBearingY - slot->metrics.height; - if (transform && slot->format != FT_GLYPH_FORMAT_BITMAP) - transformBoundingBox(&left, &top, &right, &bottom, &matrix); - left = FLOOR(left); - right = CEIL(right); - bottom = FLOOR(bottom); - top = CEIL(top); - - int hpixels = TRUNC(right - left); - // subpixel position requires one more pixel - if (subPixelPosition > 0 && format != Format_Mono) - hpixels++; - - if (hsubpixel) - hpixels = hpixels*3 + 8; - info.width = hpixels; - info.height = TRUNC(top - bottom); - info.x = TRUNC(left); - info.y = TRUNC(top); - if (hsubpixel) { - info.width /= 3; - info.x -= 1; - } - - // If any of the metrics are too large to fit, don't cache them - if (areMetricsTooLarge(info)) - return 0; - - int pitch = (format == Format_Mono ? ((info.width + 31) & ~31) >> 3 : - (format == Format_A8 ? (info.width + 3) & ~3 : info.width * 4)); - if (glyph_buffer_size < pitch * info.height) { - glyph_buffer_size = pitch * info.height; - glyph_buffer.reset(new uchar[glyph_buffer_size]); - memset(glyph_buffer.data(), 0, glyph_buffer_size); - } - - if (slot->format == FT_GLYPH_FORMAT_OUTLINE) { - FT_Bitmap bitmap; - bitmap.rows = info.height*vfactor; - bitmap.width = hpixels; - bitmap.pitch = format == Format_Mono ? (((info.width + 31) & ~31) >> 3) : ((bitmap.width + 3) & ~3); - int bitmap_buffer_size = bitmap.rows * bitmap.pitch; - if (!hsubpixel && vfactor == 1 && format != Format_A32) { - Q_ASSERT(glyph_buffer_size <= bitmap_buffer_size); - bitmap.buffer = glyph_buffer.data(); - } else { - bitmap.buffer = new uchar[bitmap_buffer_size]; - memset(bitmap.buffer, 0, bitmap_buffer_size); - } - bitmap.pixel_mode = format == Format_Mono ? FT_PIXEL_MODE_MONO : FT_PIXEL_MODE_GRAY; - FT_Matrix matrix; - matrix.xx = (hsubpixel ? 3 : 1) << 16; - matrix.yy = vfactor << 16; - matrix.yx = matrix.xy = 0; - - FT_Outline_Transform(&slot->outline, &matrix); - FT_Outline_Translate (&slot->outline, (hsubpixel ? -3*left +(4<<6) : -left), -bottom*vfactor); - FT_Outline_Get_Bitmap(slot->library, &slot->outline, &bitmap); - if (hsubpixel) { - Q_ASSERT (bitmap.pixel_mode == FT_PIXEL_MODE_GRAY); - Q_ASSERT(antialias); - uchar *convoluted = new uchar[bitmap_buffer_size]; - bool useLegacyLcdFilter = false; - useLegacyLcdFilter = (lcdFilterType == FT_LCD_FILTER_LEGACY); - uchar *buffer = bitmap.buffer; - if (!useLegacyLcdFilter) { - convoluteBitmap(bitmap.buffer, convoluted, bitmap.width, info.height, bitmap.pitch); - buffer = convoluted; - } - convertRGBToARGB(buffer + 1, (uint *)glyph_buffer.data(), info.width, info.height, bitmap.pitch, subpixelType != Subpixel_RGB, useLegacyLcdFilter); - delete [] convoluted; - } else if (vfactor != 1) { - convertRGBToARGB_V(bitmap.buffer, (uint *)glyph_buffer.data(), info.width, info.height, bitmap.pitch, subpixelType != Subpixel_VRGB, true); - } else if (format == Format_A32 && bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) { - convertGRAYToARGB(bitmap.buffer, (uint *)glyph_buffer.data(), info.width, info.height, bitmap.pitch); - } - - if (bitmap.buffer != glyph_buffer.data()) - delete [] bitmap.buffer; - } else if (slot->format == FT_GLYPH_FORMAT_BITMAP) { -#if ((FREETYPE_MAJOR*10000 + FREETYPE_MINOR*100) >= 20500) - Q_ASSERT(slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO || slot->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA); -#else - Q_ASSERT(slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO); -#endif - uchar *src = slot->bitmap.buffer; - uchar *dst = glyph_buffer.data(); - int h = slot->bitmap.rows; - if (format == Format_Mono) { - int bytes = ((info.width + 7) & ~7) >> 3; - while (h--) { - memcpy (dst, src, bytes); - dst += pitch; - src += slot->bitmap.pitch; - } - } else if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) { - if (hsubpixel) { - while (h--) { - uint *dd = (uint *)dst; - *dd++ = 0; - for (int x = 0; x < static_cast<int>(slot->bitmap.width); x++) { - uint a = ((src[x >> 3] & (0x80 >> (x & 7))) ? 0xffffff : 0x000000); - *dd++ = a; - } - *dd++ = 0; - dst += pitch; - src += slot->bitmap.pitch; - } - } else if (vfactor != 1) { - while (h--) { - uint *dd = (uint *)dst; - for (int x = 0; x < static_cast<int>(slot->bitmap.width); x++) { - uint a = ((src[x >> 3] & (0x80 >> (x & 7))) ? 0xffffff : 0x000000); - *dd++ = a; - } - dst += pitch; - src += slot->bitmap.pitch; - } - } else { - while (h--) { - for (int x = 0; x < static_cast<int>(slot->bitmap.width); x++) { - unsigned char a = ((src[x >> 3] & (0x80 >> (x & 7))) ? 0xff : 0x00); - dst[x] = a; - } - dst += pitch; - src += slot->bitmap.pitch; - } - } - } -#if ((FREETYPE_MAJOR*10000 + FREETYPE_MINOR*100) >= 20500) - else if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) - { - while (h--) { -#if Q_BYTE_ORDER == Q_BIG_ENDIAN - const quint32 *srcPixel = (const quint32 *)src; - quint32 *dstPixel = (quint32 *)dst; - for (int x = 0; x < static_cast<int>(slot->bitmap.width); x++, srcPixel++, dstPixel++) { - const quint32 pixel = *srcPixel; - *dstPixel = qbswap(pixel); - } -#else - memcpy(dst, src, slot->bitmap.width * 4); -#endif - dst += slot->bitmap.pitch; - src += slot->bitmap.pitch; - } - info.width = info.linearAdvance = info.xOff = slot->bitmap.width; - info.height = slot->bitmap.rows; - info.x = slot->bitmap_left; - info.y = slot->bitmap_top; - } -#endif - } else { - qWarning("QFontEngine: Glyph neither outline nor bitmap format=%d", slot->format); - return 0; - } - } - - - if (!g) { - g = new Glyph; - g->data = 0; - } - - g->linearAdvance = info.linearAdvance; - g->width = info.width; - g->height = info.height; - g->x = info.x; - g->y = info.y; - g->advance = info.xOff; - g->format = format; - delete [] g->data; - g->data = glyph_buffer.take(); - - if (set) - set->setGlyph(glyph, subPixelPosition, g); - - return g; -} - -QFontEngine::FaceId QFontEngineFT::faceId() const -{ - return face_id; -} - -QFontEngine::Properties QFontEngineFT::properties() const -{ - Properties p = freetype->properties(); - if (p.postscriptName.isEmpty()) { - p.postscriptName = QFontEngine::convertToPostscriptFontFamilyName(fontDef.family.toUtf8()); - } - - return freetype->properties(); -} - -QFixed QFontEngineFT::emSquareSize() const -{ - if (FT_IS_SCALABLE(freetype->face)) - return freetype->face->units_per_EM; - else - return freetype->face->size->metrics.y_ppem; -} - -bool QFontEngineFT::getSfntTableData(uint tag, uchar *buffer, uint *length) const -{ - return ft_getSfntTable(freetype->face, tag, buffer, length); -} - -int QFontEngineFT::synthesized() const -{ - int s = 0; - if ((fontDef.style != QFont::StyleNormal) && !(freetype->face->style_flags & FT_STYLE_FLAG_ITALIC)) - s = SynthesizedItalic; - if ((fontDef.weight >= QFont::Bold) && !(freetype->face->style_flags & FT_STYLE_FLAG_BOLD)) - s |= SynthesizedBold; - if (fontDef.stretch != 100 && FT_IS_SCALABLE(freetype->face)) - s |= SynthesizedStretch; - return s; -} - -QFixed QFontEngineFT::ascent() const -{ - QFixed v = QFixed::fromFixed(metrics.ascender); - if (scalableBitmapScaleFactor != 1) - v *= scalableBitmapScaleFactor; - return v; -} - -QFixed QFontEngineFT::capHeight() const -{ - TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(freetype->face, ft_sfnt_os2); - if (os2 && os2->version >= 2) { - lockFace(); - QFixed answer = QFixed::fromFixed(FT_MulFix(os2->sCapHeight, freetype->face->size->metrics.y_scale)); - unlockFace(); - return answer; - } - return calculatedCapHeight(); -} - -QFixed QFontEngineFT::descent() const -{ - QFixed v = QFixed::fromFixed(-metrics.descender); - if (scalableBitmapScaleFactor != 1) - v *= scalableBitmapScaleFactor; - return v; -} - -QFixed QFontEngineFT::leading() const -{ - QFixed v = QFixed::fromFixed(metrics.height - metrics.ascender + metrics.descender); - if (scalableBitmapScaleFactor != 1) - v *= scalableBitmapScaleFactor; - return v; -} - -QFixed QFontEngineFT::xHeight() const -{ - TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(freetype->face, ft_sfnt_os2); - if (os2 && os2->sxHeight) { - lockFace(); - QFixed answer = QFixed(os2->sxHeight * freetype->face->size->metrics.y_ppem) / emSquareSize(); - unlockFace(); - return answer; - } - - return QFontEngine::xHeight(); -} - -QFixed QFontEngineFT::averageCharWidth() const -{ - TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(freetype->face, ft_sfnt_os2); - if (os2 && os2->xAvgCharWidth) { - lockFace(); - QFixed answer = QFixed(os2->xAvgCharWidth * freetype->face->size->metrics.x_ppem) / emSquareSize(); - unlockFace(); - return answer; - } - - return QFontEngine::averageCharWidth(); -} - -qreal QFontEngineFT::maxCharWidth() const -{ - QFixed max_advance = QFixed::fromFixed(metrics.max_advance); - if (scalableBitmapScaleFactor != 1) - max_advance *= scalableBitmapScaleFactor; - return max_advance.toReal(); -} - -QFixed QFontEngineFT::lineThickness() const -{ - return line_thickness; -} - -QFixed QFontEngineFT::underlinePosition() const -{ - return underline_position; -} - -void QFontEngineFT::doKerning(QGlyphLayout *g, QFontEngine::ShaperFlags flags) const -{ - if (!kerning_pairs_loaded) { - kerning_pairs_loaded = true; - lockFace(); - if (freetype->face->size->metrics.x_ppem != 0) { - QFixed scalingFactor = emSquareSize() / QFixed(freetype->face->size->metrics.x_ppem); - unlockFace(); - const_cast<QFontEngineFT *>(this)->loadKerningPairs(scalingFactor); - } else { - unlockFace(); - } - } - - if (shouldUseDesignMetrics(flags) && !(fontDef.styleStrategy & QFont::ForceIntegerMetrics)) - flags |= DesignMetrics; - else - flags &= ~DesignMetrics; - - QFontEngine::doKerning(g, flags); -} - -static inline FT_Matrix QTransformToFTMatrix(const QTransform &matrix) -{ - FT_Matrix m; - - m.xx = FT_Fixed(matrix.m11() * 65536); - m.xy = FT_Fixed(-matrix.m21() * 65536); - m.yx = FT_Fixed(-matrix.m12() * 65536); - m.yy = FT_Fixed(matrix.m22() * 65536); - - return m; -} - -QFontEngineFT::QGlyphSet *QFontEngineFT::loadGlyphSet(const QTransform &matrix) -{ - if (matrix.type() > QTransform::TxShear || !cacheEnabled) - return 0; - - // FT_Set_Transform only supports scalable fonts - if (!FT_IS_SCALABLE(freetype->face)) - return matrix.type() <= QTransform::TxTranslate ? &defaultGlyphSet : nullptr; - - FT_Matrix m = QTransformToFTMatrix(matrix); - - QGlyphSet *gs = 0; - - for (int i = 0; i < transformedGlyphSets.count(); ++i) { - const QGlyphSet &g = transformedGlyphSets.at(i); - if (g.transformationMatrix.xx == m.xx - && g.transformationMatrix.xy == m.xy - && g.transformationMatrix.yx == m.yx - && g.transformationMatrix.yy == m.yy) { - - // found a match, move it to the front - transformedGlyphSets.move(i, 0); - gs = &transformedGlyphSets[0]; - break; - } - } - - if (!gs) { - // don't cache more than 10 transformations - if (transformedGlyphSets.count() >= 10) { - transformedGlyphSets.move(transformedGlyphSets.size() - 1, 0); - } else { - transformedGlyphSets.prepend(QGlyphSet()); - } - gs = &transformedGlyphSets[0]; - gs->clear(); - gs->transformationMatrix = m; - gs->outline_drawing = fontDef.pixelSize * fontDef.pixelSize * qAbs(matrix.det()) >= QT_MAX_CACHED_GLYPH_SIZE * QT_MAX_CACHED_GLYPH_SIZE; - } - Q_ASSERT(gs != 0); - - return gs; -} - -void QFontEngineFT::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics) -{ - FT_Face face = lockFace(Unscaled); - FT_Set_Transform(face, 0, 0); - FT_Load_Glyph(face, glyph, FT_LOAD_NO_BITMAP); - - int left = face->glyph->metrics.horiBearingX; - int right = face->glyph->metrics.horiBearingX + face->glyph->metrics.width; - int top = face->glyph->metrics.horiBearingY; - int bottom = face->glyph->metrics.horiBearingY - face->glyph->metrics.height; - - QFixedPoint p; - p.x = 0; - p.y = 0; - - metrics->width = QFixed::fromFixed(right-left); - metrics->height = QFixed::fromFixed(top-bottom); - metrics->x = QFixed::fromFixed(left); - metrics->y = QFixed::fromFixed(-top); - metrics->xoff = QFixed::fromFixed(face->glyph->advance.x); - - if (!FT_IS_SCALABLE(freetype->face)) - QFreetypeFace::addBitmapToPath(face->glyph, p, path); - else - QFreetypeFace::addGlyphToPath(face, face->glyph, p, path, face->units_per_EM << 6, face->units_per_EM << 6); - - FT_Set_Transform(face, &freetype->matrix, 0); - unlockFace(); -} - -bool QFontEngineFT::supportsTransformation(const QTransform &transform) const -{ - return transform.type() <= QTransform::TxRotate; -} - -void QFontEngineFT::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags) -{ - if (!glyphs.numGlyphs) - return; - - if (FT_IS_SCALABLE(freetype->face)) { - QFontEngine::addOutlineToPath(x, y, glyphs, path, flags); - } else { - QVarLengthArray<QFixedPoint> positions; - QVarLengthArray<glyph_t> positioned_glyphs; - QTransform matrix; - matrix.translate(x, y); - getGlyphPositions(glyphs, matrix, flags, positioned_glyphs, positions); - - FT_Face face = lockFace(Unscaled); - for (int gl = 0; gl < glyphs.numGlyphs; gl++) { - FT_UInt glyph = positioned_glyphs[gl]; - FT_Load_Glyph(face, glyph, FT_LOAD_TARGET_MONO); - QFreetypeFace::addBitmapToPath(face->glyph, positions[gl], path); - } - unlockFace(); - } -} - -void QFontEngineFT::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs, - QPainterPath *path, QTextItem::RenderFlags) -{ - FT_Face face = lockFace(Unscaled); - - for (int gl = 0; gl < numGlyphs; gl++) { - FT_UInt glyph = glyphs[gl]; - - FT_Load_Glyph(face, glyph, FT_LOAD_NO_BITMAP); - - FT_GlyphSlot g = face->glyph; - if (g->format != FT_GLYPH_FORMAT_OUTLINE) - continue; - if (embolden) - FT_GlyphSlot_Embolden(g); - if (obliquen) - FT_GlyphSlot_Oblique(g); - QFreetypeFace::addGlyphToPath(face, g, positions[gl], path, xsize, ysize); - } - unlockFace(); -} - -glyph_t QFontEngineFT::glyphIndex(uint ucs4) const -{ - glyph_t glyph = ucs4 < QFreetypeFace::cmapCacheSize ? freetype->cmapCache[ucs4] : 0; - if (glyph == 0) { - FT_Face face = freetype->face; - glyph = FT_Get_Char_Index(face, ucs4); - if (glyph == 0) { - // Certain fonts don't have no-break space and tab, - // while we usually want to render them as space - if (ucs4 == QChar::Nbsp || ucs4 == QChar::Tabulation) { - glyph = FT_Get_Char_Index(face, QChar::Space); - } else if (freetype->symbol_map) { - // Symbol fonts can have more than one CMAPs, FreeType should take the - // correct one for us by default, so we always try FT_Get_Char_Index - // first. If it didn't work (returns 0), we will explicitly set the - // CMAP to symbol font one and try again. symbol_map is not always the - // correct one because in certain fonts like Wingdings symbol_map only - // contains PUA codepoints instead of the common ones. - FT_Set_Charmap(face, freetype->symbol_map); - glyph = FT_Get_Char_Index(face, ucs4); - FT_Set_Charmap(face, freetype->unicode_map); - } - } - if (ucs4 < QFreetypeFace::cmapCacheSize) - freetype->cmapCache[ucs4] = glyph; - } - - return glyph; -} - -bool QFontEngineFT::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, - QFontEngine::ShaperFlags flags) const -{ - Q_ASSERT(glyphs->numGlyphs >= *nglyphs); - if (*nglyphs < len) { - *nglyphs = len; - return false; - } - - int glyph_pos = 0; - if (freetype->symbol_map) { - FT_Face face = freetype->face; - QStringIterator it(str, str + len); - while (it.hasNext()) { - uint uc = it.next(); - glyphs->glyphs[glyph_pos] = uc < QFreetypeFace::cmapCacheSize ? freetype->cmapCache[uc] : 0; - if ( !glyphs->glyphs[glyph_pos] ) { - // Symbol fonts can have more than one CMAPs, FreeType should take the - // correct one for us by default, so we always try FT_Get_Char_Index - // first. If it didn't work (returns 0), we will explicitly set the - // CMAP to symbol font one and try again. symbol_map is not always the - // correct one because in certain fonts like Wingdings symbol_map only - // contains PUA codepoints instead of the common ones. - glyph_t glyph = FT_Get_Char_Index(face, uc); - // Certain symbol fonts don't have no-break space (0xa0) and tab (0x9), - // while we usually want to render them as space - if (!glyph && (uc == 0xa0 || uc == 0x9)) { - uc = 0x20; - glyph = FT_Get_Char_Index(face, uc); - } - if (!glyph) { - FT_Set_Charmap(face, freetype->symbol_map); - glyph = FT_Get_Char_Index(face, uc); - FT_Set_Charmap(face, freetype->unicode_map); - } - glyphs->glyphs[glyph_pos] = glyph; - if (uc < QFreetypeFace::cmapCacheSize) - freetype->cmapCache[uc] = glyph; - } - ++glyph_pos; - } - } else { - FT_Face face = freetype->face; - QStringIterator it(str, str + len); - while (it.hasNext()) { - uint uc = it.next(); - glyphs->glyphs[glyph_pos] = uc < QFreetypeFace::cmapCacheSize ? freetype->cmapCache[uc] : 0; - if (!glyphs->glyphs[glyph_pos]) { - { - redo: - glyph_t glyph = FT_Get_Char_Index(face, uc); - if (!glyph && (uc == 0xa0 || uc == 0x9)) { - uc = 0x20; - goto redo; - } - glyphs->glyphs[glyph_pos] = glyph; - if (uc < QFreetypeFace::cmapCacheSize) - freetype->cmapCache[uc] = glyph; - } - } - ++glyph_pos; - } - } - - *nglyphs = glyph_pos; - glyphs->numGlyphs = glyph_pos; - - if (!(flags & GlyphIndicesOnly)) - recalcAdvances(glyphs, flags); - - return true; -} - -bool QFontEngineFT::shouldUseDesignMetrics(QFontEngine::ShaperFlags flags) const -{ - if (!FT_IS_SCALABLE(freetype->face)) - return false; - - return default_hint_style == HintNone || default_hint_style == HintLight || (flags & DesignMetrics); -} - -QFixed QFontEngineFT::scaledBitmapMetrics(QFixed m) const -{ - return m * scalableBitmapScaleFactor; -} - -glyph_metrics_t QFontEngineFT::scaledBitmapMetrics(const glyph_metrics_t &m, const QTransform &t) const -{ - QTransform trans; - trans.setMatrix(t.m11(), t.m12(), t.m13(), - t.m21(), t.m22(), t.m23(), - 0, 0, t.m33()); - const qreal scaleFactor = scalableBitmapScaleFactor.toReal(); - trans.scale(scaleFactor, scaleFactor); - - QRectF rect(m.x.toReal(), m.y.toReal(), m.width.toReal(), m.height.toReal()); - QPointF offset(m.xoff.toReal(), m.yoff.toReal()); - - rect = trans.mapRect(rect); - offset = trans.map(offset); - - glyph_metrics_t metrics; - metrics.x = QFixed::fromReal(rect.x()); - metrics.y = QFixed::fromReal(rect.y()); - metrics.width = QFixed::fromReal(rect.width()); - metrics.height = QFixed::fromReal(rect.height()); - metrics.xoff = QFixed::fromReal(offset.x()); - metrics.yoff = QFixed::fromReal(offset.y()); - return metrics; -} - -void QFontEngineFT::recalcAdvances(QGlyphLayout *glyphs, QFontEngine::ShaperFlags flags) const -{ - FT_Face face = 0; - bool design = shouldUseDesignMetrics(flags); - for (int i = 0; i < glyphs->numGlyphs; i++) { - Glyph *g = cacheEnabled ? defaultGlyphSet.getGlyph(glyphs->glyphs[i]) : 0; - // Since we are passing Format_None to loadGlyph, use same default format logic as loadGlyph - GlyphFormat acceptableFormat = (defaultFormat != Format_None) ? defaultFormat : Format_Mono; - if (g && g->format == acceptableFormat) { - glyphs->advances[i] = design ? QFixed::fromFixed(g->linearAdvance) : QFixed(g->advance); - } else { - if (!face) - face = lockFace(); - g = loadGlyph(cacheEnabled ? &defaultGlyphSet : 0, glyphs->glyphs[i], 0, Format_None, true); - if (g) - glyphs->advances[i] = design ? QFixed::fromFixed(g->linearAdvance) : QFixed(g->advance); - else - glyphs->advances[i] = design ? QFixed::fromFixed(face->glyph->linearHoriAdvance >> 10) - : QFixed::fromFixed(face->glyph->metrics.horiAdvance).round(); - if (!cacheEnabled && g != &emptyGlyph) - delete g; - } - - if (scalableBitmapScaleFactor != 1) - glyphs->advances[i] *= scalableBitmapScaleFactor; - } - if (face) - unlockFace(); - - if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) { - for (int i = 0; i < glyphs->numGlyphs; ++i) - glyphs->advances[i] = glyphs->advances[i].round(); - } -} - -glyph_metrics_t QFontEngineFT::boundingBox(const QGlyphLayout &glyphs) -{ - FT_Face face = 0; - - glyph_metrics_t overall; - // initialize with line height, we get the same behaviour on all platforms - if (!isScalableBitmap()) { - overall.y = -ascent(); - overall.height = ascent() + descent(); - } else { - overall.y = QFixed::fromFixed(-metrics.ascender); - overall.height = QFixed::fromFixed(metrics.ascender - metrics.descender); - } - - QFixed ymax = 0; - QFixed xmax = 0; - for (int i = 0; i < glyphs.numGlyphs; i++) { - Glyph *g = cacheEnabled ? defaultGlyphSet.getGlyph(glyphs.glyphs[i]) : 0; - if (!g) { - if (!face) - face = lockFace(); - g = loadGlyph(cacheEnabled ? &defaultGlyphSet : 0, glyphs.glyphs[i], 0, Format_None, true); - } - if (g) { - QFixed x = overall.xoff + glyphs.offsets[i].x + g->x; - QFixed y = overall.yoff + glyphs.offsets[i].y - g->y; - overall.x = qMin(overall.x, x); - overall.y = qMin(overall.y, y); - xmax = qMax(xmax, x + g->width); - ymax = qMax(ymax, y + g->height); - overall.xoff += g->advance; - if (!cacheEnabled && g != &emptyGlyph) - delete g; - } else { - int left = FLOOR(face->glyph->metrics.horiBearingX); - int right = CEIL(face->glyph->metrics.horiBearingX + face->glyph->metrics.width); - int top = CEIL(face->glyph->metrics.horiBearingY); - int bottom = FLOOR(face->glyph->metrics.horiBearingY - face->glyph->metrics.height); - - QFixed x = overall.xoff + glyphs.offsets[i].x - (-TRUNC(left)); - QFixed y = overall.yoff + glyphs.offsets[i].y - TRUNC(top); - overall.x = qMin(overall.x, x); - overall.y = qMin(overall.y, y); - xmax = qMax(xmax, x + TRUNC(right - left)); - ymax = qMax(ymax, y + TRUNC(top - bottom)); - overall.xoff += int(TRUNC(ROUND(face->glyph->advance.x))); - } - } - overall.height = qMax(overall.height, ymax - overall.y); - overall.width = xmax - overall.x; - - if (face) - unlockFace(); - - if (isScalableBitmap()) - overall = scaledBitmapMetrics(overall, QTransform()); - return overall; -} - -glyph_metrics_t QFontEngineFT::boundingBox(glyph_t glyph) -{ - FT_Face face = 0; - glyph_metrics_t overall; - Glyph *g = cacheEnabled ? defaultGlyphSet.getGlyph(glyph) : 0; - if (!g) { - face = lockFace(); - g = loadGlyph(cacheEnabled ? &defaultGlyphSet : 0, glyph, 0, Format_None, true); - } - if (g) { - overall.x = g->x; - overall.y = -g->y; - overall.width = g->width; - overall.height = g->height; - overall.xoff = g->advance; - if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) - overall.xoff = overall.xoff.round(); - if (!cacheEnabled && g != &emptyGlyph) - delete g; - } else { - int left = FLOOR(face->glyph->metrics.horiBearingX); - int right = CEIL(face->glyph->metrics.horiBearingX + face->glyph->metrics.width); - int top = CEIL(face->glyph->metrics.horiBearingY); - int bottom = FLOOR(face->glyph->metrics.horiBearingY - face->glyph->metrics.height); - - overall.width = TRUNC(right-left); - overall.height = TRUNC(top-bottom); - overall.x = TRUNC(left); - overall.y = -TRUNC(top); - overall.xoff = TRUNC(ROUND(face->glyph->advance.x)); - } - if (face) - unlockFace(); - - if (isScalableBitmap()) - overall = scaledBitmapMetrics(overall, QTransform()); - return overall; -} - -glyph_metrics_t QFontEngineFT::boundingBox(glyph_t glyph, const QTransform &matrix) -{ - return alphaMapBoundingBox(glyph, 0, matrix, QFontEngine::Format_None); -} - -glyph_metrics_t QFontEngineFT::alphaMapBoundingBox(glyph_t glyph, QFixed subPixelPosition, const QTransform &matrix, QFontEngine::GlyphFormat format) -{ - Glyph *g = loadGlyphFor(glyph, subPixelPosition, format, matrix, true); - - glyph_metrics_t overall; - if (g) { - overall.x = g->x; - overall.y = -g->y; - overall.width = g->width; - overall.height = g->height; - overall.xoff = g->advance; - if (!cacheEnabled && g != &emptyGlyph) - delete g; - } else { - FT_Face face = lockFace(); - int left = FLOOR(face->glyph->metrics.horiBearingX); - int right = CEIL(face->glyph->metrics.horiBearingX + face->glyph->metrics.width); - int top = CEIL(face->glyph->metrics.horiBearingY); - int bottom = FLOOR(face->glyph->metrics.horiBearingY - face->glyph->metrics.height); - - overall.width = TRUNC(right-left); - overall.height = TRUNC(top-bottom); - overall.x = TRUNC(left); - overall.y = -TRUNC(top); - overall.xoff = TRUNC(ROUND(face->glyph->advance.x)); - unlockFace(); - } - - if (isScalableBitmap()) - overall = scaledBitmapMetrics(overall, matrix); - return overall; -} - -static inline QImage alphaMapFromGlyphData(QFontEngineFT::Glyph *glyph, QFontEngine::GlyphFormat glyphFormat) -{ - if (glyph == nullptr || glyph->height == 0 || glyph->width == 0) - return QImage(); - - QImage::Format format = QImage::Format_Invalid; - int bytesPerLine = -1; - switch (glyphFormat) { - case QFontEngine::Format_Mono: - format = QImage::Format_Mono; - bytesPerLine = ((glyph->width + 31) & ~31) >> 3; - break; - case QFontEngine::Format_A8: - format = QImage::Format_Alpha8; - bytesPerLine = (glyph->width + 3) & ~3; - break; - case QFontEngine::Format_A32: - format = QImage::Format_RGB32; - bytesPerLine = glyph->width * 4; - break; - default: - Q_UNREACHABLE(); - }; - - QImage img(static_cast<const uchar *>(glyph->data), glyph->width, glyph->height, bytesPerLine, format); - if (format == QImage::Format_Mono) - img.setColor(1, QColor(Qt::white).rgba()); // Expands color table to 2 items; item 0 set to transparent. - return img; -} - -QFontEngine::Glyph *QFontEngineFT::glyphData(glyph_t glyphIndex, QFixed subPixelPosition, - QFontEngine::GlyphFormat neededFormat, const QTransform &t) -{ - Q_ASSERT(cacheEnabled); - - if (isBitmapFont()) - neededFormat = Format_Mono; - else if (neededFormat == Format_None && defaultFormat != Format_None) - neededFormat = defaultFormat; - else if (neededFormat == Format_None) - neededFormat = Format_A8; - - Glyph *glyph = loadGlyphFor(glyphIndex, subPixelPosition, neededFormat, t); - if (!glyph || !glyph->width || !glyph->height) - return nullptr; - - return glyph; -} - -static inline bool is2dRotation(const QTransform &t) -{ - return qFuzzyCompare(t.m11(), t.m22()) && qFuzzyCompare(t.m12(), -t.m21()) - && qFuzzyCompare(t.m11()*t.m22() - t.m12()*t.m21(), qreal(1.0)); -} - -QFontEngineFT::Glyph *QFontEngineFT::loadGlyphFor(glyph_t g, - QFixed subPixelPosition, - GlyphFormat format, - const QTransform &t, - bool fetchBoundingBox, - bool disableOutlineDrawing) -{ - QGlyphSet *glyphSet = loadGlyphSet(t); - if (glyphSet != 0 && glyphSet->outline_drawing && !disableOutlineDrawing && !fetchBoundingBox) - return 0; - - Glyph *glyph = glyphSet != 0 ? glyphSet->getGlyph(g, subPixelPosition) : 0; - if (!glyph || glyph->format != format || (!fetchBoundingBox && !glyph->data)) { - QScopedValueRollback<HintStyle> saved_default_hint_style(default_hint_style); - if (t.type() >= QTransform::TxScale && !is2dRotation(t)) - default_hint_style = HintNone; // disable hinting if the glyphs are transformed - - lockFace(); - FT_Matrix m = this->matrix; - FT_Matrix ftMatrix = glyphSet != 0 ? glyphSet->transformationMatrix : QTransformToFTMatrix(t); - FT_Matrix_Multiply(&ftMatrix, &m); - freetype->matrix = m; - glyph = loadGlyph(glyphSet, g, subPixelPosition, format, false, disableOutlineDrawing); - unlockFace(); - } - - return glyph; -} - -QImage QFontEngineFT::alphaMapForGlyph(glyph_t g, QFixed subPixelPosition) -{ - return alphaMapForGlyph(g, subPixelPosition, QTransform()); -} - -QImage QFontEngineFT::alphaMapForGlyph(glyph_t g, QFixed subPixelPosition, const QTransform &t) -{ - const GlyphFormat neededFormat = antialias ? Format_A8 : Format_Mono; - - Glyph *glyph = loadGlyphFor(g, subPixelPosition, neededFormat, t, false, true); - - QImage img = alphaMapFromGlyphData(glyph, neededFormat); - img = img.copy(); - - if (!cacheEnabled && glyph != &emptyGlyph) - delete glyph; - - return img; -} - -QImage QFontEngineFT::alphaRGBMapForGlyph(glyph_t g, QFixed subPixelPosition, const QTransform &t) -{ - if (t.type() > QTransform::TxRotate) - return QFontEngine::alphaRGBMapForGlyph(g, subPixelPosition, t); - - const GlyphFormat neededFormat = Format_A32; - - Glyph *glyph = loadGlyphFor(g, subPixelPosition, neededFormat, t, false, true); - - QImage img = alphaMapFromGlyphData(glyph, neededFormat); - img = img.copy(); - - if (!cacheEnabled && glyph != &emptyGlyph) - delete glyph; - - if (!img.isNull()) - return img; - - return QFontEngine::alphaRGBMapForGlyph(g, subPixelPosition, t); -} - -QImage QFontEngineFT::bitmapForGlyph(glyph_t g, QFixed subPixelPosition, const QTransform &t, const QColor &color) -{ - Q_UNUSED(color); - - Glyph *glyph = loadGlyphFor(g, subPixelPosition, defaultFormat, t); - if (glyph == nullptr) - return QImage(); - - QImage img; - if (defaultFormat == GlyphFormat::Format_ARGB) - img = QImage(glyph->data, glyph->width, glyph->height, QImage::Format_ARGB32_Premultiplied).copy(); - else if (defaultFormat == GlyphFormat::Format_Mono) - img = QImage(glyph->data, glyph->width, glyph->height, QImage::Format_Mono).copy(); - - if (!img.isNull() && (!t.isIdentity() || scalableBitmapScaleFactor != 1)) { - QTransform trans(t); - const qreal scaleFactor = scalableBitmapScaleFactor.toReal(); - trans.scale(scaleFactor, scaleFactor); - img = img.transformed(trans, Qt::SmoothTransformation); - } - - if (!cacheEnabled && glyph != &emptyGlyph) - delete glyph; - - return img; -} - -void QFontEngineFT::removeGlyphFromCache(glyph_t glyph) -{ - defaultGlyphSet.removeGlyphFromCache(glyph, 0); -} - -int QFontEngineFT::glyphCount() const -{ - int count = 0; - FT_Face face = lockFace(); - if (face) { - count = face->num_glyphs; - unlockFace(); - } - return count; -} - -FT_Face QFontEngineFT::lockFace(Scaling scale) const -{ - freetype->lock(); - FT_Face face = freetype->face; - if (scale == Unscaled) { - if (FT_Set_Char_Size(face, face->units_per_EM << 6, face->units_per_EM << 6, 0, 0) == 0) { - freetype->xsize = face->units_per_EM << 6; - freetype->ysize = face->units_per_EM << 6; - } - } else if (freetype->xsize != xsize || freetype->ysize != ysize) { - FT_Set_Char_Size(face, xsize, ysize, 0, 0); - freetype->xsize = xsize; - freetype->ysize = ysize; - } - if (freetype->matrix.xx != matrix.xx || - freetype->matrix.yy != matrix.yy || - freetype->matrix.xy != matrix.xy || - freetype->matrix.yx != matrix.yx) { - freetype->matrix = matrix; - FT_Set_Transform(face, &freetype->matrix, 0); - } - - return face; -} - -void QFontEngineFT::unlockFace() const -{ - freetype->unlock(); -} - -FT_Face QFontEngineFT::non_locked_face() const -{ - return freetype->face; -} - - -QFontEngineFT::QGlyphSet::QGlyphSet() - : outline_drawing(false) -{ - transformationMatrix.xx = 0x10000; - transformationMatrix.yy = 0x10000; - transformationMatrix.xy = 0; - transformationMatrix.yx = 0; - memset(fast_glyph_data, 0, sizeof(fast_glyph_data)); - fast_glyph_count = 0; -} - -QFontEngineFT::QGlyphSet::~QGlyphSet() -{ - clear(); -} - -void QFontEngineFT::QGlyphSet::clear() -{ - if (fast_glyph_count > 0) { - for (int i = 0; i < 256; ++i) { - if (fast_glyph_data[i]) { - delete fast_glyph_data[i]; - fast_glyph_data[i] = 0; - } - } - fast_glyph_count = 0; - } - qDeleteAll(glyph_data); - glyph_data.clear(); -} - -void QFontEngineFT::QGlyphSet::removeGlyphFromCache(glyph_t index, QFixed subPixelPosition) -{ - if (useFastGlyphData(index, subPixelPosition)) { - if (fast_glyph_data[index]) { - delete fast_glyph_data[index]; - fast_glyph_data[index] = 0; - if (fast_glyph_count > 0) - --fast_glyph_count; - } - } else { - delete glyph_data.take(GlyphAndSubPixelPosition(index, subPixelPosition)); - } -} - -void QFontEngineFT::QGlyphSet::setGlyph(glyph_t index, QFixed subPixelPosition, Glyph *glyph) -{ - if (useFastGlyphData(index, subPixelPosition)) { - if (!fast_glyph_data[index]) - ++fast_glyph_count; - fast_glyph_data[index] = glyph; - } else { - glyph_data.insert(GlyphAndSubPixelPosition(index, subPixelPosition), glyph); - } -} - -int QFontEngineFT::getPointInOutline(glyph_t glyph, int flags, quint32 point, QFixed *xpos, QFixed *ypos, quint32 *nPoints) -{ - lockFace(); - bool hsubpixel = true; - int vfactor = 1; - int load_flags = loadFlags(0, Format_A8, flags, hsubpixel, vfactor); - int result = freetype->getPointInOutline(glyph, load_flags, point, xpos, ypos, nPoints); - unlockFace(); - return result; -} - -bool QFontEngineFT::initFromFontEngine(const QFontEngineFT *fe) -{ - if (!init(fe->faceId(), fe->antialias, fe->defaultFormat, fe->freetype)) - return false; - - // Increase the reference of this QFreetypeFace since one more QFontEngineFT - // will be using it - freetype->ref.ref(); - - default_load_flags = fe->default_load_flags; - default_hint_style = fe->default_hint_style; - antialias = fe->antialias; - transform = fe->transform; - embolden = fe->embolden; - obliquen = fe->obliquen; - subpixelType = fe->subpixelType; - lcdFilterType = fe->lcdFilterType; - embeddedbitmap = fe->embeddedbitmap; - - return true; -} - -QFontEngine *QFontEngineFT::cloneWithSize(qreal pixelSize) const -{ - QFontDef fontDef(this->fontDef); - fontDef.pixelSize = pixelSize; - QFontEngineFT *fe = new QFontEngineFT(fontDef); - if (!fe->initFromFontEngine(this)) { - delete fe; - return 0; - } else { - return fe; - } -} - -Qt::HANDLE QFontEngineFT::handle() const -{ - return non_locked_face(); -} - -QT_END_NAMESPACE - -#endif // QT_NO_FREETYPE diff --git a/src/platformsupport/fontdatabases/freetype/qfontengine_ft_p.h b/src/platformsupport/fontdatabases/freetype/qfontengine_ft_p.h deleted file mode 100644 index 2863d206d2..0000000000 --- a/src/platformsupport/fontdatabases/freetype/qfontengine_ft_p.h +++ /dev/null @@ -1,347 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#ifndef QFONTENGINE_FT_P_H -#define QFONTENGINE_FT_P_H -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "private/qfontengine_p.h" - -#ifndef QT_NO_FREETYPE - -#include <ft2build.h> -#include FT_FREETYPE_H - - -#ifndef Q_OS_WIN -#include <unistd.h> -#endif - -#include <qmutex.h> - -QT_BEGIN_NAMESPACE - -class QFontEngineFTRawFont; -class QFontconfigDatabase; - -/* - * This class represents one font file on disk (like Arial.ttf) and is shared between all the font engines - * that show this font file (at different pixel sizes). - */ -class QFreetypeFace -{ -public: - void computeSize(const QFontDef &fontDef, int *xsize, int *ysize, bool *outline_drawing, QFixed *scalableBitmapScaleFactor); - QFontEngine::Properties properties() const; - bool getSfntTable(uint tag, uchar *buffer, uint *length) const; - - static QFreetypeFace *getFace(const QFontEngine::FaceId &face_id, - const QByteArray &fontData = QByteArray()); - void release(const QFontEngine::FaceId &face_id); - - // locks the struct for usage. Any read/write operations require locking. - void lock() - { - _lock.lock(); - } - void unlock() - { - _lock.unlock(); - } - - FT_Face face; - int xsize; // 26.6 - int ysize; // 26.6 - FT_Matrix matrix; - FT_CharMap unicode_map; - FT_CharMap symbol_map; - - enum { cmapCacheSize = 0x200 }; - glyph_t cmapCache[cmapCacheSize]; - - int fsType() const; - - int getPointInOutline(glyph_t glyph, int flags, quint32 point, QFixed *xpos, QFixed *ypos, quint32 *nPoints); - - bool isScalableBitmap() const; - - static void addGlyphToPath(FT_Face face, FT_GlyphSlot g, const QFixedPoint &point, QPainterPath *path, FT_Fixed x_scale, FT_Fixed y_scale); - static void addBitmapToPath(FT_GlyphSlot slot, const QFixedPoint &point, QPainterPath *path); - -private: - friend class QFontEngineFT; - friend class QtFreetypeData; - friend struct QScopedPointerDeleter<QFreetypeFace>; - QFreetypeFace() : _lock(QMutex::Recursive) {} - ~QFreetypeFace() {} - void cleanup(); - QAtomicInt ref; - QMutex _lock; - QByteArray fontData; - - QFontEngine::Holder hbFace; -}; - -class QFontEngineFT : public QFontEngine -{ -public: - struct GlyphInfo { - int linearAdvance; - unsigned short width; - unsigned short height; - short x; - short y; - short xOff; - short yOff; - }; - - struct GlyphAndSubPixelPosition - { - GlyphAndSubPixelPosition(glyph_t g, QFixed spp) : glyph(g), subPixelPosition(spp) {} - - bool operator==(const GlyphAndSubPixelPosition &other) const - { - return glyph == other.glyph && subPixelPosition == other.subPixelPosition; - } - - glyph_t glyph; - QFixed subPixelPosition; - }; - - struct QGlyphSet - { - QGlyphSet(); - ~QGlyphSet(); - FT_Matrix transformationMatrix; - bool outline_drawing; - - void removeGlyphFromCache(glyph_t index, QFixed subPixelPosition); - void clear(); - inline bool useFastGlyphData(glyph_t index, QFixed subPixelPosition) const { - return (index < 256 && subPixelPosition == 0); - } - inline Glyph *getGlyph(glyph_t index, QFixed subPixelPosition = 0) const; - void setGlyph(glyph_t index, QFixed spp, Glyph *glyph); - - inline bool isGlyphMissing(glyph_t index) const { return missing_glyphs.contains(index); } - inline void setGlyphMissing(glyph_t index) const { missing_glyphs.insert(index); } -private: - mutable QHash<GlyphAndSubPixelPosition, Glyph *> glyph_data; // maps from glyph index to glyph data - mutable QSet<glyph_t> missing_glyphs; - mutable Glyph *fast_glyph_data[256]; // for fast lookup of glyphs < 256 - mutable int fast_glyph_count; - }; - - QFontEngine::FaceId faceId() const override; - QFontEngine::Properties properties() const override; - QFixed emSquareSize() const override; - bool supportsSubPixelPositions() const override - { - return default_hint_style == HintLight || - default_hint_style == HintNone; - } - - bool getSfntTableData(uint tag, uchar *buffer, uint *length) const override; - int synthesized() const override; - - QFixed ascent() const override; - QFixed capHeight() const override; - QFixed descent() const override; - QFixed leading() const override; - QFixed xHeight() const override; - QFixed averageCharWidth() const override; - - qreal maxCharWidth() const override; - QFixed lineThickness() const override; - QFixed underlinePosition() const override; - - glyph_t glyphIndex(uint ucs4) const override; - void doKerning(QGlyphLayout *, ShaperFlags) const override; - - void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics) override; - - bool supportsTransformation(const QTransform &transform) const override; - - void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs, - QPainterPath *path, QTextItem::RenderFlags flags) override; - void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, - QPainterPath *path, QTextItem::RenderFlags flags) override; - - bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, ShaperFlags flags) const override; - - glyph_metrics_t boundingBox(const QGlyphLayout &glyphs) override; - glyph_metrics_t boundingBox(glyph_t glyph) override; - glyph_metrics_t boundingBox(glyph_t glyph, const QTransform &matrix) override; - - void recalcAdvances(QGlyphLayout *glyphs, ShaperFlags flags) const override; - QImage alphaMapForGlyph(glyph_t g) override { return alphaMapForGlyph(g, 0); } - QImage alphaMapForGlyph(glyph_t, QFixed) override; - QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t) override; - QImage alphaRGBMapForGlyph(glyph_t, QFixed subPixelPosition, const QTransform &t) override; - QImage bitmapForGlyph(glyph_t, QFixed subPixelPosition, const QTransform &t, const QColor &color) override; - glyph_metrics_t alphaMapBoundingBox(glyph_t glyph, - QFixed subPixelPosition, - const QTransform &matrix, - QFontEngine::GlyphFormat format) override; - Glyph *glyphData(glyph_t glyph, QFixed subPixelPosition, - GlyphFormat neededFormat, const QTransform &t) override; - bool hasInternalCaching() const override { return cacheEnabled; } - bool expectsGammaCorrectedBlending() const override; - - void removeGlyphFromCache(glyph_t glyph) override; - int glyphMargin(QFontEngine::GlyphFormat /* format */) override { return 0; } - - int glyphCount() const override; - - enum Scaling { - Scaled, - Unscaled - }; - FT_Face lockFace(Scaling scale = Scaled) const; - void unlockFace() const; - - FT_Face non_locked_face() const; - - inline bool drawAntialiased() const { return antialias; } - inline bool invalid() const { return xsize == 0 && ysize == 0; } - inline bool isBitmapFont() const { return defaultFormat == Format_Mono; } - inline bool isScalableBitmap() const { return freetype->isScalableBitmap(); } - - inline Glyph *loadGlyph(uint glyph, QFixed subPixelPosition, GlyphFormat format = Format_None, bool fetchMetricsOnly = false, bool disableOutlineDrawing = false) const - { return loadGlyph(cacheEnabled ? &defaultGlyphSet : 0, glyph, subPixelPosition, format, fetchMetricsOnly, disableOutlineDrawing); } - Glyph *loadGlyph(QGlyphSet *set, uint glyph, QFixed subPixelPosition, GlyphFormat = Format_None, bool fetchMetricsOnly = false, bool disableOutlineDrawing = false) const; - Glyph *loadGlyphFor(glyph_t g, QFixed subPixelPosition, GlyphFormat format, const QTransform &t, bool fetchBoundingBox = false, bool disableOutlineDrawing = false); - - QGlyphSet *loadGlyphSet(const QTransform &matrix); - - QFontEngineFT(const QFontDef &fd); - virtual ~QFontEngineFT(); - - bool init(FaceId faceId, bool antiaalias, GlyphFormat defaultFormat = Format_None, - const QByteArray &fontData = QByteArray()); - bool init(FaceId faceId, bool antialias, GlyphFormat format, - QFreetypeFace *freetypeFace); - - int getPointInOutline(glyph_t glyph, int flags, quint32 point, QFixed *xpos, QFixed *ypos, quint32 *nPoints) override; - - void setQtDefaultHintStyle(QFont::HintingPreference hintingPreference); - void setDefaultHintStyle(HintStyle style) override; - - QFontEngine *cloneWithSize(qreal pixelSize) const override; - Qt::HANDLE handle() const override; - bool initFromFontEngine(const QFontEngineFT *fontEngine); - - HintStyle defaultHintStyle() const { return default_hint_style; } - - static QFontEngineFT *create(const QFontDef &fontDef, FaceId faceId, const QByteArray &fontData = QByteArray()); - static QFontEngineFT *create(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference); - -protected: - - QFreetypeFace *freetype; - mutable int default_load_flags; - HintStyle default_hint_style; - bool antialias; - bool transform; - bool embolden; - bool obliquen; - SubpixelAntialiasingType subpixelType; - int lcdFilterType; - bool embeddedbitmap; - bool cacheEnabled; - bool forceAutoHint; - bool stemDarkeningDriver; - -private: - friend class QFontEngineFTRawFont; - friend class QFontconfigDatabase; - friend class QFreeTypeFontDatabase; - friend class QFontEngineMultiFontConfig; - - int loadFlags(QGlyphSet *set, GlyphFormat format, int flags, bool &hsubpixel, int &vfactor) const; - bool shouldUseDesignMetrics(ShaperFlags flags) const; - QFixed scaledBitmapMetrics(QFixed m) const; - glyph_metrics_t scaledBitmapMetrics(const glyph_metrics_t &m, const QTransform &matrix) const; - - GlyphFormat defaultFormat; - FT_Matrix matrix; - - QList<QGlyphSet> transformedGlyphSets; - mutable QGlyphSet defaultGlyphSet; - - QFontEngine::FaceId face_id; - - int xsize; - int ysize; - - QFixed line_thickness; - QFixed underline_position; - - FT_Size_Metrics metrics; - mutable bool kerning_pairs_loaded; - QFixed scalableBitmapScaleFactor; -}; - -inline uint qHash(const QFontEngineFT::GlyphAndSubPixelPosition &g) -{ - return (g.glyph << 8) | (g.subPixelPosition * 10).round().toInt(); -} - -inline QFontEngineFT::Glyph *QFontEngineFT::QGlyphSet::getGlyph(glyph_t index, QFixed subPixelPosition) const -{ - if (useFastGlyphData(index, subPixelPosition)) - return fast_glyph_data[index]; - return glyph_data.value(GlyphAndSubPixelPosition(index, subPixelPosition)); -} - -extern FT_Library qt_getFreetype(); - -QT_END_NAMESPACE - -#endif // QT_NO_FREETYPE - -#endif // QFONTENGINE_FT_P_H diff --git a/src/platformsupport/fontdatabases/freetype/qfreetypefontdatabase.cpp b/src/platformsupport/fontdatabases/freetype/qfreetypefontdatabase.cpp deleted file mode 100644 index 4baba64de3..0000000000 --- a/src/platformsupport/fontdatabases/freetype/qfreetypefontdatabase.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qfreetypefontdatabase_p.h" - -#include <QtGui/private/qguiapplication_p.h> -#include <qpa/qplatformscreen.h> - -#include <QtCore/QFile> -#include <QtCore/QLibraryInfo> -#include <QtCore/QDir> -#include <QtCore/QtEndian> - -#undef QT_NO_FREETYPE -#include <QtFontDatabaseSupport/private/qfontengine_ft_p.h> - -#include <ft2build.h> -#include FT_TRUETYPE_TABLES_H -#include FT_ERRORS_H - -QT_BEGIN_NAMESPACE - -void QFreeTypeFontDatabase::populateFontDatabase() -{ - QString fontpath = fontDir(); - QDir dir(fontpath); - - if (!dir.exists()) { - qWarning("QFontDatabase: Cannot find font directory %s.\n" - "Note that Qt no longer ships fonts. Deploy some (from https://dejavu-fonts.github.io/ for example) or switch to fontconfig.", - qPrintable(fontpath)); - return; - } - - QStringList nameFilters; - nameFilters << QLatin1String("*.ttf") - << QLatin1String("*.ttc") - << QLatin1String("*.pfa") - << QLatin1String("*.pfb") - << QLatin1String("*.otf"); - - const auto fis = dir.entryInfoList(nameFilters, QDir::Files); - for (const QFileInfo &fi : fis) { - const QByteArray file = QFile::encodeName(fi.absoluteFilePath()); - QFreeTypeFontDatabase::addTTFile(QByteArray(), file); - } -} - -QFontEngine *QFreeTypeFontDatabase::fontEngine(const QFontDef &fontDef, void *usrPtr) -{ - FontFile *fontfile = static_cast<FontFile *>(usrPtr); - QFontEngine::FaceId faceId; - faceId.filename = QFile::encodeName(fontfile->fileName); - faceId.index = fontfile->indexValue; - - return QFontEngineFT::create(fontDef, faceId); -} - -QFontEngine *QFreeTypeFontDatabase::fontEngine(const QByteArray &fontData, qreal pixelSize, - QFont::HintingPreference hintingPreference) -{ - return QFontEngineFT::create(fontData, pixelSize, hintingPreference); -} - -QStringList QFreeTypeFontDatabase::addApplicationFont(const QByteArray &fontData, const QString &fileName) -{ - return QFreeTypeFontDatabase::addTTFile(fontData, fileName.toLocal8Bit()); -} - -void QFreeTypeFontDatabase::releaseHandle(void *handle) -{ - FontFile *file = static_cast<FontFile *>(handle); - delete file; -} - -extern FT_Library qt_getFreetype(); - -QStringList QFreeTypeFontDatabase::addTTFile(const QByteArray &fontData, const QByteArray &file) -{ - FT_Library library = qt_getFreetype(); - - int index = 0; - int numFaces = 0; - QStringList families; - do { - FT_Face face; - FT_Error error; - if (!fontData.isEmpty()) { - error = FT_New_Memory_Face(library, (const FT_Byte *)fontData.constData(), fontData.size(), index, &face); - } else { - error = FT_New_Face(library, file.constData(), index, &face); - } - if (error != FT_Err_Ok) { - qDebug() << "FT_New_Face failed with index" << index << ':' << hex << error; - break; - } - numFaces = face->num_faces; - - QFont::Weight weight = QFont::Normal; - - QFont::Style style = QFont::StyleNormal; - if (face->style_flags & FT_STYLE_FLAG_ITALIC) - style = QFont::StyleItalic; - - if (face->style_flags & FT_STYLE_FLAG_BOLD) - weight = QFont::Bold; - - bool fixedPitch = (face->face_flags & FT_FACE_FLAG_FIXED_WIDTH); - - QSupportedWritingSystems writingSystems; - // detect symbol fonts - for (int i = 0; i < face->num_charmaps; ++i) { - FT_CharMap cm = face->charmaps[i]; - if (cm->encoding == FT_ENCODING_ADOBE_CUSTOM - || cm->encoding == FT_ENCODING_MS_SYMBOL) { - writingSystems.setSupported(QFontDatabase::Symbol); - break; - } - } - - TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(face, ft_sfnt_os2); - if (os2) { - quint32 unicodeRange[4] = { - quint32(os2->ulUnicodeRange1), - quint32(os2->ulUnicodeRange2), - quint32(os2->ulUnicodeRange3), - quint32(os2->ulUnicodeRange4) - }; - quint32 codePageRange[2] = { - quint32(os2->ulCodePageRange1), - quint32(os2->ulCodePageRange2) - }; - - writingSystems = QPlatformFontDatabase::writingSystemsFromTrueTypeBits(unicodeRange, codePageRange); - - if (os2->usWeightClass) { - weight = QPlatformFontDatabase::weightFromInteger(os2->usWeightClass); - } else if (os2->panose[2]) { - int w = os2->panose[2]; - if (w <= 1) - weight = QFont::Thin; - else if (w <= 2) - weight = QFont::ExtraLight; - else if (w <= 3) - weight = QFont::Light; - else if (w <= 5) - weight = QFont::Normal; - else if (w <= 6) - weight = QFont::Medium; - else if (w <= 7) - weight = QFont::DemiBold; - else if (w <= 8) - weight = QFont::Bold; - else if (w <= 9) - weight = QFont::ExtraBold; - else if (w <= 10) - weight = QFont::Black; - } - } - - QString family = QString::fromLatin1(face->family_name); - FontFile *fontFile = new FontFile; - fontFile->fileName = QFile::decodeName(file); - fontFile->indexValue = index; - - QFont::Stretch stretch = QFont::Unstretched; - - registerFont(family,QString::fromLatin1(face->style_name),QString(),weight,style,stretch,true,true,0,fixedPitch,writingSystems,fontFile); - - families.append(family); - - FT_Done_Face(face); - ++index; - } while (index < numFaces); - return families; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/fontdatabases/freetype/qfreetypefontdatabase_p.h b/src/platformsupport/fontdatabases/freetype/qfreetypefontdatabase_p.h deleted file mode 100644 index 0b2956b16e..0000000000 --- a/src/platformsupport/fontdatabases/freetype/qfreetypefontdatabase_p.h +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QFREETYPEFONTDATABASE_H -#define QFREETYPEFONTDATABASE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <qpa/qplatformfontdatabase.h> -#include <QtCore/QByteArray> -#include <QtCore/QString> - -QT_BEGIN_NAMESPACE - -struct FontFile -{ - QString fileName; - int indexValue; -}; - -class QFreeTypeFontDatabase : public QPlatformFontDatabase -{ -public: - void populateFontDatabase() override; - QFontEngine *fontEngine(const QFontDef &fontDef, void *handle) override; - QFontEngine *fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference) override; - QStringList addApplicationFont(const QByteArray &fontData, const QString &fileName) override; - void releaseHandle(void *handle) override; - - static QStringList addTTFile(const QByteArray &fontData, const QByteArray &file); -}; - -QT_END_NAMESPACE - -#endif // QFREETYPEFONTDATABASE_H diff --git a/src/platformsupport/fontdatabases/genericunix/genericunix.pri b/src/platformsupport/fontdatabases/genericunix/genericunix.pri deleted file mode 100644 index e9db6c07e2..0000000000 --- a/src/platformsupport/fontdatabases/genericunix/genericunix.pri +++ /dev/null @@ -1 +0,0 @@ -HEADERS += $$PWD/qgenericunixfontdatabase_p.h diff --git a/src/platformsupport/fontdatabases/genericunix/qgenericunixfontdatabase_p.h b/src/platformsupport/fontdatabases/genericunix/qgenericunixfontdatabase_p.h deleted file mode 100644 index ccf5ad6d13..0000000000 --- a/src/platformsupport/fontdatabases/genericunix/qgenericunixfontdatabase_p.h +++ /dev/null @@ -1,64 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QGENERICUNIXFONTDATABASE_H -#define QGENERICUNIXFONTDATABASE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qtguiglobal_p.h> - -#if QT_CONFIG(fontconfig) -#include <QtFontDatabaseSupport/private/qfontconfigdatabase_p.h> -typedef QFontconfigDatabase QGenericUnixFontDatabase; -#else -#include <QtFontDatabaseSupport/private/qfreetypefontdatabase_p.h> -typedef QFreeTypeFontDatabase QGenericUnixFontDatabase; -#endif //Q_FONTCONFIGDATABASE - -#endif // QGENERICUNIXFONTDATABASE_H diff --git a/src/platformsupport/fontdatabases/mac/coretext.pri b/src/platformsupport/fontdatabases/mac/coretext.pri deleted file mode 100644 index 95b9926e65..0000000000 --- a/src/platformsupport/fontdatabases/mac/coretext.pri +++ /dev/null @@ -1,15 +0,0 @@ -HEADERS += $$PWD/qcoretextfontdatabase_p.h $$PWD/qfontengine_coretext_p.h -OBJECTIVE_SOURCES += $$PWD/qfontengine_coretext.mm $$PWD/qcoretextfontdatabase.mm - -LIBS_PRIVATE += \ - -framework CoreFoundation \ - -framework CoreGraphics \ - -framework CoreText \ - -framework Foundation - -macos: \ - LIBS_PRIVATE += -framework AppKit -else: \ - LIBS_PRIVATE += -framework UIKit - -CONFIG += watchos_coretext diff --git a/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase.mm b/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase.mm deleted file mode 100644 index 047773d8e3..0000000000 --- a/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase.mm +++ /dev/null @@ -1,763 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qglobal.h" - -#include <sys/param.h> - -#if defined(Q_OS_OSX) -#import <AppKit/AppKit.h> -#import <IOKit/graphics/IOGraphicsLib.h> -#elif defined(QT_PLATFORM_UIKIT) -#import <UIKit/UIFont.h> -#endif - -#include "qcoretextfontdatabase_p.h" -#include "qfontengine_coretext_p.h" -#if QT_CONFIG(settings) -#include <QtCore/QSettings> -#endif -#include <QtCore/QtEndian> -#ifndef QT_NO_FREETYPE -#include <QtFontDatabaseSupport/private/qfontengine_ft_p.h> -#endif - -QT_BEGIN_NAMESPACE - -// this could become a list of all languages used for each writing -// system, instead of using the single most common language. -static const char *languageForWritingSystem[] = { - 0, // Any - "en", // Latin - "el", // Greek - "ru", // Cyrillic - "hy", // Armenian - "he", // Hebrew - "ar", // Arabic - "syr", // Syriac - "div", // Thaana - "hi", // Devanagari - "bn", // Bengali - "pa", // Gurmukhi - "gu", // Gujarati - "or", // Oriya - "ta", // Tamil - "te", // Telugu - "kn", // Kannada - "ml", // Malayalam - "si", // Sinhala - "th", // Thai - "lo", // Lao - "bo", // Tibetan - "my", // Myanmar - "ka", // Georgian - "km", // Khmer - "zh-Hans", // SimplifiedChinese - "zh-Hant", // TraditionalChinese - "ja", // Japanese - "ko", // Korean - "vi", // Vietnamese - 0, // Symbol - "sga", // Ogham - "non", // Runic - "man" // N'Ko -}; -enum { LanguageCount = sizeof(languageForWritingSystem) / sizeof(const char *) }; - -#ifdef Q_OS_OSX -static NSInteger languageMapSort(id obj1, id obj2, void *context) -{ - NSArray<NSString *> *map1 = reinterpret_cast<NSArray<NSString *> *>(obj1); - NSArray<NSString *> *map2 = reinterpret_cast<NSArray<NSString *> *>(obj2); - NSArray<NSString *> *languages = reinterpret_cast<NSArray<NSString *> *>(context); - - NSString *lang1 = [map1 objectAtIndex:0]; - NSString *lang2 = [map2 objectAtIndex:0]; - - return [languages indexOfObject:lang1] - [languages indexOfObject:lang2]; -} -#endif - -QCoreTextFontDatabase::QCoreTextFontDatabase() - : m_hasPopulatedAliases(false) -{ -} - -QCoreTextFontDatabase::~QCoreTextFontDatabase() -{ - for (CTFontDescriptorRef ref : qAsConst(m_systemFontDescriptors)) - CFRelease(ref); -} - -void QCoreTextFontDatabase::populateFontDatabase() -{ - QCFType<CFArrayRef> familyNames = CTFontManagerCopyAvailableFontFamilyNames(); - for (NSString *familyName in familyNames.as<const NSArray *>()) - QPlatformFontDatabase::registerFontFamily(QString::fromNSString(familyName)); - - // Force creating the theme fonts to get the descriptors in m_systemFontDescriptors - if (m_themeFonts.isEmpty()) - (void)themeFonts(); - - Q_FOREACH (CTFontDescriptorRef fontDesc, m_systemFontDescriptors) - populateFromDescriptor(fontDesc); - - Q_ASSERT(!m_hasPopulatedAliases); -} - -bool QCoreTextFontDatabase::populateFamilyAliases() -{ -#if defined(Q_OS_MACOS) - if (m_hasPopulatedAliases) - return false; - - QCFType<CFArrayRef> familyNames = CTFontManagerCopyAvailableFontFamilyNames(); - for (NSString *familyName in familyNames.as<const NSArray *>()) { - NSFontManager *fontManager = [NSFontManager sharedFontManager]; - NSString *localizedFamilyName = [fontManager localizedNameForFamily:familyName face:nil]; - if (![localizedFamilyName isEqual:familyName]) { - QPlatformFontDatabase::registerAliasToFontFamily( - QString::fromNSString(familyName), - QString::fromNSString(localizedFamilyName)); - } - } - m_hasPopulatedAliases = true; - return true; -#else - return false; -#endif -} - -void QCoreTextFontDatabase::populateFamily(const QString &familyName) -{ - QCFType<CFMutableDictionaryRef> attributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, QCFString(familyName)); - QCFType<CTFontDescriptorRef> nameOnlyDescriptor = CTFontDescriptorCreateWithAttributes(attributes); - - // A single family might match several different fonts with different styles eg. - QCFType<CFArrayRef> matchingFonts = (CFArrayRef) CTFontDescriptorCreateMatchingFontDescriptors(nameOnlyDescriptor, 0); - if (!matchingFonts) { - qWarning() << "QCoreTextFontDatabase: Found no matching fonts for family" << familyName; - return; - } - - const int numFonts = CFArrayGetCount(matchingFonts); - for (int i = 0; i < numFonts; ++i) - populateFromDescriptor(CTFontDescriptorRef(CFArrayGetValueAtIndex(matchingFonts, i)), familyName); -} - -void QCoreTextFontDatabase::invalidate() -{ - m_hasPopulatedAliases = false; -} - -struct FontDescription { - QCFString familyName; - QCFString styleName; - QString foundryName; - QFont::Weight weight; - QFont::Style style; - QFont::Stretch stretch; - qreal pointSize; - bool fixedPitch; - QSupportedWritingSystems writingSystems; -}; - -#ifndef QT_NO_DEBUG_STREAM -Q_DECL_UNUSED static inline QDebug operator<<(QDebug debug, const FontDescription &fd) -{ - QDebugStateSaver saver(debug); - return debug.nospace() << "FontDescription(" - << "familyName=" << QString(fd.familyName) - << ", styleName=" << QString(fd.styleName) - << ", foundry=" << fd.foundryName - << ", weight=" << fd.weight - << ", style=" << fd.style - << ", stretch=" << fd.stretch - << ", pointSize=" << fd.pointSize - << ", fixedPitch=" << fd.fixedPitch - << ", writingSystems=" << fd.writingSystems - << ")"; -} -#endif - -static void getFontDescription(CTFontDescriptorRef font, FontDescription *fd) -{ - QCFType<CFDictionaryRef> styles = (CFDictionaryRef) CTFontDescriptorCopyAttribute(font, kCTFontTraitsAttribute); - - fd->foundryName = QStringLiteral("CoreText"); - fd->familyName = (CFStringRef) CTFontDescriptorCopyAttribute(font, kCTFontFamilyNameAttribute); - fd->styleName = (CFStringRef)CTFontDescriptorCopyAttribute(font, kCTFontStyleNameAttribute); - fd->weight = QFont::Normal; - fd->style = QFont::StyleNormal; - fd->stretch = QFont::Unstretched; - fd->fixedPitch = false; - - if (QCFType<CTFontRef> tempFont = CTFontCreateWithFontDescriptor(font, 0.0, 0)) { - uint tag = MAKE_TAG('O', 'S', '/', '2'); - CTFontRef tempFontRef = tempFont; - void *userData = reinterpret_cast<void *>(&tempFontRef); - uint length = 128; - QVarLengthArray<uchar, 128> os2Table(length); - if (QCoreTextFontEngine::ct_getSfntTable(userData, tag, os2Table.data(), &length) && length >= 86) { - if (length > uint(os2Table.length())) { - os2Table.resize(length); - if (!QCoreTextFontEngine::ct_getSfntTable(userData, tag, os2Table.data(), &length)) - Q_UNREACHABLE(); - Q_ASSERT(length >= 86); - } - quint32 unicodeRange[4] = { - qFromBigEndian<quint32>(os2Table.data() + 42), - qFromBigEndian<quint32>(os2Table.data() + 46), - qFromBigEndian<quint32>(os2Table.data() + 50), - qFromBigEndian<quint32>(os2Table.data() + 54) - }; - quint32 codePageRange[2] = { - qFromBigEndian<quint32>(os2Table.data() + 78), - qFromBigEndian<quint32>(os2Table.data() + 82) - }; - fd->writingSystems = QPlatformFontDatabase::writingSystemsFromTrueTypeBits(unicodeRange, codePageRange); - } - } - - if (styles) { - if (CFNumberRef weightValue = (CFNumberRef) CFDictionaryGetValue(styles, kCTFontWeightTrait)) { - double normalizedWeight; - if (CFNumberGetValue(weightValue, kCFNumberFloat64Type, &normalizedWeight)) - fd->weight = QCoreTextFontEngine::qtWeightFromCFWeight(float(normalizedWeight)); - } - if (CFNumberRef italic = (CFNumberRef) CFDictionaryGetValue(styles, kCTFontSlantTrait)) { - double d; - if (CFNumberGetValue(italic, kCFNumberDoubleType, &d)) { - if (d > 0.0) - fd->style = QFont::StyleItalic; - } - } - if (CFNumberRef symbolic = (CFNumberRef) CFDictionaryGetValue(styles, kCTFontSymbolicTrait)) { - int d; - if (CFNumberGetValue(symbolic, kCFNumberSInt32Type, &d)) { - if (d & kCTFontMonoSpaceTrait) - fd->fixedPitch = true; - if (d & kCTFontExpandedTrait) - fd->stretch = QFont::Expanded; - else if (d & kCTFontCondensedTrait) - fd->stretch = QFont::Condensed; - } - } - } - - if (QCFType<CFNumberRef> size = (CFNumberRef) CTFontDescriptorCopyAttribute(font, kCTFontSizeAttribute)) { - if (CFNumberIsFloatType(size)) { - double d; - CFNumberGetValue(size, kCFNumberDoubleType, &d); - fd->pointSize = d; - } else { - int i; - CFNumberGetValue(size, kCFNumberIntType, &i); - fd->pointSize = i; - } - } - - if (QCFType<CFArrayRef> languages = (CFArrayRef) CTFontDescriptorCopyAttribute(font, kCTFontLanguagesAttribute)) { - CFIndex length = CFArrayGetCount(languages); - for (int i = 1; i < LanguageCount; ++i) { - if (!languageForWritingSystem[i]) - continue; - QCFString lang = CFStringCreateWithCString(NULL, languageForWritingSystem[i], kCFStringEncodingASCII); - if (CFArrayContainsValue(languages, CFRangeMake(0, length), lang)) - fd->writingSystems.setSupported(QFontDatabase::WritingSystem(i)); - } - } -} - -void QCoreTextFontDatabase::populateFromDescriptor(CTFontDescriptorRef font, const QString &familyName) -{ - FontDescription fd; - getFontDescription(font, &fd); - - // Note: The familyName we are registering, and the family name of the font descriptor, may not - // match, as CTFontDescriptorCreateMatchingFontDescriptors will return descriptors for replacement - // fonts if a font family does not have any fonts available on the system. - QString family = !familyName.isNull() ? familyName : static_cast<QString>(fd.familyName); - - CFRetain(font); - QPlatformFontDatabase::registerFont(family, fd.styleName, fd.foundryName, fd.weight, fd.style, fd.stretch, - true /* antialiased */, true /* scalable */, 0 /* pixelSize, ignored as font is scalable */, - fd.fixedPitch, fd.writingSystems, (void *)font); -} - -static NSString * const kQtFontDataAttribute = @"QtFontDataAttribute"; - -template <typename T> -T *descriptorAttribute(CTFontDescriptorRef descriptor, CFStringRef name) -{ - return [static_cast<T *>(CTFontDescriptorCopyAttribute(descriptor, name)) autorelease]; -} - -void QCoreTextFontDatabase::releaseHandle(void *handle) -{ - CTFontDescriptorRef descriptor = static_cast<CTFontDescriptorRef>(handle); - if (NSValue *fontDataValue = descriptorAttribute<NSValue>(descriptor, (CFStringRef)kQtFontDataAttribute)) { - QByteArray *fontData = static_cast<QByteArray *>(fontDataValue.pointerValue); - delete fontData; - } - CFRelease(descriptor); -} - -extern CGAffineTransform qt_transform_from_fontdef(const QFontDef &fontDef); - -template <> -QFontEngine *QCoreTextFontDatabaseEngineFactory<QCoreTextFontEngine>::fontEngine(const QFontDef &fontDef, void *usrPtr) -{ - QCFType<CTFontDescriptorRef> descriptor = QCFType<CTFontDescriptorRef>::constructFromGet( - static_cast<CTFontDescriptorRef>(usrPtr)); - - // CoreText will sometimes invalidate information in font descriptors that refer - // to system fonts in certain function calls or application states. While the descriptor - // looks the same from the outside, some internal plumbing is different, causing the results - // of creating CTFonts from those descriptors unreliable. The work-around for this - // is to copy the attributes of those descriptors each time we make a new CTFont - // from them instead of referring to the original, as that may trigger the CoreText bug. - if (m_systemFontDescriptors.contains(descriptor)) { - QCFType<CFDictionaryRef> attributes = CTFontDescriptorCopyAttributes(descriptor); - descriptor = CTFontDescriptorCreateWithAttributes(attributes); - } - - // Since we do not pass in the destination DPI to CoreText when making - // the font, we need to pass in a point size which is scaled to include - // the DPI. The default DPI for the screen is 72, thus the scale factor - // is destinationDpi / 72, but since pixelSize = pointSize / 72 * dpi, - // the pixelSize is actually the scaled point size for the destination - // DPI, and we can use that directly. - qreal scaledPointSize = fontDef.pixelSize; - - CGAffineTransform matrix = qt_transform_from_fontdef(fontDef); - if (QCFType<CTFontRef> font = CTFontCreateWithFontDescriptor(descriptor, scaledPointSize, &matrix)) - return new QCoreTextFontEngine(font, fontDef); - - return nullptr; -} - -#ifndef QT_NO_FREETYPE -template <> -QFontEngine *QCoreTextFontDatabaseEngineFactory<QFontEngineFT>::fontEngine(const QFontDef &fontDef, void *usrPtr) -{ - CTFontDescriptorRef descriptor = static_cast<CTFontDescriptorRef>(usrPtr); - - if (NSValue *fontDataValue = descriptorAttribute<NSValue>(descriptor, (CFStringRef)kQtFontDataAttribute)) { - QByteArray *fontData = static_cast<QByteArray *>(fontDataValue.pointerValue); - return QFontEngineFT::create(*fontData, fontDef.pixelSize, - static_cast<QFont::HintingPreference>(fontDef.hintingPreference)); - } else if (NSURL *url = descriptorAttribute<NSURL>(descriptor, kCTFontURLAttribute)) { - Q_ASSERT(url.fileURL); - QFontEngine::FaceId faceId; - faceId.filename = QString::fromNSString(url.path).toUtf8(); - return QFontEngineFT::create(fontDef, faceId); - } - Q_UNREACHABLE(); -} -#endif - -template <class T> -QFontEngine *QCoreTextFontDatabaseEngineFactory<T>::fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference) -{ - return T::create(fontData, pixelSize, hintingPreference); -} - -// Explicitly instantiate so that we don't need the plugin to involve FreeType -template class QCoreTextFontDatabaseEngineFactory<QCoreTextFontEngine>; -#ifndef QT_NO_FREETYPE -template class QCoreTextFontDatabaseEngineFactory<QFontEngineFT>; -#endif - -QFont::StyleHint styleHintFromNSString(NSString *style) -{ - if ([style isEqual: @"sans-serif"]) - return QFont::SansSerif; - else if ([style isEqual: @"monospace"]) - return QFont::Monospace; - else if ([style isEqual: @"cursive"]) - return QFont::Cursive; - else if ([style isEqual: @"serif"]) - return QFont::Serif; - else if ([style isEqual: @"fantasy"]) - return QFont::Fantasy; - else // if ([style isEqual: @"default"]) - return QFont::AnyStyle; -} - -#ifdef Q_OS_OSX -static QString familyNameFromPostScriptName(NSString *psName) -{ - QCFType<CTFontDescriptorRef> fontDescriptor = (CTFontDescriptorRef) CTFontDescriptorCreateWithNameAndSize((CFStringRef)psName, 12.0); - QCFString familyName = (CFStringRef) CTFontDescriptorCopyAttribute(fontDescriptor, kCTFontFamilyNameAttribute); - QString name = QString::fromCFString(familyName); - if (name.isEmpty()) - qWarning() << "QCoreTextFontDatabase: Failed to resolve family name for PostScript name " << QString::fromCFString((CFStringRef)psName); - - return name; -} -#endif - -static void addExtraFallbacks(QStringList *fallbackList) -{ -#if defined(Q_OS_MACOS) - // Since we are only returning a list of default fonts for the current language, we do not - // cover all unicode completely. This was especially an issue for some of the common script - // symbols such as mathematical symbols, currency or geometric shapes. To minimize the risk - // of missing glyphs, we add Arial Unicode MS as a final fail safe, since this covers most - // of Unicode 2.1. - if (!fallbackList->contains(QStringLiteral("Arial Unicode MS"))) - fallbackList->append(QStringLiteral("Arial Unicode MS")); - // Since some symbols (specifically Braille) are not in Arial Unicode MS, we - // add Apple Symbols to cover those too. - if (!fallbackList->contains(QStringLiteral("Apple Symbols"))) - fallbackList->append(QStringLiteral("Apple Symbols")); -#else - Q_UNUSED(fallbackList) -#endif -} - -QStringList QCoreTextFontDatabase::fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const -{ - Q_UNUSED(style); - Q_UNUSED(script); - - QMacAutoReleasePool pool; - - static QHash<QString, QStringList> fallbackLists; - - if (!family.isEmpty()) { - QCFType<CFMutableDictionaryRef> attributes = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, QCFString(family)); - if (QCFType<CTFontDescriptorRef> fontDescriptor = CTFontDescriptorCreateWithAttributes(attributes)) { - if (QCFType<CTFontRef> font = CTFontCreateWithFontDescriptor(fontDescriptor, 12.0, 0)) { - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSArray *languages = [defaults stringArrayForKey: @"AppleLanguages"]; - - QCFType<CFArrayRef> cascadeList = (CFArrayRef) CTFontCopyDefaultCascadeListForLanguages(font, (CFArrayRef) languages); - if (cascadeList) { - QStringList fallbackList; - const int numCascades = CFArrayGetCount(cascadeList); - for (int i = 0; i < numCascades; ++i) { - CTFontDescriptorRef fontFallback = (CTFontDescriptorRef) CFArrayGetValueAtIndex(cascadeList, i); - QCFString fallbackFamilyName = (CFStringRef) CTFontDescriptorCopyAttribute(fontFallback, kCTFontFamilyNameAttribute); - fallbackList.append(QString::fromCFString(fallbackFamilyName)); - } - - addExtraFallbacks(&fallbackList); - extern QStringList qt_sort_families_by_writing_system(QChar::Script, const QStringList &); - fallbackList = qt_sort_families_by_writing_system(script, fallbackList); - - return fallbackList; - } - } - } - } - - // We were not able to find a fallback for the specific family, - // so we fall back to the stylehint. - - static const QString styleLookupKey = QString::fromLatin1(".QFontStyleHint_%1"); - - static bool didPopulateStyleFallbacks = false; - if (!didPopulateStyleFallbacks) { -#if defined(Q_OS_MACX) - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSArray<NSString *> *languages = [defaults stringArrayForKey:@"AppleLanguages"]; - - NSDictionary<NSString *, id> *fallbackDict = [NSDictionary<NSString *, id> dictionaryWithContentsOfFile:@"/System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreText.framework/Resources/DefaultFontFallbacks.plist"]; - - for (NSString *style in [fallbackDict allKeys]) { - NSArray *list = [fallbackDict valueForKey:style]; - QFont::StyleHint fallbackStyleHint = styleHintFromNSString(style); - QStringList fallbackList; - for (id item in list) { - // sort the array based on system language preferences - if ([item isKindOfClass:[NSArray class]]) { - NSArray *langs = [reinterpret_cast<NSArray *>(item) - sortedArrayUsingFunction:languageMapSort context:languages]; - for (NSArray<NSString *> *map in langs) - fallbackList.append(familyNameFromPostScriptName([map objectAtIndex:1])); - } - else if ([item isKindOfClass: [NSString class]]) - fallbackList.append(familyNameFromPostScriptName(item)); - } - - fallbackList.append(QLatin1String("Apple Color Emoji")); - - addExtraFallbacks(&fallbackList); - fallbackLists[styleLookupKey.arg(fallbackStyleHint)] = fallbackList; - } -#else - QStringList staticFallbackList; - staticFallbackList << QString::fromLatin1("Helvetica,Apple Color Emoji,Geeza Pro,Arial Hebrew,Thonburi,Kailasa" - "Hiragino Kaku Gothic ProN,.Heiti J,Apple SD Gothic Neo,.Heiti K,Heiti SC,Heiti TC" - "Bangla Sangam MN,Devanagari Sangam MN,Gujarati Sangam MN,Gurmukhi MN,Kannada Sangam MN" - "Malayalam Sangam MN,Oriya Sangam MN,Sinhala Sangam MN,Tamil Sangam MN,Telugu Sangam MN" - "Euphemia UCAS,.PhoneFallback").split(QLatin1String(",")); - - for (int i = QFont::Helvetica; i <= QFont::Fantasy; ++i) - fallbackLists[styleLookupKey.arg(i)] = staticFallbackList; -#endif - - didPopulateStyleFallbacks = true; - } - - Q_ASSERT(!fallbackLists.isEmpty()); - return fallbackLists[styleLookupKey.arg(styleHint)]; -} - -QStringList QCoreTextFontDatabase::addApplicationFont(const QByteArray &fontData, const QString &fileName) -{ - QCFType<CFArrayRef> fonts; - - if (!fontData.isEmpty()) { - QCFType<CFDataRef> fontDataReference = fontData.toRawCFData(); - if (QCFType<CTFontDescriptorRef> descriptor = CTFontManagerCreateFontDescriptorFromData(fontDataReference)) { - // There's no way to get the data back out of a font descriptor created with - // CTFontManagerCreateFontDescriptorFromData, so we attach the data manually. - NSDictionary *attributes = @{ kQtFontDataAttribute : [NSValue valueWithPointer:new QByteArray(fontData)] }; - descriptor = CTFontDescriptorCreateCopyWithAttributes(descriptor, (CFDictionaryRef)attributes); - CFMutableArrayRef array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - CFArrayAppendValue(array, descriptor); - fonts = array; - } - } else { - QCFType<CFURLRef> fontURL = QUrl::fromLocalFile(fileName).toCFURL(); - fonts = CTFontManagerCreateFontDescriptorsFromURL(fontURL); - } - - if (!fonts) - return QStringList(); - - QStringList families; - const int numFonts = CFArrayGetCount(fonts); - for (int i = 0; i < numFonts; ++i) { - CTFontDescriptorRef fontDescriptor = CTFontDescriptorRef(CFArrayGetValueAtIndex(fonts, i)); - populateFromDescriptor(fontDescriptor); - QCFType<CFStringRef> familyName = CFStringRef(CTFontDescriptorCopyAttribute(fontDescriptor, kCTFontFamilyNameAttribute)); - families.append(QString::fromCFString(familyName)); - } - - // Note: We don't do font matching via CoreText for application fonts, so we don't - // need to enable font matching for them via CTFontManagerEnableFontDescriptors. - - return families; -} - -bool QCoreTextFontDatabase::isPrivateFontFamily(const QString &family) const -{ - if (family.startsWith(QLatin1Char('.')) || family == QLatin1String("LastResort")) - return true; - - return QPlatformFontDatabase::isPrivateFontFamily(family); -} - -static CTFontUIFontType fontTypeFromTheme(QPlatformTheme::Font f) -{ - switch (f) { - case QPlatformTheme::SystemFont: - return kCTFontUIFontSystem; - - case QPlatformTheme::MenuFont: - case QPlatformTheme::MenuBarFont: - case QPlatformTheme::MenuItemFont: - return kCTFontUIFontMenuItem; - - case QPlatformTheme::MessageBoxFont: - return kCTFontUIFontEmphasizedSystem; - - case QPlatformTheme::LabelFont: - return kCTFontUIFontSystem; - - case QPlatformTheme::TipLabelFont: - return kCTFontUIFontToolTip; - - case QPlatformTheme::StatusBarFont: - return kCTFontUIFontSystem; - - case QPlatformTheme::TitleBarFont: - return kCTFontUIFontWindowTitle; - - case QPlatformTheme::MdiSubWindowTitleFont: - return kCTFontUIFontSystem; - - case QPlatformTheme::DockWidgetTitleFont: - return kCTFontUIFontSmallSystem; - - case QPlatformTheme::PushButtonFont: - return kCTFontUIFontPushButton; - - case QPlatformTheme::CheckBoxFont: - case QPlatformTheme::RadioButtonFont: - return kCTFontUIFontSystem; - - case QPlatformTheme::ToolButtonFont: - return kCTFontUIFontSmallToolbar; - - case QPlatformTheme::ItemViewFont: - return kCTFontUIFontSystem; - - case QPlatformTheme::ListViewFont: - return kCTFontUIFontViews; - - case QPlatformTheme::HeaderViewFont: - return kCTFontUIFontSmallSystem; - - case QPlatformTheme::ListBoxFont: - return kCTFontUIFontViews; - - case QPlatformTheme::ComboMenuItemFont: - return kCTFontUIFontSystem; - - case QPlatformTheme::ComboLineEditFont: - return kCTFontUIFontViews; - - case QPlatformTheme::SmallFont: - return kCTFontUIFontSmallSystem; - - case QPlatformTheme::MiniFont: - return kCTFontUIFontMiniSystem; - - case QPlatformTheme::FixedFont: - return kCTFontUIFontUserFixedPitch; - - default: - return kCTFontUIFontSystem; - } -} - -static CTFontDescriptorRef fontDescriptorFromTheme(QPlatformTheme::Font f) -{ -#if defined(QT_PLATFORM_UIKIT) - // Use Dynamic Type to resolve theme fonts if possible, to get - // correct font sizes and style based on user configuration. - NSString *textStyle = 0; - switch (f) { - case QPlatformTheme::TitleBarFont: - case QPlatformTheme::HeaderViewFont: - textStyle = UIFontTextStyleHeadline; - break; - case QPlatformTheme::MdiSubWindowTitleFont: - textStyle = UIFontTextStyleSubheadline; - break; - case QPlatformTheme::TipLabelFont: - case QPlatformTheme::SmallFont: - textStyle = UIFontTextStyleFootnote; - break; - case QPlatformTheme::MiniFont: - textStyle = UIFontTextStyleCaption2; - break; - case QPlatformTheme::FixedFont: - // Fall back to regular code path, as iOS doesn't provide - // an appropriate text style for this theme font. - break; - default: - textStyle = UIFontTextStyleBody; - break; - } - - if (textStyle) { - UIFontDescriptor *desc = [UIFontDescriptor preferredFontDescriptorWithTextStyle:textStyle]; - return static_cast<CTFontDescriptorRef>(CFBridgingRetain(desc)); - } -#endif // Q_OS_IOS, Q_OS_TVOS, Q_OS_WATCHOS - - // OSX default case and iOS fallback case - CTFontUIFontType fontType = fontTypeFromTheme(f); - QCFType<CTFontRef> ctFont = CTFontCreateUIFontForLanguage(fontType, 0.0, NULL); - return CTFontCopyFontDescriptor(ctFont); -} - -const QHash<QPlatformTheme::Font, QFont *> &QCoreTextFontDatabase::themeFonts() const -{ - if (m_themeFonts.isEmpty()) { - for (long f = QPlatformTheme::SystemFont; f < QPlatformTheme::NFonts; f++) { - QPlatformTheme::Font ft = static_cast<QPlatformTheme::Font>(f); - m_themeFonts.insert(ft, themeFont(ft)); - } - } - - return m_themeFonts; -} - -QFont *QCoreTextFontDatabase::themeFont(QPlatformTheme::Font f) const -{ - CTFontDescriptorRef fontDesc = fontDescriptorFromTheme(f); - FontDescription fd; - getFontDescription(fontDesc, &fd); - - if (!m_systemFontDescriptors.contains(fontDesc)) - m_systemFontDescriptors.insert(fontDesc); - else - CFRelease(fontDesc); - - QFont *font = new QFont(fd.familyName, fd.pointSize, fd.weight, fd.style == QFont::StyleItalic); - return font; -} - -QFont QCoreTextFontDatabase::defaultFont() const -{ - if (defaultFontName.isEmpty()) { - QCFType<CTFontRef> font = CTFontCreateUIFontForLanguage(kCTFontUIFontSystem, 12.0, NULL); - defaultFontName = (QString) QCFString(CTFontCopyFullName(font)); - } - - return QFont(defaultFontName); -} - -bool QCoreTextFontDatabase::fontsAlwaysScalable() const -{ - return true; -} - -QList<int> QCoreTextFontDatabase::standardSizes() const -{ - QList<int> ret; - static const unsigned short standard[] = - { 9, 10, 11, 12, 13, 14, 18, 24, 36, 48, 64, 72, 96, 144, 288, 0 }; - ret.reserve(int(sizeof(standard) / sizeof(standard[0]))); - const unsigned short *sizes = standard; - while (*sizes) ret << *sizes++; - return ret; -} - -QT_END_NAMESPACE - diff --git a/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase_p.h b/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase_p.h deleted file mode 100644 index 05f6ed641c..0000000000 --- a/src/platformsupport/fontdatabases/mac/qcoretextfontdatabase_p.h +++ /dev/null @@ -1,115 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QCORETEXTFONTDATABASE_H -#define QCORETEXTFONTDATABASE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <qglobal.h> - -#include <qpa/qplatformfontdatabase.h> -#include <qpa/qplatformtheme.h> -#include <private/qcore_mac_p.h> - -Q_FORWARD_DECLARE_CF_TYPE(CTFontDescriptor); -Q_FORWARD_DECLARE_CF_TYPE(CTFont); - -Q_DECLARE_METATYPE(QCFType<CGFontRef>); -Q_DECLARE_METATYPE(QCFType<CFURLRef>); - -QT_BEGIN_NAMESPACE - -class QCoreTextFontDatabase : public QPlatformFontDatabase -{ -public: - QCoreTextFontDatabase(); - ~QCoreTextFontDatabase(); - void populateFontDatabase() override; - bool populateFamilyAliases() override; - void populateFamily(const QString &familyName) override; - void invalidate() override; - - QStringList fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const override; - QStringList addApplicationFont(const QByteArray &fontData, const QString &fileName) override; - void releaseHandle(void *handle) override; - bool isPrivateFontFamily(const QString &family) const override; - QFont defaultFont() const override; - bool fontsAlwaysScalable() const override; - QList<int> standardSizes() const override; - - // For iOS and OS X platform themes - QFont *themeFont(QPlatformTheme::Font) const; - const QHash<QPlatformTheme::Font, QFont *> &themeFonts() const; - -protected: - mutable QSet<CTFontDescriptorRef> m_systemFontDescriptors; - -private: - void populateFromDescriptor(CTFontDescriptorRef font, const QString &familyName = QString()); - - mutable QString defaultFontName; - - mutable QHash<QPlatformTheme::Font, QFont *> m_themeFonts; - bool m_hasPopulatedAliases; -}; - -// Split out into separate template class so that the compiler doesn't have -// to generate code for each override in QCoreTextFontDatabase for each T. - -template <class T> -class QCoreTextFontDatabaseEngineFactory : public QCoreTextFontDatabase -{ -public: - QFontEngine *fontEngine(const QFontDef &fontDef, void *handle) override; - QFontEngine *fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference) override; -}; - -QT_END_NAMESPACE - -#endif // QCORETEXTFONTDATABASE_H diff --git a/src/platformsupport/fontdatabases/mac/qfontengine_coretext.mm b/src/platformsupport/fontdatabases/mac/qfontengine_coretext.mm deleted file mode 100644 index 072dd1a28a..0000000000 --- a/src/platformsupport/fontdatabases/mac/qfontengine_coretext.mm +++ /dev/null @@ -1,1055 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qfontengine_coretext_p.h" - -#include <qpa/qplatformfontdatabase.h> -#include <QtCore/qendian.h> -#if QT_CONFIG(settings) -#include <QtCore/qsettings.h> -#endif -#include <QtCore/qoperatingsystemversion.h> -#include <private/qcoregraphics_p.h> -#include <private/qimage_p.h> - -#include <cmath> - -#if defined(Q_OS_MACOS) -#import <AppKit/AppKit.h> -#endif - -#if defined(QT_PLATFORM_UIKIT) -#import <UIKit/UIKit.h> -#endif - -// These are available cross platform, exported as kCTFontWeightXXX from CoreText.framework, -// but they are not documented and are not in public headers so are private API and exposed -// only through the NSFontWeightXXX and UIFontWeightXXX aliases in AppKit and UIKit (rdar://26109857) -#if defined(Q_OS_MACOS) -#define kCTFontWeightUltraLight NSFontWeightUltraLight -#define kCTFontWeightThin NSFontWeightThin -#define kCTFontWeightLight NSFontWeightLight -#define kCTFontWeightRegular NSFontWeightRegular -#define kCTFontWeightMedium NSFontWeightMedium -#define kCTFontWeightSemibold NSFontWeightSemibold -#define kCTFontWeightBold NSFontWeightBold -#define kCTFontWeightHeavy NSFontWeightHeavy -#define kCTFontWeightBlack NSFontWeightBlack -#elif defined(QT_PLATFORM_UIKIT) -#define kCTFontWeightUltraLight UIFontWeightUltraLight -#define kCTFontWeightThin UIFontWeightThin -#define kCTFontWeightLight UIFontWeightLight -#define kCTFontWeightRegular UIFontWeightRegular -#define kCTFontWeightMedium UIFontWeightMedium -#define kCTFontWeightSemibold UIFontWeightSemibold -#define kCTFontWeightBold UIFontWeightBold -#define kCTFontWeightHeavy UIFontWeightHeavy -#define kCTFontWeightBlack UIFontWeightBlack -#endif - -QT_BEGIN_NAMESPACE - -Q_LOGGING_CATEGORY(lcQpaFonts, "qt.qpa.fonts") - -static float SYNTHETIC_ITALIC_SKEW = std::tan(14.f * std::acos(0.f) / 90.f); - -bool QCoreTextFontEngine::ct_getSfntTable(void *user_data, uint tag, uchar *buffer, uint *length) -{ - CTFontRef ctfont = *(CTFontRef *)user_data; - - QCFType<CFDataRef> table = CTFontCopyTable(ctfont, tag, 0); - if (!table) - return false; - - CFIndex tableLength = CFDataGetLength(table); - if (buffer && int(*length) >= tableLength) - CFDataGetBytes(table, CFRangeMake(0, tableLength), buffer); - *length = tableLength; - Q_ASSERT(int(*length) > 0); - return true; -} - -QFont::Weight QCoreTextFontEngine::qtWeightFromCFWeight(float value) -{ -#define COMPARE_WEIGHT_DISTANCE(ct_weight, qt_weight) \ - { \ - float d; \ - if ((d = qAbs(value - ct_weight)) < distance) { \ - distance = d; \ - ret = qt_weight; \ - } \ - } - - float distance = qAbs(value - kCTFontWeightBlack); - QFont::Weight ret = QFont::Black; - - // Compare distance to system weight to find the closest match. - // (Note: Must go from high to low, so that midpoints are rounded up) - COMPARE_WEIGHT_DISTANCE(kCTFontWeightHeavy, QFont::ExtraBold); - COMPARE_WEIGHT_DISTANCE(kCTFontWeightBold, QFont::Bold); - COMPARE_WEIGHT_DISTANCE(kCTFontWeightSemibold, QFont::DemiBold); - COMPARE_WEIGHT_DISTANCE(kCTFontWeightMedium, QFont::Medium); - COMPARE_WEIGHT_DISTANCE(kCTFontWeightRegular, QFont::Normal); - COMPARE_WEIGHT_DISTANCE(kCTFontWeightLight, QFont::Light); - COMPARE_WEIGHT_DISTANCE(kCTFontWeightThin, QFont::ExtraLight); - COMPARE_WEIGHT_DISTANCE(kCTFontWeightUltraLight, QFont::Thin); - -#undef COMPARE_WEIGHT_DISTANCE - - return ret; -} - -CGAffineTransform qt_transform_from_fontdef(const QFontDef &fontDef) -{ - CGAffineTransform transform = CGAffineTransformIdentity; - if (fontDef.stretch && fontDef.stretch != 100) - transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1); - return transform; -} - -// Keeps font data alive until engine is disposed -class QCoreTextRawFontEngine : public QCoreTextFontEngine -{ -public: - QCoreTextRawFontEngine(CGFontRef font, const QFontDef &def, const QByteArray &fontData) - : QCoreTextFontEngine(font, def) - , m_fontData(fontData) - {} - QFontEngine *cloneWithSize(qreal pixelSize) const - { - QFontDef newFontDef = fontDef; - newFontDef.pixelSize = pixelSize; - newFontDef.pointSize = pixelSize * 72.0 / qt_defaultDpi(); - - return new QCoreTextRawFontEngine(cgFont, newFontDef, m_fontData); - } - QByteArray m_fontData; -}; - -QCoreTextFontEngine *QCoreTextFontEngine::create(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference) -{ - Q_UNUSED(hintingPreference); - - QCFType<CFDataRef> fontDataReference = fontData.toRawCFData(); - QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithCFData(fontDataReference); - - // Note: CTFontCreateWithGraphicsFont (which we call from the QCoreTextFontEngine - // constructor) has a bug causing it to retain the CGFontRef but never release it. - // The result is that we are leaking the CGFont, CGDataProvider, and CGData, but - // as the CGData is created from the raw QByteArray data, which we deref in the - // subclass above during destruction, we're at least not leaking the font data, - // (unless CoreText copies it internally). http://stackoverflow.com/questions/40805382/ - QCFType<CGFontRef> cgFont = CGFontCreateWithDataProvider(dataProvider); - - if (!cgFont) { - qWarning("QCoreTextFontEngine::create: CGFontCreateWithDataProvider failed"); - return nullptr; - } - - QFontDef def; - def.pixelSize = pixelSize; - def.pointSize = pixelSize * 72.0 / qt_defaultDpi(); - return new QCoreTextRawFontEngine(cgFont, def, fontData); -} - -QCoreTextFontEngine::QCoreTextFontEngine(CTFontRef font, const QFontDef &def) - : QCoreTextFontEngine(def) -{ - ctfont = QCFType<CTFontRef>::constructFromGet(font); - cgFont = CTFontCopyGraphicsFont(font, nullptr); - init(); -} - -QCoreTextFontEngine::QCoreTextFontEngine(CGFontRef font, const QFontDef &def) - : QCoreTextFontEngine(def) -{ - cgFont = QCFType<CGFontRef>::constructFromGet(font); - ctfont = CTFontCreateWithGraphicsFont(font, fontDef.pixelSize, &transform, nullptr); - init(); -} - -QCoreTextFontEngine::QCoreTextFontEngine(const QFontDef &def) - : QFontEngine(Mac) -{ - fontDef = def; - transform = qt_transform_from_fontdef(fontDef); -} - -QCoreTextFontEngine::~QCoreTextFontEngine() -{ -} - -void QCoreTextFontEngine::init() -{ - Q_ASSERT(ctfont); - Q_ASSERT(cgFont); - - face_id.index = 0; - QCFString name = CTFontCopyName(ctfont, kCTFontUniqueNameKey); - face_id.filename = QString::fromCFString(name).toUtf8(); - - QCFString family = CTFontCopyFamilyName(ctfont); - fontDef.family = family; - - QCFString styleName = (CFStringRef) CTFontCopyAttribute(ctfont, kCTFontStyleNameAttribute); - fontDef.styleName = styleName; - - synthesisFlags = 0; - CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(ctfont); - - if (traits & kCTFontColorGlyphsTrait) - glyphFormat = QFontEngine::Format_ARGB; - else if (shouldSmoothFont() && fontSmoothing() == FontSmoothing::Subpixel) - glyphFormat = QFontEngine::Format_A32; - else - glyphFormat = QFontEngine::Format_A8; - - if (traits & kCTFontItalicTrait) - fontDef.style = QFont::StyleItalic; - - static const auto getTraitValue = [](CFDictionaryRef allTraits, CFStringRef trait) -> float { - if (CFDictionaryContainsKey(allTraits, trait)) { - CFNumberRef traitNum = (CFNumberRef) CFDictionaryGetValue(allTraits, trait); - float v = 0; - CFNumberGetValue(traitNum, kCFNumberFloatType, &v); - return v; - } - return 0; - }; - - QCFType<CFDictionaryRef> allTraits = CTFontCopyTraits(ctfont); - fontDef.weight = QCoreTextFontEngine::qtWeightFromCFWeight(getTraitValue(allTraits, kCTFontWeightTrait)); - int slant = static_cast<int>(getTraitValue(allTraits, kCTFontSlantTrait) * 500 + 500); - if (slant > 500 && !(traits & kCTFontItalicTrait)) - fontDef.style = QFont::StyleOblique; - - if (fontDef.weight >= QFont::Bold && !(traits & kCTFontBoldTrait)) - synthesisFlags |= SynthesizedBold; - // XXX: we probably don't need to synthesis italic for oblique font - if (fontDef.style != QFont::StyleNormal && !(traits & kCTFontItalicTrait)) - synthesisFlags |= SynthesizedItalic; - - avgCharWidth = 0; - QByteArray os2Table = getSfntTable(MAKE_TAG('O', 'S', '/', '2')); - unsigned emSize = CTFontGetUnitsPerEm(ctfont); - if (os2Table.size() >= 10) { - fsType = qFromBigEndian<quint16>(os2Table.constData() + 8); - // qAbs is a workaround for weird fonts like Lucida Grande - qint16 width = qAbs(qFromBigEndian<qint16>(os2Table.constData() + 2)); - avgCharWidth = QFixed::fromReal(width * fontDef.pixelSize / emSize); - } else - avgCharWidth = QFontEngine::averageCharWidth(); - - underlineThickness = QFixed::fromReal(CTFontGetUnderlineThickness(ctfont)); - underlinePos = -QFixed::fromReal(CTFontGetUnderlinePosition(ctfont)); - - cache_cost = (CTFontGetAscent(ctfont) + CTFontGetDescent(ctfont)) * avgCharWidth.toInt() * 2000; - - // HACK hb_coretext requires both CTFont and CGFont but user_data is only void* - Q_ASSERT((void *)(&ctfont + 1) == (void *)&cgFont); - faceData.user_data = &ctfont; - faceData.get_font_table = ct_getSfntTable; - - kerningPairsLoaded = false; -} - -glyph_t QCoreTextFontEngine::glyphIndex(uint ucs4) const -{ - int len = 0; - - QChar str[2]; - if (Q_UNLIKELY(QChar::requiresSurrogates(ucs4))) { - str[len++] = QChar(QChar::highSurrogate(ucs4)); - str[len++] = QChar(QChar::lowSurrogate(ucs4)); - } else { - str[len++] = QChar(ucs4); - } - - CGGlyph glyphIndices[2]; - - CTFontGetGlyphsForCharacters(ctfont, (const UniChar *)str, glyphIndices, len); - - return glyphIndices[0]; -} - -bool QCoreTextFontEngine::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, - int *nglyphs, QFontEngine::ShaperFlags flags) const -{ - Q_ASSERT(glyphs->numGlyphs >= *nglyphs); - if (*nglyphs < len) { - *nglyphs = len; - return false; - } - - QVarLengthArray<CGGlyph> cgGlyphs(len); - CTFontGetGlyphsForCharacters(ctfont, (const UniChar*)str, cgGlyphs.data(), len); - - int glyph_pos = 0; - for (int i = 0; i < len; ++i) { - glyphs->glyphs[glyph_pos] = cgGlyphs[i]; - if (glyph_pos < i) - cgGlyphs[glyph_pos] = cgGlyphs[i]; - glyph_pos++; - - // If it's a non-BMP char, skip the lower part of surrogate pair and go - // directly to the next char without increasing glyph_pos - if (str[i].isHighSurrogate() && i < len-1 && str[i+1].isLowSurrogate()) - ++i; - } - - *nglyphs = glyph_pos; - glyphs->numGlyphs = glyph_pos; - - if (!(flags & GlyphIndicesOnly)) - loadAdvancesForGlyphs(cgGlyphs, glyphs); - - return true; -} - -glyph_metrics_t QCoreTextFontEngine::boundingBox(const QGlyphLayout &glyphs) -{ - QFixed w; - bool round = fontDef.styleStrategy & QFont::ForceIntegerMetrics; - - for (int i = 0; i < glyphs.numGlyphs; ++i) { - w += round ? glyphs.effectiveAdvance(i).round() - : glyphs.effectiveAdvance(i); - } - return glyph_metrics_t(0, -(ascent()), w - lastRightBearing(glyphs, round), ascent()+descent(), w, 0); -} - -glyph_metrics_t QCoreTextFontEngine::boundingBox(glyph_t glyph) -{ - glyph_metrics_t ret; - CGGlyph g = glyph; - CGRect rect = CTFontGetBoundingRectsForGlyphs(ctfont, kCTFontOrientationHorizontal, &g, 0, 1); - if (synthesisFlags & QFontEngine::SynthesizedItalic) { - rect.size.width += rect.size.height * SYNTHETIC_ITALIC_SKEW; - } - ret.width = QFixed::fromReal(rect.size.width); - ret.height = QFixed::fromReal(rect.size.height); - ret.x = QFixed::fromReal(rect.origin.x); - ret.y = -QFixed::fromReal(rect.origin.y) - ret.height; - CGSize advances[1]; - CTFontGetAdvancesForGlyphs(ctfont, kCTFontOrientationHorizontal, &g, advances, 1); - ret.xoff = QFixed::fromReal(advances[0].width); - ret.yoff = QFixed::fromReal(advances[0].height); - - if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) { - ret.xoff = ret.xoff.round(); - ret.yoff = ret.yoff.round(); - } - - return ret; -} - -QFixed QCoreTextFontEngine::ascent() const -{ - return (fontDef.styleStrategy & QFont::ForceIntegerMetrics) - ? QFixed::fromReal(CTFontGetAscent(ctfont)).round() - : QFixed::fromReal(CTFontGetAscent(ctfont)); -} - -QFixed QCoreTextFontEngine::capHeight() const -{ - QFixed c = QFixed::fromReal(CTFontGetCapHeight(ctfont)); - if (c <= 0) - return calculatedCapHeight(); - - if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) - c = c.round(); - - return c; -} - -QFixed QCoreTextFontEngine::descent() const -{ - QFixed d = QFixed::fromReal(CTFontGetDescent(ctfont)); - if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) - d = d.round(); - - return d; -} -QFixed QCoreTextFontEngine::leading() const -{ - return (fontDef.styleStrategy & QFont::ForceIntegerMetrics) - ? QFixed::fromReal(CTFontGetLeading(ctfont)).round() - : QFixed::fromReal(CTFontGetLeading(ctfont)); -} -QFixed QCoreTextFontEngine::xHeight() const -{ - return (fontDef.styleStrategy & QFont::ForceIntegerMetrics) - ? QFixed::fromReal(CTFontGetXHeight(ctfont)).round() - : QFixed::fromReal(CTFontGetXHeight(ctfont)); -} - -QFixed QCoreTextFontEngine::averageCharWidth() const -{ - return (fontDef.styleStrategy & QFont::ForceIntegerMetrics) - ? avgCharWidth.round() : avgCharWidth; -} - -qreal QCoreTextFontEngine::maxCharWidth() const -{ - // ### FIXME: 'W' might not be the widest character, but this is better than nothing - const glyph_t glyph = glyphIndex('W'); - glyph_metrics_t bb = const_cast<QCoreTextFontEngine *>(this)->boundingBox(glyph); - return bb.xoff.toReal(); -} - -bool QCoreTextFontEngine::hasColorGlyphs() const -{ - return glyphFormat == QFontEngine::Format_ARGB; -} - -void QCoreTextFontEngine::draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight) -{ - QVarLengthArray<QFixedPoint> positions; - QVarLengthArray<glyph_t> glyphs; - QTransform matrix; - matrix.translate(x, y); - getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions); - if (glyphs.size() == 0) - return; - - CGContextSetFontSize(ctx, fontDef.pixelSize); - - CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx); - - CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, -1, 0, -paintDeviceHeight); - - CGAffineTransformConcat(cgMatrix, oldTextMatrix); - - if (synthesisFlags & QFontEngine::SynthesizedItalic) - cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -SYNTHETIC_ITALIC_SKEW, 1, 0, 0)); - - cgMatrix = CGAffineTransformConcat(cgMatrix, transform); - - CGContextSetTextMatrix(ctx, cgMatrix); - - CGContextSetTextDrawingMode(ctx, kCGTextFill); - - QVarLengthArray<CGPoint> cgPositions(glyphs.size()); - QVarLengthArray<CGGlyph> cgGlyphs(glyphs.size()); - const qreal firstX = positions[0].x.toReal(); - const qreal firstY = positions[0].y.toReal(); - for (int i = 0; i < glyphs.size(); ++i) { - cgPositions[i].x = positions[i].x.toReal() - firstX; - cgPositions[i].y = positions[i].y.toReal() - firstY; - cgGlyphs[i] = glyphs[i]; - } - - //NSLog(@"Font inDraw %@ ctfont %@", CGFontCopyFullName(cgFont), CTFontCopyFamilyName(ctfont)); - - CGContextSetTextPosition(ctx, positions[0].x.toReal(), positions[0].y.toReal()); - CTFontDrawGlyphs(ctfont, cgGlyphs.data(), cgPositions.data(), glyphs.size(), ctx); - - if (synthesisFlags & QFontEngine::SynthesizedBold) { - CGContextSetTextPosition(ctx, positions[0].x.toReal() + 0.5 * lineThickness().toReal(), - positions[0].y.toReal()); - CTFontDrawGlyphs(ctfont, cgGlyphs.data(), cgPositions.data(), glyphs.size(), ctx); - } - - CGContextSetTextMatrix(ctx, oldTextMatrix); -} - -struct ConvertPathInfo -{ - ConvertPathInfo(QPainterPath *newPath, const QPointF &newPos, qreal newStretch = 1.0) : - path(newPath), pos(newPos), stretch(newStretch) {} - QPainterPath *path; - QPointF pos; - qreal stretch; -}; - -static void convertCGPathToQPainterPath(void *info, const CGPathElement *element) -{ - ConvertPathInfo *myInfo = static_cast<ConvertPathInfo *>(info); - switch(element->type) { - case kCGPathElementMoveToPoint: - myInfo->path->moveTo((element->points[0].x * myInfo->stretch) + myInfo->pos.x(), - element->points[0].y + myInfo->pos.y()); - break; - case kCGPathElementAddLineToPoint: - myInfo->path->lineTo((element->points[0].x * myInfo->stretch) + myInfo->pos.x(), - element->points[0].y + myInfo->pos.y()); - break; - case kCGPathElementAddQuadCurveToPoint: - myInfo->path->quadTo((element->points[0].x * myInfo->stretch) + myInfo->pos.x(), - element->points[0].y + myInfo->pos.y(), - (element->points[1].x * myInfo->stretch) + myInfo->pos.x(), - element->points[1].y + myInfo->pos.y()); - break; - case kCGPathElementAddCurveToPoint: - myInfo->path->cubicTo((element->points[0].x * myInfo->stretch) + myInfo->pos.x(), - element->points[0].y + myInfo->pos.y(), - (element->points[1].x * myInfo->stretch) + myInfo->pos.x(), - element->points[1].y + myInfo->pos.y(), - (element->points[2].x * myInfo->stretch) + myInfo->pos.x(), - element->points[2].y + myInfo->pos.y()); - break; - case kCGPathElementCloseSubpath: - myInfo->path->closeSubpath(); - break; - default: - qCWarning(lcQpaFonts) << "Unhandled path transform type: " << element->type; - } - -} - -void QCoreTextFontEngine::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nGlyphs, - QPainterPath *path, QTextItem::RenderFlags) -{ - if (hasColorGlyphs()) - return; // We can't convert color-glyphs to path - - CGAffineTransform cgMatrix = CGAffineTransformIdentity; - cgMatrix = CGAffineTransformScale(cgMatrix, 1, -1); - - if (synthesisFlags & QFontEngine::SynthesizedItalic) - cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -SYNTHETIC_ITALIC_SKEW, 1, 0, 0)); - - qreal stretch = fontDef.stretch ? qreal(fontDef.stretch) / 100 : 1.0; - for (int i = 0; i < nGlyphs; ++i) { - QCFType<CGPathRef> cgpath = CTFontCreatePathForGlyph(ctfont, glyphs[i], &cgMatrix); - ConvertPathInfo info(path, positions[i].toPointF(), stretch); - CGPathApply(cgpath, &info, convertCGPathToQPainterPath); - } -} - -static void qcoretextfontengine_scaleMetrics(glyph_metrics_t &br, const QTransform &matrix) -{ - if (matrix.isScaling()) { - qreal hscale = matrix.m11(); - qreal vscale = matrix.m22(); - br.width = QFixed::fromReal(br.width.toReal() * hscale); - br.height = QFixed::fromReal(br.height.toReal() * vscale); - br.x = QFixed::fromReal(br.x.toReal() * hscale); - br.y = QFixed::fromReal(br.y.toReal() * vscale); - } -} - -glyph_metrics_t QCoreTextFontEngine::alphaMapBoundingBox(glyph_t glyph, QFixed subPixelPosition, const QTransform &matrix, GlyphFormat format) -{ - if (matrix.type() > QTransform::TxScale) - return QFontEngine::alphaMapBoundingBox(glyph, subPixelPosition, matrix, format); - - glyph_metrics_t br = boundingBox(glyph); - qcoretextfontengine_scaleMetrics(br, matrix); - - // Normalize width and height - if (br.width < 0) - br.width = -br.width; - if (br.height < 0) - br.height = -br.height; - - if (format == QFontEngine::Format_A8 || format == QFontEngine::Format_A32) { - // Drawing a glyph at x-position 0 with anti-aliasing enabled - // will potentially fill the pixel to the left of 0, as the - // coordinates are not aligned to the center of pixels. To - // prevent clipping of this pixel we need to shift the glyph - // in the bitmap one pixel to the right. The shift needs to - // be reflected in the glyph metrics as well, so that the final - // position of the glyph is correct, which is why doing the - // shift in imageForGlyph() is not enough. - br.x -= 1; - - // As we've shifted the glyph one pixel to the right, we need - // to expand the width of the alpha map bounding box as well. - br.width += 1; - - // But we have the same anti-aliasing problem on the right - // hand side of the glyph, eg. if the width of the glyph - // results in the bounding rect landing between two pixels. - // We pad the bounding rect again to account for the possible - // anti-aliased drawing. - br.width += 1; - - // We also shift the glyph to right right based on the subpixel - // position, so we pad the bounding box to take account for the - // subpixel positions that may result in the glyph being drawn - // one pixel to the right of the 0-subpixel position. - br.width += 1; - - // The same same logic as for the x-position needs to be applied - // to the y-position, except we don't need to compensate for - // the subpixel positioning. - br.y -= 1; - br.height += 2; - } - - return br; -} - -/* - Apple has gone through many iterations of its font smoothing algorithms, - and there are many ways to enable or disable certain aspects of it. As - keeping up with all the different toggles and behavior differences between - macOS versions is tricky, we resort to rendering a single glyph in a few - configurations, picking up the font smoothing algorithm from the observed - result. - - The possible values are: - - - Disabled: No font smoothing is applied. - - Possibly triggered by the user unchecking the "Use font smoothing when - available" checkbox in the system preferences or setting AppleFontSmoothing - to 0. Also controlled by the CGContextSetAllowsFontSmoothing() API, - which gets its default from the settings above. This API overrides - the more granular CGContextSetShouldSmoothFonts(), which we use to - enable (request) or disable font smoothing. - - Note that this does not exclude normal antialiasing, controlled by - the CGContextSetShouldAntialias() API. - - - Subpixel: Font smoothing is applied, and affects subpixels. - - This was the default mode on macOS versions prior to 10.14 (Mojave). - The font dilation (stem darkening) parameters were controlled by the - AppleFontSmoothing setting, ranging from 1 to 3 (light to strong). - - On Mojave it is no longer supported, but can be triggered by a legacy - override (CGFontRenderingFontSmoothingDisabled=NO), so we need to - still account for it, otherwise users will have a bad time. - - - Grayscale: Font smoothing is applied, but does not affect subpixels. - - This is the default mode on macOS 10.14 (Mojave). The font dilation - (stem darkening) parameters are not affected by the AppleFontSmoothing - setting, but are instead computed based on the fill color used when - drawing the glyphs (white fill gives a lighter dilation than black - fill). This affects how we build our glyph cache, since we produce - alpha maps by drawing white on black. -*/ -QCoreTextFontEngine::FontSmoothing QCoreTextFontEngine::fontSmoothing() -{ - static const FontSmoothing cachedFontSmoothing = [] { - static const int kSize = 10; - QCFType<CTFontRef> font = CTFontCreateWithName(CFSTR("Helvetica"), kSize, nullptr); - - UniChar character('X'); CGGlyph glyph; - CTFontGetGlyphsForCharacters(font, &character, &glyph, 1); - - auto drawGlyph = [&](bool smooth) -> QImage { - QImage image(kSize, kSize, QImage::Format_RGB32); - image.fill(0); - - QMacCGContext ctx(&image); - CGContextSetTextDrawingMode(ctx, kCGTextFill); - CGContextSetGrayFillColor(ctx, 1, 1); - - // Will be ignored if CGContextSetAllowsFontSmoothing() has been - // set to false by CoreGraphics based on user defaults. - CGContextSetShouldSmoothFonts(ctx, smooth); - - CTFontDrawGlyphs(font, &glyph, &CGPointZero, 1, ctx); - return image; - }; - - QImage nonSmoothed = drawGlyph(false); - QImage smoothed = drawGlyph(true); - - FontSmoothing fontSmoothing = FontSmoothing::Disabled; - [&] { - for (int x = 0; x < kSize; ++x) { - for (int y = 0; y < kSize; ++y) { - QRgb sp = smoothed.pixel(x, y); - if (qRed(sp) != qGreen(sp) || qRed(sp) != qBlue(sp)) { - fontSmoothing = FontSmoothing::Subpixel; - return; - } - - if (sp != nonSmoothed.pixel(x, y)) - fontSmoothing = FontSmoothing::Grayscale; - } - } - }(); - - auto defaults = [NSUserDefaults standardUserDefaults]; - qCDebug(lcQpaFonts) << "Resolved font smoothing algorithm. Defaults =" - << [[defaults dictionaryRepresentation] dictionaryWithValuesForKeys:@[ - @"AppleFontSmoothing", - @"CGFontRenderingFontSmoothingDisabled" - ]] << "Result =" << fontSmoothing; - - return fontSmoothing; - }(); - - return cachedFontSmoothing; -} - -bool QCoreTextFontEngine::shouldAntialias() const -{ - return !(fontDef.styleStrategy & QFont::NoAntialias); -} - -bool QCoreTextFontEngine::shouldSmoothFont() const -{ - if (hasColorGlyphs()) - return false; - - if (!shouldAntialias()) - return false; - - switch (fontSmoothing()) { - case Disabled: return false; - case Subpixel: return !(fontDef.styleStrategy & QFont::NoSubpixelAntialias); - case Grayscale: return true; - } - - Q_UNREACHABLE(); -} - -bool QCoreTextFontEngine::expectsGammaCorrectedBlending() const -{ - return shouldSmoothFont() && fontSmoothing() == Subpixel; -} - -qreal QCoreTextFontEngine::fontSmoothingGamma() -{ - return 2.0; -} - -QImage QCoreTextFontEngine::imageForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &matrix, const QColor &color) -{ - glyph_metrics_t br = alphaMapBoundingBox(glyph, subPixelPosition, matrix, glyphFormat); - - QImage::Format imageFormat = hasColorGlyphs() ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32; - QImage im(br.width.ceil().toInt(), br.height.ceil().toInt(), imageFormat); - if (!im.width() || !im.height()) - return im; - - QCFType<CGColorSpaceRef> colorspace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); - QCFType<CGContextRef> ctx = CGBitmapContextCreate(im.bits(), im.width(), im.height(), - 8, im.bytesPerLine(), colorspace, - qt_mac_bitmapInfoForImage(im)); - Q_ASSERT(ctx); - - CGContextSetShouldAntialias(ctx, shouldAntialias()); - - const bool shouldSmooth = shouldSmoothFont(); - CGContextSetShouldSmoothFonts(ctx, shouldSmooth); - -#if defined(Q_OS_MACOS) - auto glyphColor = [&] { - if (shouldSmooth && fontSmoothing() == Grayscale) { - // The grayscale font smoothing algorithm introduced in macOS Mojave (10.14) adjusts - // its dilation (stem darkening) parameters based on the fill color. This means our - // default approach of drawing white on black to produce the alpha map will result - // in non-native looking text when then drawn as black on white during the final blit. - // As a workaround we use the application's current appearance to decide whether to - // draw with white or black fill, and then invert the glyph image in the latter case, - // producing an alpha map. This covers the most common use-cases, but longer term we - // should propagate the fill color all the way from the paint engine, and include it - //in the key for the glyph cache. - - if (!qt_mac_applicationIsInDarkMode()) - return kCGColorBlack; - } - return kCGColorWhite; - }(); - - const bool blackOnWhiteGlyphs = glyphColor == kCGColorBlack; - if (blackOnWhiteGlyphs) - im.fill(Qt::white); - else -#endif - im.fill(0); - - CGContextSetFontSize(ctx, fontDef.pixelSize); - - CGAffineTransform cgMatrix = CGAffineTransformIdentity; - - if (synthesisFlags & QFontEngine::SynthesizedItalic) - cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, SYNTHETIC_ITALIC_SKEW, 1, 0, 0)); - - if (!hasColorGlyphs()) // CTFontDrawGlyphs incorporates the font's matrix already - cgMatrix = CGAffineTransformConcat(cgMatrix, transform); - - if (matrix.isScaling()) - cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMakeScale(matrix.m11(), matrix.m22())); - - CGGlyph cgGlyph = glyph; - qreal pos_x = -br.x.truncate() + subPixelPosition.toReal(); - qreal pos_y = im.height() + br.y.toReal(); - - if (!hasColorGlyphs()) { - CGContextSetTextMatrix(ctx, cgMatrix); -#if defined(Q_OS_MACOS) - CGContextSetFillColorWithColor(ctx, CGColorGetConstantColor(glyphColor)); -#else - CGContextSetRGBFillColor(ctx, 1, 1, 1, 1); -#endif - CGContextSetTextDrawingMode(ctx, kCGTextFill); - CGContextSetTextPosition(ctx, pos_x, pos_y); - - CTFontDrawGlyphs(ctfont, &cgGlyph, &CGPointZero, 1, ctx); - - if (synthesisFlags & QFontEngine::SynthesizedBold) { - CGContextSetTextPosition(ctx, pos_x + 0.5 * lineThickness().toReal(), pos_y); - CTFontDrawGlyphs(ctfont, &cgGlyph, &CGPointZero, 1, ctx); - } - } else { - CGContextSetRGBFillColor(ctx, color.redF(), color.greenF(), color.blueF(), color.alphaF()); - - // CGContextSetTextMatrix does not work with color glyphs, so we use - // the CTM instead. This means we must translate the CTM as well, to - // set the glyph position, instead of using CGContextSetTextPosition. - CGContextTranslateCTM(ctx, pos_x, pos_y); - CGContextConcatCTM(ctx, cgMatrix); - - // CGContextShowGlyphsWithAdvances does not support the 'sbix' color-bitmap - // glyphs in the Apple Color Emoji font, so we use CTFontDrawGlyphs instead. - CTFontDrawGlyphs(ctfont, &cgGlyph, &CGPointZero, 1, ctx); - } - - if (expectsGammaCorrectedBlending()) - qGamma_correct_back_to_linear_cs(&im); - -#if defined(Q_OS_MACOS) - if (blackOnWhiteGlyphs) - im.invertPixels(); -#endif - - return im; -} - -QImage QCoreTextFontEngine::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition) -{ - return alphaMapForGlyph(glyph, subPixelPosition, QTransform()); -} - -QImage QCoreTextFontEngine::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &x) -{ - if (x.type() > QTransform::TxScale) - return QFontEngine::alphaMapForGlyph(glyph, subPixelPosition, x); - - QImage im = imageForGlyph(glyph, subPixelPosition, x); - - QImage alphaMap(im.width(), im.height(), QImage::Format_Alpha8); - - for (int y=0; y<im.height(); ++y) { - uint *src = (uint*) im.scanLine(y); - uchar *dst = alphaMap.scanLine(y); - for (int x=0; x<im.width(); ++x) { - *dst = qGray(*src); - ++dst; - ++src; - } - } - - return alphaMap; -} - -QImage QCoreTextFontEngine::alphaRGBMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &x) -{ - if (x.type() > QTransform::TxScale) - return QFontEngine::alphaRGBMapForGlyph(glyph, subPixelPosition, x); - - return imageForGlyph(glyph, subPixelPosition, x); -} - -QImage QCoreTextFontEngine::bitmapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t, const QColor &color) -{ - if (t.type() > QTransform::TxScale) - return QFontEngine::bitmapForGlyph(glyph, subPixelPosition, t, color); - - return imageForGlyph(glyph, subPixelPosition, t, color); -} - -void QCoreTextFontEngine::recalcAdvances(QGlyphLayout *glyphs, QFontEngine::ShaperFlags flags) const -{ - Q_UNUSED(flags); - - const int numGlyphs = glyphs->numGlyphs; - QVarLengthArray<CGGlyph> cgGlyphs(numGlyphs); - - for (int i = 0; i < numGlyphs; ++i) { - Q_ASSERT(!QFontEngineMulti::highByte(glyphs->glyphs[i])); - cgGlyphs[i] = glyphs->glyphs[i]; - } - - loadAdvancesForGlyphs(cgGlyphs, glyphs); -} - -void QCoreTextFontEngine::loadAdvancesForGlyphs(QVarLengthArray<CGGlyph> &cgGlyphs, QGlyphLayout *glyphs) const -{ - const int numGlyphs = glyphs->numGlyphs; - QVarLengthArray<CGSize> advances(numGlyphs); - CTFontGetAdvancesForGlyphs(ctfont, kCTFontOrientationHorizontal, cgGlyphs.data(), advances.data(), numGlyphs); - - for (int i = 0; i < numGlyphs; ++i) { - QFixed advance = QFixed::fromReal(advances[i].width); - glyphs->advances[i] = fontDef.styleStrategy & QFont::ForceIntegerMetrics - ? advance.round() : advance; - } -} - -QFontEngine::FaceId QCoreTextFontEngine::faceId() const -{ - return face_id; -} - -bool QCoreTextFontEngine::canRender(const QChar *string, int len) const -{ - QVarLengthArray<CGGlyph> cgGlyphs(len); - return CTFontGetGlyphsForCharacters(ctfont, (const UniChar *) string, cgGlyphs.data(), len); -} - -bool QCoreTextFontEngine::getSfntTableData(uint tag, uchar *buffer, uint *length) const -{ - return ct_getSfntTable((void *)&ctfont, tag, buffer, length); -} - -void QCoreTextFontEngine::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metric) -{ - CGAffineTransform cgMatrix = CGAffineTransformIdentity; - - qreal emSquare = CTFontGetUnitsPerEm(ctfont); - qreal scale = emSquare / CTFontGetSize(ctfont); - cgMatrix = CGAffineTransformScale(cgMatrix, scale, -scale); - - QCFType<CGPathRef> cgpath = CTFontCreatePathForGlyph(ctfont, (CGGlyph) glyph, &cgMatrix); - ConvertPathInfo info(path, QPointF(0,0)); - CGPathApply(cgpath, &info, convertCGPathToQPainterPath); - - *metric = boundingBox(glyph); - // scale the metrics too - metric->width = QFixed::fromReal(metric->width.toReal() * scale); - metric->height = QFixed::fromReal(metric->height.toReal() * scale); - metric->x = QFixed::fromReal(metric->x.toReal() * scale); - metric->y = QFixed::fromReal(metric->y.toReal() * scale); - metric->xoff = QFixed::fromReal(metric->xoff.toReal() * scale); - metric->yoff = QFixed::fromReal(metric->yoff.toReal() * scale); -} - -QFixed QCoreTextFontEngine::emSquareSize() const -{ - return QFixed(int(CTFontGetUnitsPerEm(ctfont))); -} - -QFontEngine *QCoreTextFontEngine::cloneWithSize(qreal pixelSize) const -{ - QFontDef newFontDef = fontDef; - newFontDef.pixelSize = pixelSize; - newFontDef.pointSize = pixelSize * 72.0 / qt_defaultDpi(); - - return new QCoreTextFontEngine(cgFont, newFontDef); -} - -Qt::HANDLE QCoreTextFontEngine::handle() const -{ - return (Qt::HANDLE)(static_cast<CTFontRef>(ctfont)); -} - -bool QCoreTextFontEngine::supportsTransformation(const QTransform &transform) const -{ - if (transform.type() < QTransform::TxScale) - return true; - else if (transform.type() == QTransform::TxScale && - transform.m11() >= 0 && transform.m22() >= 0) - return true; - else - return false; -} - -QFixed QCoreTextFontEngine::lineThickness() const -{ - return underlineThickness; -} - -QFixed QCoreTextFontEngine::underlinePosition() const -{ - return underlinePos; -} - -QFontEngine::Properties QCoreTextFontEngine::properties() const -{ - Properties result; - - QCFString psName, copyright; - psName = CTFontCopyPostScriptName(ctfont); - copyright = CTFontCopyName(ctfont, kCTFontCopyrightNameKey); - result.postscriptName = QString::fromCFString(psName).toUtf8(); - result.copyright = QString::fromCFString(copyright).toUtf8(); - - qreal emSquare = CTFontGetUnitsPerEm(ctfont); - qreal scale = emSquare / CTFontGetSize(ctfont); - - CGRect cgRect = CTFontGetBoundingBox(ctfont); - result.boundingBox = QRectF(cgRect.origin.x * scale, - -CTFontGetAscent(ctfont) * scale, - cgRect.size.width * scale, - cgRect.size.height * scale); - - result.emSquare = emSquareSize(); - result.ascent = QFixed::fromReal(CTFontGetAscent(ctfont) * scale); - result.descent = QFixed::fromReal(CTFontGetDescent(ctfont) * scale); - result.leading = QFixed::fromReal(CTFontGetLeading(ctfont) * scale); - result.italicAngle = QFixed::fromReal(CTFontGetSlantAngle(ctfont)); - result.capHeight = QFixed::fromReal(CTFontGetCapHeight(ctfont) * scale); - result.lineWidth = QFixed::fromReal(CTFontGetUnderlineThickness(ctfont) * scale); - - if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) { - result.ascent = result.ascent.round(); - result.descent = result.descent.round(); - result.leading = result.leading.round(); - result.italicAngle = result.italicAngle.round(); - result.capHeight = result.capHeight.round(); - result.lineWidth = result.lineWidth.round(); - } - - return result; -} - -void QCoreTextFontEngine::doKerning(QGlyphLayout *g, ShaperFlags flags) const -{ - if (!kerningPairsLoaded) { - kerningPairsLoaded = true; - qreal emSquare = CTFontGetUnitsPerEm(ctfont); - qreal scale = emSquare / CTFontGetSize(ctfont); - - const_cast<QCoreTextFontEngine *>(this)->loadKerningPairs(QFixed::fromReal(scale)); - } - - QFontEngine::doKerning(g, flags); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/fontdatabases/mac/qfontengine_coretext_p.h b/src/platformsupport/fontdatabases/mac/qfontengine_coretext_p.h deleted file mode 100644 index 51d839688d..0000000000 --- a/src/platformsupport/fontdatabases/mac/qfontengine_coretext_p.h +++ /dev/null @@ -1,161 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QFONTENGINE_CORETEXT_P_H -#define QFONTENGINE_CORETEXT_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <private/qfontengine_p.h> -#include <private/qcore_mac_p.h> -#include <QtCore/qloggingcategory.h> - -#ifdef Q_OS_OSX -#include <ApplicationServices/ApplicationServices.h> -#else -#include <CoreText/CoreText.h> -#include <CoreGraphics/CoreGraphics.h> -#endif - -QT_BEGIN_NAMESPACE - -Q_DECLARE_LOGGING_CATEGORY(lcQpaFonts) - -class QCoreTextFontEngine : public QFontEngine -{ - Q_GADGET - -public: - QCoreTextFontEngine(CTFontRef font, const QFontDef &def); - QCoreTextFontEngine(CGFontRef font, const QFontDef &def); - ~QCoreTextFontEngine(); - - glyph_t glyphIndex(uint ucs4) const override; - bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, ShaperFlags flags) const override; - void recalcAdvances(QGlyphLayout *, ShaperFlags) const override; - - glyph_metrics_t boundingBox(const QGlyphLayout &glyphs) override; - glyph_metrics_t boundingBox(glyph_t glyph) override; - - QFixed ascent() const override; - QFixed capHeight() const override; - QFixed descent() const override; - QFixed leading() const override; - QFixed xHeight() const override; - qreal maxCharWidth() const override; - QFixed averageCharWidth() const override; - - void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs, - QPainterPath *path, QTextItem::RenderFlags) override; - - bool canRender(const QChar *string, int len) const override; - - int synthesized() const override { return synthesisFlags; } - bool supportsSubPixelPositions() const override { return true; } - - QFixed lineThickness() const override; - QFixed underlinePosition() const override; - - void draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight); - - FaceId faceId() const override; - bool getSfntTableData(uint /*tag*/, uchar * /*buffer*/, uint * /*length*/) const override; - void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics) override; - QImage alphaMapForGlyph(glyph_t, QFixed subPixelPosition) override; - QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t) override; - QImage alphaRGBMapForGlyph(glyph_t, QFixed subPixelPosition, const QTransform &t) override; - glyph_metrics_t alphaMapBoundingBox(glyph_t glyph, QFixed, const QTransform &matrix, GlyphFormat) override; - QImage bitmapForGlyph(glyph_t, QFixed subPixelPosition, const QTransform &t, const QColor &color) override; - QFixed emSquareSize() const override; - void doKerning(QGlyphLayout *g, ShaperFlags flags) const override; - - bool supportsTransformation(const QTransform &transform) const override; - bool expectsGammaCorrectedBlending() const override; - - QFontEngine *cloneWithSize(qreal pixelSize) const override; - Qt::HANDLE handle() const override; - int glyphMargin(QFontEngine::GlyphFormat format) override { Q_UNUSED(format); return 0; } - - QFontEngine::Properties properties() const override; - - enum FontSmoothing { Disabled, Subpixel, Grayscale }; - Q_ENUM(FontSmoothing); - - static FontSmoothing fontSmoothing(); - static qreal fontSmoothingGamma(); - - static bool ct_getSfntTable(void *user_data, uint tag, uchar *buffer, uint *length); - static QFont::Weight qtWeightFromCFWeight(float value); - - static QCoreTextFontEngine *create(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference); - -protected: - QCoreTextFontEngine(const QFontDef &def); - void init(); - QImage imageForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &m, const QColor &color = QColor()); - void loadAdvancesForGlyphs(QVarLengthArray<CGGlyph> &cgGlyphs, QGlyphLayout *glyphs) const; - bool hasColorGlyphs() const; - bool shouldAntialias() const; - bool shouldSmoothFont() const; - - QCFType<CTFontRef> ctfont; - QCFType<CGFontRef> cgFont; - int synthesisFlags; - CGAffineTransform transform; - QFixed avgCharWidth; - QFixed underlineThickness; - QFixed underlinePos; - QFontEngine::FaceId face_id; - mutable bool kerningPairsLoaded; -}; - -CGAffineTransform qt_transform_from_fontdef(const QFontDef &fontDef); - -QT_END_NAMESPACE - -#endif // QFONTENGINE_CORETEXT_P_H diff --git a/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase.cpp b/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase.cpp deleted file mode 100644 index 9e6e5d88c7..0000000000 --- a/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase.cpp +++ /dev/null @@ -1,2106 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qwindowsfontdatabase_p.h" -#include "qwindowsfontdatabase_ft_p.h" // for default font -#include "qwindowsfontengine_p.h" -#include "qwindowsfontenginedirectwrite_p.h" -#include <QtCore/qt_windows.h> - -#include <QtGui/QFont> -#include <QtGui/QGuiApplication> -#include <QtGui/private/qhighdpiscaling_p.h> - -#include <QtCore/qmath.h> -#include <QtCore/QDebug> -#include <QtCore/QFile> -#include <QtCore/QtEndian> -#include <QtCore/QThreadStorage> -#include <QtCore/private/qsystemlibrary_p.h> - -#include <wchar.h> - -#if !defined(QT_NO_DIRECTWRITE) -# if defined(QT_USE_DIRECTWRITE2) -# include <dwrite_2.h> -# else -# include <dwrite.h> -# endif -# include <d2d1.h> -#endif - -QT_BEGIN_NAMESPACE - -Q_LOGGING_CATEGORY(lcQpaFonts, "qt.qpa.fonts") - -#ifndef QT_NO_DIRECTWRITE -// ### fixme: Consider direct linking of dwrite.dll once Windows Vista pre SP2 is dropped (QTBUG-49711) - -typedef HRESULT (WINAPI *DWriteCreateFactoryType)(DWRITE_FACTORY_TYPE, const IID &, IUnknown **); - -static inline DWriteCreateFactoryType resolveDWriteCreateFactory() -{ - QSystemLibrary library(QStringLiteral("dwrite")); - QFunctionPointer result = library.resolve("DWriteCreateFactory"); - if (Q_UNLIKELY(!result)) { - qWarning("Unable to load dwrite.dll"); - return nullptr; - } - return reinterpret_cast<DWriteCreateFactoryType>(result); -} - -static void createDirectWriteFactory(IDWriteFactory **factory) -{ - *factory = nullptr; - - static const DWriteCreateFactoryType dWriteCreateFactory = resolveDWriteCreateFactory(); - if (!dWriteCreateFactory) - return; - - IUnknown *result = NULL; -#if defined(QT_USE_DIRECTWRITE2) - dWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory2), &result); -#endif - - if (result == NULL) { - if (FAILED(dWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), &result))) { - qErrnoWarning("DWriteCreateFactory failed"); - return; - } - } - - *factory = static_cast<IDWriteFactory *>(result); -} - -static inline bool useDirectWrite(QFont::HintingPreference hintingPreference, - const QString &familyName = QString(), - bool isColorFont = false) -{ - const unsigned options = QWindowsFontDatabase::fontOptions(); - if (Q_UNLIKELY(options & QWindowsFontDatabase::DontUseDirectWriteFonts)) - return false; - - // At some scales, GDI will misrender the MingLiU font, so we force use of - // DirectWrite to work around the issue. - if (Q_UNLIKELY(familyName.startsWith(QLatin1String("MingLiU")))) - return true; - - if (isColorFont) - return (options & QWindowsFontDatabase::DontUseColorFonts) == 0; - - return hintingPreference == QFont::PreferNoHinting - || hintingPreference == QFont::PreferVerticalHinting - || (QHighDpiScaling::isActive() && hintingPreference == QFont::PreferDefaultHinting); -} -#endif // !QT_NO_DIRECTWRITE - -// Helper classes for creating font engines directly from font data -namespace { - -# pragma pack(1) - - // Common structure for all formats of the "name" table - struct NameTable - { - quint16 format; - quint16 count; - quint16 stringOffset; - }; - - struct NameRecord - { - quint16 platformID; - quint16 encodingID; - quint16 languageID; - quint16 nameID; - quint16 length; - quint16 offset; - }; - - struct OffsetSubTable - { - quint32 scalerType; - quint16 numTables; - quint16 searchRange; - quint16 entrySelector; - quint16 rangeShift; - }; - - struct TableDirectory - { - quint32 identifier; - quint32 checkSum; - quint32 offset; - quint32 length; - }; - - struct OS2Table - { - quint16 version; - qint16 avgCharWidth; - quint16 weightClass; - quint16 widthClass; - quint16 type; - qint16 subscriptXSize; - qint16 subscriptYSize; - qint16 subscriptXOffset; - qint16 subscriptYOffset; - qint16 superscriptXSize; - qint16 superscriptYSize; - qint16 superscriptXOffset; - qint16 superscriptYOffset; - qint16 strikeOutSize; - qint16 strikeOutPosition; - qint16 familyClass; - quint8 panose[10]; - quint32 unicodeRanges[4]; - quint8 vendorID[4]; - quint16 selection; - quint16 firstCharIndex; - quint16 lastCharIndex; - qint16 typoAscender; - qint16 typoDescender; - qint16 typoLineGap; - quint16 winAscent; - quint16 winDescent; - quint32 codepageRanges[2]; - qint16 height; - qint16 capHeight; - quint16 defaultChar; - quint16 breakChar; - quint16 maxContext; - }; - -# pragma pack() - - class EmbeddedFont - { - public: - EmbeddedFont(const QByteArray &fontData) : m_fontData(fontData) {} - - QString changeFamilyName(const QString &newFamilyName); - QByteArray data() const { return m_fontData; } - TableDirectory *tableDirectoryEntry(const QByteArray &tagName); - QString familyName(TableDirectory *nameTableDirectory = 0); - - private: - QByteArray m_fontData; - }; - - TableDirectory *EmbeddedFont::tableDirectoryEntry(const QByteArray &tagName) - { - Q_ASSERT(tagName.size() == 4); - quint32 tagId = *(reinterpret_cast<const quint32 *>(tagName.constData())); - const size_t fontDataSize = m_fontData.size(); - if (Q_UNLIKELY(fontDataSize < sizeof(OffsetSubTable))) - return 0; - - OffsetSubTable *offsetSubTable = reinterpret_cast<OffsetSubTable *>(m_fontData.data()); - TableDirectory *tableDirectory = reinterpret_cast<TableDirectory *>(offsetSubTable + 1); - - const size_t tableCount = qFromBigEndian<quint16>(offsetSubTable->numTables); - if (Q_UNLIKELY(fontDataSize < sizeof(OffsetSubTable) + sizeof(TableDirectory) * tableCount)) - return 0; - - TableDirectory *tableDirectoryEnd = tableDirectory + tableCount; - for (TableDirectory *entry = tableDirectory; entry < tableDirectoryEnd; ++entry) { - if (entry->identifier == tagId) - return entry; - } - - return 0; - } - - QString EmbeddedFont::familyName(TableDirectory *nameTableDirectoryEntry) - { - QString name; - - if (nameTableDirectoryEntry == 0) - nameTableDirectoryEntry = tableDirectoryEntry("name"); - - if (nameTableDirectoryEntry != 0) { - quint32 offset = qFromBigEndian<quint32>(nameTableDirectoryEntry->offset); - if (Q_UNLIKELY(quint32(m_fontData.size()) < offset + sizeof(NameTable))) - return QString(); - - NameTable *nameTable = reinterpret_cast<NameTable *>(m_fontData.data() + offset); - NameRecord *nameRecord = reinterpret_cast<NameRecord *>(nameTable + 1); - - quint16 nameTableCount = qFromBigEndian<quint16>(nameTable->count); - if (Q_UNLIKELY(quint32(m_fontData.size()) < offset + sizeof(NameRecord) * nameTableCount)) - return QString(); - - for (int i = 0; i < nameTableCount; ++i, ++nameRecord) { - if (qFromBigEndian<quint16>(nameRecord->nameID) == 1 - && qFromBigEndian<quint16>(nameRecord->platformID) == 3 // Windows - && qFromBigEndian<quint16>(nameRecord->languageID) == 0x0409) { // US English - quint16 stringOffset = qFromBigEndian<quint16>(nameTable->stringOffset); - quint16 nameOffset = qFromBigEndian<quint16>(nameRecord->offset); - quint16 nameLength = qFromBigEndian<quint16>(nameRecord->length); - - if (Q_UNLIKELY(quint32(m_fontData.size()) < offset + stringOffset + nameOffset + nameLength)) - return QString(); - - const void *ptr = reinterpret_cast<const quint8 *>(nameTable) - + stringOffset - + nameOffset; - - const quint16 *s = reinterpret_cast<const quint16 *>(ptr); - const quint16 *e = s + nameLength / sizeof(quint16); - while (s != e) - name += QChar( qFromBigEndian<quint16>(*s++)); - break; - } - } - } - - return name; - } - - QString EmbeddedFont::changeFamilyName(const QString &newFamilyName) - { - TableDirectory *nameTableDirectoryEntry = tableDirectoryEntry("name"); - if (nameTableDirectoryEntry == 0) - return QString(); - - QString oldFamilyName = familyName(nameTableDirectoryEntry); - - // Reserve size for name table header, five required name records and string - const int requiredRecordCount = 5; - quint16 nameIds[requiredRecordCount] = { 1, 2, 3, 4, 6 }; - - int sizeOfHeader = sizeof(NameTable) + sizeof(NameRecord) * requiredRecordCount; - int newFamilyNameSize = newFamilyName.size() * int(sizeof(quint16)); - - const QString regularString = QString::fromLatin1("Regular"); - int regularStringSize = regularString.size() * int(sizeof(quint16)); - - // Align table size of table to 32 bits (pad with 0) - int fullSize = ((sizeOfHeader + newFamilyNameSize + regularStringSize) & ~3) + 4; - - QByteArray newNameTable(fullSize, char(0)); - - { - NameTable *nameTable = reinterpret_cast<NameTable *>(newNameTable.data()); - nameTable->count = qbswap<quint16>(requiredRecordCount); - nameTable->stringOffset = qbswap<quint16>(sizeOfHeader); - - NameRecord *nameRecord = reinterpret_cast<NameRecord *>(nameTable + 1); - for (int i = 0; i < requiredRecordCount; ++i, nameRecord++) { - nameRecord->nameID = qbswap<quint16>(nameIds[i]); - nameRecord->encodingID = qbswap<quint16>(1); - nameRecord->languageID = qbswap<quint16>(0x0409); - nameRecord->platformID = qbswap<quint16>(3); - nameRecord->length = qbswap<quint16>(newFamilyNameSize); - - // Special case for sub-family - if (nameIds[i] == 4) { - nameRecord->offset = qbswap<quint16>(newFamilyNameSize); - nameRecord->length = qbswap<quint16>(regularStringSize); - } - } - - // nameRecord now points to string data - quint16 *stringStorage = reinterpret_cast<quint16 *>(nameRecord); - const quint16 *sourceString = newFamilyName.utf16(); - for (int i = 0; i < newFamilyName.size(); ++i) - stringStorage[i] = qbswap<quint16>(sourceString[i]); - stringStorage += newFamilyName.size(); - - sourceString = regularString.utf16(); - for (int i = 0; i < regularString.size(); ++i) - stringStorage[i] = qbswap<quint16>(sourceString[i]); - } - - quint32 *p = reinterpret_cast<quint32 *>(newNameTable.data()); - quint32 *tableEnd = reinterpret_cast<quint32 *>(newNameTable.data() + fullSize); - - quint32 checkSum = 0; - while (p < tableEnd) - checkSum += qFromBigEndian<quint32>(*(p++)); - - nameTableDirectoryEntry->checkSum = qbswap<quint32>(checkSum); - nameTableDirectoryEntry->offset = qbswap<quint32>(m_fontData.size()); - nameTableDirectoryEntry->length = qbswap<quint32>(fullSize); - - m_fontData.append(newNameTable); - - return oldFamilyName; - } - -#if !defined(QT_NO_DIRECTWRITE) - - class DirectWriteFontFileStream: public IDWriteFontFileStream - { - Q_DISABLE_COPY(DirectWriteFontFileStream) - public: - DirectWriteFontFileStream(const QByteArray &fontData) - : m_fontData(fontData) - , m_referenceCount(0) - { - } - virtual ~DirectWriteFontFileStream() - { - } - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **object); - ULONG STDMETHODCALLTYPE AddRef(); - ULONG STDMETHODCALLTYPE Release(); - - HRESULT STDMETHODCALLTYPE ReadFileFragment(const void **fragmentStart, UINT64 fileOffset, - UINT64 fragmentSize, OUT void **fragmentContext); - void STDMETHODCALLTYPE ReleaseFileFragment(void *fragmentContext); - HRESULT STDMETHODCALLTYPE GetFileSize(OUT UINT64 *fileSize); - HRESULT STDMETHODCALLTYPE GetLastWriteTime(OUT UINT64 *lastWriteTime); - - private: - QByteArray m_fontData; - ULONG m_referenceCount; - }; - - HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::QueryInterface(REFIID iid, void **object) - { - if (iid == IID_IUnknown || iid == __uuidof(IDWriteFontFileStream)) { - *object = this; - AddRef(); - return S_OK; - } else { - *object = NULL; - return E_NOINTERFACE; - } - } - - ULONG STDMETHODCALLTYPE DirectWriteFontFileStream::AddRef() - { - return InterlockedIncrement(&m_referenceCount); - } - - ULONG STDMETHODCALLTYPE DirectWriteFontFileStream::Release() - { - ULONG newCount = InterlockedDecrement(&m_referenceCount); - if (newCount == 0) - delete this; - return newCount; - } - - HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::ReadFileFragment( - const void **fragmentStart, - UINT64 fileOffset, - UINT64 fragmentSize, - OUT void **fragmentContext) - { - *fragmentContext = NULL; - if (fileOffset + fragmentSize <= quint64(m_fontData.size())) { - *fragmentStart = m_fontData.data() + fileOffset; - return S_OK; - } else { - *fragmentStart = NULL; - return E_FAIL; - } - } - - void STDMETHODCALLTYPE DirectWriteFontFileStream::ReleaseFileFragment(void *) - { - } - - HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::GetFileSize(UINT64 *fileSize) - { - *fileSize = m_fontData.size(); - return S_OK; - } - - HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::GetLastWriteTime(UINT64 *lastWriteTime) - { - *lastWriteTime = 0; - return E_NOTIMPL; - } - - class DirectWriteFontFileLoader: public IDWriteFontFileLoader - { - public: - DirectWriteFontFileLoader() : m_referenceCount(0) {} - virtual ~DirectWriteFontFileLoader() - { - } - - inline void addKey(const void *key, const QByteArray &fontData) - { - Q_ASSERT(!m_fontDatas.contains(key)); - m_fontDatas.insert(key, fontData); - } - - inline void removeKey(const void *key) - { - m_fontDatas.remove(key); - } - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **object); - ULONG STDMETHODCALLTYPE AddRef(); - ULONG STDMETHODCALLTYPE Release(); - - HRESULT STDMETHODCALLTYPE CreateStreamFromKey(void const *fontFileReferenceKey, - UINT32 fontFileReferenceKeySize, - OUT IDWriteFontFileStream **fontFileStream); - - private: - ULONG m_referenceCount; - QHash<const void *, QByteArray> m_fontDatas; - }; - - HRESULT STDMETHODCALLTYPE DirectWriteFontFileLoader::QueryInterface(const IID &iid, - void **object) - { - if (iid == IID_IUnknown || iid == __uuidof(IDWriteFontFileLoader)) { - *object = this; - AddRef(); - return S_OK; - } else { - *object = NULL; - return E_NOINTERFACE; - } - } - - ULONG STDMETHODCALLTYPE DirectWriteFontFileLoader::AddRef() - { - return InterlockedIncrement(&m_referenceCount); - } - - ULONG STDMETHODCALLTYPE DirectWriteFontFileLoader::Release() - { - ULONG newCount = InterlockedDecrement(&m_referenceCount); - if (newCount == 0) - delete this; - return newCount; - } - - HRESULT STDMETHODCALLTYPE DirectWriteFontFileLoader::CreateStreamFromKey( - void const *fontFileReferenceKey, - UINT32 fontFileReferenceKeySize, - IDWriteFontFileStream **fontFileStream) - { - Q_UNUSED(fontFileReferenceKeySize); - - if (fontFileReferenceKeySize != sizeof(const void *)) { - qWarning("%s: Wrong key size", __FUNCTION__); - return E_FAIL; - } - - const void *key = *reinterpret_cast<void * const *>(fontFileReferenceKey); - *fontFileStream = NULL; - auto it = m_fontDatas.constFind(key); - if (it == m_fontDatas.constEnd()) - return E_FAIL; - - QByteArray fontData = it.value(); - DirectWriteFontFileStream *stream = new DirectWriteFontFileStream(fontData); - stream->AddRef(); - *fontFileStream = stream; - - return S_OK; - } - - class CustomFontFileLoader - { - public: - CustomFontFileLoader() : m_directWriteFontFileLoader(nullptr) - { - createDirectWriteFactory(&m_directWriteFactory); - - if (m_directWriteFactory) { - m_directWriteFontFileLoader = new DirectWriteFontFileLoader(); - m_directWriteFactory->RegisterFontFileLoader(m_directWriteFontFileLoader); - } - } - - ~CustomFontFileLoader() - { - if (m_directWriteFactory != 0 && m_directWriteFontFileLoader != 0) - m_directWriteFactory->UnregisterFontFileLoader(m_directWriteFontFileLoader); - - if (m_directWriteFactory != 0) - m_directWriteFactory->Release(); - } - - void addKey(const void *key, const QByteArray &fontData) - { - if (m_directWriteFontFileLoader != 0) - m_directWriteFontFileLoader->addKey(key, fontData); - } - - void removeKey(const void *key) - { - if (m_directWriteFontFileLoader != 0) - m_directWriteFontFileLoader->removeKey(key); - } - - IDWriteFontFileLoader *loader() const - { - return m_directWriteFontFileLoader; - } - - private: - IDWriteFactory *m_directWriteFactory; - DirectWriteFontFileLoader *m_directWriteFontFileLoader; - }; - -#endif - -} // Anonymous namespace - -/*! - \struct QWindowsFontEngineData - \brief Static constant data shared by the font engines. - \ingroup qt-lighthouse-win -*/ - -QWindowsFontEngineData::QWindowsFontEngineData() - : fontSmoothingGamma(QWindowsFontDatabase::fontSmoothingGamma()) -{ - // from qapplication_win.cpp - UINT result = 0; - if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &result, 0)) - clearTypeEnabled = (result == FE_FONTSMOOTHINGCLEARTYPE); - - const qreal gray_gamma = 2.31; - for (int i=0; i<256; ++i) - pow_gamma[i] = uint(qRound(qPow(i / qreal(255.), gray_gamma) * 2047)); - - HDC displayDC = GetDC(0); - hdc = CreateCompatibleDC(displayDC); - ReleaseDC(0, displayDC); -} - -unsigned QWindowsFontDatabase::m_fontOptions = 0; - -void QWindowsFontDatabase::setFontOptions(unsigned options) -{ - m_fontOptions = options & (QWindowsFontDatabase::DontUseDirectWriteFonts | - QWindowsFontDatabase::DontUseColorFonts); -} - -unsigned QWindowsFontDatabase::fontOptions() -{ - return m_fontOptions; -} - -QWindowsFontEngineData::~QWindowsFontEngineData() -{ - if (hdc) - DeleteDC(hdc); -#if !defined(QT_NO_DIRECTWRITE) - if (directWriteGdiInterop) - directWriteGdiInterop->Release(); - if (directWriteFactory) - directWriteFactory->Release(); -#endif -} - -qreal QWindowsFontDatabase::fontSmoothingGamma() -{ - int winSmooth; - qreal result = 1; - if (SystemParametersInfo(0x200C /* SPI_GETFONTSMOOTHINGCONTRAST */, 0, &winSmooth, 0)) - result = qreal(winSmooth) / qreal(1000.0); - - // Safeguard ourselves against corrupt registry values... - if (result > 5 || result < 1) - result = qreal(1.4); - return result; -} - -#if !defined(QT_NO_DIRECTWRITE) -static inline bool initDirectWrite(QWindowsFontEngineData *d) -{ - if (!d->directWriteFactory) { - createDirectWriteFactory(&d->directWriteFactory); - if (!d->directWriteFactory) - return false; - } - if (!d->directWriteGdiInterop) { - const HRESULT hr = d->directWriteFactory->GetGdiInterop(&d->directWriteGdiInterop); - if (FAILED(hr)) { - qErrnoWarning("%s: GetGdiInterop failed", __FUNCTION__); - return false; - } - } - return true; -} - -#endif // !defined(QT_NO_DIRECTWRITE) - -/*! - \class QWindowsFontDatabase - \brief Font database for Windows - - \note The Qt 4.8 WIndows font database employed a mechanism of - delayed population of the database again passing a font name - to EnumFontFamiliesEx(), working around the fact that - EnumFontFamiliesEx() does not list all fonts by default. - This should be introduced to Lighthouse as well? - - \internal - \ingroup qt-lighthouse-win -*/ - -#ifndef QT_NO_DEBUG_STREAM -QDebug operator<<(QDebug d, const QFontDef &def) -{ - QDebugStateSaver saver(d); - d.nospace(); - d.noquote(); - d << "QFontDef(Family=\"" << def.family << '"'; - if (!def.styleName.isEmpty()) - d << ", stylename=" << def.styleName; - d << ", pointsize=" << def.pointSize << ", pixelsize=" << def.pixelSize - << ", styleHint=" << def.styleHint << ", weight=" << def.weight - << ", stretch=" << def.stretch << ", hintingPreference=" - << def.hintingPreference << ')'; - return d; -} - -QDebug operator<<(QDebug d, const LOGFONT &lf) -{ - QDebugStateSaver saver(d); - d.nospace(); - d.noquote(); - d << "LOGFONT(\"" << QString::fromWCharArray(lf.lfFaceName) - << "\", lfWidth=" << lf.lfWidth << ", lfHeight=" << lf.lfHeight << ')'; - return d; -} -#endif // !QT_NO_DEBUG_STREAM - -static inline QFontDatabase::WritingSystem writingSystemFromCharSet(uchar charSet) -{ - switch (charSet) { - case ANSI_CHARSET: - case EASTEUROPE_CHARSET: - case BALTIC_CHARSET: - case TURKISH_CHARSET: - return QFontDatabase::Latin; - case GREEK_CHARSET: - return QFontDatabase::Greek; - case RUSSIAN_CHARSET: - return QFontDatabase::Cyrillic; - case HEBREW_CHARSET: - return QFontDatabase::Hebrew; - case ARABIC_CHARSET: - return QFontDatabase::Arabic; - case THAI_CHARSET: - return QFontDatabase::Thai; - case GB2312_CHARSET: - return QFontDatabase::SimplifiedChinese; - case CHINESEBIG5_CHARSET: - return QFontDatabase::TraditionalChinese; - case SHIFTJIS_CHARSET: - return QFontDatabase::Japanese; - case HANGUL_CHARSET: - case JOHAB_CHARSET: - return QFontDatabase::Korean; - case VIETNAMESE_CHARSET: - return QFontDatabase::Vietnamese; - case SYMBOL_CHARSET: - return QFontDatabase::Symbol; - default: - break; - } - return QFontDatabase::Any; -} - -#ifdef MAKE_TAG -#undef MAKE_TAG -#endif -// GetFontData expects the tags in little endian ;( -#define MAKE_TAG(ch1, ch2, ch3, ch4) (\ - (((quint32)(ch4)) << 24) | \ - (((quint32)(ch3)) << 16) | \ - (((quint32)(ch2)) << 8) | \ - ((quint32)(ch1)) \ - ) - -bool qt_localizedName(const QString &name) -{ - const QChar *c = name.unicode(); - for (int i = 0; i < name.length(); ++i) { - if (c[i].unicode() >= 0x100) - return true; - } - return false; -} - -namespace { - -static QString readName(bool unicode, const uchar *string, int length) -{ - QString out; - if (unicode) { - // utf16 - - length /= 2; - out.resize(length); - QChar *uc = out.data(); - for (int i = 0; i < length; ++i) - uc[i] = qt_getUShort(string + 2*i); - } else { - // Apple Roman - - out.resize(length); - QChar *uc = out.data(); - for (int i = 0; i < length; ++i) - uc[i] = QLatin1Char(char(string[i])); - } - return out; -} - -enum FieldTypeValue { - FamilyId = 1, - StyleId = 2, - PreferredFamilyId = 16, - PreferredStyleId = 17, -}; - -enum PlatformFieldValue { - PlatformId_Unicode = 0, - PlatformId_Apple = 1, - PlatformId_Microsoft = 3 -}; - -QFontNames qt_getCanonicalFontNames(const uchar *table, quint32 bytes) -{ - QFontNames out; - const int NameRecordSize = 12; - const int MS_LangIdEnglish = 0x009; - - // get the name table - quint16 count; - quint16 string_offset; - const unsigned char *names; - - if (bytes < 8) - return out; - - if (qt_getUShort(table) != 0) - return out; - - count = qt_getUShort(table + 2); - string_offset = qt_getUShort(table + 4); - names = table + 6; - - if (string_offset >= bytes || 6 + count*NameRecordSize > string_offset) - return out; - - enum PlatformIdType { - NotFound = 0, - Unicode = 1, - Apple = 2, - Microsoft = 3 - }; - - PlatformIdType idStatus[4] = { NotFound, NotFound, NotFound, NotFound }; - int ids[4] = { -1, -1, -1, -1 }; - - for (int i = 0; i < count; ++i) { - // search for the correct name entries - - quint16 platform_id = qt_getUShort(names + i*NameRecordSize); - quint16 encoding_id = qt_getUShort(names + 2 + i*NameRecordSize); - quint16 language_id = qt_getUShort(names + 4 + i*NameRecordSize); - quint16 name_id = qt_getUShort(names + 6 + i*NameRecordSize); - - PlatformIdType *idType = nullptr; - int *id = nullptr; - - switch (name_id) { - case FamilyId: - idType = &idStatus[0]; - id = &ids[0]; - break; - case StyleId: - idType = &idStatus[1]; - id = &ids[1]; - break; - case PreferredFamilyId: - idType = &idStatus[2]; - id = &ids[2]; - break; - case PreferredStyleId: - idType = &idStatus[3]; - id = &ids[3]; - break; - default: - continue; - } - - quint16 length = qt_getUShort(names + 8 + i*NameRecordSize); - quint16 offset = qt_getUShort(names + 10 + i*NameRecordSize); - if (DWORD(string_offset + offset + length) > bytes) - continue; - - if ((platform_id == PlatformId_Microsoft - && (encoding_id == 0 || encoding_id == 1)) - && ((language_id & 0x3ff) == MS_LangIdEnglish - || *idType < Microsoft)) { - *id = i; - *idType = Microsoft; - } - // not sure if encoding id 4 for Unicode is utf16 or ucs4... - else if (platform_id == PlatformId_Unicode && encoding_id < 4 && *idType < Unicode) { - *id = i; - *idType = Unicode; - } - else if (platform_id == PlatformId_Apple && encoding_id == 0 && language_id == 0 && *idType < Apple) { - *id = i; - *idType = Apple; - } - } - - QString strings[4]; - for (int i = 0; i < 4; ++i) { - if (idStatus[i] == NotFound) - continue; - int id = ids[i]; - quint16 length = qt_getUShort(names + 8 + id * NameRecordSize); - quint16 offset = qt_getUShort(names + 10 + id * NameRecordSize); - const unsigned char *string = table + string_offset + offset; - strings[i] = readName(idStatus[i] != Apple, string, length); - } - - out.name = strings[0]; - out.style = strings[1]; - out.preferredName = strings[2]; - out.preferredStyle = strings[3]; - return out; -} - -} // namespace - -QString qt_getEnglishName(const QString &familyName, bool includeStyle) -{ - QString i18n_name; - QString faceName = familyName; - faceName.truncate(LF_FACESIZE - 1); - - HDC hdc = GetDC( 0 ); - LOGFONT lf; - memset(&lf, 0, sizeof(LOGFONT)); - faceName.toWCharArray(lf.lfFaceName); - lf.lfFaceName[faceName.size()] = 0; - lf.lfCharSet = DEFAULT_CHARSET; - HFONT hfont = CreateFontIndirect(&lf); - - if (!hfont) { - ReleaseDC(0, hdc); - return QString(); - } - - HGDIOBJ oldobj = SelectObject( hdc, hfont ); - - const DWORD name_tag = MAKE_TAG( 'n', 'a', 'm', 'e' ); - - // get the name table - unsigned char *table = 0; - - DWORD bytes = GetFontData( hdc, name_tag, 0, 0, 0 ); - if ( bytes == GDI_ERROR ) { - // ### Unused variable - // int err = GetLastError(); - goto error; - } - - table = new unsigned char[bytes]; - GetFontData(hdc, name_tag, 0, table, bytes); - if ( bytes == GDI_ERROR ) - goto error; - - { - const QFontNames names = qt_getCanonicalFontNames(table, bytes); - i18n_name = names.name; - if (includeStyle) - i18n_name += QLatin1Char(' ') + names.style; - } -error: - delete [] table; - SelectObject( hdc, oldobj ); - DeleteObject( hfont ); - ReleaseDC( 0, hdc ); - - //qDebug("got i18n name of '%s' for font '%s'", i18n_name.latin1(), familyName.toLocal8Bit().data()); - return i18n_name; -} - -// Note this duplicates parts of qt_getEnglishName, we should try to unify the two functions. -QFontNames qt_getCanonicalFontNames(const LOGFONT &lf) -{ - QFontNames fontNames; - HDC hdc = GetDC(0); - HFONT hfont = CreateFontIndirect(&lf); - - if (!hfont) { - ReleaseDC(0, hdc); - return fontNames; - } - - HGDIOBJ oldobj = SelectObject(hdc, hfont); - - // get the name table - QByteArray table; - const DWORD name_tag = MAKE_TAG('n', 'a', 'm', 'e'); - DWORD bytes = GetFontData(hdc, name_tag, 0, 0, 0); - if (bytes != GDI_ERROR) { - table.resize(bytes); - - if (GetFontData(hdc, name_tag, 0, table.data(), bytes) != GDI_ERROR) - fontNames = qt_getCanonicalFontNames(reinterpret_cast<const uchar*>(table.constData()), bytes); - } - - SelectObject(hdc, oldobj); - DeleteObject(hfont); - ReleaseDC(0, hdc); - - return fontNames; -} - -static QChar *createFontFile(const QString &faceName) -{ - QChar *faceNamePtr = nullptr; - if (!faceName.isEmpty()) { - const int nameLength = qMin(faceName.length(), LF_FACESIZE - 1); - faceNamePtr = new QChar[nameLength + 1]; - memcpy(static_cast<void *>(faceNamePtr), faceName.utf16(), sizeof(wchar_t) * nameLength); - faceNamePtr[nameLength] = 0; - } - return faceNamePtr; -} - -static bool addFontToDatabase(QString familyName, - QString styleName, - const LOGFONT &logFont, - const TEXTMETRIC *textmetric, - const FONTSIGNATURE *signature, - int type) -{ - // the "@family" fonts are just the same as "family". Ignore them. - if (familyName.isEmpty() || familyName.at(0) == QLatin1Char('@') || familyName.startsWith(QLatin1String("WST_"))) - return false; - - uchar charSet = logFont.lfCharSet; - - static const int SMOOTH_SCALABLE = 0xffff; - const QString foundryName; // No such concept. - const bool fixed = !(textmetric->tmPitchAndFamily & TMPF_FIXED_PITCH); - const bool ttf = (textmetric->tmPitchAndFamily & TMPF_TRUETYPE); - const bool scalable = textmetric->tmPitchAndFamily & (TMPF_VECTOR|TMPF_TRUETYPE); - const int size = scalable ? SMOOTH_SCALABLE : textmetric->tmHeight; - const QFont::Style style = textmetric->tmItalic ? QFont::StyleItalic : QFont::StyleNormal; - const bool antialias = false; - const QFont::Weight weight = QPlatformFontDatabase::weightFromInteger(textmetric->tmWeight); - const QFont::Stretch stretch = QFont::Unstretched; - -#ifndef QT_NO_DEBUG_OUTPUT - if (lcQpaFonts().isDebugEnabled()) { - QString message; - QTextStream str(&message); - str << __FUNCTION__ << ' ' << familyName << ' ' << charSet << " TTF=" << ttf; - if (type & DEVICE_FONTTYPE) - str << " DEVICE"; - if (type & RASTER_FONTTYPE) - str << " RASTER"; - if (type & TRUETYPE_FONTTYPE) - str << " TRUETYPE"; - str << " scalable=" << scalable << " Size=" << size - << " Style=" << style << " Weight=" << weight - << " stretch=" << stretch; - qCDebug(lcQpaFonts) << message; - } -#endif - QString englishName; - QString faceName; - - QString subFamilyName; - QString subFamilyStyle; - if (ttf) { - // Look-up names registered in the font - QFontNames canonicalNames = qt_getCanonicalFontNames(logFont); - if (qt_localizedName(familyName) && !canonicalNames.name.isEmpty()) - englishName = canonicalNames.name; - if (!canonicalNames.preferredName.isEmpty()) { - subFamilyName = familyName; - subFamilyStyle = styleName; - faceName = familyName; // Remember the original name for later lookups - familyName = canonicalNames.preferredName; - styleName = canonicalNames.preferredStyle; - } - } - - QSupportedWritingSystems writingSystems; - if (type & TRUETYPE_FONTTYPE) { - Q_ASSERT(signature); - quint32 unicodeRange[4] = { - signature->fsUsb[0], signature->fsUsb[1], - signature->fsUsb[2], signature->fsUsb[3] - }; - quint32 codePageRange[2] = { - signature->fsCsb[0], signature->fsCsb[1] - }; - writingSystems = QPlatformFontDatabase::writingSystemsFromTrueTypeBits(unicodeRange, codePageRange); - // ### Hack to work around problem with Thai text on Windows 7. Segoe UI contains - // the symbol for Baht, and Windows thus reports that it supports the Thai script. - // Since it's the default UI font on this platform, most widgets will be unable to - // display Thai text by default. As a temporary work around, we special case Segoe UI - // and remove the Thai script from its list of supported writing systems. - if (writingSystems.supported(QFontDatabase::Thai) && - familyName == QLatin1String("Segoe UI")) - writingSystems.setSupported(QFontDatabase::Thai, false); - } else { - const QFontDatabase::WritingSystem ws = writingSystemFromCharSet(charSet); - if (ws != QFontDatabase::Any) - writingSystems.setSupported(ws); - } - - QPlatformFontDatabase::registerFont(familyName, styleName, foundryName, weight, - style, stretch, antialias, scalable, size, fixed, writingSystems, createFontFile(faceName)); - - // add fonts windows can generate for us: - if (weight <= QFont::DemiBold && styleName.isEmpty()) - QPlatformFontDatabase::registerFont(familyName, QString(), foundryName, QFont::Bold, - style, stretch, antialias, scalable, size, fixed, writingSystems, createFontFile(faceName)); - if (style != QFont::StyleItalic && styleName.isEmpty()) - QPlatformFontDatabase::registerFont(familyName, QString(), foundryName, weight, - QFont::StyleItalic, stretch, antialias, scalable, size, fixed, writingSystems, createFontFile(faceName)); - if (weight <= QFont::DemiBold && style != QFont::StyleItalic && styleName.isEmpty()) - QPlatformFontDatabase::registerFont(familyName, QString(), foundryName, QFont::Bold, - QFont::StyleItalic, stretch, antialias, scalable, size, fixed, writingSystems, createFontFile(faceName)); - - if (!subFamilyName.isEmpty() && familyName != subFamilyName) { - QPlatformFontDatabase::registerFont(subFamilyName, subFamilyStyle, foundryName, weight, - style, stretch, antialias, scalable, size, fixed, writingSystems, createFontFile(faceName)); - } - - if (!englishName.isEmpty() && englishName != familyName) - QPlatformFontDatabase::registerAliasToFontFamily(familyName, englishName); - - return true; -} - -static int QT_WIN_CALLBACK storeFont(const LOGFONT *logFont, const TEXTMETRIC *textmetric, - DWORD type, LPARAM lparam) -{ - const ENUMLOGFONTEX *f = reinterpret_cast<const ENUMLOGFONTEX *>(logFont); - const QString familyName = QString::fromWCharArray(f->elfLogFont.lfFaceName); - const QString styleName = QString::fromWCharArray(f->elfStyle); - - // NEWTEXTMETRICEX (passed for TT fonts) is a NEWTEXTMETRIC, which according - // to the documentation is identical to a TEXTMETRIC except for the last four - // members, which we don't use anyway - const FONTSIGNATURE *signature = nullptr; - if (type & TRUETYPE_FONTTYPE) { - signature = &reinterpret_cast<const NEWTEXTMETRICEX *>(textmetric)->ntmFontSig; - // We get a callback for each script-type supported, but we register them all - // at once using the signature, so we only need one call to addFontToDatabase(). - QSet<QPair<QString,QString>> *foundFontAndStyles = reinterpret_cast<QSet<QPair<QString,QString>> *>(lparam); - QPair<QString,QString> fontAndStyle(familyName, styleName); - if (foundFontAndStyles->contains(fontAndStyle)) - return 1; - foundFontAndStyles->insert(fontAndStyle); - } - addFontToDatabase(familyName, styleName, *logFont, textmetric, signature, type); - - // keep on enumerating - return 1; -} - -void QWindowsFontDatabase::populateFamily(const QString &familyName) -{ - qCDebug(lcQpaFonts) << familyName; - if (familyName.size() >= LF_FACESIZE) { - qCWarning(lcQpaFonts) << "Unable to enumerate family '" << familyName << '\''; - return; - } - HDC dummy = GetDC(0); - LOGFONT lf; - lf.lfCharSet = DEFAULT_CHARSET; - familyName.toWCharArray(lf.lfFaceName); - lf.lfFaceName[familyName.size()] = 0; - lf.lfPitchAndFamily = 0; - QSet<QPair<QString,QString>> foundFontAndStyles; - EnumFontFamiliesEx(dummy, &lf, storeFont, reinterpret_cast<intptr_t>(&foundFontAndStyles), 0); - ReleaseDC(0, dummy); -} - -static int QT_WIN_CALLBACK populateFontFamilies(const LOGFONT *logFont, const TEXTMETRIC *textmetric, - DWORD, LPARAM) -{ - // the "@family" fonts are just the same as "family". Ignore them. - const ENUMLOGFONTEX *f = reinterpret_cast<const ENUMLOGFONTEX *>(logFont); - const wchar_t *faceNameW = f->elfLogFont.lfFaceName; - if (faceNameW[0] && faceNameW[0] != L'@' && wcsncmp(faceNameW, L"WST_", 4)) { - const QString faceName = QString::fromWCharArray(faceNameW); - QPlatformFontDatabase::registerFontFamily(faceName); - // Register current font's english name as alias - const bool ttf = (textmetric->tmPitchAndFamily & TMPF_TRUETYPE); - if (ttf && qt_localizedName(faceName)) { - const QString englishName = qt_getEnglishName(faceName); - if (!englishName.isEmpty()) - QPlatformFontDatabase::registerAliasToFontFamily(faceName, englishName); - } - } - return 1; // continue -} - -void QWindowsFontDatabase::addDefaultEUDCFont() -{ - QString path; - { - HKEY key; - if (RegOpenKeyEx(HKEY_CURRENT_USER, - L"EUDC\\1252", - 0, - KEY_READ, - &key) != ERROR_SUCCESS) { - return; - } - - WCHAR value[MAX_PATH]; - DWORD bufferSize = sizeof(value); - ZeroMemory(value, bufferSize); - - if (RegQueryValueEx(key, - L"SystemDefaultEUDCFont", - nullptr, - nullptr, - reinterpret_cast<LPBYTE>(value), - &bufferSize) == ERROR_SUCCESS) { - path = QString::fromWCharArray(value); - } - - RegCloseKey(key); - } - - if (!path.isEmpty()) { - QFile file(path); - if (!file.open(QIODevice::ReadOnly)) { - qCWarning(lcQpaFonts) << "Unable to open default EUDC font:" << path; - return; - } - - m_eudcFonts = addApplicationFont(file.readAll(), path); - } -} - -void QWindowsFontDatabase::populateFontDatabase() -{ - removeApplicationFonts(); - HDC dummy = GetDC(0); - LOGFONT lf; - lf.lfCharSet = DEFAULT_CHARSET; - lf.lfFaceName[0] = 0; - lf.lfPitchAndFamily = 0; - EnumFontFamiliesEx(dummy, &lf, populateFontFamilies, 0, 0); - ReleaseDC(0, dummy); - // Work around EnumFontFamiliesEx() not listing the system font. - QString systemDefaultFamily = QWindowsFontDatabase::systemDefaultFont().family(); - if (QPlatformFontDatabase::resolveFontFamilyAlias(systemDefaultFamily) == systemDefaultFamily) - QPlatformFontDatabase::registerFontFamily(systemDefaultFamily); - addDefaultEUDCFont(); -} - -typedef QSharedPointer<QWindowsFontEngineData> QWindowsFontEngineDataPtr; - -typedef QThreadStorage<QWindowsFontEngineDataPtr> FontEngineThreadLocalData; - -Q_GLOBAL_STATIC(FontEngineThreadLocalData, fontEngineThreadLocalData) - -QSharedPointer<QWindowsFontEngineData> sharedFontData() -{ - FontEngineThreadLocalData *data = fontEngineThreadLocalData(); - if (!data->hasLocalData()) - data->setLocalData(QSharedPointer<QWindowsFontEngineData>::create()); - return data->localData(); -} - -QWindowsFontDatabase::QWindowsFontDatabase() -{ - // Properties accessed by QWin32PrintEngine (Qt Print Support) - static const int hfontMetaTypeId = qRegisterMetaType<HFONT>(); - static const int logFontMetaTypeId = qRegisterMetaType<LOGFONT>(); - Q_UNUSED(hfontMetaTypeId) - Q_UNUSED(logFontMetaTypeId) - - if (lcQpaFonts().isDebugEnabled()) { - const QWindowsFontEngineDataPtr data = sharedFontData(); - qCDebug(lcQpaFonts) << __FUNCTION__ << "Clear type: " - << data->clearTypeEnabled << "gamma: " << data->fontSmoothingGamma; - } -} - -QWindowsFontDatabase::~QWindowsFontDatabase() -{ - removeApplicationFonts(); -} - -QFontEngine * QWindowsFontDatabase::fontEngine(const QFontDef &fontDef, void *handle) -{ - const QString faceName(static_cast<const QChar*>(handle)); - QFontEngine *fe = QWindowsFontDatabase::createEngine(fontDef, faceName, - defaultVerticalDPI(), - sharedFontData()); - qCDebug(lcQpaFonts) << __FUNCTION__ << "FONTDEF" << fontDef << fe << handle; - return fe; -} - -QFontEngine *QWindowsFontDatabase::fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference) -{ - EmbeddedFont font(fontData); - QFontEngine *fontEngine = 0; - -#if !defined(QT_NO_DIRECTWRITE) - if (!useDirectWrite(hintingPreference)) -#endif - { - GUID guid; - CoCreateGuid(&guid); - -QT_WARNING_PUSH -QT_WARNING_DISABLE_GCC("-Wstrict-aliasing") - QString uniqueFamilyName = QLatin1Char('f') - + QString::number(guid.Data1, 36) + QLatin1Char('-') - + QString::number(guid.Data2, 36) + QLatin1Char('-') - + QString::number(guid.Data3, 36) + QLatin1Char('-') - + QString::number(*reinterpret_cast<quint64 *>(guid.Data4), 36); -QT_WARNING_POP - - QString actualFontName = font.changeFamilyName(uniqueFamilyName); - if (actualFontName.isEmpty()) { - qWarning("%s: Can't change family name of font", __FUNCTION__); - return 0; - } - - DWORD count = 0; - QByteArray newFontData = font.data(); - HANDLE fontHandle = - AddFontMemResourceEx(const_cast<char *>(newFontData.constData()), - DWORD(newFontData.size()), 0, &count); - if (count == 0 && fontHandle != 0) { - RemoveFontMemResourceEx(fontHandle); - fontHandle = 0; - } - - if (fontHandle == 0) { - qWarning("%s: AddFontMemResourceEx failed", __FUNCTION__); - } else { - QFontDef request; - request.family = uniqueFamilyName; - request.pixelSize = pixelSize; - request.styleStrategy = QFont::PreferMatch; - request.hintingPreference = hintingPreference; - request.stretch = QFont::Unstretched; - - fontEngine = QWindowsFontDatabase::createEngine(request, QString(), - defaultVerticalDPI(), - sharedFontData()); - - if (fontEngine) { - if (request.family != fontEngine->fontDef.family) { - qWarning("%s: Failed to load font. Got fallback instead: %s", - __FUNCTION__, qPrintable(fontEngine->fontDef.family)); - if (fontEngine->ref.load() == 0) - delete fontEngine; - fontEngine = 0; - } else { - Q_ASSERT(fontEngine->ref.load() == 0); - - // Override the generated font name - switch (fontEngine->type()) { - case QFontEngine::Win: - static_cast<QWindowsFontEngine *>(fontEngine)->setUniqueFamilyName(uniqueFamilyName); - fontEngine->fontDef.family = actualFontName; - break; - -#if !defined(QT_NO_DIRECTWRITE) - case QFontEngine::DirectWrite: - static_cast<QWindowsFontEngineDirectWrite *>(fontEngine)->setUniqueFamilyName(uniqueFamilyName); - fontEngine->fontDef.family = actualFontName; - break; -#endif // !QT_NO_DIRECTWRITE - - default: - Q_ASSERT_X(false, Q_FUNC_INFO, "Unhandled font engine."); - } - - UniqueFontData uniqueData; - uniqueData.handle = fontHandle; - uniqueData.refCount.ref(); - m_uniqueFontData[uniqueFamilyName] = uniqueData; - } - } else { - RemoveFontMemResourceEx(fontHandle); - } - } - } -#if !defined(QT_NO_DIRECTWRITE) - else { - CustomFontFileLoader fontFileLoader; - fontFileLoader.addKey(this, fontData); - - QSharedPointer<QWindowsFontEngineData> fontEngineData = sharedFontData(); - if (!initDirectWrite(fontEngineData.data())) - return 0; - - IDWriteFontFile *fontFile = 0; - void *key = this; - - HRESULT hres = fontEngineData->directWriteFactory->CreateCustomFontFileReference(&key, - sizeof(void *), - fontFileLoader.loader(), - &fontFile); - if (FAILED(hres)) { - qErrnoWarning(hres, "%s: CreateCustomFontFileReference failed", __FUNCTION__); - return 0; - } - - BOOL isSupportedFontType; - DWRITE_FONT_FILE_TYPE fontFileType; - DWRITE_FONT_FACE_TYPE fontFaceType; - UINT32 numberOfFaces; - fontFile->Analyze(&isSupportedFontType, &fontFileType, &fontFaceType, &numberOfFaces); - if (!isSupportedFontType) { - fontFile->Release(); - return 0; - } - - IDWriteFontFace *directWriteFontFace = 0; - hres = fontEngineData->directWriteFactory->CreateFontFace(fontFaceType, - 1, - &fontFile, - 0, - DWRITE_FONT_SIMULATIONS_NONE, - &directWriteFontFace); - if (FAILED(hres)) { - qErrnoWarning(hres, "%s: CreateFontFace failed", __FUNCTION__); - fontFile->Release(); - return 0; - } - - fontFile->Release(); - - fontEngine = new QWindowsFontEngineDirectWrite(directWriteFontFace, - pixelSize, - fontEngineData); - - // Get font family from font data - fontEngine->fontDef.family = font.familyName(); - fontEngine->fontDef.hintingPreference = hintingPreference; - - directWriteFontFace->Release(); - } -#endif - - // Get style and weight info - if (fontEngine != 0) { - TableDirectory *os2TableEntry = font.tableDirectoryEntry("OS/2"); - if (os2TableEntry != 0) { - const OS2Table *os2Table = - reinterpret_cast<const OS2Table *>(fontData.constData() - + qFromBigEndian<quint32>(os2TableEntry->offset)); - - bool italic = qFromBigEndian<quint16>(os2Table->selection) & (1 << 0); - bool oblique = qFromBigEndian<quint16>(os2Table->selection) & (1 << 9); - - if (italic) - fontEngine->fontDef.style = QFont::StyleItalic; - else if (oblique) - fontEngine->fontDef.style = QFont::StyleOblique; - else - fontEngine->fontDef.style = QFont::StyleNormal; - - fontEngine->fontDef.weight = QPlatformFontDatabase::weightFromInteger(qFromBigEndian<quint16>(os2Table->weightClass)); - } - } - - qCDebug(lcQpaFonts) << __FUNCTION__ << "FONTDATA" << fontData << pixelSize << hintingPreference << fontEngine; - return fontEngine; -} - -static QList<quint32> getTrueTypeFontOffsets(const uchar *fontData) -{ - QList<quint32> offsets; - const quint32 headerTag = *reinterpret_cast<const quint32 *>(fontData); - if (headerTag != MAKE_TAG('t', 't', 'c', 'f')) { - if (headerTag != MAKE_TAG(0, 1, 0, 0) - && headerTag != MAKE_TAG('O', 'T', 'T', 'O') - && headerTag != MAKE_TAG('t', 'r', 'u', 'e') - && headerTag != MAKE_TAG('t', 'y', 'p', '1')) - return offsets; - offsets << 0; - return offsets; - } - const quint32 numFonts = qFromBigEndian<quint32>(fontData + 8); - for (uint i = 0; i < numFonts; ++i) { - offsets << qFromBigEndian<quint32>(fontData + 12 + i * 4); - } - return offsets; -} - -static void getFontTable(const uchar *fileBegin, const uchar *data, quint32 tag, const uchar **table, quint32 *length) -{ - const quint16 numTables = qFromBigEndian<quint16>(data + 4); - for (uint i = 0; i < numTables; ++i) { - const quint32 offset = 12 + 16 * i; - if (*reinterpret_cast<const quint32 *>(data + offset) == tag) { - *table = fileBegin + qFromBigEndian<quint32>(data + offset + 8); - *length = qFromBigEndian<quint32>(data + offset + 12); - return; - } - } - *table = 0; - *length = 0; - return; -} - -static void getFamiliesAndSignatures(const QByteArray &fontData, - QList<QFontNames> *families, - QVector<FONTSIGNATURE> *signatures, - QVector<QFontValues> *values) -{ - const uchar *data = reinterpret_cast<const uchar *>(fontData.constData()); - - QList<quint32> offsets = getTrueTypeFontOffsets(data); - if (offsets.isEmpty()) - return; - - for (int i = 0; i < offsets.count(); ++i) { - const uchar *font = data + offsets.at(i); - const uchar *table; - quint32 length; - getFontTable(data, font, MAKE_TAG('n', 'a', 'm', 'e'), &table, &length); - if (!table) - continue; - QFontNames names = qt_getCanonicalFontNames(table, length); - if (names.name.isEmpty()) - continue; - - families->append(qMove(names)); - - if (values || signatures) - getFontTable(data, font, MAKE_TAG('O', 'S', '/', '2'), &table, &length); - - if (values) { - QFontValues fontValues; - if (table && length >= 64) { - // Read in some details about the font, offset calculated based on the specification - fontValues.weight = qFromBigEndian<quint16>(table + 4); - - quint16 fsSelection = qFromBigEndian<quint16>(table + 62); - fontValues.isItalic = (fsSelection & 1) != 0; - fontValues.isUnderlined = (fsSelection & (1 << 1)) != 0; - fontValues.isOverstruck = (fsSelection & (1 << 4)) != 0; - } - values->append(std::move(fontValues)); - } - - if (signatures) { - FONTSIGNATURE signature; - if (table && length >= 86) { - // Offsets taken from OS/2 table in the TrueType spec - signature.fsUsb[0] = qFromBigEndian<quint32>(table + 42); - signature.fsUsb[1] = qFromBigEndian<quint32>(table + 46); - signature.fsUsb[2] = qFromBigEndian<quint32>(table + 50); - signature.fsUsb[3] = qFromBigEndian<quint32>(table + 54); - - signature.fsCsb[0] = qFromBigEndian<quint32>(table + 78); - signature.fsCsb[1] = qFromBigEndian<quint32>(table + 82); - } else { - memset(&signature, 0, sizeof(signature)); - } - signatures->append(signature); - } - } -} - -QStringList QWindowsFontDatabase::addApplicationFont(const QByteArray &fontData, const QString &fileName) -{ - WinApplicationFont font; - font.fileName = fileName; - QVector<FONTSIGNATURE> signatures; - QVector<QFontValues> fontValues; - QList<QFontNames> families; - QStringList familyNames; - - if (!fontData.isEmpty()) { - getFamiliesAndSignatures(fontData, &families, &signatures, &fontValues); - if (families.isEmpty()) - return familyNames; - - DWORD dummy = 0; - font.handle = - AddFontMemResourceEx(const_cast<char *>(fontData.constData()), - DWORD(fontData.size()), 0, &dummy); - if (font.handle == 0) - return QStringList(); - - // Memory fonts won't show up in enumeration, so do add them the hard way. - for (int j = 0; j < families.count(); ++j) { - const auto &family = families.at(j); - const QString &familyName = family.name; - const QString &styleName = family.style; - familyNames << familyName; - HDC hdc = GetDC(0); - LOGFONT lf; - memset(&lf, 0, sizeof(LOGFONT)); - memcpy(lf.lfFaceName, familyName.utf16(), sizeof(wchar_t) * qMin(LF_FACESIZE - 1, familyName.size())); - lf.lfCharSet = DEFAULT_CHARSET; - const QFontValues &values = fontValues.at(j); - lf.lfWeight = values.weight; - if (values.isItalic) - lf.lfItalic = TRUE; - if (values.isOverstruck) - lf.lfStrikeOut = TRUE; - if (values.isUnderlined) - lf.lfUnderline = TRUE; - HFONT hfont = CreateFontIndirect(&lf); - HGDIOBJ oldobj = SelectObject(hdc, hfont); - - TEXTMETRIC textMetrics; - GetTextMetrics(hdc, &textMetrics); - - addFontToDatabase(familyName, styleName, lf, &textMetrics, &signatures.at(j), - TRUETYPE_FONTTYPE); - - SelectObject(hdc, oldobj); - DeleteObject(hfont); - ReleaseDC(0, hdc); - } - } else { - QFile f(fileName); - if (!f.open(QIODevice::ReadOnly)) - return QStringList(); - QByteArray data = f.readAll(); - f.close(); - - getFamiliesAndSignatures(data, &families, nullptr, nullptr); - if (families.isEmpty()) - return QStringList(); - - if (AddFontResourceExW((wchar_t*)fileName.utf16(), FR_PRIVATE, 0) == 0) - return QStringList(); - - font.handle = 0; - - // Fonts based on files are added via populate, as they will show up in font enumeration. - for (int j = 0; j < families.count(); ++j) { - const QString familyName = families.at(j).name; - familyNames << familyName; - populateFamily(familyName); - } - } - - m_applicationFonts << font; - - return familyNames; -} - -void QWindowsFontDatabase::removeApplicationFonts() -{ - for (const WinApplicationFont &font : qAsConst(m_applicationFonts)) { - if (font.handle) { - RemoveFontMemResourceEx(font.handle); - } else { - RemoveFontResourceExW(reinterpret_cast<LPCWSTR>(font.fileName.utf16()), - FR_PRIVATE, nullptr); - } - } - m_applicationFonts.clear(); - m_eudcFonts.clear(); -} - -void QWindowsFontDatabase::releaseHandle(void *handle) -{ - const QChar *faceName = reinterpret_cast<const QChar *>(handle); - delete[] faceName; -} - -QString QWindowsFontDatabase::fontDir() const -{ - const QString result = QPlatformFontDatabase::fontDir(); - qCDebug(lcQpaFonts) << __FUNCTION__ << result; - return result; -} - -bool QWindowsFontDatabase::fontsAlwaysScalable() const -{ - return false; -} - -void QWindowsFontDatabase::derefUniqueFont(const QString &uniqueFont) -{ - if (m_uniqueFontData.contains(uniqueFont)) { - if (!m_uniqueFontData[uniqueFont].refCount.deref()) { - RemoveFontMemResourceEx(m_uniqueFontData[uniqueFont].handle); - m_uniqueFontData.remove(uniqueFont); - } - } -} - -void QWindowsFontDatabase::refUniqueFont(const QString &uniqueFont) -{ - if (m_uniqueFontData.contains(uniqueFont)) - m_uniqueFontData[uniqueFont].refCount.ref(); -} - -// ### fixme Qt 6 (QTBUG-58610): See comment at QWindowsFontDatabase::systemDefaultFont() -HFONT QWindowsFontDatabase::systemFont() -{ - static const auto stock_sysfont = - reinterpret_cast<HFONT>(GetStockObject(DEFAULT_GUI_FONT)); - return stock_sysfont; -} - -// Creation functions - -static const char *other_tryFonts[] = { - "Arial", - "MS UI Gothic", - "Gulim", - "SimSun", - "PMingLiU", - "Arial Unicode MS", - 0 -}; - -static const char *jp_tryFonts [] = { - "MS UI Gothic", - "Arial", - "Gulim", - "SimSun", - "PMingLiU", - "Arial Unicode MS", - 0 -}; - -static const char *ch_CN_tryFonts [] = { - "SimSun", - "Arial", - "PMingLiU", - "Gulim", - "MS UI Gothic", - "Arial Unicode MS", - 0 -}; - -static const char *ch_TW_tryFonts [] = { - "PMingLiU", - "Arial", - "SimSun", - "Gulim", - "MS UI Gothic", - "Arial Unicode MS", - 0 -}; - -static const char *kr_tryFonts[] = { - "Gulim", - "Arial", - "PMingLiU", - "SimSun", - "MS UI Gothic", - "Arial Unicode MS", - 0 -}; - -static const char **tryFonts = 0; - -LOGFONT QWindowsFontDatabase::fontDefToLOGFONT(const QFontDef &request, const QString &faceName) -{ - LOGFONT lf; - memset(&lf, 0, sizeof(LOGFONT)); - - lf.lfHeight = -qRound(request.pixelSize); - lf.lfWidth = 0; - lf.lfEscapement = 0; - lf.lfOrientation = 0; - if (request.weight == 50) - lf.lfWeight = FW_DONTCARE; - else - lf.lfWeight = (request.weight*900)/99; - lf.lfItalic = request.style != QFont::StyleNormal; - lf.lfCharSet = DEFAULT_CHARSET; - - int strat = OUT_DEFAULT_PRECIS; - if (request.styleStrategy & QFont::PreferBitmap) { - strat = OUT_RASTER_PRECIS; - } else if (request.styleStrategy & QFont::PreferDevice) { - strat = OUT_DEVICE_PRECIS; - } else if (request.styleStrategy & QFont::PreferOutline) { - strat = OUT_OUTLINE_PRECIS; - } else if (request.styleStrategy & QFont::ForceOutline) { - strat = OUT_TT_ONLY_PRECIS; - } - - lf.lfOutPrecision = strat; - - int qual = DEFAULT_QUALITY; - - if (request.styleStrategy & QFont::PreferMatch) - qual = DRAFT_QUALITY; - else if (request.styleStrategy & QFont::PreferQuality) - qual = PROOF_QUALITY; - - if (request.styleStrategy & QFont::PreferAntialias) { - qual = (request.styleStrategy & QFont::NoSubpixelAntialias) == 0 - ? CLEARTYPE_QUALITY : ANTIALIASED_QUALITY; - } else if (request.styleStrategy & QFont::NoAntialias) { - qual = NONANTIALIASED_QUALITY; - } else if ((request.styleStrategy & QFont::NoSubpixelAntialias) && sharedFontData()->clearTypeEnabled) { - qual = ANTIALIASED_QUALITY; - } - - lf.lfQuality = qual; - - lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; - - int hint = FF_DONTCARE; - switch (request.styleHint) { - case QFont::Helvetica: - hint = FF_SWISS; - break; - case QFont::Times: - hint = FF_ROMAN; - break; - case QFont::Courier: - hint = FF_MODERN; - break; - case QFont::OldEnglish: - hint = FF_DECORATIVE; - break; - case QFont::System: - hint = FF_MODERN; - break; - default: - break; - } - - lf.lfPitchAndFamily = DEFAULT_PITCH | hint; - - QString fam = faceName; - if (fam.isEmpty()) - fam = request.family; - if (Q_UNLIKELY(fam.size() >= LF_FACESIZE)) { - qCritical("%s: Family name '%s' is too long.", __FUNCTION__, qPrintable(fam)); - fam.truncate(LF_FACESIZE - 1); - } - - if (fam.isEmpty()) - fam = QStringLiteral("MS Sans Serif"); - - if (fam == QLatin1String("MS Sans Serif") - && (request.style == QFont::StyleItalic || (-lf.lfHeight > 18 && -lf.lfHeight != 24))) { - fam = QStringLiteral("Arial"); // MS Sans Serif has bearing problems in italic, and does not scale - } - if (fam == QLatin1String("Courier") && !(request.styleStrategy & QFont::PreferBitmap)) - fam = QStringLiteral("Courier New"); - - memcpy(lf.lfFaceName, fam.utf16(), fam.size() * sizeof(wchar_t)); - - return lf; -} - -QStringList QWindowsFontDatabase::extraTryFontsForFamily(const QString &family) -{ - QStringList result; - QFontDatabase db; - if (!db.writingSystems(family).contains(QFontDatabase::Symbol)) { - if (!tryFonts) { - LANGID lid = GetUserDefaultLangID(); - switch (lid&0xff) { - case LANG_CHINESE: // Chinese - if ( lid == 0x0804 || lid == 0x1004) // China mainland and Singapore - tryFonts = ch_CN_tryFonts; - else - tryFonts = ch_TW_tryFonts; // Taiwan, Hong Kong and Macau - break; - case LANG_JAPANESE: - tryFonts = jp_tryFonts; - break; - case LANG_KOREAN: - tryFonts = kr_tryFonts; - break; - default: - tryFonts = other_tryFonts; - break; - } - } - QFontDatabase db; - const QStringList families = db.families(); - const char **tf = tryFonts; - while (tf && *tf) { - // QTBUG-31689, family might be an English alias for a localized font name. - const QString family = QString::fromLatin1(*tf); - if (families.contains(family) || db.hasFamily(family)) - result << family; - ++tf; - } - } - result.append(QStringLiteral("Segoe UI Emoji")); - result.append(QStringLiteral("Segoe UI Symbol")); - return result; -} - -QString QWindowsFontDatabase::familyForStyleHint(QFont::StyleHint styleHint) -{ - switch (styleHint) { - case QFont::Times: - return QStringLiteral("Times New Roman"); - case QFont::Courier: - return QStringLiteral("Courier New"); - case QFont::Monospace: - return QStringLiteral("Courier New"); - case QFont::Cursive: - return QStringLiteral("Comic Sans MS"); - case QFont::Fantasy: - return QStringLiteral("Impact"); - case QFont::Decorative: - return QStringLiteral("Old English"); - case QFont::Helvetica: - return QStringLiteral("Arial"); - case QFont::System: - default: - break; - } - return QStringLiteral("MS Shell Dlg 2"); -} - -QStringList QWindowsFontDatabase::fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const -{ - QStringList result; - result.append(QWindowsFontDatabase::familyForStyleHint(styleHint)); - result.append(m_eudcFonts); - result.append(QWindowsFontDatabase::extraTryFontsForFamily(family)); - result.append(QPlatformFontDatabase::fallbacksForFamily(family, style, styleHint, script)); - - qCDebug(lcQpaFonts) << __FUNCTION__ << family << style << styleHint - << script << result; - return result; -} - - -QFontEngine *QWindowsFontDatabase::createEngine(const QFontDef &request, const QString &faceName, - int dpi, - const QSharedPointer<QWindowsFontEngineData> &data) -{ - QFontEngine *fe = 0; - - LOGFONT lf = fontDefToLOGFONT(request, faceName); - const bool preferClearTypeAA = lf.lfQuality == CLEARTYPE_QUALITY; - - if (request.stretch != 100) { - HFONT hfont = CreateFontIndirect(&lf); - if (!hfont) { - qErrnoWarning("%s: CreateFontIndirect failed", __FUNCTION__); - hfont = QWindowsFontDatabase::systemFont(); - } - - HGDIOBJ oldObj = SelectObject(data->hdc, hfont); - TEXTMETRIC tm; - if (!GetTextMetrics(data->hdc, &tm)) - qErrnoWarning("%s: GetTextMetrics failed", __FUNCTION__); - else - lf.lfWidth = tm.tmAveCharWidth * request.stretch / 100; - SelectObject(data->hdc, oldObj); - - DeleteObject(hfont); - } - -#if !defined(QT_NO_DIRECTWRITE) - if (initDirectWrite(data.data())) { - const QString fam = QString::fromWCharArray(lf.lfFaceName); - const QString nameSubstitute = QWindowsFontEngineDirectWrite::fontNameSubstitute(fam); - if (nameSubstitute != fam) { - const int nameSubstituteLength = qMin(nameSubstitute.length(), LF_FACESIZE - 1); - memcpy(lf.lfFaceName, nameSubstitute.utf16(), nameSubstituteLength * sizeof(wchar_t)); - lf.lfFaceName[nameSubstituteLength] = 0; - } - - HFONT hfont = CreateFontIndirect(&lf); - if (!hfont) { - qErrnoWarning("%s: CreateFontIndirect failed", __FUNCTION__); - } else { - HGDIOBJ oldFont = SelectObject(data->hdc, hfont); - - IDWriteFontFace *directWriteFontFace = NULL; - HRESULT hr = data->directWriteGdiInterop->CreateFontFaceFromHdc(data->hdc, &directWriteFontFace); - if (FAILED(hr)) { - const QString errorString = qt_error_string(int(hr)); - qWarning().noquote().nospace() << "DirectWrite: CreateFontFaceFromHDC() failed (" - << errorString << ") for " << request << ' ' << lf << " dpi=" << dpi; - } else { - bool isColorFont = false; -#if defined(QT_USE_DIRECTWRITE2) - IDWriteFontFace2 *directWriteFontFace2 = nullptr; - if (SUCCEEDED(directWriteFontFace->QueryInterface(__uuidof(IDWriteFontFace2), - reinterpret_cast<void **>(&directWriteFontFace2)))) { - if (directWriteFontFace2->IsColorFont()) - isColorFont = directWriteFontFace2->GetPaletteEntryCount() > 0; - } -#endif - const QFont::HintingPreference hintingPreference = - static_cast<QFont::HintingPreference>(request.hintingPreference); - const bool useDw = useDirectWrite(hintingPreference, fam, isColorFont); - qCDebug(lcQpaFonts) << __FUNCTION__ << request.family << request.pointSize - << "pt" << "hintingPreference=" << hintingPreference << "color=" << isColorFont - << dpi << "dpi" << "useDirectWrite=" << useDw; - if (useDw) { - QWindowsFontEngineDirectWrite *fedw = new QWindowsFontEngineDirectWrite(directWriteFontFace, - request.pixelSize, - data); - - wchar_t n[64]; - GetTextFace(data->hdc, 64, n); - - QFontDef fontDef = request; - fontDef.family = QString::fromWCharArray(n); - - if (isColorFont) - fedw->glyphFormat = QFontEngine::Format_ARGB; - fedw->initFontInfo(fontDef, dpi); - fe = fedw; - } else { - directWriteFontFace->Release(); - } - } - - SelectObject(data->hdc, oldFont); - DeleteObject(hfont); - } - } -#endif // QT_NO_DIRECTWRITE - - if (!fe) { - QWindowsFontEngine *few = new QWindowsFontEngine(request.family, lf, data); - if (preferClearTypeAA) - few->glyphFormat = QFontEngine::Format_A32; - few->initFontInfo(request, dpi); - fe = few; - } - - return fe; -} - -QFont QWindowsFontDatabase::systemDefaultFont() -{ -#if QT_VERSION >= 0x060000 - // Qt 6: Obtain default GUI font (typically "Segoe UI, 9pt", see QTBUG-58610) - NONCLIENTMETRICS ncm; - ncm.cbSize = FIELD_OFFSET(NONCLIENTMETRICS, lfMessageFont) + sizeof(LOGFONT); - SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize , &ncm, 0); - const QFont systemFont = QWindowsFontDatabase::LOGFONT_to_QFont(ncm.lfMessageFont); -#else - LOGFONT lf; - GetObject(QWindowsFontDatabase::systemFont(), sizeof(lf), &lf); - QFont systemFont = QWindowsFontDatabase::LOGFONT_to_QFont(lf); - // "MS Shell Dlg 2" is the correct system font >= Win2k - if (systemFont.family() == QLatin1String("MS Shell Dlg")) - systemFont.setFamily(QStringLiteral("MS Shell Dlg 2")); - // Qt 5 by (Qt 4) legacy uses GetStockObject(DEFAULT_GUI_FONT) to - // obtain the default GUI font (typically "MS Shell Dlg 2, 8pt"). This has been - // long deprecated; the message font of the NONCLIENTMETRICS structure obtained by - // SystemParametersInfo(SPI_GETNONCLIENTMETRICS) should be used instead (see - // QWindowsTheme::refreshFonts(), typically "Segoe UI, 9pt"), which is larger. -#endif // Qt 5 - qCDebug(lcQpaFonts) << __FUNCTION__ << systemFont; - return systemFont; -} - -QFont QWindowsFontDatabase::LOGFONT_to_QFont(const LOGFONT& logFont, int verticalDPI_In) -{ - if (verticalDPI_In <= 0) - verticalDPI_In = defaultVerticalDPI(); - QFont qFont(QString::fromWCharArray(logFont.lfFaceName)); - qFont.setItalic(logFont.lfItalic); - if (logFont.lfWeight != FW_DONTCARE) - qFont.setWeight(QPlatformFontDatabase::weightFromInteger(logFont.lfWeight)); - const qreal logFontHeight = qAbs(logFont.lfHeight); - qFont.setPointSizeF(logFontHeight * 72.0 / qreal(verticalDPI_In)); - qFont.setUnderline(logFont.lfUnderline); - qFont.setOverline(false); - qFont.setStrikeOut(logFont.lfStrikeOut); - return qFont; -} - -int QWindowsFontDatabase::defaultVerticalDPI() -{ - static int vDPI = -1; - if (vDPI == -1) { - if (HDC defaultDC = GetDC(0)) { - vDPI = GetDeviceCaps(defaultDC, LOGPIXELSY); - ReleaseDC(0, defaultDC); - } else { - // FIXME: Resolve now or return 96 and keep unresolved? - vDPI = 96; - } - } - return vDPI; -} - -QString QWindowsFontDatabase::readRegistryString(HKEY parentHandle, const wchar_t *keyPath, const wchar_t *keyName) -{ - QString result; - HKEY handle = 0; - if (RegOpenKeyEx(parentHandle, keyPath, 0, KEY_READ, &handle) == ERROR_SUCCESS) { - // get the size and type of the value - DWORD dataType; - DWORD dataSize; - if (RegQueryValueEx(handle, keyName, 0, &dataType, 0, &dataSize) == ERROR_SUCCESS) { - if (dataType == REG_SZ || dataType == REG_EXPAND_SZ) { - dataSize += 2; // '\0' missing? - QVarLengthArray<unsigned char> data(dataSize); - data[dataSize - 2] = data[dataSize - 1] = '\0'; - if (RegQueryValueEx(handle, keyName, 0, 0, data.data(), &dataSize) == ERROR_SUCCESS) - result = QString::fromWCharArray(reinterpret_cast<const wchar_t *>(data.data())); - } - } - RegCloseKey(handle); - } - return result; -} - -bool QWindowsFontDatabase::isPrivateFontFamily(const QString &family) const -{ - return m_eudcFonts.contains(family) || QPlatformFontDatabase::isPrivateFontFamily(family); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase_ft.cpp b/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase_ft.cpp deleted file mode 100644 index fdef0f5ff1..0000000000 --- a/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase_ft.cpp +++ /dev/null @@ -1,444 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qwindowsfontdatabase_ft_p.h" -#include "qwindowsfontdatabase_p.h" - -#include <QtFontDatabaseSupport/private/qfontengine_ft_p.h> - -#include <ft2build.h> -#include FT_TRUETYPE_TABLES_H - -#include <QtCore/QDir> -#include <QtCore/QDirIterator> -#include <QtCore/QSettings> -#include <QtCore/QRegularExpression> -#include <QtGui/QGuiApplication> -#include <QtGui/QFontDatabase> - -#include <wchar.h> - -QT_BEGIN_NAMESPACE - -static inline QFontDatabase::WritingSystem writingSystemFromCharSet(uchar charSet) -{ - switch (charSet) { - case ANSI_CHARSET: - case EASTEUROPE_CHARSET: - case BALTIC_CHARSET: - case TURKISH_CHARSET: - return QFontDatabase::Latin; - case GREEK_CHARSET: - return QFontDatabase::Greek; - case RUSSIAN_CHARSET: - return QFontDatabase::Cyrillic; - case HEBREW_CHARSET: - return QFontDatabase::Hebrew; - case ARABIC_CHARSET: - return QFontDatabase::Arabic; - case THAI_CHARSET: - return QFontDatabase::Thai; - case GB2312_CHARSET: - return QFontDatabase::SimplifiedChinese; - case CHINESEBIG5_CHARSET: - return QFontDatabase::TraditionalChinese; - case SHIFTJIS_CHARSET: - return QFontDatabase::Japanese; - case HANGUL_CHARSET: - case JOHAB_CHARSET: - return QFontDatabase::Korean; - case VIETNAMESE_CHARSET: - return QFontDatabase::Vietnamese; - case SYMBOL_CHARSET: - return QFontDatabase::Symbol; - default: - break; - } - return QFontDatabase::Any; -} - -static FontFile * createFontFile(const QString &fileName, int index) -{ - FontFile *fontFile = new FontFile; - fontFile->fileName = fileName; - fontFile->indexValue = index; - return fontFile; -} - -namespace { -struct FontKey -{ - QString fileName; - QStringList fontNames; -}; -} // namespace - -typedef QVector<FontKey> FontKeys; - -static FontKeys &fontKeys() -{ - static FontKeys result; - if (result.isEmpty()) { - const QStringList keys = { QStringLiteral("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"), - QStringLiteral("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts") }; - for (const auto key : keys) { - const QSettings fontRegistry(key, QSettings::NativeFormat); - const QStringList allKeys = fontRegistry.allKeys(); - const QString trueType = QStringLiteral("(TrueType)"); -#if QT_CONFIG(regularexpression) - const QRegularExpression sizeListMatch(QStringLiteral("\\s(\\d+,)+\\d+")); -#else - const QRegExp sizeListMatch(QLatin1String("\\s(\\d+,)+\\d+")); -#endif - Q_ASSERT(sizeListMatch.isValid()); - const int size = allKeys.size(); - result.reserve(result.size() + size); - for (int i = 0; i < size; ++i) { - FontKey fontKey; - const QString ®istryFontKey = allKeys.at(i); - fontKey.fileName = fontRegistry.value(registryFontKey).toString(); - QString realKey = registryFontKey; - realKey.remove(trueType); - realKey.remove(sizeListMatch); - const auto fontNames = QStringRef(&realKey).trimmed().split(QLatin1Char('&')); - fontKey.fontNames.reserve(fontNames.size()); - for (const QStringRef &fontName : fontNames) - fontKey.fontNames.append(fontName.trimmed().toString()); - result.append(fontKey); - } - } - } - return result; -} - -static const FontKey *findFontKey(const QString &name, int *indexIn = nullptr) -{ - const FontKeys &keys = fontKeys(); - for (auto it = keys.constBegin(), cend = keys.constEnd(); it != cend; ++it) { - const int index = it->fontNames.indexOf(name); - if (index >= 0) { - if (indexIn) - *indexIn = index; - return &(*it); - } - } - if (indexIn) - *indexIn = -1; - return nullptr; -} - -static bool addFontToDatabase(QString familyName, - QString styleName, - const QString &fullName, - const LOGFONT &logFont, - const TEXTMETRIC *textmetric, - const FONTSIGNATURE *signature, - int type) -{ - // the "@family" fonts are just the same as "family". Ignore them. - if (familyName.isEmpty() || familyName.at(0) == QLatin1Char('@') || familyName.startsWith(QLatin1String("WST_"))) - return false; - - uchar charSet = logFont.lfCharSet; - - static const int SMOOTH_SCALABLE = 0xffff; - const QString foundryName; // No such concept. - const bool fixed = !(textmetric->tmPitchAndFamily & TMPF_FIXED_PITCH); - const bool ttf = (textmetric->tmPitchAndFamily & TMPF_TRUETYPE); - const bool scalable = textmetric->tmPitchAndFamily & (TMPF_VECTOR|TMPF_TRUETYPE); - const int size = scalable ? SMOOTH_SCALABLE : textmetric->tmHeight; - const QFont::Style style = textmetric->tmItalic ? QFont::StyleItalic : QFont::StyleNormal; - const bool antialias = false; - const QFont::Weight weight = QPlatformFontDatabase::weightFromInteger(textmetric->tmWeight); - const QFont::Stretch stretch = QFont::Unstretched; - -#ifndef QT_NO_DEBUG_STREAM - if (lcQpaFonts().isDebugEnabled()) { - QString message; - QTextStream str(&message); - str << __FUNCTION__ << ' ' << familyName << "::" << fullName << ' ' << charSet << " TTF=" << ttf; - if (type & DEVICE_FONTTYPE) - str << " DEVICE"; - if (type & RASTER_FONTTYPE) - str << " RASTER"; - if (type & TRUETYPE_FONTTYPE) - str << " TRUETYPE"; - str << " scalable=" << scalable << " Size=" << size - << " Style=" << style << " Weight=" << weight - << " stretch=" << stretch; - qCDebug(lcQpaFonts) << message; - } -#endif - - QString englishName; - QString faceName = familyName; - - QString subFamilyName; - QString subFamilyStyle; - if (ttf) { - // Look-up names registered in the font - QFontNames canonicalNames = qt_getCanonicalFontNames(logFont); - if (qt_localizedName(familyName) && !canonicalNames.name.isEmpty()) - englishName = canonicalNames.name; - if (!canonicalNames.preferredName.isEmpty()) { - subFamilyName = familyName; - subFamilyStyle = styleName; - familyName = canonicalNames.preferredName; - styleName = canonicalNames.preferredStyle; - } - } - - QSupportedWritingSystems writingSystems; - if (type & TRUETYPE_FONTTYPE) { - Q_ASSERT(signature); - quint32 unicodeRange[4] = { - signature->fsUsb[0], signature->fsUsb[1], - signature->fsUsb[2], signature->fsUsb[3] - }; - quint32 codePageRange[2] = { - signature->fsCsb[0], signature->fsCsb[1] - }; - writingSystems = QPlatformFontDatabase::writingSystemsFromTrueTypeBits(unicodeRange, codePageRange); - // ### Hack to work around problem with Thai text on Windows 7. Segoe UI contains - // the symbol for Baht, and Windows thus reports that it supports the Thai script. - // Since it's the default UI font on this platform, most widgets will be unable to - // display Thai text by default. As a temporary work around, we special case Segoe UI - // and remove the Thai script from its list of supported writing systems. - if (writingSystems.supported(QFontDatabase::Thai) && - faceName == QLatin1String("Segoe UI")) - writingSystems.setSupported(QFontDatabase::Thai, false); - } else { - const QFontDatabase::WritingSystem ws = writingSystemFromCharSet(charSet); - if (ws != QFontDatabase::Any) - writingSystems.setSupported(ws); - } - - int index = 0; - const FontKey *key = findFontKey(fullName, &index); - if (!key) { - // On non-English locales, the styles of the font may be localized in enumeration, but - // not in the registry. - QLocale systemLocale = QLocale::system(); - if (systemLocale.language() != QLocale::C - && systemLocale.language() != QLocale::English - && styleName != QLatin1String("Italic") - && styleName != QLatin1String("Bold")) { - key = findFontKey(qt_getEnglishName(fullName, true), &index); - } - if (!key) - key = findFontKey(faceName, &index); - if (!key && !englishName.isEmpty()) - key = findFontKey(englishName, &index); - if (!key) - return false; - } - QString value = key->fileName; - if (value.isEmpty()) - return false; - - if (!QDir::isAbsolutePath(value)) - value.prepend(QFile::decodeName(qgetenv("windir") + "\\Fonts\\")); - - QPlatformFontDatabase::registerFont(familyName, styleName, foundryName, weight, style, stretch, - antialias, scalable, size, fixed, writingSystems, createFontFile(value, index)); - - // add fonts windows can generate for us: - if (weight <= QFont::DemiBold && styleName.isEmpty()) - QPlatformFontDatabase::registerFont(familyName, QString(), foundryName, QFont::Bold, style, stretch, - antialias, scalable, size, fixed, writingSystems, createFontFile(value, index)); - - if (style != QFont::StyleItalic && styleName.isEmpty()) - QPlatformFontDatabase::registerFont(familyName, QString(), foundryName, weight, QFont::StyleItalic, stretch, - antialias, scalable, size, fixed, writingSystems, createFontFile(value, index)); - - if (weight <= QFont::DemiBold && style != QFont::StyleItalic && styleName.isEmpty()) - QPlatformFontDatabase::registerFont(familyName, QString(), foundryName, QFont::Bold, QFont::StyleItalic, stretch, - antialias, scalable, size, fixed, writingSystems, createFontFile(value, index)); - - if (!subFamilyName.isEmpty() && familyName != subFamilyName) { - QPlatformFontDatabase::registerFont(subFamilyName, subFamilyStyle, foundryName, weight, - style, stretch, antialias, scalable, size, fixed, writingSystems, createFontFile(value, index)); - } - - if (!englishName.isEmpty() && englishName != familyName) - QPlatformFontDatabase::registerAliasToFontFamily(familyName, englishName); - - return true; -} - -static int QT_WIN_CALLBACK storeFont(const LOGFONT *logFont, const TEXTMETRIC *textmetric, - DWORD type, LPARAM lparam) -{ - const ENUMLOGFONTEX *f = reinterpret_cast<const ENUMLOGFONTEX *>(logFont); - const QString faceName = QString::fromWCharArray(f->elfLogFont.lfFaceName); - const QString styleName = QString::fromWCharArray(f->elfStyle); - const QString fullName = QString::fromWCharArray(f->elfFullName); - - // NEWTEXTMETRICEX (passed for TT fonts) is a NEWTEXTMETRIC, which according - // to the documentation is identical to a TEXTMETRIC except for the last four - // members, which we don't use anyway - const FONTSIGNATURE *signature = nullptr; - if (type & TRUETYPE_FONTTYPE) { - signature = &reinterpret_cast<const NEWTEXTMETRICEX *>(textmetric)->ntmFontSig; - // We get a callback for each script-type supported, but we register them all - // at once using the signature, so we only need one call to addFontToDatabase(). - QSet<QPair<QString,QString>> *foundFontAndStyles = reinterpret_cast<QSet<QPair<QString,QString>> *>(lparam); - QPair<QString,QString> fontAndStyle(faceName, styleName); - if (foundFontAndStyles->contains(fontAndStyle)) - return 1; - foundFontAndStyles->insert(fontAndStyle); - } - addFontToDatabase(faceName, styleName, fullName, *logFont, textmetric, signature, type); - - // keep on enumerating - return 1; -} - -/*! - \brief Populate font database using EnumFontFamiliesEx(). - - Normally, leaving the name empty should enumerate - all fonts, however, system fonts like "MS Shell Dlg 2" - are only found when specifying the name explicitly. -*/ - -void QWindowsFontDatabaseFT::populateFamily(const QString &familyName) -{ - qCDebug(lcQpaFonts) << familyName; - if (familyName.size() >= LF_FACESIZE) { - qCWarning(lcQpaFonts) << "Unable to enumerate family '" << familyName << '\''; - return; - } - HDC dummy = GetDC(0); - LOGFONT lf; - memset(&lf, 0, sizeof(LOGFONT)); - familyName.toWCharArray(lf.lfFaceName); - lf.lfFaceName[familyName.size()] = 0; - lf.lfCharSet = DEFAULT_CHARSET; - lf.lfPitchAndFamily = 0; - QSet<QPair<QString,QString>> foundFontAndStyles; - EnumFontFamiliesEx(dummy, &lf, storeFont, reinterpret_cast<intptr_t>(&foundFontAndStyles), 0); - ReleaseDC(0, dummy); -} - -// Delayed population of font families - -static int QT_WIN_CALLBACK populateFontFamilies(const LOGFONT *logFont, const TEXTMETRIC *textmetric, - DWORD, LPARAM) -{ - const ENUMLOGFONTEX *f = reinterpret_cast<const ENUMLOGFONTEX *>(logFont); - // the "@family" fonts are just the same as "family". Ignore them. - const wchar_t *faceNameW = f->elfLogFont.lfFaceName; - if (faceNameW[0] && faceNameW[0] != L'@' && wcsncmp(faceNameW, L"WST_", 4)) { - // Register only font families for which a font file exists for delayed population - const bool ttf = textmetric->tmPitchAndFamily & TMPF_TRUETYPE; - const QString faceName = QString::fromWCharArray(faceNameW); - const FontKey *key = findFontKey(faceName); - if (!key) { - key = findFontKey(QString::fromWCharArray(f->elfFullName)); - if (!key && ttf && qt_localizedName(faceName)) - key = findFontKey(qt_getEnglishName(faceName)); - } - if (key) { - QPlatformFontDatabase::registerFontFamily(faceName); - // Register current font's english name as alias - if (ttf && qt_localizedName(faceName)) { - const QString englishName = qt_getEnglishName(faceName); - if (!englishName.isEmpty()) - QPlatformFontDatabase::registerAliasToFontFamily(faceName, englishName); - } - } - } - return 1; // continue -} - -void QWindowsFontDatabaseFT::populateFontDatabase() -{ - HDC dummy = GetDC(0); - LOGFONT lf; - lf.lfCharSet = DEFAULT_CHARSET; - lf.lfFaceName[0] = 0; - lf.lfPitchAndFamily = 0; - EnumFontFamiliesEx(dummy, &lf, populateFontFamilies, 0, 0); - ReleaseDC(0, dummy); - // Work around EnumFontFamiliesEx() not listing the system font - QString systemDefaultFamily = QWindowsFontDatabase::systemDefaultFont().family(); - if (QPlatformFontDatabase::resolveFontFamilyAlias(systemDefaultFamily) == systemDefaultFamily) - QPlatformFontDatabase::registerFontFamily(systemDefaultFamily); -} - -QFontEngine * QWindowsFontDatabaseFT::fontEngine(const QFontDef &fontDef, void *handle) -{ - QFontEngine *fe = QFreeTypeFontDatabase::fontEngine(fontDef, handle); - qCDebug(lcQpaFonts) << __FUNCTION__ << "FONTDEF" << fontDef.family << fe << handle; - return fe; -} - -QFontEngine *QWindowsFontDatabaseFT::fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference) -{ - QFontEngine *fe = QFreeTypeFontDatabase::fontEngine(fontData, pixelSize, hintingPreference); - qCDebug(lcQpaFonts) << __FUNCTION__ << "FONTDATA" << fontData << pixelSize << hintingPreference << fe; - return fe; -} - -QStringList QWindowsFontDatabaseFT::fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const -{ - QStringList result; - result.append(QWindowsFontDatabase::familyForStyleHint(styleHint)); - result.append(QWindowsFontDatabase::extraTryFontsForFamily(family)); - result.append(QFreeTypeFontDatabase::fallbacksForFamily(family, style, styleHint, script)); - - qCDebug(lcQpaFonts) << __FUNCTION__ << family << style << styleHint - << script << result; - - return result; -} -QString QWindowsFontDatabaseFT::fontDir() const -{ - const QString result = QLatin1String(qgetenv("windir")) + QLatin1String("/Fonts");//QPlatformFontDatabase::fontDir(); - qCDebug(lcQpaFonts) << __FUNCTION__ << result; - return result; -} - -QFont QWindowsFontDatabaseFT::defaultFont() const -{ - return QWindowsFontDatabase::systemDefaultFont(); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase_ft_p.h b/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase_ft_p.h deleted file mode 100644 index c3d201b3a0..0000000000 --- a/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase_ft_p.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QWINDOWSFONTDATABASEFT_H -#define QWINDOWSFONTDATABASEFT_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtFontDatabaseSupport/private/qfreetypefontdatabase_p.h> -#include <QtCore/QSharedPointer> -#include <QtCore/qt_windows.h> - -QT_BEGIN_NAMESPACE - -class QWindowsFontDatabaseFT : public QFreeTypeFontDatabase -{ -public: - void populateFontDatabase() override; - void populateFamily(const QString &familyName) override; - QFontEngine *fontEngine(const QFontDef &fontDef, void *handle) override; - QFontEngine *fontEngine(const QByteArray &fontData, qreal pixelSize, - QFont::HintingPreference hintingPreference) override; - - QStringList fallbacksForFamily(const QString &family, QFont::Style style, - QFont::StyleHint styleHint, - QChar::Script script) const override; - - QString fontDir() const override; - QFont defaultFont() const override; -}; - -QT_END_NAMESPACE - -#endif // QWINDOWSFONTDATABASEFT_H diff --git a/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase_p.h b/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase_p.h deleted file mode 100644 index afba86bbe1..0000000000 --- a/src/platformsupport/fontdatabases/windows/qwindowsfontdatabase_p.h +++ /dev/null @@ -1,193 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QWINDOWSFONTDATABASE_H -#define QWINDOWSFONTDATABASE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <qpa/qplatformfontdatabase.h> -#include <QtCore/QSharedPointer> -#include <QtCore/QLoggingCategory> -#include <QtCore/qt_windows.h> - -#if !defined(QT_NO_DIRECTWRITE) - struct IDWriteFactory; - struct IDWriteGdiInterop; -#endif - -QT_BEGIN_NAMESPACE - -Q_DECLARE_LOGGING_CATEGORY(lcQpaFonts) - -class QWindowsFontEngineData -{ - Q_DISABLE_COPY(QWindowsFontEngineData) -public: - QWindowsFontEngineData(); - ~QWindowsFontEngineData(); - - uint pow_gamma[256]; - - bool clearTypeEnabled = false; - qreal fontSmoothingGamma; - HDC hdc = 0; -#if !defined(QT_NO_DIRECTWRITE) - IDWriteFactory *directWriteFactory = nullptr; - IDWriteGdiInterop *directWriteGdiInterop = nullptr; -#endif -}; - -class QWindowsFontDatabase : public QPlatformFontDatabase -{ - Q_DISABLE_COPY(QWindowsFontDatabase) -public: - enum FontOptions { - // Relevant bits from QWindowsIntegration::Options - DontUseDirectWriteFonts = 0x40, - DontUseColorFonts = 0x80 - }; - - QWindowsFontDatabase(); - ~QWindowsFontDatabase() override; - - void populateFontDatabase() override; - void populateFamily(const QString &familyName) override; - QFontEngine *fontEngine(const QFontDef &fontDef, void *handle) override; - QFontEngine *fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference) override; - QStringList fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const override; - QStringList addApplicationFont(const QByteArray &fontData, const QString &fileName) override; - void releaseHandle(void *handle) override; - QString fontDir() const override; - - QFont defaultFont() const override { return systemDefaultFont(); } - bool fontsAlwaysScalable() const override; - void derefUniqueFont(const QString &uniqueFont); - void refUniqueFont(const QString &uniqueFont); - bool isPrivateFontFamily(const QString &family) const override; - - static QFont systemDefaultFont(); - - static QFontEngine *createEngine(const QFontDef &request, const QString &faceName, - int dpi, - const QSharedPointer<QWindowsFontEngineData> &data); - - static HFONT systemFont(); - static QFont LOGFONT_to_QFont(const LOGFONT& lf, int verticalDPI = 0); - - static qreal fontSmoothingGamma(); - static LOGFONT fontDefToLOGFONT(const QFontDef &fontDef, const QString &faceName); - - static QStringList extraTryFontsForFamily(const QString &family); - static QString familyForStyleHint(QFont::StyleHint styleHint); - - static int defaultVerticalDPI(); - - static void setFontOptions(unsigned options); - static unsigned fontOptions(); - - static QString readRegistryString(HKEY parentHandle, const wchar_t *keyPath, const wchar_t *keyName); - -private: - void removeApplicationFonts(); - void addDefaultEUDCFont(); - - struct WinApplicationFont { - HANDLE handle; - QString fileName; - }; - - QList<WinApplicationFont> m_applicationFonts; - - struct UniqueFontData { - HANDLE handle; - QAtomicInt refCount; - }; - - QMap<QString, UniqueFontData> m_uniqueFontData; - - static unsigned m_fontOptions; - QStringList m_eudcFonts; -}; - -#ifndef QT_NO_DEBUG_STREAM -QDebug operator<<(QDebug, const QFontDef &def); -#endif - -inline quint16 qt_getUShort(const unsigned char *p) -{ - quint16 val; - val = *p++ << 8; - val |= *p; - - return val; -} - -struct QFontNames -{ - QString name; // e.g. "DejaVu Sans Condensed" - QString style; // e.g. "Italic" - QString preferredName; // e.g. "DejaVu Sans" - QString preferredStyle; // e.g. "Condensed Italic" -}; - -struct QFontValues -{ - quint16 weight = 0; - bool isItalic = false; - bool isOverstruck = false; - bool isUnderlined = false; -}; - -bool qt_localizedName(const QString &name); -QString qt_getEnglishName(const QString &familyName, bool includeStyle = false); -QFontNames qt_getCanonicalFontNames(const LOGFONT &lf); - -QT_END_NAMESPACE - -#endif // QWINDOWSFONTDATABASE_H diff --git a/src/platformsupport/fontdatabases/windows/qwindowsfontengine.cpp b/src/platformsupport/fontdatabases/windows/qwindowsfontengine.cpp deleted file mode 100644 index 2ae378c558..0000000000 --- a/src/platformsupport/fontdatabases/windows/qwindowsfontengine.cpp +++ /dev/null @@ -1,1211 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qwindowsfontengine_p.h" -#include "qwindowsnativeimage_p.h" -#include "qwindowsfontdatabase_p.h" -#include <QtCore/qt_windows.h> -#include "qwindowsfontenginedirectwrite_p.h" - -#include <QtGui/qpa/qplatformintegration.h> -#include <QtGui/private/qtextengine_p.h> // glyph_metrics_t -#include <QtGui/private/qguiapplication_p.h> -#include <QtGui/QPaintDevice> -#include <QtGui/QBitmap> -#include <QtGui/QPainter> -#include <QtGui/private/qpainter_p.h> -#include <QtGui/QPaintEngine> -#include <QtGui/private/qpaintengine_raster_p.h> - -#include <QtCore/QtEndian> -#include <QtCore/QFile> -#include <QtCore/qmath.h> -#include <QtCore/QTextStream> -#include <QtCore/QThreadStorage> -#include <QtCore/private/qsystemlibrary_p.h> -#include <QtCore/private/qstringiterator_p.h> - -#include <QtCore/QDebug> - -#include <limits.h> - -#if !defined(QT_NO_DIRECTWRITE) -# include <dwrite.h> -# include <comdef.h> -#endif - -QT_BEGIN_NAMESPACE - -//### mingw needed define -#ifndef TT_PRIM_CSPLINE -#define TT_PRIM_CSPLINE 3 -#endif - -// GetFontData expects the tags in little endian ;( -#define MAKE_LITTLE_ENDIAN_TAG(ch1, ch2, ch3, ch4) (\ - (((quint32)(ch4)) << 24) | \ - (((quint32)(ch3)) << 16) | \ - (((quint32)(ch2)) << 8) | \ - ((quint32)(ch1)) \ - ) - -// common DC for all fonts - -typedef BOOL (WINAPI *PtrGetCharWidthI)(HDC, UINT, UINT, LPWORD, LPINT); -static PtrGetCharWidthI ptrGetCharWidthI = 0; -static bool resolvedGetCharWidthI = false; - -static void resolveGetCharWidthI() -{ - if (resolvedGetCharWidthI) - return; - resolvedGetCharWidthI = true; - ptrGetCharWidthI = (PtrGetCharWidthI)QSystemLibrary::resolve(QStringLiteral("gdi32"), "GetCharWidthI"); -} - -// general font engine - -QFixed QWindowsFontEngine::lineThickness() const -{ - if(lineWidth > 0) - return lineWidth; - - return QFontEngine::lineThickness(); -} - -static OUTLINETEXTMETRIC *getOutlineTextMetric(HDC hdc) -{ - const auto size = GetOutlineTextMetrics(hdc, 0, nullptr); - auto otm = reinterpret_cast<OUTLINETEXTMETRIC *>(malloc(size)); - GetOutlineTextMetrics(hdc, size, otm); - return otm; -} - -bool QWindowsFontEngine::hasCFFTable() const -{ - HDC hdc = m_fontEngineData->hdc; - SelectObject(hdc, hfont); - return GetFontData(hdc, MAKE_LITTLE_ENDIAN_TAG('C', 'F', 'F', ' '), 0, 0, 0) != GDI_ERROR; -} - -bool QWindowsFontEngine::hasCMapTable() const -{ - HDC hdc = m_fontEngineData->hdc; - SelectObject(hdc, hfont); - return GetFontData(hdc, MAKE_LITTLE_ENDIAN_TAG('c', 'm', 'a', 'p'), 0, 0, 0) != GDI_ERROR; -} - -static inline QString stringFromOutLineTextMetric(const OUTLINETEXTMETRIC *otm, PSTR offset) -{ - const uchar *p = reinterpret_cast<const uchar *>(otm) + quintptr(offset); - return QString::fromWCharArray(reinterpret_cast<const wchar_t *>(p)); -} - -void QWindowsFontEngine::getCMap() -{ - ttf = (bool)(tm.tmPitchAndFamily & TMPF_TRUETYPE) || hasCMapTable(); - - cffTable = hasCFFTable(); - - HDC hdc = m_fontEngineData->hdc; - SelectObject(hdc, hfont); - bool symb = false; - if (ttf) { - cmapTable = getSfntTable(MAKE_TAG('c', 'm', 'a', 'p')); - cmap = QFontEngine::getCMap(reinterpret_cast<const uchar *>(cmapTable.constData()), - cmapTable.size(), &symb, &cmapSize); - } - if (!cmap) { - ttf = false; - symb = false; - } - symbol = symb; - designToDevice = 1; - _faceId.index = 0; - if(cmap) { - OUTLINETEXTMETRIC *otm = getOutlineTextMetric(hdc); - unitsPerEm = int(otm->otmEMSquare); - const QFixed unitsPerEmF(unitsPerEm); - designToDevice = unitsPerEmF / QFixed::fromReal(fontDef.pixelSize); - x_height = int(otm->otmsXHeight); - loadKerningPairs(designToDevice); - _faceId.filename = QFile::encodeName(stringFromOutLineTextMetric(otm, otm->otmpFullName)); - lineWidth = otm->otmsUnderscoreSize; - fsType = otm->otmfsType; - free(otm); - - } else { - unitsPerEm = tm.tmHeight; - } -} - -int QWindowsFontEngine::getGlyphIndexes(const QChar *str, int numChars, QGlyphLayout *glyphs) const -{ - int glyph_pos = 0; - { - if (symbol) { - QStringIterator it(str, str + numChars); - while (it.hasNext()) { - const uint uc = it.next(); - glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, cmapSize, uc); - if(!glyphs->glyphs[glyph_pos] && uc < 0x100) - glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, cmapSize, uc + 0xf000); - ++glyph_pos; - } - } else if (ttf) { - QStringIterator it(str, str + numChars); - while (it.hasNext()) { - const uint uc = it.next(); - glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, cmapSize, uc); - ++glyph_pos; - } - } else { - QStringIterator it(str, str + numChars); - while (it.hasNext()) { - const uint uc = it.next(); - if (uc >= tm.tmFirstChar && uc <= tm.tmLastChar) - glyphs->glyphs[glyph_pos] = uc; - else - glyphs->glyphs[glyph_pos] = 0; - ++glyph_pos; - } - } - } - glyphs->numGlyphs = glyph_pos; - return glyph_pos; -} - -/*! - \class QWindowsFontEngine - \brief Standard Windows font engine. - \internal - \ingroup qt-lighthouse-win - - Will probably be superseded by a common Free Type font engine in Qt 5.X. -*/ - -QWindowsFontEngine::QWindowsFontEngine(const QString &name, - LOGFONT lf, - const QSharedPointer<QWindowsFontEngineData> &fontEngineData) - : QFontEngine(Win), - m_fontEngineData(fontEngineData), - _name(name), - m_logfont(lf), - ttf(0), - hasOutline(0) -{ - qCDebug(lcQpaFonts) << __FUNCTION__ << name << lf.lfHeight; - hfont = CreateFontIndirect(&m_logfont); - if (!hfont) { - qErrnoWarning("%s: CreateFontIndirect failed for family '%s'", __FUNCTION__, qPrintable(name)); - hfont = QWindowsFontDatabase::systemFont(); - } - - HDC hdc = m_fontEngineData->hdc; - SelectObject(hdc, hfont); - const BOOL res = GetTextMetrics(hdc, &tm); - if (!res) { - qErrnoWarning("%s: GetTextMetrics failed", __FUNCTION__); - ZeroMemory(&tm, sizeof(TEXTMETRIC)); - } - - fontDef.pixelSize = -lf.lfHeight; - fontDef.fixedPitch = !(tm.tmPitchAndFamily & TMPF_FIXED_PITCH); - - cache_cost = tm.tmHeight * tm.tmAveCharWidth * 2000; - getCMap(); - - if (!resolvedGetCharWidthI) - resolveGetCharWidthI(); - - // ### Properties accessed by QWin32PrintEngine (QtPrintSupport) - QVariantMap userData; - userData.insert(QStringLiteral("logFont"), QVariant::fromValue(m_logfont)); - userData.insert(QStringLiteral("hFont"), QVariant::fromValue(hfont)); - userData.insert(QStringLiteral("trueType"), QVariant(bool(ttf))); - setUserData(userData); - - hasUnreliableOutline = (tm.tmPitchAndFamily & (TMPF_TRUETYPE | TMPF_VECTOR)) == 0; -} - -QWindowsFontEngine::~QWindowsFontEngine() -{ - if (designAdvances) - free(designAdvances); - - if (widthCache) - free(widthCache); - - // make sure we aren't by accident still selected - SelectObject(m_fontEngineData->hdc, QWindowsFontDatabase::systemFont()); - - if (!DeleteObject(hfont)) - qErrnoWarning("%s: QFontEngineWin: failed to delete font...", __FUNCTION__); - qCDebug(lcQpaFonts) << __FUNCTION__ << _name; - - if (!uniqueFamilyName.isEmpty()) { - if (QPlatformIntegration *pi = QGuiApplicationPrivate::platformIntegration()) { - QPlatformFontDatabase *pfdb = pi->fontDatabase(); - static_cast<QWindowsFontDatabase *>(pfdb)->derefUniqueFont(uniqueFamilyName); - } - } -} - -glyph_t QWindowsFontEngine::glyphIndex(uint ucs4) const -{ - glyph_t glyph = 0; - - if (symbol) { - glyph = getTrueTypeGlyphIndex(cmap, cmapSize, ucs4); - if (glyph == 0 && ucs4 < 0x100) - glyph = getTrueTypeGlyphIndex(cmap, cmapSize, ucs4 + 0xf000); - } else if (ttf) { - glyph = getTrueTypeGlyphIndex(cmap, cmapSize, ucs4); - } else if (ucs4 >= tm.tmFirstChar && ucs4 <= tm.tmLastChar) { - glyph = ucs4; - } - - return glyph; -} - -HGDIOBJ QWindowsFontEngine::selectDesignFont() const -{ - LOGFONT f = m_logfont; - f.lfHeight = -unitsPerEm; - f.lfWidth = 0; - HFONT designFont = CreateFontIndirect(&f); - return SelectObject(m_fontEngineData->hdc, designFont); -} - -bool QWindowsFontEngine::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QFontEngine::ShaperFlags flags) const -{ - Q_ASSERT(glyphs->numGlyphs >= *nglyphs); - if (*nglyphs < len) { - *nglyphs = len; - return false; - } - - glyphs->numGlyphs = *nglyphs; - *nglyphs = getGlyphIndexes(str, len, glyphs); - - if (!(flags & GlyphIndicesOnly)) - recalcAdvances(glyphs, flags); - - return true; -} - -inline void calculateTTFGlyphWidth(HDC hdc, UINT glyph, int &width) -{ - if (ptrGetCharWidthI) - ptrGetCharWidthI(hdc, glyph, 1, 0, &width); -} - -void QWindowsFontEngine::recalcAdvances(QGlyphLayout *glyphs, QFontEngine::ShaperFlags flags) const -{ - HGDIOBJ oldFont = 0; - HDC hdc = m_fontEngineData->hdc; - if (ttf && (flags & DesignMetrics)) { - for(int i = 0; i < glyphs->numGlyphs; i++) { - unsigned int glyph = glyphs->glyphs[i]; - if(int(glyph) >= designAdvancesSize) { - const int newSize = int(glyph + 256) >> 8 << 8; - designAdvances = reinterpret_cast<QFixed *>(realloc(designAdvances, size_t(newSize) * sizeof(QFixed))); - Q_CHECK_PTR(designAdvances); - for(int i = designAdvancesSize; i < newSize; ++i) - designAdvances[i] = -1000000; - designAdvancesSize = newSize; - } - if (designAdvances[glyph] < -999999) { - if (!oldFont) - oldFont = selectDesignFont(); - - int width = 0; - calculateTTFGlyphWidth(hdc, glyph, width); - designAdvances[glyph] = QFixed(width) / designToDevice; - } - glyphs->advances[i] = designAdvances[glyph]; - } - if(oldFont) - DeleteObject(SelectObject(hdc, oldFont)); - } else { - for(int i = 0; i < glyphs->numGlyphs; i++) { - unsigned int glyph = glyphs->glyphs[i]; - - if (glyph >= widthCacheSize) { - const uint newSize = (glyph + 256) >> 8 << 8; - widthCache = reinterpret_cast<unsigned char *>(realloc(widthCache, newSize * sizeof(QFixed))); - Q_CHECK_PTR(widthCache); - memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize); - widthCacheSize = newSize; - } - glyphs->advances[i] = widthCache[glyph]; - // font-width cache failed - if (glyphs->advances[i].value() == 0) { - int width = 0; - if (!oldFont) - oldFont = SelectObject(hdc, hfont); - - if (!ttf) { - QChar ch[2] = { ushort(glyph), 0 }; - int chrLen = 1; - if (QChar::requiresSurrogates(glyph)) { - ch[0] = QChar::highSurrogate(glyph); - ch[1] = QChar::lowSurrogate(glyph); - ++chrLen; - } - SIZE size = {0, 0}; - GetTextExtentPoint32(hdc, reinterpret_cast<const wchar_t *>(ch), chrLen, &size); - width = size.cx; - } else { - calculateTTFGlyphWidth(hdc, glyph, width); - } - glyphs->advances[i] = width; - // if glyph's within cache range, store it for later - if (width > 0 && width < 0x100) - widthCache[glyph] = uchar(width); - } - } - - if (oldFont) - SelectObject(hdc, oldFont); - } -} - -glyph_metrics_t QWindowsFontEngine::boundingBox(const QGlyphLayout &glyphs) -{ - if (glyphs.numGlyphs == 0) - return glyph_metrics_t(); - - QFixed w = 0; - for (int i = 0; i < glyphs.numGlyphs; ++i) - w += glyphs.effectiveAdvance(i); - - return glyph_metrics_t(0, -tm.tmAscent, w - lastRightBearing(glyphs), tm.tmHeight, w, 0); -} - -bool QWindowsFontEngine::getOutlineMetrics(glyph_t glyph, const QTransform &t, glyph_metrics_t *metrics) const -{ - Q_ASSERT(metrics != 0); - - HDC hdc = m_fontEngineData->hdc; - - GLYPHMETRICS gm; - DWORD res = 0; - MAT2 mat; - mat.eM11.value = mat.eM22.value = 1; - mat.eM11.fract = mat.eM22.fract = 0; - mat.eM21.value = mat.eM12.value = 0; - mat.eM21.fract = mat.eM12.fract = 0; - - if (t.type() > QTransform::TxTranslate) { - // We need to set the transform using the HDC's world - // matrix rather than using the MAT2 above, because the - // results provided when transforming via MAT2 does not - // match the glyphs that are drawn using a WorldTransform - XFORM xform; - xform.eM11 = FLOAT(t.m11()); - xform.eM12 = FLOAT(t.m12()); - xform.eM21 = FLOAT(t.m21()); - xform.eM22 = FLOAT(t.m22()); - xform.eDx = 0; - xform.eDy = 0; - SetGraphicsMode(hdc, GM_ADVANCED); - SetWorldTransform(hdc, &xform); - } - - uint format = GGO_METRICS; - if (ttf) - format |= GGO_GLYPH_INDEX; - res = GetGlyphOutline(hdc, glyph, format, &gm, 0, 0, &mat); - - if (t.type() > QTransform::TxTranslate) { - XFORM xform; - xform.eM11 = xform.eM22 = 1; - xform.eM12 = xform.eM21 = xform.eDx = xform.eDy = 0; - SetWorldTransform(hdc, &xform); - SetGraphicsMode(hdc, GM_COMPATIBLE); - } - - if (res != GDI_ERROR) { - *metrics = glyph_metrics_t(gm.gmptGlyphOrigin.x, -gm.gmptGlyphOrigin.y, - int(gm.gmBlackBoxX), int(gm.gmBlackBoxY), - gm.gmCellIncX, gm.gmCellIncY); - return true; - } else { - return false; - } -} - -glyph_metrics_t QWindowsFontEngine::boundingBox(glyph_t glyph, const QTransform &t) -{ - HDC hdc = m_fontEngineData->hdc; - SelectObject(hdc, hfont); - - glyph_metrics_t glyphMetrics; - bool success = getOutlineMetrics(glyph, t, &glyphMetrics); - - if (!ttf && !success) { - // Bitmap fonts - wchar_t ch = wchar_t(glyph); - ABCFLOAT abc; - GetCharABCWidthsFloat(hdc, ch, ch, &abc); - int width = qRound(abc.abcfB); - - return glyph_metrics_t(QFixed::fromReal(abc.abcfA), -tm.tmAscent, width, tm.tmHeight, width, 0).transformed(t); - } - - return glyphMetrics; -} - -QFixed QWindowsFontEngine::ascent() const -{ - return tm.tmAscent; -} - -QFixed QWindowsFontEngine::descent() const -{ - return tm.tmDescent; -} - -QFixed QWindowsFontEngine::leading() const -{ - return tm.tmExternalLeading; -} - -namespace { -# pragma pack(1) - - struct OS2Table - { - quint16 version; - qint16 avgCharWidth; - quint16 weightClass; - quint16 widthClass; - quint16 type; - qint16 subscriptXSize; - qint16 subscriptYSize; - qint16 subscriptXOffset; - qint16 subscriptYOffset; - qint16 superscriptXSize; - qint16 superscriptYSize; - qint16 superscriptXOffset; - qint16 superscriptYOffset; - qint16 strikeOutSize; - qint16 strikeOutPosition; - qint16 familyClass; - quint8 panose[10]; - quint32 unicodeRanges[4]; - quint8 vendorID[4]; - quint16 selection; - quint16 firstCharIndex; - quint16 lastCharIndex; - qint16 typoAscender; - qint16 typoDescender; - qint16 typoLineGap; - quint16 winAscent; - quint16 winDescent; - quint32 codepageRanges[2]; - qint16 height; - qint16 capHeight; - quint16 defaultChar; - quint16 breakChar; - quint16 maxContext; - }; - -# pragma pack() -} - -QFixed QWindowsFontEngine::capHeight() const -{ - const QByteArray tableData = getSfntTable(MAKE_TAG('O', 'S', '/', '2')); - if (size_t(tableData.size()) >= sizeof(OS2Table)) { - const OS2Table *table = reinterpret_cast<const OS2Table *>(tableData.constData()); - if (qFromBigEndian<quint16>(table->version) >= 2) { - qint16 capHeight = qFromBigEndian<qint16>(table->capHeight); - if (capHeight > 0) - return QFixed(capHeight) / designToDevice; - } - } - return calculatedCapHeight(); -} - -QFixed QWindowsFontEngine::xHeight() const -{ - if(x_height >= 0) - return x_height; - return QFontEngine::xHeight(); -} - -QFixed QWindowsFontEngine::averageCharWidth() const -{ - return tm.tmAveCharWidth; -} - -qreal QWindowsFontEngine::maxCharWidth() const -{ - return tm.tmMaxCharWidth; -} - -enum { max_font_count = 256 }; -static const ushort char_table[] = { - 40, - 67, - 70, - 75, - 86, - 88, - 89, - 91, - 102, - 114, - 124, - 127, - 205, - 645, - 884, - 922, - 1070, - 12386, - 0 -}; - -static const int char_table_entries = sizeof(char_table)/sizeof(ushort); - -#ifndef Q_CC_MINGW -void QWindowsFontEngine::getGlyphBearings(glyph_t glyph, qreal *leftBearing, qreal *rightBearing) -{ - HDC hdc = m_fontEngineData->hdc; - SelectObject(hdc, hfont); - - if (ttf) { - ABC abcWidths; - GetCharABCWidthsI(hdc, glyph, 1, 0, &abcWidths); - if (leftBearing) - *leftBearing = abcWidths.abcA; - if (rightBearing) - *rightBearing = abcWidths.abcC; - } else { - QFontEngine::getGlyphBearings(glyph, leftBearing, rightBearing); - } -} -#endif // Q_CC_MINGW - -bool QWindowsFontEngine::hasUnreliableGlyphOutline() const -{ - return hasUnreliableOutline || QFontEngine::hasUnreliableGlyphOutline(); -} - -qreal QWindowsFontEngine::minLeftBearing() const -{ - if (lbearing == SHRT_MIN) - minRightBearing(); // calculates both - - return lbearing; -} - -qreal QWindowsFontEngine::minRightBearing() const -{ - if (rbearing == SHRT_MIN) { - int ml = 0; - int mr = 0; - HDC hdc = m_fontEngineData->hdc; - SelectObject(hdc, hfont); - if (ttf) { - ABC *abc = 0; - int n = tm.tmLastChar - tm.tmFirstChar; - if (n <= max_font_count) { - abc = new ABC[n+1]; - GetCharABCWidths(hdc, tm.tmFirstChar, tm.tmLastChar, abc); - } else { - abc = new ABC[char_table_entries+1]; - for(int i = 0; i < char_table_entries; i++) - GetCharABCWidths(hdc, char_table[i], char_table[i], abc + i); - n = char_table_entries; - } - ml = abc[0].abcA; - mr = abc[0].abcC; - for (int i = 1; i < n; i++) { - if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) { - ml = qMin(ml,abc[i].abcA); - mr = qMin(mr,abc[i].abcC); - } - } - delete [] abc; - } else { - ABCFLOAT *abc = 0; - int n = tm.tmLastChar - tm.tmFirstChar+1; - if (n <= max_font_count) { - abc = new ABCFLOAT[n]; - GetCharABCWidthsFloat(hdc, tm.tmFirstChar, tm.tmLastChar, abc); - } else { - abc = new ABCFLOAT[char_table_entries]; - for(int i = 0; i < char_table_entries; i++) - GetCharABCWidthsFloat(hdc, char_table[i], char_table[i], abc+i); - n = char_table_entries; - } - float fml = abc[0].abcfA; - float fmr = abc[0].abcfC; - for (int i=1; i<n; i++) { - if (abc[i].abcfA + abc[i].abcfB + abc[i].abcfC != 0) { - fml = qMin(fml,abc[i].abcfA); - fmr = qMin(fmr,abc[i].abcfC); - } - } - ml = int(fml - 0.9999); - mr = int(fmr - 0.9999); - delete [] abc; - } - lbearing = ml; - rbearing = mr; - } - - return rbearing; -} - -static inline double qt_fixed_to_double(const FIXED &p) { - return ((p.value << 16) + p.fract) / 65536.0; -} - -static inline QPointF qt_to_qpointf(const POINTFX &pt, qreal scale, qreal stretch) { - return QPointF(qt_fixed_to_double(pt.x) * scale * stretch, -qt_fixed_to_double(pt.y) * scale); -} - -#ifndef GGO_UNHINTED -#define GGO_UNHINTED 0x0100 -#endif - -static bool addGlyphToPath(glyph_t glyph, const QFixedPoint &position, HDC hdc, - QPainterPath *path, bool ttf, glyph_metrics_t *metric = 0, - qreal scale = 1.0, qreal stretch = 1.0) -{ - MAT2 mat; - mat.eM11.value = mat.eM22.value = 1; - mat.eM11.fract = mat.eM22.fract = 0; - mat.eM21.value = mat.eM12.value = 0; - mat.eM21.fract = mat.eM12.fract = 0; - - GLYPHMETRICS gMetric; - memset(&gMetric, 0, sizeof(GLYPHMETRICS)); - - if (metric) { - // If metrics requested, retrieve first using GGO_METRICS, because the returned - // values are incorrect for OpenType PS fonts if obtained at the same time as the - // glyph paths themselves (ie. with GGO_NATIVE as the format). - uint format = GGO_METRICS; - if (ttf) - format |= GGO_GLYPH_INDEX; - if (GetGlyphOutline(hdc, glyph, format, &gMetric, 0, 0, &mat) == GDI_ERROR) - return false; - // #### obey scale - *metric = glyph_metrics_t(gMetric.gmptGlyphOrigin.x, -gMetric.gmptGlyphOrigin.y, - int(gMetric.gmBlackBoxX), int(gMetric.gmBlackBoxY), - gMetric.gmCellIncX, gMetric.gmCellIncY); - } - - uint glyphFormat = GGO_NATIVE; - - if (ttf) - glyphFormat |= GGO_GLYPH_INDEX; - - const DWORD bufferSize = GetGlyphOutline(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat); - if (bufferSize == GDI_ERROR) - return false; - - char *dataBuffer = new char[bufferSize]; - DWORD ret = GDI_ERROR; - ret = GetGlyphOutline(hdc, glyph, glyphFormat, &gMetric, bufferSize, dataBuffer, &mat); - if (ret == GDI_ERROR) { - delete [] dataBuffer; - return false; - } - - DWORD offset = 0; - DWORD headerOffset = 0; - - QPointF oset = position.toPointF(); - while (headerOffset < bufferSize) { - const TTPOLYGONHEADER *ttph = reinterpret_cast<const TTPOLYGONHEADER *>(dataBuffer + headerOffset); - - QPointF lastPoint(qt_to_qpointf(ttph->pfxStart, scale, stretch)); - path->moveTo(lastPoint + oset); - offset += sizeof(TTPOLYGONHEADER); - while (offset < headerOffset + ttph->cb) { - const TTPOLYCURVE *curve = reinterpret_cast<const TTPOLYCURVE *>(dataBuffer + offset); - switch (curve->wType) { - case TT_PRIM_LINE: { - for (int i=0; i<curve->cpfx; ++i) { - QPointF p = qt_to_qpointf(curve->apfx[i], scale, stretch) + oset; - path->lineTo(p); - } - break; - } - case TT_PRIM_QSPLINE: { - const QPainterPath::Element &elm = path->elementAt(path->elementCount()-1); - QPointF prev(elm.x, elm.y); - QPointF endPoint; - for (int i=0; i<curve->cpfx - 1; ++i) { - QPointF p1 = qt_to_qpointf(curve->apfx[i], scale, stretch) + oset; - QPointF p2 = qt_to_qpointf(curve->apfx[i+1], scale, stretch) + oset; - if (i < curve->cpfx - 2) { - endPoint = QPointF((p1.x() + p2.x()) / 2, (p1.y() + p2.y()) / 2); - } else { - endPoint = p2; - } - - path->quadTo(p1, endPoint); - prev = endPoint; - } - - break; - } - case TT_PRIM_CSPLINE: { - for (int i=0; i<curve->cpfx; ) { - QPointF p2 = qt_to_qpointf(curve->apfx[i++], scale, stretch) + oset; - QPointF p3 = qt_to_qpointf(curve->apfx[i++], scale, stretch) + oset; - QPointF p4 = qt_to_qpointf(curve->apfx[i++], scale, stretch) + oset; - path->cubicTo(p2, p3, p4); - } - break; - } - default: - qWarning("QFontEngineWin::addOutlineToPath, unhandled switch case"); - } - offset += sizeof(TTPOLYCURVE) + (curve->cpfx-1) * sizeof(POINTFX); - } - path->closeSubpath(); - headerOffset += ttph->cb; - } - delete [] dataBuffer; - - return true; -} - -void QWindowsFontEngine::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs, - QPainterPath *path, QTextItem::RenderFlags) -{ - LOGFONT lf = m_logfont; - // The sign must be negative here to make sure we match against character height instead of - // hinted cell height. This ensures that we get linear matching, and we need this for - // paths since we later on apply a scaling transform to the glyph outline to get the - // font at the correct pixel size. - lf.lfHeight = -unitsPerEm; - lf.lfWidth = 0; - HFONT hf = CreateFontIndirect(&lf); - HDC hdc = m_fontEngineData->hdc; - HGDIOBJ oldfont = SelectObject(hdc, hf); - - qreal scale = qreal(fontDef.pixelSize) / unitsPerEm; - qreal stretch = fontDef.stretch ? qreal(fontDef.stretch) / 100 : 1.0; - for(int i = 0; i < nglyphs; ++i) { - if (!addGlyphToPath(glyphs[i], positions[i], hdc, path, ttf, /*metric*/0, - scale, stretch)) { - // Some windows fonts, like "Modern", are vector stroke - // fonts, which are reported as TMPF_VECTOR but do not - // support GetGlyphOutline, and thus we set this bit so - // that addOutLineToPath can check it and return safely... - hasOutline = false; - break; - } - } - DeleteObject(SelectObject(hdc, oldfont)); -} - -void QWindowsFontEngine::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, - QPainterPath *path, QTextItem::RenderFlags flags) -{ - if(tm.tmPitchAndFamily & (TMPF_TRUETYPE | TMPF_VECTOR)) { - hasOutline = true; - QFontEngine::addOutlineToPath(x, y, glyphs, path, flags); - if (hasOutline) { - // has_outline is set to false if addGlyphToPath gets - // false from GetGlyphOutline, meaning its not an outline - // font. - return; - } - } - QFontEngine::addBitmapFontToPath(x, y, glyphs, path, flags); -} - -QFontEngine::FaceId QWindowsFontEngine::faceId() const -{ - return _faceId; -} - -QT_BEGIN_INCLUDE_NAMESPACE -#include <qdebug.h> -QT_END_INCLUDE_NAMESPACE - -int QWindowsFontEngine::synthesized() const -{ - if(synthesized_flags == -1) { - synthesized_flags = 0; - if(ttf) { - const DWORD HEAD = MAKE_LITTLE_ENDIAN_TAG('h', 'e', 'a', 'd'); - HDC hdc = m_fontEngineData->hdc; - SelectObject(hdc, hfont); - uchar data[4]; - GetFontData(hdc, HEAD, 44, &data, 4); - USHORT macStyle = qt_getUShort(data); - if (tm.tmItalic && !(macStyle & 2)) - synthesized_flags = SynthesizedItalic; - if (fontDef.stretch != 100 && ttf) - synthesized_flags |= SynthesizedStretch; - if (tm.tmWeight >= 500 && tm.tmWeight < 750 && !(macStyle & 1)) - synthesized_flags |= SynthesizedBold; - //qDebug() << "font is" << _name << - // "it=" << (macStyle & 2) << fontDef.style << "flags=" << synthesized_flags; - } - } - return synthesized_flags; -} - -QFixed QWindowsFontEngine::emSquareSize() const -{ - return unitsPerEm; -} - -QFontEngine::Properties QWindowsFontEngine::properties() const -{ - LOGFONT lf = m_logfont; - lf.lfHeight = unitsPerEm; - HFONT hf = CreateFontIndirect(&lf); - HDC hdc = m_fontEngineData->hdc; - HGDIOBJ oldfont = SelectObject(hdc, hf); - OUTLINETEXTMETRIC *otm = getOutlineTextMetric(hdc); - Properties p; - p.emSquare = unitsPerEm; - p.italicAngle = otm->otmItalicAngle; - const QByteArray name = stringFromOutLineTextMetric(otm, otm->otmpFamilyName).toLatin1() - + stringFromOutLineTextMetric(otm, otm->otmpStyleName).toLatin1(); - p.postscriptName = QFontEngine::convertToPostscriptFontFamilyName(name); - p.boundingBox = QRectF(otm->otmrcFontBox.left, -otm->otmrcFontBox.top, - otm->otmrcFontBox.right - otm->otmrcFontBox.left, - otm->otmrcFontBox.top - otm->otmrcFontBox.bottom); - p.ascent = otm->otmAscent; - p.descent = -otm->otmDescent; - p.leading = int(otm->otmLineGap); - p.capHeight = 0; - p.lineWidth = otm->otmsUnderscoreSize; - free(otm); - DeleteObject(SelectObject(hdc, oldfont)); - return p; -} - -void QWindowsFontEngine::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics) -{ - LOGFONT lf = m_logfont; - lf.lfHeight = -unitsPerEm; - int flags = synthesized(); - if(flags & SynthesizedItalic) - lf.lfItalic = false; - lf.lfWidth = 0; - HFONT hf = CreateFontIndirect(&lf); - HDC hdc = m_fontEngineData->hdc; - HGDIOBJ oldfont = SelectObject(hdc, hf); - QFixedPoint p; - p.x = 0; - p.y = 0; - addGlyphToPath(glyph, p, hdc, path, ttf, metrics); - DeleteObject(SelectObject(hdc, oldfont)); -} - -bool QWindowsFontEngine::getSfntTableData(uint tag, uchar *buffer, uint *length) const -{ - if (!ttf && !cffTable) - return false; - HDC hdc = m_fontEngineData->hdc; - SelectObject(hdc, hfont); - DWORD t = qbswap<quint32>(tag); - *length = GetFontData(hdc, t, 0, buffer, *length); - Q_ASSERT(*length == GDI_ERROR || int(*length) > 0); - return *length != GDI_ERROR; -} - -#if !defined(CLEARTYPE_QUALITY) -# define CLEARTYPE_QUALITY 5 -#endif - -QWindowsNativeImage *QWindowsFontEngine::drawGDIGlyph(HFONT font, glyph_t glyph, int margin, - const QTransform &t, - QImage::Format mask_format) -{ - Q_UNUSED(mask_format) - glyph_metrics_t gm = boundingBox(glyph); - -// printf(" -> for glyph %4x\n", glyph); - - int gx = gm.x.toInt(); - int gy = gm.y.toInt(); - int iw = gm.width.toInt(); - int ih = gm.height.toInt(); - - if (iw <= 0 || ih <= 0) - return 0; - - bool has_transformation = t.type() > QTransform::TxTranslate; - - unsigned int options = ttf ? ETO_GLYPH_INDEX : 0; - XFORM xform; - - if (has_transformation) { - xform.eM11 = FLOAT(t.m11()); - xform.eM12 = FLOAT(t.m12()); - xform.eM21 = FLOAT(t.m21()); - xform.eM22 = FLOAT(t.m22()); - xform.eDx = margin; - xform.eDy = margin; - - const HDC hdc = m_fontEngineData->hdc; - - SetGraphicsMode(hdc, GM_ADVANCED); - SetWorldTransform(hdc, &xform); - HGDIOBJ old_font = SelectObject(hdc, font); - - const UINT ggo_options = GGO_METRICS | (ttf ? GGO_GLYPH_INDEX : 0); - GLYPHMETRICS tgm; - MAT2 mat; - memset(&mat, 0, sizeof(mat)); - mat.eM11.value = mat.eM22.value = 1; - - const DWORD result = GetGlyphOutline(hdc, glyph, ggo_options, &tgm, 0, 0, &mat); - - XFORM identity = {1, 0, 0, 1, 0, 0}; - SetWorldTransform(hdc, &identity); - SetGraphicsMode(hdc, GM_COMPATIBLE); - SelectObject(hdc, old_font); - - if (result == GDI_ERROR) { - const int errorCode = int(GetLastError()); - qErrnoWarning(errorCode, "QWinFontEngine: unable to query transformed glyph metrics (GetGlyphOutline() failed, error %d)...", errorCode); - return 0; - } - - iw = int(tgm.gmBlackBoxX); - ih = int(tgm.gmBlackBoxY); - - xform.eDx -= tgm.gmptGlyphOrigin.x; - xform.eDy += tgm.gmptGlyphOrigin.y; - } - - // The padding here needs to be kept in sync with the values in alphaMapBoundingBox. - QWindowsNativeImage *ni = new QWindowsNativeImage(iw + 2 * margin, - ih + 2 * margin, - QWindowsNativeImage::systemFormat()); - - /*If cleartype is enabled we use the standard system format even on Windows CE - and not the special textbuffer format we have to use if cleartype is disabled*/ - - ni->image().fill(0xffffffff); - - HDC hdc = ni->hdc(); - - SelectObject(hdc, GetStockObject(NULL_BRUSH)); - SelectObject(hdc, GetStockObject(BLACK_PEN)); - SetTextColor(hdc, RGB(0,0,0)); - SetBkMode(hdc, TRANSPARENT); - SetTextAlign(hdc, TA_BASELINE); - - HGDIOBJ old_font = SelectObject(hdc, font); - - if (has_transformation) { - SetGraphicsMode(hdc, GM_ADVANCED); - SetWorldTransform(hdc, &xform); - ExtTextOut(hdc, 0, 0, options, 0, reinterpret_cast<LPCWSTR>(&glyph), 1, 0); - } else { - ExtTextOut(hdc, -gx + margin, -gy + margin, options, 0, reinterpret_cast<LPCWSTR>(&glyph), 1, 0); - } - - SelectObject(hdc, old_font); - return ni; -} - -glyph_metrics_t QWindowsFontEngine::alphaMapBoundingBox(glyph_t glyph, QFixed, const QTransform &matrix, GlyphFormat format) -{ - int margin = 0; - if (format == QFontEngine::Format_A32 || format == QFontEngine::Format_ARGB) - margin = glyphMargin(QFontEngine::Format_A32); - glyph_metrics_t gm = boundingBox(glyph, matrix); - gm.width += margin * 2; - gm.height += margin * 2; - return gm; -} - -QImage QWindowsFontEngine::alphaMapForGlyph(glyph_t glyph, const QTransform &xform) -{ - HFONT font = hfont; - - bool clearTypeTemporarilyDisabled = (m_fontEngineData->clearTypeEnabled && m_logfont.lfQuality != NONANTIALIASED_QUALITY); - if (clearTypeTemporarilyDisabled) { - LOGFONT lf = m_logfont; - lf.lfQuality = ANTIALIASED_QUALITY; - font = CreateFontIndirect(&lf); - } - QImage::Format mask_format = QWindowsNativeImage::systemFormat(); - mask_format = QImage::Format_RGB32; - - const QWindowsNativeImage *mask = drawGDIGlyph(font, glyph, 0, xform, mask_format); - if (mask == 0) { - if (m_fontEngineData->clearTypeEnabled) - DeleteObject(font); - return QImage(); - } - - QImage alphaMap(mask->width(), mask->height(), QImage::Format_Alpha8); - - - // Copy data... Cannot use QPainter here as GDI has messed up the - // Alpha channel of the ni.image pixels... - for (int y=0; y<mask->height(); ++y) { - uchar *dest = alphaMap.scanLine(y); - if (mask->image().format() == QImage::Format_RGB16) { - const qint16 *src = reinterpret_cast<const qint16 *>(mask->image().constScanLine(y)); - for (int x=0; x<mask->width(); ++x) - dest[x] = 255 - qGray(src[x]); - } else { - const uint *src = reinterpret_cast<const uint *>(mask->image().constScanLine(y)); - for (int x=0; x<mask->width(); ++x) { - if (QWindowsNativeImage::systemFormat() == QImage::Format_RGB16) - dest[x] = 255 - qGray(src[x]); - else - dest[x] = 255 - (m_fontEngineData->pow_gamma[qGray(src[x])] * 255. / 2047.); - } - } - } - - // Cleanup... - delete mask; - if (clearTypeTemporarilyDisabled) { - DeleteObject(font); - } - - return alphaMap; -} - -#define SPI_GETFONTSMOOTHINGCONTRAST 0x200C -#define SPI_SETFONTSMOOTHINGCONTRAST 0x200D - -QImage QWindowsFontEngine::alphaRGBMapForGlyph(glyph_t glyph, QFixed, const QTransform &t) -{ - HFONT font = hfont; - - UINT contrast; - SystemParametersInfo(SPI_GETFONTSMOOTHINGCONTRAST, 0, &contrast, 0); - SystemParametersInfo(SPI_SETFONTSMOOTHINGCONTRAST, 0, reinterpret_cast<void *>(quintptr(1000)), 0); - - int margin = glyphMargin(QFontEngine::Format_A32); - QWindowsNativeImage *mask = drawGDIGlyph(font, glyph, margin, t, QImage::Format_RGB32); - SystemParametersInfo(SPI_SETFONTSMOOTHINGCONTRAST, 0, reinterpret_cast<void *>(quintptr(contrast)), 0); - - if (mask == 0) - return QImage(); - - // Gracefully handle the odd case when the display is 16-bit - const QImage source = mask->image().depth() == 32 - ? mask->image() - : mask->image().convertToFormat(QImage::Format_RGB32); - - QImage rgbMask(mask->width(), mask->height(), QImage::Format_RGB32); - for (int y=0; y<mask->height(); ++y) { - auto dest = reinterpret_cast<uint *>(rgbMask.scanLine(y)); - const uint *src = reinterpret_cast<const uint *>(source.constScanLine(y)); - for (int x=0; x<mask->width(); ++x) { - dest[x] = 0xffffffff - (0x00ffffff & src[x]); - } - } - - delete mask; - - return rgbMask; -} - -QFontEngine *QWindowsFontEngine::cloneWithSize(qreal pixelSize) const -{ - QFontDef request = fontDef; - QString actualFontName = request.family; - if (!uniqueFamilyName.isEmpty()) - request.family = uniqueFamilyName; - request.pixelSize = pixelSize; - const QString faceName = QString::fromWCharArray(m_logfont.lfFaceName); - - QFontEngine *fontEngine = - QWindowsFontDatabase::createEngine(request, faceName, - QWindowsFontDatabase::defaultVerticalDPI(), - m_fontEngineData); - if (fontEngine) { - fontEngine->fontDef.family = actualFontName; - if (!uniqueFamilyName.isEmpty()) { - static_cast<QWindowsFontEngine *>(fontEngine)->setUniqueFamilyName(uniqueFamilyName); - if (QPlatformIntegration *pi = QGuiApplicationPrivate::platformIntegration()) { - QPlatformFontDatabase *pfdb = pi->fontDatabase(); - static_cast<QWindowsFontDatabase *>(pfdb)->refUniqueFont(uniqueFamilyName); - } - } - } - return fontEngine; -} - -Qt::HANDLE QWindowsFontEngine::handle() const -{ - return hfont; -} - -void QWindowsFontEngine::initFontInfo(const QFontDef &request, - int dpi) -{ - fontDef = request; // most settings are equal - HDC dc = m_fontEngineData->hdc; - SelectObject(dc, hfont); - wchar_t n[64]; - GetTextFace(dc, 64, n); - fontDef.family = QString::fromWCharArray(n); - fontDef.fixedPitch = !(tm.tmPitchAndFamily & TMPF_FIXED_PITCH); - if (fontDef.pointSize < 0) { - fontDef.pointSize = fontDef.pixelSize * 72. / dpi; - } else if (fontDef.pixelSize == -1) { - fontDef.pixelSize = qRound(fontDef.pointSize * dpi / 72.); - } -} - -bool QWindowsFontEngine::supportsTransformation(const QTransform &transform) const -{ - // Support all transformations for ttf files, and translations for raster fonts - return ttf || transform.type() <= QTransform::TxTranslate; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/fontdatabases/windows/qwindowsfontengine_p.h b/src/platformsupport/fontdatabases/windows/qwindowsfontengine_p.h deleted file mode 100644 index 2b575a9b45..0000000000 --- a/src/platformsupport/fontdatabases/windows/qwindowsfontengine_p.h +++ /dev/null @@ -1,175 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QWINDOWSFONTENGINE_H -#define QWINDOWSFONTENGINE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qfontengine_p.h> - -#include <QtGui/QImage> -#include <QtCore/QSharedPointer> -#include <QtCore/QMetaType> - -#include <QtCore/qt_windows.h> - -QT_BEGIN_NAMESPACE - -class QWindowsNativeImage; -class QWindowsFontEngineData; - -class QWindowsFontEngine : public QFontEngine -{ - Q_DISABLE_COPY(QWindowsFontEngine) -public: - QWindowsFontEngine(const QString &name, LOGFONT lf, - const QSharedPointer<QWindowsFontEngineData> &fontEngineData); - - ~QWindowsFontEngine() override; - void initFontInfo(const QFontDef &request, - int dpi); - - QFixed lineThickness() const override; - Properties properties() const override; - void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics) override; - FaceId faceId() const override; - bool getSfntTableData(uint tag, uchar *buffer, uint *length) const override; - int synthesized() const override; - QFixed emSquareSize() const override; - - glyph_t glyphIndex(uint ucs4) const override; - bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, ShaperFlags flags) const override; - void recalcAdvances(QGlyphLayout *glyphs, ShaperFlags) const override; - - void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags) override; - void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs, - QPainterPath *path, QTextItem::RenderFlags flags) override; - - HGDIOBJ selectDesignFont() const; - - glyph_metrics_t boundingBox(const QGlyphLayout &glyphs) override; - glyph_metrics_t boundingBox(glyph_t g) override { return boundingBox(g, QTransform()); } - glyph_metrics_t boundingBox(glyph_t g, const QTransform &t) override; - - - QFixed ascent() const override; - QFixed descent() const override; - QFixed leading() const override; - QFixed xHeight() const override; - QFixed capHeight() const override; - QFixed averageCharWidth() const override; - qreal maxCharWidth() const override; - qreal minLeftBearing() const override; - qreal minRightBearing() const override; - - QImage alphaMapForGlyph(glyph_t t) override { return alphaMapForGlyph(t, QTransform()); } - QImage alphaMapForGlyph(glyph_t, const QTransform &xform) override; - QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, const QTransform &xform) override; - glyph_metrics_t alphaMapBoundingBox(glyph_t glyph, QFixed, const QTransform &matrix, GlyphFormat) override; - - QFontEngine *cloneWithSize(qreal pixelSize) const override; - Qt::HANDLE handle() const override; - bool supportsTransformation(const QTransform &transform) const override; - -#ifndef Q_CC_MINGW - void getGlyphBearings(glyph_t glyph, qreal *leftBearing = 0, qreal *rightBearing = 0) override; -#endif - - bool hasUnreliableGlyphOutline() const override; - - int getGlyphIndexes(const QChar *ch, int numChars, QGlyphLayout *glyphs) const; - void getCMap(); - - bool getOutlineMetrics(glyph_t glyph, const QTransform &t, glyph_metrics_t *metrics) const; - - const QSharedPointer<QWindowsFontEngineData> &fontEngineData() const { return m_fontEngineData; } - - void setUniqueFamilyName(const QString &newName) { uniqueFamilyName = newName; } - -private: - QWindowsNativeImage *drawGDIGlyph(HFONT font, glyph_t, int margin, const QTransform &xform, - QImage::Format mask_format); - bool hasCFFTable() const; - bool hasCMapTable() const; - - const QSharedPointer<QWindowsFontEngineData> m_fontEngineData; - - const QString _name; - QString uniqueFamilyName; - HFONT hfont = 0; - const LOGFONT m_logfont; - uint ttf : 1; - uint hasOutline : 1; - uint hasUnreliableOutline : 1; - uint cffTable : 1; - TEXTMETRIC tm; - const unsigned char *cmap = nullptr; - int cmapSize = 0; - QByteArray cmapTable; - mutable qreal lbearing = SHRT_MIN; - mutable qreal rbearing = SHRT_MIN; - QFixed designToDevice; - int unitsPerEm = 0; - QFixed x_height = -1; - FaceId _faceId; - - mutable int synthesized_flags = -1; - mutable QFixed lineWidth = -1; - mutable unsigned char *widthCache = nullptr; - mutable uint widthCacheSize = 0; - mutable QFixed *designAdvances = nullptr; - mutable int designAdvancesSize = 0; -}; - -QT_END_NAMESPACE - -Q_DECLARE_METATYPE(HFONT) -Q_DECLARE_METATYPE(LOGFONT) - -#endif // QWINDOWSFONTENGINE_H diff --git a/src/platformsupport/fontdatabases/windows/qwindowsfontenginedirectwrite.cpp b/src/platformsupport/fontdatabases/windows/qwindowsfontenginedirectwrite.cpp deleted file mode 100644 index a7ee65f4b8..0000000000 --- a/src/platformsupport/fontdatabases/windows/qwindowsfontenginedirectwrite.cpp +++ /dev/null @@ -1,1031 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT_NO_DIRECTWRITE - -#include "qwindowsfontenginedirectwrite_p.h" -#include "qwindowsfontdatabase_p.h" - -#include <QtCore/QtEndian> -#include <QtCore/QVarLengthArray> -#include <QtCore/QFile> -#include <private/qstringiterator_p.h> -#include <QtCore/private/qsystemlibrary_p.h> -#include <QtGui/private/qguiapplication_p.h> -#include <qpa/qplatformintegration.h> -#include <QtGui/private/qhighdpiscaling_p.h> - -#if defined(QT_USE_DIRECTWRITE2) -# include <dwrite_2.h> -#else -# include <dwrite.h> -#endif - -#include <d2d1.h> - -QT_BEGIN_NAMESPACE - -// Convert from design units to logical pixels -#define DESIGN_TO_LOGICAL(DESIGN_UNIT_VALUE) \ - QFixed::fromReal((qreal(DESIGN_UNIT_VALUE) / qreal(m_unitsPerEm)) * fontDef.pixelSize) - -namespace { - - class GeometrySink: public IDWriteGeometrySink - { - Q_DISABLE_COPY(GeometrySink) - public: - GeometrySink(QPainterPath *path) - : m_refCount(0), m_path(path) - { - Q_ASSERT(m_path != 0); - } - virtual ~GeometrySink() = default; - - IFACEMETHOD_(void, AddBeziers)(const D2D1_BEZIER_SEGMENT *beziers, UINT bezierCount); - IFACEMETHOD_(void, AddLines)(const D2D1_POINT_2F *points, UINT pointCount); - IFACEMETHOD_(void, BeginFigure)(D2D1_POINT_2F startPoint, D2D1_FIGURE_BEGIN figureBegin); - IFACEMETHOD(Close)(); - IFACEMETHOD_(void, EndFigure)(D2D1_FIGURE_END figureEnd); - IFACEMETHOD_(void, SetFillMode)(D2D1_FILL_MODE fillMode); - IFACEMETHOD_(void, SetSegmentFlags)(D2D1_PATH_SEGMENT vertexFlags); - - IFACEMETHOD_(unsigned long, AddRef)(); - IFACEMETHOD_(unsigned long, Release)(); - IFACEMETHOD(QueryInterface)(IID const &riid, void **ppvObject); - - private: - inline static QPointF fromD2D1_POINT_2F(const D2D1_POINT_2F &inp) - { - return QPointF(inp.x, inp.y); - } - - unsigned long m_refCount; - QPointF m_startPoint; - QPainterPath *m_path; - }; - - void GeometrySink::AddBeziers(const D2D1_BEZIER_SEGMENT *beziers, - UINT bezierCount) - { - for (uint i=0; i<bezierCount; ++i) { - QPointF c1 = fromD2D1_POINT_2F(beziers[i].point1); - QPointF c2 = fromD2D1_POINT_2F(beziers[i].point2); - QPointF p2 = fromD2D1_POINT_2F(beziers[i].point3); - - m_path->cubicTo(c1, c2, p2); - } - } - - void GeometrySink::AddLines(const D2D1_POINT_2F *points, UINT pointsCount) - { - for (uint i=0; i<pointsCount; ++i) - m_path->lineTo(fromD2D1_POINT_2F(points[i])); - } - - void GeometrySink::BeginFigure(D2D1_POINT_2F startPoint, - D2D1_FIGURE_BEGIN /*figureBegin*/) - { - m_startPoint = fromD2D1_POINT_2F(startPoint); - m_path->moveTo(m_startPoint); - } - - IFACEMETHODIMP GeometrySink::Close() - { - return E_NOTIMPL; - } - - void GeometrySink::EndFigure(D2D1_FIGURE_END figureEnd) - { - if (figureEnd == D2D1_FIGURE_END_CLOSED) - m_path->closeSubpath(); - } - - void GeometrySink::SetFillMode(D2D1_FILL_MODE fillMode) - { - m_path->setFillRule(fillMode == D2D1_FILL_MODE_ALTERNATE - ? Qt::OddEvenFill - : Qt::WindingFill); - } - - void GeometrySink::SetSegmentFlags(D2D1_PATH_SEGMENT /*vertexFlags*/) - { - /* Not implemented */ - } - - IFACEMETHODIMP_(unsigned long) GeometrySink::AddRef() - { - return InterlockedIncrement(&m_refCount); - } - - IFACEMETHODIMP_(unsigned long) GeometrySink::Release() - { - unsigned long newCount = InterlockedDecrement(&m_refCount); - if (newCount == 0) - { - delete this; - return 0; - } - - return newCount; - } - - IFACEMETHODIMP GeometrySink::QueryInterface(IID const &riid, void **ppvObject) - { - if (__uuidof(IDWriteGeometrySink) == riid) { - *ppvObject = this; - } else if (__uuidof(IUnknown) == riid) { - *ppvObject = this; - } else { - *ppvObject = NULL; - return E_FAIL; - } - - AddRef(); - return S_OK; - } - -} - -static DWRITE_RENDERING_MODE hintingPreferenceToRenderingMode(QFont::HintingPreference hintingPreference) -{ - if (QHighDpiScaling::isActive() && hintingPreference == QFont::PreferDefaultHinting) - hintingPreference = QFont::PreferVerticalHinting; - - switch (hintingPreference) { - case QFont::PreferNoHinting: - return DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC; - case QFont::PreferVerticalHinting: - return DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL; - default: - return DWRITE_RENDERING_MODE_CLEARTYPE_GDI_CLASSIC; - } -} - -/*! - \class QWindowsFontEngineDirectWrite - \brief Windows font engine using Direct Write. - \internal - \ingroup qt-lighthouse-win - - Font engine for subpixel positioned text on Windows Vista - (with platform update) and Windows 7. If selected during - configuration, the engine will be selected only when the hinting - preference of a font is set to None or Vertical hinting. The font - database uses most of the same logic but creates a direct write - font based on the LOGFONT rather than a GDI handle. - - Will probably be superseded by a common Free Type font engine in Qt 5.X. -*/ - -QWindowsFontEngineDirectWrite::QWindowsFontEngineDirectWrite(IDWriteFontFace *directWriteFontFace, - qreal pixelSize, - const QSharedPointer<QWindowsFontEngineData> &d) - : QFontEngine(DirectWrite) - , m_fontEngineData(d) - , m_directWriteFontFace(directWriteFontFace) - , m_directWriteBitmapRenderTarget(0) - , m_lineThickness(-1) - , m_unitsPerEm(-1) - , m_ascent(-1) - , m_capHeight(-1) - , m_descent(-1) - , m_xHeight(-1) - , m_lineGap(-1) -{ - qCDebug(lcQpaFonts) << __FUNCTION__ << pixelSize; - - Q_ASSERT(m_directWriteFontFace); - - m_fontEngineData->directWriteFactory->AddRef(); - m_directWriteFontFace->AddRef(); - - fontDef.pixelSize = pixelSize; - collectMetrics(); - cache_cost = (m_ascent.toInt() + m_descent.toInt()) * m_xHeight.toInt() * 2000; -} - -QWindowsFontEngineDirectWrite::~QWindowsFontEngineDirectWrite() -{ - qCDebug(lcQpaFonts) << __FUNCTION__; - - m_fontEngineData->directWriteFactory->Release(); - m_directWriteFontFace->Release(); - - if (m_directWriteBitmapRenderTarget != 0) - m_directWriteBitmapRenderTarget->Release(); - - if (!m_uniqueFamilyName.isEmpty()) { - QPlatformFontDatabase *pfdb = QGuiApplicationPrivate::platformIntegration()->fontDatabase(); - static_cast<QWindowsFontDatabase *>(pfdb)->derefUniqueFont(m_uniqueFamilyName); - } -} - -#ifndef Q_CC_MINGW -typedef IDWriteLocalFontFileLoader QIdWriteLocalFontFileLoader; - -static UUID uuidIdWriteLocalFontFileLoader() -{ - return __uuidof(IDWriteLocalFontFileLoader); -} -#else // !Q_CC_MINGW -DECLARE_INTERFACE_(QIdWriteLocalFontFileLoader, IDWriteFontFileLoader) -{ - STDMETHOD(GetFilePathLengthFromKey)(THIS_ void const *, UINT32, UINT32*) PURE; - STDMETHOD(GetFilePathFromKey)(THIS_ void const *, UINT32, WCHAR *, UINT32) PURE; - STDMETHOD(GetLastWriteTimeFromKey)(THIS_ void const *, UINT32, FILETIME *) PURE; -}; - -static UUID uuidIdWriteLocalFontFileLoader() -{ - static const UUID result = { 0xb2d9f3ec, 0xc9fe, 0x4a11, {0xa2, 0xec, 0xd8, 0x62, 0x8, 0xf7, 0xc0, 0xa2}}; - return result; -} -#endif // Q_CC_MINGW - -QString QWindowsFontEngineDirectWrite::filenameFromFontFile(IDWriteFontFile *fontFile) -{ - IDWriteFontFileLoader *loader = nullptr; - - HRESULT hr = fontFile->GetLoader(&loader); - if (FAILED(hr)) { - qErrnoWarning("%s: GetLoader failed", __FUNCTION__); - return QString(); - } - - QIdWriteLocalFontFileLoader *localLoader = nullptr; - hr = loader->QueryInterface(uuidIdWriteLocalFontFileLoader(), - reinterpret_cast<void **>(&localLoader)); - - const void *fontFileReferenceKey = nullptr; - UINT32 fontFileReferenceKeySize = 0; - if (SUCCEEDED(hr)) { - hr = fontFile->GetReferenceKey(&fontFileReferenceKey, - &fontFileReferenceKeySize); - if (FAILED(hr)) - qErrnoWarning(hr, "%s: GetReferenceKey failed", __FUNCTION__); - } - - UINT32 filePathLength = 0; - if (SUCCEEDED(hr)) { - hr = localLoader->GetFilePathLengthFromKey(fontFileReferenceKey, - fontFileReferenceKeySize, - &filePathLength); - if (FAILED(hr)) - qErrnoWarning(hr, "GetFilePathLength failed", __FUNCTION__); - } - - QString ret; - if (SUCCEEDED(hr) && filePathLength > 0) { - QVarLengthArray<wchar_t> filePath(filePathLength + 1); - - hr = localLoader->GetFilePathFromKey(fontFileReferenceKey, - fontFileReferenceKeySize, - filePath.data(), - filePathLength + 1); - if (FAILED(hr)) - qErrnoWarning(hr, "%s: GetFilePathFromKey failed", __FUNCTION__); - else - ret = QString::fromWCharArray(filePath.data()); - } - - if (localLoader != nullptr) - localLoader->Release(); - - if (loader != nullptr) - loader->Release(); - return ret; -} - -void QWindowsFontEngineDirectWrite::collectMetrics() -{ - DWRITE_FONT_METRICS metrics; - - m_directWriteFontFace->GetMetrics(&metrics); - m_unitsPerEm = metrics.designUnitsPerEm; - - m_lineThickness = DESIGN_TO_LOGICAL(metrics.underlineThickness); - m_ascent = DESIGN_TO_LOGICAL(metrics.ascent); - m_capHeight = DESIGN_TO_LOGICAL(metrics.capHeight); - m_descent = DESIGN_TO_LOGICAL(metrics.descent); - m_xHeight = DESIGN_TO_LOGICAL(metrics.xHeight); - m_lineGap = DESIGN_TO_LOGICAL(metrics.lineGap); - m_underlinePosition = DESIGN_TO_LOGICAL(metrics.underlinePosition); - - IDWriteFontFile *fontFile = nullptr; - UINT32 numberOfFiles = 1; - if (SUCCEEDED(m_directWriteFontFace->GetFiles(&numberOfFiles, &fontFile))) { - m_faceId.filename = QFile::encodeName(filenameFromFontFile(fontFile)); - fontFile->Release(); - } - - QByteArray table = getSfntTable(MAKE_TAG('h', 'h', 'e', 'a')); - const int advanceWidthMaxLocation = 10; - if (table.size() >= advanceWidthMaxLocation + int(sizeof(quint16))) { - quint16 advanceWidthMax = qFromBigEndian<quint16>(table.constData() + advanceWidthMaxLocation); - m_maxAdvanceWidth = DESIGN_TO_LOGICAL(advanceWidthMax); - } -} - -QFixed QWindowsFontEngineDirectWrite::underlinePosition() const -{ - if (m_underlinePosition > 0) - return m_underlinePosition; - else - return QFontEngine::underlinePosition(); -} - -QFixed QWindowsFontEngineDirectWrite::lineThickness() const -{ - if (m_lineThickness > 0) - return m_lineThickness; - else - return QFontEngine::lineThickness(); -} - -bool QWindowsFontEngineDirectWrite::getSfntTableData(uint tag, uchar *buffer, uint *length) const -{ - bool ret = false; - - const void *tableData = 0; - UINT32 tableSize; - void *tableContext = 0; - BOOL exists; - HRESULT hr = m_directWriteFontFace->TryGetFontTable(qbswap<quint32>(tag), - &tableData, &tableSize, - &tableContext, &exists); - if (SUCCEEDED(hr)) { - if (exists) { - ret = true; - if (buffer && *length >= tableSize) - memcpy(buffer, tableData, tableSize); - *length = tableSize; - Q_ASSERT(int(*length) > 0); - } - m_directWriteFontFace->ReleaseFontTable(tableContext); - } else { - qErrnoWarning("%s: TryGetFontTable failed", __FUNCTION__); - } - - return ret; -} - -QFixed QWindowsFontEngineDirectWrite::emSquareSize() const -{ - if (m_unitsPerEm > 0) - return m_unitsPerEm; - else - return QFontEngine::emSquareSize(); -} - -glyph_t QWindowsFontEngineDirectWrite::glyphIndex(uint ucs4) const -{ - UINT16 glyphIndex; - - HRESULT hr = m_directWriteFontFace->GetGlyphIndicesW(&ucs4, 1, &glyphIndex); - if (FAILED(hr)) { - qErrnoWarning("%s: glyphIndex failed", __FUNCTION__); - glyphIndex = 0; - } - - return glyphIndex; -} - -bool QWindowsFontEngineDirectWrite::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, - int *nglyphs, QFontEngine::ShaperFlags flags) const -{ - Q_ASSERT(glyphs->numGlyphs >= *nglyphs); - if (*nglyphs < len) { - *nglyphs = len; - return false; - } - - QVarLengthArray<UINT32> codePoints(len); - int actualLength = 0; - QStringIterator it(str, str + len); - while (it.hasNext()) - codePoints[actualLength++] = it.next(); - - QVarLengthArray<UINT16> glyphIndices(actualLength); - HRESULT hr = m_directWriteFontFace->GetGlyphIndicesW(codePoints.data(), actualLength, - glyphIndices.data()); - if (FAILED(hr)) { - qErrnoWarning("%s: GetGlyphIndicesW failed", __FUNCTION__); - return false; - } - - for (int i = 0; i < actualLength; ++i) - glyphs->glyphs[i] = glyphIndices.at(i); - - *nglyphs = actualLength; - glyphs->numGlyphs = actualLength; - - if (!(flags & GlyphIndicesOnly)) - recalcAdvances(glyphs, 0); - - return true; -} - -QFontEngine::FaceId QWindowsFontEngineDirectWrite::faceId() const -{ - return m_faceId; -} - -void QWindowsFontEngineDirectWrite::recalcAdvances(QGlyphLayout *glyphs, QFontEngine::ShaperFlags) const -{ - QVarLengthArray<UINT16> glyphIndices(glyphs->numGlyphs); - - // ### Caching? - for(int i=0; i<glyphs->numGlyphs; i++) - glyphIndices[i] = UINT16(glyphs->glyphs[i]); - - QVarLengthArray<DWRITE_GLYPH_METRICS> glyphMetrics(glyphIndices.size()); - HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(glyphIndices.data(), - glyphIndices.size(), - glyphMetrics.data()); - if (SUCCEEDED(hr)) { - qreal stretch = fontDef.stretch != QFont::AnyStretch ? fontDef.stretch / 100.0 : 1.0; - for (int i = 0; i < glyphs->numGlyphs; ++i) - glyphs->advances[i] = DESIGN_TO_LOGICAL(glyphMetrics[i].advanceWidth * stretch); - if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) { - for (int i = 0; i < glyphs->numGlyphs; ++i) - glyphs->advances[i] = glyphs->advances[i].round(); - } - } else { - qErrnoWarning("%s: GetDesignGlyphMetrics failed", __FUNCTION__); - } -} - -void QWindowsFontEngineDirectWrite::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs, - QPainterPath *path, QTextItem::RenderFlags flags) -{ - QVarLengthArray<UINT16> glyphIndices(nglyphs); - QVarLengthArray<DWRITE_GLYPH_OFFSET> glyphOffsets(nglyphs); - QVarLengthArray<FLOAT> glyphAdvances(nglyphs); - - for (int i=0; i<nglyphs; ++i) { - glyphIndices[i] = glyphs[i]; - glyphOffsets[i].advanceOffset = positions[i].x.toReal(); - glyphOffsets[i].ascenderOffset = -positions[i].y.toReal(); - glyphAdvances[i] = 0.0; - } - - GeometrySink geometrySink(path); - HRESULT hr = m_directWriteFontFace->GetGlyphRunOutline( - fontDef.pixelSize, - glyphIndices.data(), - glyphAdvances.data(), - glyphOffsets.data(), - nglyphs, - false, - flags & QTextItem::RightToLeft, - &geometrySink - ); - - if (FAILED(hr)) - qErrnoWarning("%s: GetGlyphRunOutline failed", __FUNCTION__); -} - -glyph_metrics_t QWindowsFontEngineDirectWrite::boundingBox(const QGlyphLayout &glyphs) -{ - if (glyphs.numGlyphs == 0) - return glyph_metrics_t(); - - bool round = fontDef.styleStrategy & QFont::ForceIntegerMetrics; - - QFixed w = 0; - for (int i = 0; i < glyphs.numGlyphs; ++i) { - w += round ? glyphs.effectiveAdvance(i).round() : glyphs.effectiveAdvance(i); - - } - - return glyph_metrics_t(0, -m_ascent, w - lastRightBearing(glyphs), m_ascent + m_descent, w, 0); -} - -glyph_metrics_t QWindowsFontEngineDirectWrite::boundingBox(glyph_t g) -{ - UINT16 glyphIndex = g; - - DWRITE_GLYPH_METRICS glyphMetrics; - HRESULT hr = m_directWriteFontFace->GetDesignGlyphMetrics(&glyphIndex, 1, &glyphMetrics); - if (SUCCEEDED(hr)) { - QFixed advanceWidth = DESIGN_TO_LOGICAL(glyphMetrics.advanceWidth); - QFixed leftSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.leftSideBearing); - QFixed rightSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.rightSideBearing); - QFixed advanceHeight = DESIGN_TO_LOGICAL(glyphMetrics.advanceHeight); - QFixed verticalOriginY = DESIGN_TO_LOGICAL(glyphMetrics.verticalOriginY); - QFixed topSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.topSideBearing); - QFixed bottomSideBearing = DESIGN_TO_LOGICAL(glyphMetrics.bottomSideBearing); - - if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) { - advanceWidth = advanceWidth.round(); - advanceHeight = advanceHeight.round(); - } - - QFixed width = advanceWidth - leftSideBearing - rightSideBearing; - QFixed height = advanceHeight - topSideBearing - bottomSideBearing; - return glyph_metrics_t(leftSideBearing, - -verticalOriginY + topSideBearing, - width, - height, - advanceWidth, - 0); - } else { - qErrnoWarning("%s: GetDesignGlyphMetrics failed", __FUNCTION__); - } - - return glyph_metrics_t(); -} - -QFixed QWindowsFontEngineDirectWrite::ascent() const -{ - return fontDef.styleStrategy & QFont::ForceIntegerMetrics - ? m_ascent.round() - : m_ascent; -} - -QFixed QWindowsFontEngineDirectWrite::capHeight() const -{ - if (m_capHeight <= 0) - return calculatedCapHeight(); - - return fontDef.styleStrategy & QFont::ForceIntegerMetrics - ? m_capHeight.round() - : m_capHeight; -} - -QFixed QWindowsFontEngineDirectWrite::descent() const -{ - return fontDef.styleStrategy & QFont::ForceIntegerMetrics - ? m_descent.round() - : m_descent; -} - -QFixed QWindowsFontEngineDirectWrite::leading() const -{ - return fontDef.styleStrategy & QFont::ForceIntegerMetrics - ? m_lineGap.round() - : m_lineGap; -} - -QFixed QWindowsFontEngineDirectWrite::xHeight() const -{ - return fontDef.styleStrategy & QFont::ForceIntegerMetrics - ? m_xHeight.round() - : m_xHeight; -} - -qreal QWindowsFontEngineDirectWrite::maxCharWidth() const -{ - return fontDef.styleStrategy & QFont::ForceIntegerMetrics - ? m_maxAdvanceWidth.round().toReal() - : m_maxAdvanceWidth.toReal(); -} - -QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t) -{ - QImage im = alphaRGBMapForGlyph(glyph, subPixelPosition, t); - - QImage alphaMap(im.width(), im.height(), QImage::Format_Alpha8); - - for (int y=0; y<im.height(); ++y) { - const uint *src = reinterpret_cast<const uint *>(im.constScanLine(y)); - uchar *dst = alphaMap.scanLine(y); - for (int x=0; x<im.width(); ++x) { - *dst = 255 - (m_fontEngineData->pow_gamma[qGray(0xffffffff - *src)] * 255. / 2047.); - ++dst; - ++src; - } - } - - return alphaMap; -} - -QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition) -{ - return alphaMapForGlyph(glyph, subPixelPosition, QTransform()); -} - -bool QWindowsFontEngineDirectWrite::supportsSubPixelPositions() const -{ - return true; -} - -QImage QWindowsFontEngineDirectWrite::imageForGlyph(glyph_t t, - QFixed subPixelPosition, - int margin, - const QTransform &originalTransform, - const QColor &color) -{ - UINT16 glyphIndex = t; - FLOAT glyphAdvance = 0; - - DWRITE_GLYPH_OFFSET glyphOffset; - glyphOffset.advanceOffset = 0; - glyphOffset.ascenderOffset = 0; - - DWRITE_GLYPH_RUN glyphRun; - glyphRun.fontFace = m_directWriteFontFace; - glyphRun.fontEmSize = fontDef.pixelSize; - glyphRun.glyphCount = 1; - glyphRun.glyphIndices = &glyphIndex; - glyphRun.glyphAdvances = &glyphAdvance; - glyphRun.isSideways = false; - glyphRun.bidiLevel = 0; - glyphRun.glyphOffsets = &glyphOffset; - - QTransform xform = originalTransform; - if (fontDef.stretch != 100 && fontDef.stretch != QFont::AnyStretch) - xform.scale(fontDef.stretch / 100.0, 1.0); - - DWRITE_MATRIX transform; - transform.dx = subPixelPosition.toReal(); - transform.dy = 0; - transform.m11 = xform.m11(); - transform.m12 = xform.m12(); - transform.m21 = xform.m21(); - transform.m22 = xform.m22(); - - DWRITE_RENDERING_MODE renderMode = - hintingPreferenceToRenderingMode(QFont::HintingPreference(fontDef.hintingPreference)); - - IDWriteGlyphRunAnalysis *glyphAnalysis = NULL; - HRESULT hr = m_fontEngineData->directWriteFactory->CreateGlyphRunAnalysis( - &glyphRun, - 1.0f, - &transform, - renderMode, - DWRITE_MEASURING_MODE_NATURAL, - 0.0, 0.0, - &glyphAnalysis - ); - - if (SUCCEEDED(hr)) { - RECT rect; - glyphAnalysis->GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1, &rect); - - QRect boundingRect = QRect(QPoint(rect.left - margin, - rect.top - margin), - QPoint(rect.right + margin, - rect.bottom + margin)); - - - const int width = boundingRect.width() - 1; // -1 due to Qt's off-by-one definition of a QRect - const int height = boundingRect.height() - 1; - - QImage image; -#if defined(QT_USE_DIRECTWRITE2) - HRESULT hr = DWRITE_E_NOCOLOR; - IDWriteColorGlyphRunEnumerator *enumerator = 0; - IDWriteFactory2 *factory2 = nullptr; - if (glyphFormat == QFontEngine::Format_ARGB - && SUCCEEDED(m_fontEngineData->directWriteFactory->QueryInterface(__uuidof(IDWriteFactory2), - reinterpret_cast<void **>(&factory2)))) { - hr = factory2->TranslateColorGlyphRun(0.0f, - 0.0f, - &glyphRun, - NULL, - DWRITE_MEASURING_MODE_NATURAL, - NULL, - 0, - &enumerator); - image = QImage(width, height, QImage::Format_ARGB32_Premultiplied); - image.fill(0); - } else -#endif - { - image = QImage(width, height, QImage::Format_RGB32); - image.fill(0xffffffff); - } - -#if defined(QT_USE_DIRECTWRITE2) - BOOL ok = true; - - if (SUCCEEDED(hr)) { - while (SUCCEEDED(hr) && ok) { - const DWRITE_COLOR_GLYPH_RUN *colorGlyphRun = 0; - hr = enumerator->GetCurrentRun(&colorGlyphRun); - if (FAILED(hr)) { // No colored runs, only outline - qErrnoWarning(hr, "%s: IDWriteColorGlyphRunEnumerator::GetCurrentRun failed", __FUNCTION__); - break; - } - - IDWriteGlyphRunAnalysis *colorGlyphsAnalysis = NULL; - hr = m_fontEngineData->directWriteFactory->CreateGlyphRunAnalysis( - &colorGlyphRun->glyphRun, - 1.0f, - &transform, - renderMode, - DWRITE_MEASURING_MODE_NATURAL, - 0.0, 0.0, - &colorGlyphsAnalysis - ); - if (FAILED(hr)) { - qErrnoWarning(hr, "%s: CreateGlyphRunAnalysis failed for color run", __FUNCTION__); - break; - } - - float r, g, b, a; - if (colorGlyphRun->paletteIndex == 0xFFFF) { - r = float(color.redF()); - g = float(color.greenF()); - b = float(color.blueF()); - a = float(color.alphaF()); - } else { - r = qBound(0.0f, colorGlyphRun->runColor.r, 1.0f); - g = qBound(0.0f, colorGlyphRun->runColor.g, 1.0f); - b = qBound(0.0f, colorGlyphRun->runColor.b, 1.0f); - a = qBound(0.0f, colorGlyphRun->runColor.a, 1.0f); - } - - if (!qFuzzyIsNull(a)) { - renderGlyphRun(&image, - r, - g, - b, - a, - colorGlyphsAnalysis, - boundingRect); - } - colorGlyphsAnalysis->Release(); - - hr = enumerator->MoveNext(&ok); - if (FAILED(hr)) { - qErrnoWarning(hr, "%s: IDWriteColorGlyphRunEnumerator::MoveNext failed", __FUNCTION__); - break; - } - } - } else -#endif - { - float r, g, b, a; - if (glyphFormat == QFontEngine::Format_ARGB) { - r = float(color.redF()); - g = float(color.greenF()); - b = float(color.blueF()); - a = float(color.alphaF()); - } else { - r = g = b = a = 0.0; - } - - renderGlyphRun(&image, - r, - g, - b, - a, - glyphAnalysis, - boundingRect); - } - - glyphAnalysis->Release(); - return image; - } else { - qErrnoWarning(hr, "%s: CreateGlyphRunAnalysis failed", __FUNCTION__); - return QImage(); - } -} - - -void QWindowsFontEngineDirectWrite::renderGlyphRun(QImage *destination, - float r, - float g, - float b, - float a, - IDWriteGlyphRunAnalysis *glyphAnalysis, - const QRect &boundingRect) -{ - const int width = destination->width(); - const int height = destination->height(); - - r *= 255.0; - g *= 255.0; - b *= 255.0; - - const int size = width * height * 3; - if (size > 0) { - RECT rect; - rect.left = boundingRect.left(); - rect.top = boundingRect.top(); - rect.right = boundingRect.right(); - rect.bottom = boundingRect.bottom(); - - QVarLengthArray<BYTE, 1024> alphaValueArray(size); - BYTE *alphaValues = alphaValueArray.data(); - memset(alphaValues, 0, size); - - HRESULT hr = glyphAnalysis->CreateAlphaTexture(DWRITE_TEXTURE_CLEARTYPE_3x1, - &rect, - alphaValues, - size); - if (SUCCEEDED(hr)) { - if (destination->hasAlphaChannel()) { - for (int y = 0; y < height; ++y) { - uint *dest = reinterpret_cast<uint *>(destination->scanLine(y)); - BYTE *src = alphaValues + width * 3 * y; - - for (int x = 0; x < width; ++x) { - float redAlpha = a * *src++ / 255.0; - float greenAlpha = a * *src++ / 255.0; - float blueAlpha = a * *src++ / 255.0; - float averageAlpha = (redAlpha + greenAlpha + blueAlpha) / 3.0; - - QRgb currentRgb = dest[x]; - dest[x] = qRgba(qRound(qRed(currentRgb) * (1.0 - averageAlpha) + averageAlpha * r), - qRound(qGreen(currentRgb) * (1.0 - averageAlpha) + averageAlpha * g), - qRound(qBlue(currentRgb) * (1.0 - averageAlpha) + averageAlpha * b), - qRound(qAlpha(currentRgb) * (1.0 - averageAlpha) + averageAlpha * 255)); - } - } - - } else { - for (int y = 0; y < height; ++y) { - uint *dest = reinterpret_cast<uint *>(destination->scanLine(y)); - BYTE *src = alphaValues + width * 3 * y; - - for (int x = 0; x < width; ++x) { - dest[x] = *(src + 0) << 16 - | *(src + 1) << 8 - | *(src + 2); - - src += 3; - } - } - } - } else { - qErrnoWarning("%s: CreateAlphaTexture failed", __FUNCTION__); - } - } else { - glyphAnalysis->Release(); - qWarning("%s: Glyph has no bounds", __FUNCTION__); - } -} - -QImage QWindowsFontEngineDirectWrite::alphaRGBMapForGlyph(glyph_t t, - QFixed subPixelPosition, - const QTransform &xform) -{ - QImage mask = imageForGlyph(t, - subPixelPosition, - glyphMargin(QFontEngine::Format_A32), - xform); - - return mask.depth() == 32 - ? mask - : mask.convertToFormat(QImage::Format_RGB32); -} - -QFontEngine *QWindowsFontEngineDirectWrite::cloneWithSize(qreal pixelSize) const -{ - QWindowsFontEngineDirectWrite *fontEngine = new QWindowsFontEngineDirectWrite(m_directWriteFontFace, - pixelSize, - m_fontEngineData); - - fontEngine->fontDef = fontDef; - fontEngine->fontDef.pixelSize = pixelSize; - if (!m_uniqueFamilyName.isEmpty()) { - fontEngine->setUniqueFamilyName(m_uniqueFamilyName); - QPlatformFontDatabase *pfdb = QGuiApplicationPrivate::platformIntegration()->fontDatabase(); - static_cast<QWindowsFontDatabase *>(pfdb)->refUniqueFont(m_uniqueFamilyName); - } - - return fontEngine; -} - -Qt::HANDLE QWindowsFontEngineDirectWrite::handle() const -{ - return m_directWriteFontFace; -} - -void QWindowsFontEngineDirectWrite::initFontInfo(const QFontDef &request, - int dpi) -{ - fontDef = request; - - if (fontDef.pointSize < 0) - fontDef.pointSize = fontDef.pixelSize * 72. / dpi; - else if (fontDef.pixelSize == -1) - fontDef.pixelSize = qRound(fontDef.pointSize * dpi / 72.); -} - -QString QWindowsFontEngineDirectWrite::fontNameSubstitute(const QString &familyName) -{ - const wchar_t key[] = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes"; - const QString substitute = - QWindowsFontDatabase::readRegistryString(HKEY_LOCAL_MACHINE, key, - reinterpret_cast<const wchar_t *>(familyName.utf16())); - return substitute.isEmpty() ? familyName : substitute; -} - -glyph_metrics_t QWindowsFontEngineDirectWrite::alphaMapBoundingBox(glyph_t glyph, - QFixed subPixelPosition, - const QTransform &originalTransform, - GlyphFormat format) -{ - Q_UNUSED(format); - - QTransform matrix = originalTransform; - if (fontDef.stretch != 100 && fontDef.stretch != QFont::AnyStretch) - matrix.scale(fontDef.stretch / 100.0, 1.0); - - glyph_metrics_t bbox = QFontEngine::boundingBox(glyph, matrix); // To get transformed advance - - UINT16 glyphIndex = glyph; - FLOAT glyphAdvance = 0; - - DWRITE_GLYPH_OFFSET glyphOffset; - glyphOffset.advanceOffset = 0; - glyphOffset.ascenderOffset = 0; - - DWRITE_GLYPH_RUN glyphRun; - glyphRun.fontFace = m_directWriteFontFace; - glyphRun.fontEmSize = fontDef.pixelSize; - glyphRun.glyphCount = 1; - glyphRun.glyphIndices = &glyphIndex; - glyphRun.glyphAdvances = &glyphAdvance; - glyphRun.isSideways = false; - glyphRun.bidiLevel = 0; - glyphRun.glyphOffsets = &glyphOffset; - - DWRITE_MATRIX transform; - transform.dx = subPixelPosition.toReal(); - transform.dy = 0; - transform.m11 = matrix.m11(); - transform.m12 = matrix.m12(); - transform.m21 = matrix.m21(); - transform.m22 = matrix.m22(); - - DWRITE_RENDERING_MODE renderMode = - hintingPreferenceToRenderingMode(QFont::HintingPreference(fontDef.hintingPreference)); - - IDWriteGlyphRunAnalysis *glyphAnalysis = NULL; - HRESULT hr = m_fontEngineData->directWriteFactory->CreateGlyphRunAnalysis( - &glyphRun, - 1.0f, - &transform, - renderMode, - DWRITE_MEASURING_MODE_NATURAL, - 0.0, 0.0, - &glyphAnalysis - ); - - if (SUCCEEDED(hr)) { - RECT rect; - glyphAnalysis->GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1, &rect); - glyphAnalysis->Release(); - - int margin = glyphMargin(QFontEngine::Format_A32); - - return glyph_metrics_t(rect.left, - rect.top, - rect.right - rect.left + margin * 2, - rect.bottom - rect.top + margin * 2, - bbox.xoff, bbox.yoff); - } else { - return glyph_metrics_t(); - } -} - -QImage QWindowsFontEngineDirectWrite::bitmapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t, const QColor &color) -{ - return imageForGlyph(glyph, subPixelPosition, glyphMargin(QFontEngine::Format_A32), t, color); -} - -QT_END_NAMESPACE - -#endif // QT_NO_DIRECTWRITE diff --git a/src/platformsupport/fontdatabases/windows/qwindowsfontenginedirectwrite_p.h b/src/platformsupport/fontdatabases/windows/qwindowsfontenginedirectwrite_p.h deleted file mode 100644 index 9e13474a04..0000000000 --- a/src/platformsupport/fontdatabases/windows/qwindowsfontenginedirectwrite_p.h +++ /dev/null @@ -1,156 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QWINDOWSFONTENGINEDIRECTWRITE_H -#define QWINDOWSFONTENGINEDIRECTWRITE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/qglobal.h> - -#ifndef QT_NO_DIRECTWRITE - -#include <QtGui/private/qfontengine_p.h> -#include <QtCore/QSharedPointer> - -struct IDWriteFont; -struct IDWriteFontFace; -struct IDWriteFontFile; -struct IDWriteFactory; -struct IDWriteBitmapRenderTarget; -struct IDWriteGdiInterop; -struct IDWriteGlyphRunAnalysis; - -QT_BEGIN_NAMESPACE - -class QWindowsFontEngineData; - -class QWindowsFontEngineDirectWrite : public QFontEngine -{ - Q_DISABLE_COPY(QWindowsFontEngineDirectWrite) -public: - explicit QWindowsFontEngineDirectWrite(IDWriteFontFace *directWriteFontFace, - qreal pixelSize, - const QSharedPointer<QWindowsFontEngineData> &d); - ~QWindowsFontEngineDirectWrite() override; - - void initFontInfo(const QFontDef &request, int dpi); - - QFixed lineThickness() const override; - QFixed underlinePosition() const override; - bool getSfntTableData(uint tag, uchar *buffer, uint *length) const override; - QFixed emSquareSize() const override; - - glyph_t glyphIndex(uint ucs4) const override; - bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, - ShaperFlags flags) const override; - void recalcAdvances(QGlyphLayout *glyphs, ShaperFlags) const override; - - void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs, - QPainterPath *path, QTextItem::RenderFlags flags) override; - - glyph_metrics_t boundingBox(const QGlyphLayout &glyphs) override; - glyph_metrics_t boundingBox(glyph_t g) override; - glyph_metrics_t alphaMapBoundingBox(glyph_t glyph, QFixed, - const QTransform &matrix, GlyphFormat) override; - - QFixed ascent() const override; - QFixed capHeight() const override; - QFixed descent() const override; - QFixed leading() const override; - QFixed xHeight() const override; - qreal maxCharWidth() const override; - FaceId faceId() const override; - - bool supportsSubPixelPositions() const override; - - QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition) override; - QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t) override; - QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, const QTransform &xform) override; - QImage bitmapForGlyph(glyph_t, QFixed subPixelPosition, const QTransform &t, const QColor &color) override; - - QFontEngine *cloneWithSize(qreal pixelSize) const override; - Qt::HANDLE handle() const override; - - const QSharedPointer<QWindowsFontEngineData> &fontEngineData() const { return m_fontEngineData; } - - static QString fontNameSubstitute(const QString &familyName); - - IDWriteFontFace *directWriteFontFace() const { return m_directWriteFontFace; } - - void setUniqueFamilyName(const QString &newName) { m_uniqueFamilyName = newName; } - -private: - QImage imageForGlyph(glyph_t t, QFixed subPixelPosition, int margin, const QTransform &xform, const QColor &color = QColor()); - void collectMetrics(); - void renderGlyphRun(QImage *destination, float r, float g, float b, float a, IDWriteGlyphRunAnalysis *glyphAnalysis, const QRect &boundingRect); - static QString filenameFromFontFile(IDWriteFontFile *fontFile); - - const QSharedPointer<QWindowsFontEngineData> m_fontEngineData; - - IDWriteFontFace *m_directWriteFontFace; - IDWriteBitmapRenderTarget *m_directWriteBitmapRenderTarget; - - QFixed m_lineThickness; - QFixed m_underlinePosition; - int m_unitsPerEm; - QFixed m_ascent; - QFixed m_capHeight; - QFixed m_descent; - QFixed m_xHeight; - QFixed m_lineGap; - QFixed m_maxAdvanceWidth; - FaceId m_faceId; - QString m_uniqueFamilyName; -}; - -QT_END_NAMESPACE - -#endif // QT_NO_DIRECTWRITE - -#endif // QWINDOWSFONTENGINEDIRECTWRITE_H diff --git a/src/platformsupport/fontdatabases/windows/qwindowsnativeimage.cpp b/src/platformsupport/fontdatabases/windows/qwindowsnativeimage.cpp deleted file mode 100644 index b1133dca22..0000000000 --- a/src/platformsupport/fontdatabases/windows/qwindowsnativeimage.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qwindowsnativeimage_p.h" - -#include <QtGui/private/qpaintengine_p.h> -#include <QtGui/private/qpaintengine_raster_p.h> - -QT_BEGIN_NAMESPACE - -typedef struct { - BITMAPINFOHEADER bmiHeader; - DWORD redMask; - DWORD greenMask; - DWORD blueMask; -} BITMAPINFO_MASK; - -/*! - \class QWindowsNativeImage - \brief Windows Native image - - Note that size can be 0 (widget autotests with zero size), which - causes CreateDIBSection() to fail. - - \sa QWindowsBackingStore - \internal - \ingroup qt-lighthouse-win -*/ - -static inline HDC createDC() -{ - HDC display_dc = GetDC(0); - HDC hdc = CreateCompatibleDC(display_dc); - ReleaseDC(0, display_dc); - Q_ASSERT(hdc); - return hdc; -} - -static inline HBITMAP createDIB(HDC hdc, int width, int height, - QImage::Format format, - uchar **bitsIn) -{ - BITMAPINFO_MASK bmi; - memset(&bmi, 0, sizeof(bmi)); - bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); - bmi.bmiHeader.biWidth = width; - bmi.bmiHeader.biHeight = -height; // top-down. - bmi.bmiHeader.biPlanes = 1; - bmi.bmiHeader.biSizeImage = 0; - - if (format == QImage::Format_RGB16) { - bmi.bmiHeader.biBitCount = 16; - bmi.bmiHeader.biCompression = BI_BITFIELDS; - bmi.redMask = 0xF800; - bmi.greenMask = 0x07E0; - bmi.blueMask = 0x001F; - } else { - bmi.bmiHeader.biBitCount = 32; - bmi.bmiHeader.biCompression = BI_RGB; - bmi.redMask = 0; - bmi.greenMask = 0; - bmi.blueMask = 0; - } - - uchar *bits = nullptr; - HBITMAP bitmap = CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO *>(&bmi), - DIB_RGB_COLORS, reinterpret_cast<void **>(&bits), 0, 0); - if (Q_UNLIKELY(!bitmap || !bits)) { - qFatal("%s: CreateDIBSection failed (%dx%d, format: %d)", __FUNCTION__, - width, height, int(format)); - } - - *bitsIn = bits; - return bitmap; -} - -QWindowsNativeImage::QWindowsNativeImage(int width, int height, - QImage::Format format) : - m_hdc(createDC()) -{ - if (width != 0 && height != 0) { - uchar *bits; - m_bitmap = createDIB(m_hdc, width, height, format, &bits); - m_null_bitmap = static_cast<HBITMAP>(SelectObject(m_hdc, m_bitmap)); - m_image = QImage(bits, width, height, format); - Q_ASSERT(m_image.paintEngine()->type() == QPaintEngine::Raster); - static_cast<QRasterPaintEngine *>(m_image.paintEngine())->setDC(m_hdc); - } else { - m_image = QImage(width, height, format); - } - - GdiFlush(); -} - -QWindowsNativeImage::~QWindowsNativeImage() -{ - if (m_hdc) { - if (m_bitmap) { - if (m_null_bitmap) - SelectObject(m_hdc, m_null_bitmap); - DeleteObject(m_bitmap); - } - DeleteDC(m_hdc); - } -} - -QImage::Format QWindowsNativeImage::systemFormat() -{ - static int depth = -1; - if (depth == -1) { - if (HDC defaultDC = GetDC(0)) { - depth = GetDeviceCaps(defaultDC, BITSPIXEL); - ReleaseDC(0, defaultDC); - } else { - // FIXME Same remark as in QWindowsFontDatabase::defaultVerticalDPI() - // BONUS FIXME: Is 32 too generous/optimistic? - depth = 32; - } - } - return depth == 16 ? QImage::Format_RGB16 : QImage::Format_RGB32; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/fontdatabases/windows/qwindowsnativeimage_p.h b/src/platformsupport/fontdatabases/windows/qwindowsnativeimage_p.h deleted file mode 100644 index 6c47a527d2..0000000000 --- a/src/platformsupport/fontdatabases/windows/qwindowsnativeimage_p.h +++ /dev/null @@ -1,89 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QWINDOWSNATIVEIMAGE_H -#define QWINDOWSNATIVEIMAGE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/QtGlobal> -#include <QtCore/qt_windows.h> -#include <QtGui/QImage> - -QT_BEGIN_NAMESPACE - -class QWindowsNativeImage -{ - Q_DISABLE_COPY(QWindowsNativeImage) -public: - QWindowsNativeImage(int width, int height, - QImage::Format format); - - ~QWindowsNativeImage(); - - inline int width() const { return m_image.width(); } - inline int height() const { return m_image.height(); } - - QImage &image() { return m_image; } - const QImage &image() const { return m_image; } - - HDC hdc() const { return m_hdc; } - - static QImage::Format systemFormat(); - -private: - const HDC m_hdc; - QImage m_image; - - HBITMAP m_bitmap = 0; - HBITMAP m_null_bitmap = 0; -}; - -QT_END_NAMESPACE - -#endif // QWINDOWSNATIVEIMAGE_H diff --git a/src/platformsupport/fontdatabases/windows/windows.pri b/src/platformsupport/fontdatabases/windows/windows.pri deleted file mode 100644 index 9c529f55ea..0000000000 --- a/src/platformsupport/fontdatabases/windows/windows.pri +++ /dev/null @@ -1,34 +0,0 @@ -QT *= gui-private - -SOURCES += \ - $$PWD/qwindowsfontdatabase.cpp \ - $$PWD/qwindowsfontengine.cpp \ - $$PWD/qwindowsnativeimage.cpp - -HEADERS += \ - $$PWD/qwindowsfontdatabase_p.h \ - $$PWD/qwindowsfontengine_p.h \ - $$PWD/qwindowsnativeimage_p.h - -qtConfig(freetype) { - SOURCES += $$PWD/qwindowsfontdatabase_ft.cpp - HEADERS += $$PWD/qwindowsfontdatabase_ft_p.h -} - -qtConfig(directwrite):qtConfig(direct2d) { - qtConfig(directwrite2) { - QMAKE_USE_PRIVATE += dwrite_2 - DEFINES *= QT_USE_DIRECTWRITE2 - } else { - QMAKE_USE_PRIVATE += dwrite - } - QMAKE_USE_PRIVATE += d2d1 - - SOURCES += $$PWD/qwindowsfontenginedirectwrite.cpp - HEADERS += $$PWD/qwindowsfontenginedirectwrite_p.h -} else { - DEFINES *= QT_NO_DIRECTWRITE -} - -LIBS += -lole32 -lgdi32 -luser32 -ladvapi32 -mingw: LIBS += -luuid diff --git a/src/platformsupport/fontdatabases/winrt/qwinrtfontdatabase.cpp b/src/platformsupport/fontdatabases/winrt/qwinrtfontdatabase.cpp deleted file mode 100644 index db58e49bb2..0000000000 --- a/src/platformsupport/fontdatabases/winrt/qwinrtfontdatabase.cpp +++ /dev/null @@ -1,507 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qwinrtfontdatabase_p.h" - -#include <QtFontDatabaseSupport/private/qfontengine_ft_p.h> - -#include <QtCore/QCoreApplication> -#include <QtCore/QFile> - -#include <QtCore/QUuid> -#include <dwrite_1.h> -#include <wrl.h> -using namespace Microsoft::WRL; - -QT_BEGIN_NAMESPACE - -Q_LOGGING_CATEGORY(lcQpaFonts, "qt.qpa.fonts") - -QDebug operator<<(QDebug d, const QFontDef &def) -{ - QDebugStateSaver saver(d); - d.nospace(); - d << "Family=" << def.family << " Stylename=" << def.styleName - << " pointsize=" << def.pointSize << " pixelsize=" << def.pixelSize - << " styleHint=" << def.styleHint << " weight=" << def.weight - << " stretch=" << def.stretch << " hintingPreference=" - << def.hintingPreference; - return d; -} - -// Based on unicode range tables at http://www.microsoft.com/typography/otspec/os2.htm#ur -static QFontDatabase::WritingSystem writingSystemFromUnicodeRange(const DWRITE_UNICODE_RANGE &range) -{ - if (range.first >= 0x0000 && range.last <= 0x007F) - return QFontDatabase::Latin; - if (range.first >= 0x0370 && range.last <= 0x03FF) - return QFontDatabase::Greek; - if (range.first >= 0x0400 && range.last <= 0x04FF) - return QFontDatabase::Cyrillic; - if (range.first >= 0x0530 && range.last <= 0x058F) - return QFontDatabase::Armenian; - if (range.first >= 0x0590 && range.last <= 0x05FF) - return QFontDatabase::Hebrew; - if (range.first >= 0x0600 && range.last <= 0x06FF) - return QFontDatabase::Arabic; - if (range.first >= 0x0700 && range.last <= 0x074F) - return QFontDatabase::Syriac; - if (range.first >= 0x0780 && range.last <= 0x07BF) - return QFontDatabase::Thaana; - if (range.first >= 0x0900 && range.last <= 0x097F) - return QFontDatabase::Devanagari; - if (range.first >= 0x0980 && range.last <= 0x09FF) - return QFontDatabase::Bengali; - if (range.first >= 0x0A00 && range.last <= 0x0A7F) - return QFontDatabase::Gurmukhi; - if (range.first >= 0x0A80 && range.last <= 0x0AFF) - return QFontDatabase::Gujarati; - if (range.first >= 0x0B00 && range.last <= 0x0B7F) - return QFontDatabase::Oriya; - if (range.first >= 0x0B80 && range.last <= 0x0BFF) - return QFontDatabase::Tamil; - if (range.first >= 0x0C00 && range.last <= 0x0C7F) - return QFontDatabase::Telugu; - if (range.first >= 0x0C80 && range.last <= 0x0CFF) - return QFontDatabase::Kannada; - if (range.first >= 0x0D00 && range.last <= 0x0D7F) - return QFontDatabase::Malayalam; - if (range.first >= 0x0D80 && range.last <= 0x0DFF) - return QFontDatabase::Sinhala; - if (range.first >= 0x0E00 && range.last <= 0x0E7F) - return QFontDatabase::Thai; - if (range.first >= 0x0E80 && range.last <= 0x0EFF) - return QFontDatabase::Lao; - if (range.first >= 0x0F00 && range.last <= 0x0FFF) - return QFontDatabase::Tibetan; - if (range.first >= 0x1000 && range.last <= 0x109F) - return QFontDatabase::Myanmar; - if (range.first >= 0x10A0 && range.last <= 0x10FF) - return QFontDatabase::Georgian; - if (range.first >= 0x1780 && range.last <= 0x17FF) - return QFontDatabase::Khmer; - if (range.first >= 0x4E00 && range.last <= 0x9FFF) - return QFontDatabase::SimplifiedChinese; - if (range.first >= 0xAC00 && range.last <= 0xD7AF) - return QFontDatabase::Korean; - if (range.first >= 0x1680 && range.last <= 0x169F) - return QFontDatabase::Ogham; - if (range.first >= 0x16A0 && range.last <= 0x16FF) - return QFontDatabase::Runic; - if (range.first >= 0x07C0 && range.last <= 0x07FF) - return QFontDatabase::Nko; - - return QFontDatabase::Other; -} - -QWinRTFontDatabase::~QWinRTFontDatabase() -{ - qCDebug(lcQpaFonts) << __FUNCTION__; - - foreach (IDWriteFontFile *fontFile, m_fonts.keys()) - fontFile->Release(); - - foreach (IDWriteFontFamily *fontFamily, m_fontFamilies) - fontFamily->Release(); -} - -QString QWinRTFontDatabase::fontDir() const -{ - qCDebug(lcQpaFonts) << __FUNCTION__; - QString fontDirectory = QFreeTypeFontDatabase::fontDir(); - if (!QFile::exists(fontDirectory)) { - // Fall back to app directory + fonts, and just app directory after that - const QString applicationDirPath = QCoreApplication::applicationDirPath(); - fontDirectory = applicationDirPath + QLatin1String("/fonts"); - if (!QFile::exists(fontDirectory)) { - if (m_fontFamilies.isEmpty()) - qWarning("No fonts directory found in application package."); - fontDirectory = applicationDirPath; - } - } - return fontDirectory; -} - -QFont QWinRTFontDatabase::defaultFont() const -{ - return QFont(QStringLiteral("Segoe UI")); -} - -bool QWinRTFontDatabase::fontsAlwaysScalable() const -{ - return true; -} - -void QWinRTFontDatabase::populateFontDatabase() -{ - qCDebug(lcQpaFonts) << __FUNCTION__; - - ComPtr<IDWriteFactory1> factory; - HRESULT hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_ISOLATED, __uuidof(IDWriteFactory1), &factory); - if (FAILED(hr)) { - qWarning("Failed to create DirectWrite factory: %s", qPrintable(qt_error_string(hr))); - QFreeTypeFontDatabase::populateFontDatabase(); - return; - } - - ComPtr<IDWriteFontCollection> fontCollection; - hr = factory->GetSystemFontCollection(&fontCollection); - if (FAILED(hr)) { - qWarning("Failed to open system font collection: %s", qPrintable(qt_error_string(hr))); - QFreeTypeFontDatabase::populateFontDatabase(); - return; - } - - int fontFamilyCount = fontCollection->GetFontFamilyCount(); - for (int i = 0; i < fontFamilyCount; ++i) { - ComPtr<IDWriteFontFamily> fontFamily; - hr = fontCollection->GetFontFamily(i, &fontFamily); - if (FAILED(hr)) { - qWarning("Unable to get font family: %s", qPrintable(qt_error_string(hr))); - continue; - } - - ComPtr<IDWriteLocalizedStrings> names; - hr = fontFamily->GetFamilyNames(&names); - if (FAILED(hr)) { - qWarning("Unable to get font family names: %s", qPrintable(qt_error_string(hr))); - continue; - } - quint32 familyNameLength; - hr = names->GetStringLength(0, &familyNameLength); - if (FAILED(hr)) { - qWarning("Unable to get family name length: %s", qPrintable(qt_error_string(hr))); - continue; - } - QVector<wchar_t> familyBuffer(familyNameLength + 1); - hr = names->GetString(0, familyBuffer.data(), familyBuffer.size()); - if (FAILED(hr)) { - qWarning("Unable to create font family name: %s", qPrintable(qt_error_string(hr))); - continue; - } - QString familyName = QString::fromWCharArray(familyBuffer.data(), familyNameLength); - - m_fontFamilies.insert(familyName, fontFamily.Detach()); - - registerFontFamily(familyName); - } - - QFreeTypeFontDatabase::populateFontDatabase(); -} - -void QWinRTFontDatabase::populateFamily(const QString &familyName) -{ - qCDebug(lcQpaFonts) << __FUNCTION__ << familyName; - - IDWriteFontFamily *fontFamily = m_fontFamilies.value(familyName); - if (!fontFamily) { - qWarning("The font family %s was not found.", qPrintable(familyName)); - return; - } - - bool fontRegistered = false; - const int fontCount = fontFamily->GetFontCount(); - for (int j = 0; j < fontCount; ++j) { - ComPtr<IDWriteFont> font; - HRESULT hr = fontFamily->GetFont(j, &font); - if (FAILED(hr)) { - qWarning("Unable to get font: %s", qPrintable(qt_error_string(hr))); - continue; - } - - // Skip simulated faces - if (font->GetSimulations() != DWRITE_FONT_SIMULATIONS_NONE) - continue; - - ComPtr<IDWriteFontFace> baseFontFace; - hr = font->CreateFontFace(&baseFontFace); - if (FAILED(hr)) { - qWarning("Unable to create base font face: %s", qPrintable(qt_error_string(hr))); - continue; - } - ComPtr<IDWriteFontFace1> fontFace; - hr = baseFontFace.As(&fontFace); - if (FAILED(hr)) { - qWarning("Unable to create font face: %s", qPrintable(qt_error_string(hr))); - continue; - } - - // We can't deal with multi-file fonts - quint32 fileCount; - hr = fontFace->GetFiles(&fileCount, NULL); - if (FAILED(hr)) { - qWarning("Unable to get font file count: %s", qPrintable(qt_error_string(hr))); - continue; - } - if (fileCount != 1) - continue; - - ComPtr<IDWriteLocalizedStrings> informationalStrings; - BOOL exists; - hr = font->GetInformationalStrings(DWRITE_INFORMATIONAL_STRING_MANUFACTURER, - &informationalStrings, &exists); - if (FAILED(hr)) { - qWarning("Unable to get font foundry: %s", qPrintable(qt_error_string(hr))); - continue; - } - QString foundryName; - if (exists) { - quint32 length; - hr = informationalStrings->GetStringLength(0, &length); - if (FAILED(hr)) - qWarning("Unable to get foundry name length: %s", qPrintable(qt_error_string(hr))); - if (SUCCEEDED(hr)) { - QVector<wchar_t> buffer(length + 1); - hr = informationalStrings->GetString(0, buffer.data(), buffer.size()); - if (FAILED(hr)) - qWarning("Unable to get foundry name: %s", qPrintable(qt_error_string(hr))); - if (SUCCEEDED(hr)) - foundryName = QString::fromWCharArray(buffer.data(), length); - } - } - - QFont::Weight weight = QPlatformFontDatabase::weightFromInteger(font->GetWeight()); - - QFont::Style style; - switch (font->GetStyle()) { - default: - case DWRITE_FONT_STYLE_NORMAL: - style = QFont::StyleNormal; - break; - case DWRITE_FONT_STYLE_OBLIQUE: - style = QFont::StyleOblique; - break; - case DWRITE_FONT_STYLE_ITALIC: - style = QFont::StyleItalic; - break; - } - - QFont::Stretch stretch; - switch (font->GetStretch()) { - default: - case DWRITE_FONT_STRETCH_UNDEFINED: - case DWRITE_FONT_STRETCH_NORMAL: - stretch = QFont::Unstretched; - break; - case DWRITE_FONT_STRETCH_ULTRA_CONDENSED: - stretch = QFont::UltraCondensed; - break; - case DWRITE_FONT_STRETCH_EXTRA_CONDENSED: - stretch = QFont::ExtraCondensed; - break; - case DWRITE_FONT_STRETCH_CONDENSED: - stretch = QFont::Condensed; - break; - case DWRITE_FONT_STRETCH_SEMI_CONDENSED: - stretch = QFont::SemiCondensed; - break; - case DWRITE_FONT_STRETCH_SEMI_EXPANDED: - stretch = QFont::SemiExpanded; - break; - case DWRITE_FONT_STRETCH_EXPANDED: - stretch = QFont::Expanded; - break; - case DWRITE_FONT_STRETCH_EXTRA_EXPANDED: - stretch = QFont::ExtraExpanded; - break; - case DWRITE_FONT_STRETCH_ULTRA_EXPANDED: - stretch = QFont::UltraExpanded; - break; - } - - const bool fixedPitch = fontFace->IsMonospacedFont(); - - // Get writing systems from unicode ranges - quint32 actualRangeCount; - hr = fontFace->GetUnicodeRanges(0, nullptr, &actualRangeCount); - Q_ASSERT(hr == E_NOT_SUFFICIENT_BUFFER); - QVector<DWRITE_UNICODE_RANGE> unicodeRanges(actualRangeCount); - hr = fontFace->GetUnicodeRanges(actualRangeCount, unicodeRanges.data(), &actualRangeCount); - if (FAILED(hr)) { - qWarning("Unable to get font unicode range: %s", qPrintable(qt_error_string(hr))); - continue; - } - QSupportedWritingSystems writingSystems; - for (quint32 i = 0; i < actualRangeCount; ++i) { - const QFontDatabase::WritingSystem writingSystem = writingSystemFromUnicodeRange(unicodeRanges.at(i)); - writingSystems.setSupported(writingSystem); - } - if (writingSystems.supported(QFontDatabase::SimplifiedChinese)) { - writingSystems.setSupported(QFontDatabase::TraditionalChinese); - writingSystems.setSupported(QFontDatabase::Japanese); - } - if (writingSystems.supported(QFontDatabase::Latin)) - writingSystems.setSupported(QFontDatabase::Vietnamese); - - IDWriteFontFile *fontFile; - hr = fontFace->GetFiles(&fileCount, &fontFile); - if (FAILED(hr)) { - qWarning("Unable to get font file: %s", qPrintable(qt_error_string(hr))); - continue; - } - - FontDescription description = { fontFace->GetIndex(), QUuid::createUuid().toByteArray() }; - m_fonts.insert(fontFile, description); - registerFont(familyName, QString(), foundryName, weight, style, stretch, - true, true, 0, fixedPitch, writingSystems, fontFile); - fontRegistered = true; - } - - // Always populate something to avoid an assert - if (!fontRegistered) { - registerFont(familyName, QString(), QString(), QFont::Normal, QFont::StyleNormal, - QFont::Unstretched, false, false, 0, false, QSupportedWritingSystems(), 0); - } -} - -QFontEngine *QWinRTFontDatabase::fontEngine(const QFontDef &fontDef, void *handle) -{ - qCDebug(lcQpaFonts) << __FUNCTION__ << "FONTDEF" << fontDef << handle; - - if (!handle) // Happens if a font family population failed - return 0; - - IDWriteFontFile *fontFile = reinterpret_cast<IDWriteFontFile *>(handle); - if (!m_fonts.contains(fontFile)) - return QFreeTypeFontDatabase::fontEngine(fontDef, handle); - - const void *referenceKey; - quint32 referenceKeySize; - HRESULT hr = fontFile->GetReferenceKey(&referenceKey, &referenceKeySize); - if (FAILED(hr)) { - qWarning("Unable to get font file reference key: %s", qPrintable(qt_error_string(hr))); - return 0; - } - - ComPtr<IDWriteFontFileLoader> loader; - hr = fontFile->GetLoader(&loader); - if (FAILED(hr)) { - qWarning("Unable to get font file loader: %s", qPrintable(qt_error_string(hr))); - return 0; - } - - ComPtr<IDWriteFontFileStream> stream; - hr =loader->CreateStreamFromKey(referenceKey, referenceKeySize, &stream); - if (FAILED(hr)) { - qWarning("Unable to get font file stream: %s", qPrintable(qt_error_string(hr))); - return 0; - } - - quint64 fileSize; - hr = stream->GetFileSize(&fileSize); - if (FAILED(hr)) { - qWarning("Unable to get font file size: %s", qPrintable(qt_error_string(hr))); - return 0; - } - - const void *data; - void *context; - hr = stream->ReadFileFragment(&data, 0, fileSize, &context); - if (FAILED(hr)) { - qWarning("Unable to get font file data: %s", qPrintable(qt_error_string(hr))); - return 0; - } - const QByteArray fontData((const char *)data, fileSize); - stream->ReleaseFileFragment(context); - - QFontEngine::FaceId faceId; - const FontDescription description = m_fonts.value(fontFile); - faceId.uuid = description.uuid; - faceId.index = description.index; - - return QFontEngineFT::create(fontDef, faceId, fontData); -} - -QString QWinRTFontDatabase::familyForStyleHint(QFont::StyleHint styleHint) -{ - switch (styleHint) { - case QFont::Times: - return QStringLiteral("Times New Roman"); - case QFont::Courier: - return QStringLiteral("Courier New"); - case QFont::Monospace: - return QStringLiteral("Courier New"); - case QFont::Cursive: - return QStringLiteral("Comic Sans MS"); - case QFont::Fantasy: - return QStringLiteral("Impact"); - case QFont::Decorative: - return QStringLiteral("Old English"); - case QFont::Helvetica: - return QStringLiteral("Segoe UI"); - case QFont::System: - default: - break; - } - return QStringLiteral("Segoe UI"); -} - -QStringList QWinRTFontDatabase::fallbacksForFamily(const QString &family, QFont::Style style, - QFont::StyleHint styleHint, - QChar::Script script) const -{ - Q_UNUSED(style) - Q_UNUSED(script) - - qCDebug(lcQpaFonts) << __FUNCTION__ << family; - - QStringList result; - result.append(QWinRTFontDatabase::familyForStyleHint(styleHint)); - result.append(QFreeTypeFontDatabase::fallbacksForFamily(family, style, styleHint, script)); - return result; -} - -void QWinRTFontDatabase::releaseHandle(void *handle) -{ - qCDebug(lcQpaFonts) << __FUNCTION__ << handle; - - if (!handle) - return; - - IDWriteFontFile *fontFile = reinterpret_cast<IDWriteFontFile *>(handle); - if (m_fonts.contains(fontFile)) { - m_fonts.remove(fontFile); - fontFile->Release(); - return; - } - - QFreeTypeFontDatabase::releaseHandle(handle); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/fontdatabases/winrt/qwinrtfontdatabase_p.h b/src/platformsupport/fontdatabases/winrt/qwinrtfontdatabase_p.h deleted file mode 100644 index c21f411fff..0000000000 --- a/src/platformsupport/fontdatabases/winrt/qwinrtfontdatabase_p.h +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QWINRTFONTDATABASE_H -#define QWINRTFONTDATABASE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtFontDatabaseSupport/private/qfreetypefontdatabase_p.h> -#include <QtCore/QLoggingCategory> - -struct IDWriteFontFile; -struct IDWriteFontFamily; - -QT_BEGIN_NAMESPACE - -Q_DECLARE_LOGGING_CATEGORY(lcQpaFonts) - -struct FontDescription -{ - quint32 index; - QByteArray uuid; -}; - -class QWinRTFontDatabase : public QFreeTypeFontDatabase -{ -public: - ~QWinRTFontDatabase(); - QString fontDir() const override; - QFont defaultFont() const override; - bool fontsAlwaysScalable() const override; - void populateFontDatabase() override; - void populateFamily(const QString &familyName) override; - QFontEngine *fontEngine(const QFontDef &fontDef, void *handle) override; - QStringList fallbacksForFamily(const QString &family, QFont::Style style, - QFont::StyleHint styleHint, QChar::Script script) const override; - void releaseHandle(void *handle) override; - - static QString familyForStyleHint(QFont::StyleHint styleHint); -private: - QHash<IDWriteFontFile *, FontDescription> m_fonts; - QHash<QString, IDWriteFontFamily *> m_fontFamilies; -}; - -QT_END_NAMESPACE - -#endif // QWINRTFONTDATABASE_H diff --git a/src/platformsupport/fontdatabases/winrt/winrt.pri b/src/platformsupport/fontdatabases/winrt/winrt.pri deleted file mode 100644 index 7617df2e7a..0000000000 --- a/src/platformsupport/fontdatabases/winrt/winrt.pri +++ /dev/null @@ -1,13 +0,0 @@ -QT *= gui-private - -SOURCES += \ - $$PWD/qwinrtfontdatabase.cpp - -HEADERS += \ - $$PWD/qwinrtfontdatabase_p.h - -DEFINES += __WRL_NO_DEFAULT_LIB__ - -LIBS += -lws2_32 - -QMAKE_USE_PRIVATE += dwrite_1 diff --git a/src/platformsupport/glxconvenience/glxconvenience.pro b/src/platformsupport/glxconvenience/glxconvenience.pro deleted file mode 100644 index 8367dc5e31..0000000000 --- a/src/platformsupport/glxconvenience/glxconvenience.pro +++ /dev/null @@ -1,14 +0,0 @@ -TARGET = QtGlxSupport -MODULE = glx_support - -QT = core-private gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII - -QMAKE_USE_PRIVATE += xlib - -HEADERS += qglxconvenience_p.h -SOURCES += qglxconvenience.cpp - -load(qt_module) diff --git a/src/platformsupport/glxconvenience/qglxconvenience.cpp b/src/platformsupport/glxconvenience/qglxconvenience.cpp deleted file mode 100644 index ef413ba98d..0000000000 --- a/src/platformsupport/glxconvenience/qglxconvenience.cpp +++ /dev/null @@ -1,458 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// We have to include this before the X11 headers dragged in by -// qglxconvenience_p.h. -#include <QtCore/QByteArray> -#include <QtCore/QScopedPointer> - -#include <QtCore/qmetatype.h> -#include <QtCore/qtextstream.h> -#include "qglxconvenience_p.h" - -#include <QtCore/QLoggingCategory> -#include <QtCore/QVector> -#include <QtCore/QVarLengthArray> - -#include <GL/glxext.h> - -Q_LOGGING_CATEGORY(lcGlx, "qt.glx") - -enum { - XFocusOut = FocusOut, - XFocusIn = FocusIn, - XKeyPress = KeyPress, - XKeyRelease = KeyRelease, - XNone = None, - XRevertToParent = RevertToParent, - XGrayScale = GrayScale, - XCursorShape = CursorShape -}; -#undef FocusOut -#undef FocusIn -#undef KeyPress -#undef KeyRelease -#undef None -#undef RevertToParent -#undef GrayScale -#undef CursorShape - -#ifdef FontChange -#undef FontChange -#endif - -#ifndef GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB -#define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20B2 -#endif - -QVector<int> qglx_buildSpec(const QSurfaceFormat &format, int drawableBit, int flags) -{ - QVector<int> spec; - - spec << GLX_LEVEL - << 0 - - << GLX_RENDER_TYPE - << GLX_RGBA_BIT - - << GLX_RED_SIZE - << qMax(1, format.redBufferSize()) - - << GLX_GREEN_SIZE - << qMax(1, format.greenBufferSize()) - - << GLX_BLUE_SIZE - << qMax(1, format.blueBufferSize()) - - << GLX_ALPHA_SIZE - << qMax(0, format.alphaBufferSize()); - - if (format.swapBehavior() != QSurfaceFormat::SingleBuffer) - spec << GLX_DOUBLEBUFFER - << True; - - if (format.stereo()) - spec << GLX_STEREO - << True; - - if (format.depthBufferSize() != -1) - spec << GLX_DEPTH_SIZE - << format.depthBufferSize(); - - if (format.stencilBufferSize() != -1) - spec << GLX_STENCIL_SIZE - << format.stencilBufferSize(); - - if (format.samples() > 1) - spec << GLX_SAMPLE_BUFFERS_ARB - << 1 - << GLX_SAMPLES_ARB - << format.samples(); - - if ((flags & QGLX_SUPPORTS_SRGB) && format.colorSpace() == QSurfaceFormat::sRGBColorSpace) - spec << GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB - << True; - - spec << GLX_DRAWABLE_TYPE - << drawableBit - - << XNone; - - return spec; -} - -namespace { -struct QXcbSoftwareOpenGLEnforcer { - QXcbSoftwareOpenGLEnforcer() { - // Allow forcing LIBGL_ALWAYS_SOFTWARE for Qt 5 applications only. - // This is most useful with drivers that only support OpenGL 1. - // We need OpenGL 2, but the user probably doesn't want - // LIBGL_ALWAYS_SOFTWARE in OpenGL 1 apps. - - if (!checkedForceSoftwareOpenGL) { - // If LIBGL_ALWAYS_SOFTWARE is already set, don't mess with it. - // We want to unset LIBGL_ALWAYS_SOFTWARE at the end so it does not - // get inherited by other processes, of course only if it wasn't - // already set before. - if (!qEnvironmentVariableIsEmpty("QT_XCB_FORCE_SOFTWARE_OPENGL") - && !qEnvironmentVariableIsSet("LIBGL_ALWAYS_SOFTWARE")) - forceSoftwareOpenGL = true; - - checkedForceSoftwareOpenGL = true; - } - - if (forceSoftwareOpenGL) - qputenv("LIBGL_ALWAYS_SOFTWARE", QByteArrayLiteral("1")); - } - - ~QXcbSoftwareOpenGLEnforcer() { - // unset LIBGL_ALWAYS_SOFTWARE now so other processes don't inherit it - if (forceSoftwareOpenGL) - qunsetenv("LIBGL_ALWAYS_SOFTWARE"); - } - - static bool checkedForceSoftwareOpenGL; - static bool forceSoftwareOpenGL; -}; - -bool QXcbSoftwareOpenGLEnforcer::checkedForceSoftwareOpenGL = false; -bool QXcbSoftwareOpenGLEnforcer::forceSoftwareOpenGL = false; - -template <class T> -struct QXlibScopedPointerDeleter { - static inline void cleanup(T *pointer) { - if (pointer) - XFree(pointer); - } -}; - -template <class T> -using QXlibPointer = QScopedPointer<T, QXlibScopedPointerDeleter<T>>; - -template <class T> -using QXlibArrayPointer = QScopedArrayPointer<T, QXlibScopedPointerDeleter<T>>; -} - -GLXFBConfig qglx_findConfig(Display *display, int screen , QSurfaceFormat format, bool highestPixelFormat, int drawableBit, int flags) -{ - QXcbSoftwareOpenGLEnforcer softwareOpenGLEnforcer; - - GLXFBConfig config = 0; - - do { - const QVector<int> spec = qglx_buildSpec(format, drawableBit, flags); - - int confcount = 0; - QXlibArrayPointer<GLXFBConfig> configs(glXChooseFBConfig(display, screen, spec.constData(), &confcount)); - - if (!config && confcount > 0) { - config = configs[0]; - if (highestPixelFormat && !format.hasAlpha()) - break; - } - - const int requestedRed = qMax(0, format.redBufferSize()); - const int requestedGreen = qMax(0, format.greenBufferSize()); - const int requestedBlue = qMax(0, format.blueBufferSize()); - const int requestedAlpha = qMax(0, format.alphaBufferSize()); - - GLXFBConfig compatibleCandidate = nullptr; - for (int i = 0; i < confcount; i++) { - GLXFBConfig candidate = configs[i]; - - if ((flags & QGLX_SUPPORTS_SRGB) && format.colorSpace() == QSurfaceFormat::sRGBColorSpace) { - int srgbCapable = 0; - glXGetFBConfigAttrib(display, candidate, GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB, &srgbCapable); - if (!srgbCapable) - continue; - } - - QXlibPointer<XVisualInfo> visual(glXGetVisualFromFBConfig(display, candidate)); - if (visual.isNull()) - continue; - - const int actualRed = qPopulationCount(visual->red_mask); - const int actualGreen = qPopulationCount(visual->green_mask); - const int actualBlue = qPopulationCount(visual->blue_mask); - const int actualAlpha = visual->depth - actualRed - actualGreen - actualBlue; - - if (requestedRed && actualRed < requestedRed) - continue; - if (requestedGreen && actualGreen < requestedGreen) - continue; - if (requestedBlue && actualBlue < requestedBlue) - continue; - if (requestedAlpha && actualAlpha < requestedAlpha) - continue; - if (!compatibleCandidate) // Only pick up the first compatible one offered by the server - compatibleCandidate = candidate; - - if (requestedRed && actualRed != requestedRed) - continue; - if (requestedGreen && actualGreen != requestedGreen) - continue; - if (requestedBlue && actualBlue != requestedBlue) - continue; - if (requestedAlpha && actualAlpha != requestedAlpha) - continue; - - return candidate; - } - if (compatibleCandidate) { - qCDebug(lcGlx) << "qglx_findConfig: Found non-matching but compatible FBConfig"; - return compatibleCandidate; - } - } while (qglx_reduceFormat(&format)); - - if (!config) - qCWarning(lcGlx) << "qglx_findConfig: Failed to finding matching FBConfig for" << format; - - return config; -} - -XVisualInfo *qglx_findVisualInfo(Display *display, int screen, QSurfaceFormat *format, int drawableBit, int flags) -{ - Q_ASSERT(format); - - XVisualInfo *visualInfo = 0; - - GLXFBConfig config = qglx_findConfig(display, screen, *format, false, drawableBit, flags); - if (config) - visualInfo = glXGetVisualFromFBConfig(display, config); - - if (visualInfo) { - qglx_surfaceFormatFromGLXFBConfig(format, display, config, flags); - return visualInfo; - } - - // attempt to fall back to glXChooseVisual - do { - QVector<int> attribs = qglx_buildSpec(*format, drawableBit, flags); - visualInfo = glXChooseVisual(display, screen, attribs.data()); - - if (visualInfo) { - qglx_surfaceFormatFromVisualInfo(format, display, visualInfo, flags); - return visualInfo; - } - } while (qglx_reduceFormat(format)); - - return visualInfo; -} - -void qglx_surfaceFormatFromGLXFBConfig(QSurfaceFormat *format, Display *display, GLXFBConfig config, int flags) -{ - int redSize = 0; - int greenSize = 0; - int blueSize = 0; - int alphaSize = 0; - int depthSize = 0; - int stencilSize = 0; - int sampleBuffers = 0; - int sampleCount = 0; - int stereo = 0; - int srgbCapable = 0; - - glXGetFBConfigAttrib(display, config, GLX_RED_SIZE, &redSize); - glXGetFBConfigAttrib(display, config, GLX_GREEN_SIZE, &greenSize); - glXGetFBConfigAttrib(display, config, GLX_BLUE_SIZE, &blueSize); - glXGetFBConfigAttrib(display, config, GLX_ALPHA_SIZE, &alphaSize); - glXGetFBConfigAttrib(display, config, GLX_DEPTH_SIZE, &depthSize); - glXGetFBConfigAttrib(display, config, GLX_STENCIL_SIZE, &stencilSize); - glXGetFBConfigAttrib(display, config, GLX_SAMPLES_ARB, &sampleBuffers); - glXGetFBConfigAttrib(display, config, GLX_STEREO, &stereo); - if (flags & QGLX_SUPPORTS_SRGB) - glXGetFBConfigAttrib(display, config, GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB, &srgbCapable); - - format->setRedBufferSize(redSize); - format->setGreenBufferSize(greenSize); - format->setBlueBufferSize(blueSize); - format->setAlphaBufferSize(alphaSize); - format->setDepthBufferSize(depthSize); - format->setStencilBufferSize(stencilSize); - if (sampleBuffers) { - glXGetFBConfigAttrib(display, config, GLX_SAMPLES_ARB, &sampleCount); - format->setSamples(sampleCount); - } - format->setColorSpace(srgbCapable ? QSurfaceFormat::sRGBColorSpace : QSurfaceFormat::DefaultColorSpace); - - format->setStereo(stereo); -} - -void qglx_surfaceFormatFromVisualInfo(QSurfaceFormat *format, Display *display, XVisualInfo *visualInfo, int flags) -{ - int redSize = 0; - int greenSize = 0; - int blueSize = 0; - int alphaSize = 0; - int depthSize = 0; - int stencilSize = 0; - int sampleBuffers = 0; - int sampleCount = 0; - int stereo = 0; - int srgbCapable = 0; - - glXGetConfig(display, visualInfo, GLX_RED_SIZE, &redSize); - glXGetConfig(display, visualInfo, GLX_GREEN_SIZE, &greenSize); - glXGetConfig(display, visualInfo, GLX_BLUE_SIZE, &blueSize); - glXGetConfig(display, visualInfo, GLX_ALPHA_SIZE, &alphaSize); - glXGetConfig(display, visualInfo, GLX_DEPTH_SIZE, &depthSize); - glXGetConfig(display, visualInfo, GLX_STENCIL_SIZE, &stencilSize); - glXGetConfig(display, visualInfo, GLX_SAMPLES_ARB, &sampleBuffers); - glXGetConfig(display, visualInfo, GLX_STEREO, &stereo); - if (flags & QGLX_SUPPORTS_SRGB) - glXGetConfig(display, visualInfo, GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB, &srgbCapable); - - format->setRedBufferSize(redSize); - format->setGreenBufferSize(greenSize); - format->setBlueBufferSize(blueSize); - format->setAlphaBufferSize(alphaSize); - format->setDepthBufferSize(depthSize); - format->setStencilBufferSize(stencilSize); - if (sampleBuffers) { - glXGetConfig(display, visualInfo, GLX_SAMPLES_ARB, &sampleCount); - format->setSamples(sampleCount); - } - format->setColorSpace(srgbCapable ? QSurfaceFormat::sRGBColorSpace : QSurfaceFormat::DefaultColorSpace); - - format->setStereo(stereo); -} - -bool qglx_reduceFormat(QSurfaceFormat *format) -{ - Q_ASSERT(format); - if (std::max(std::max(format->redBufferSize(), format->greenBufferSize()), format->blueBufferSize()) > 8) { - if (format->alphaBufferSize() > 2) { - // First try to match 10 10 10 2 - format->setAlphaBufferSize(2); - return true; - } - - format->setRedBufferSize(std::min(format->redBufferSize(), 8)); - format->setGreenBufferSize(std::min(format->greenBufferSize(), 8)); - format->setBlueBufferSize(std::min(format->blueBufferSize(), 8)); - return true; - } - - if (format->redBufferSize() > 1) { - format->setRedBufferSize(1); - return true; - } - - if (format->greenBufferSize() > 1) { - format->setGreenBufferSize(1); - return true; - } - - if (format->blueBufferSize() > 1) { - format->setBlueBufferSize(1); - return true; - } - - if (format->swapBehavior() != QSurfaceFormat::SingleBuffer){ - format->setSwapBehavior(QSurfaceFormat::SingleBuffer); - return true; - } - - if (format->samples() > 1) { - format->setSamples(qMin(16, format->samples() / 2)); - return true; - } - - if (format->depthBufferSize() >= 32) { - format->setDepthBufferSize(24); - return true; - } - - if (format->depthBufferSize() > 1) { - format->setDepthBufferSize(1); - return true; - } - - if (format->depthBufferSize() > 0) { - format->setDepthBufferSize(0); - return true; - } - - if (format->hasAlpha()) { - format->setAlphaBufferSize(0); - return true; - } - - if (format->stencilBufferSize() > 1) { - format->setStencilBufferSize(1); - return true; - } - - if (format->stencilBufferSize() > 0) { - format->setStencilBufferSize(0); - return true; - } - - if (format->stereo()) { - format->setStereo(false); - return true; - } - - if (format->colorSpace() == QSurfaceFormat::sRGBColorSpace) { - format->setColorSpace(QSurfaceFormat::DefaultColorSpace); - return true; - } - - return false; -} diff --git a/src/platformsupport/glxconvenience/qglxconvenience_p.h b/src/platformsupport/glxconvenience/qglxconvenience_p.h deleted file mode 100644 index f9647bfd9a..0000000000 --- a/src/platformsupport/glxconvenience/qglxconvenience_p.h +++ /dev/null @@ -1,72 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QGLXCONVENIENCE_H -#define QGLXCONVENIENCE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QSurfaceFormat> -#include <QVector> - -#include <X11/Xlib.h> -#include <GL/glx.h> - -enum QGlxFlags -{ - QGLX_SUPPORTS_SRGB = 0x01 -}; - -QVector<int> qglx_buildSpec(const QSurfaceFormat &format, int drawableBit = GLX_WINDOW_BIT, int flags = 0); -XVisualInfo *qglx_findVisualInfo(Display *display, int screen, QSurfaceFormat *format, int drawableBit = GLX_WINDOW_BIT, int flags = 0); -GLXFBConfig qglx_findConfig(Display *display, int screen, QSurfaceFormat format, bool highestPixelFormat = false, int drawableBit = GLX_WINDOW_BIT, int flags = 0); -void qglx_surfaceFormatFromGLXFBConfig(QSurfaceFormat *format, Display *display, GLXFBConfig config, int flags = 0); -void qglx_surfaceFormatFromVisualInfo(QSurfaceFormat *format, Display *display, XVisualInfo *visualInfo, int flags = 0); -bool qglx_reduceFormat(QSurfaceFormat *format); - -#endif // QGLXCONVENIENCE_H diff --git a/src/platformsupport/graphics/graphics.pro b/src/platformsupport/graphics/graphics.pro deleted file mode 100644 index 9886ee0332..0000000000 --- a/src/platformsupport/graphics/graphics.pro +++ /dev/null @@ -1,12 +0,0 @@ -TARGET = QtGraphicsSupport -MODULE = graphics_support - -QT = core-private gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII - -HEADERS += $$PWD/qrasterbackingstore_p.h -SOURCES += $$PWD/qrasterbackingstore.cpp - -load(qt_module) diff --git a/src/platformsupport/graphics/qrasterbackingstore.cpp b/src/platformsupport/graphics/qrasterbackingstore.cpp deleted file mode 100644 index a3ffe11d19..0000000000 --- a/src/platformsupport/graphics/qrasterbackingstore.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qrasterbackingstore_p.h" - -#include <QtGui/qbackingstore.h> -#include <QtGui/qpainter.h> - -#include <private/qhighdpiscaling_p.h> -#include <qpa/qplatformwindow.h> - -QT_BEGIN_NAMESPACE - -QRasterBackingStore::QRasterBackingStore(QWindow *window) - : QPlatformBackingStore(window) -{ -} - -QRasterBackingStore::~QRasterBackingStore() -{ -} - -void QRasterBackingStore::resize(const QSize &size, const QRegion &staticContents) -{ - Q_UNUSED(staticContents); - m_requestedSize = size; -} - -QImage::Format QRasterBackingStore::format() const -{ - if (window()->format().hasAlpha()) - return QImage::Format_ARGB32_Premultiplied; - else - return QImage::Format_RGB32; -} - -QPaintDevice *QRasterBackingStore::paintDevice() -{ - return &m_image; -} - -QImage QRasterBackingStore::toImage() const -{ - return m_image; -} - -bool QRasterBackingStore::scroll(const QRegion ®ion, int dx, int dy) -{ - if (window()->surfaceType() != QSurface::RasterSurface) - return false; - - extern void qt_scrollRectInImage(QImage &, const QRect &, const QPoint &); - - const qreal devicePixelRatio = m_image.devicePixelRatio(); - const QPoint delta(dx * devicePixelRatio, dy * devicePixelRatio); - - for (const QRect &rect : region) - qt_scrollRectInImage(m_image, QRect(rect.topLeft() * devicePixelRatio, rect.size() * devicePixelRatio), delta); - - return true; -} - -void QRasterBackingStore::beginPaint(const QRegion ®ion) -{ - qreal nativeWindowDevicePixelRatio = window()->handle()->devicePixelRatio(); - QSize effectiveBufferSize = m_requestedSize * nativeWindowDevicePixelRatio; - if (m_image.devicePixelRatio() != nativeWindowDevicePixelRatio || m_image.size() != effectiveBufferSize) { - m_image = QImage(effectiveBufferSize, format()); - m_image.setDevicePixelRatio(nativeWindowDevicePixelRatio); - if (m_image.format() == QImage::Format_ARGB32_Premultiplied) - m_image.fill(Qt::transparent); - } - - if (!m_image.hasAlphaChannel()) - return; - - QPainter painter(&m_image); - painter.setCompositionMode(QPainter::CompositionMode_Source); - for (const QRect &rect : region) - painter.fillRect(rect, Qt::transparent); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/graphics/qrasterbackingstore_p.h b/src/platformsupport/graphics/qrasterbackingstore_p.h deleted file mode 100644 index 357e861d1d..0000000000 --- a/src/platformsupport/graphics/qrasterbackingstore_p.h +++ /dev/null @@ -1,81 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QRASTERBACKINGSTORE_P_H -#define QRASTERBACKINGSTORE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <qpa/qplatformbackingstore.h> - - -QT_BEGIN_NAMESPACE - -class QRasterBackingStore : public QPlatformBackingStore -{ -public: - QRasterBackingStore(QWindow *window); - ~QRasterBackingStore(); - - void resize(const QSize &size, const QRegion &staticContents) override; - bool scroll(const QRegion &area, int dx, int dy) override; - void beginPaint(const QRegion ®ion) override; - - QPaintDevice *paintDevice() override; - QImage toImage() const override; - -protected: - virtual QImage::Format format() const; - - QImage m_image; - QSize m_requestedSize; -}; - -QT_END_NAMESPACE - -#endif // QRASTERBACKINGSTORE_P_H diff --git a/src/platformsupport/input/CMakeLists.txt b/src/platformsupport/input/CMakeLists.txt new file mode 100644 index 0000000000..b7ff09d827 --- /dev/null +++ b/src/platformsupport/input/CMakeLists.txt @@ -0,0 +1,103 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: BSD-3-Clause + +qt_find_package(Libinput) +qt_find_package(XKB) +qt_find_package(Tslib) +qt_find_package(Mtdev) + +##################################################################### +## InputSupportPrivate Module: +##################################################################### + +qt_internal_add_module(InputSupportPrivate + CONFIG_MODULE_NAME input_support + STATIC + INTERNAL_MODULE + DEFINES + QT_NO_CAST_FROM_ASCII + PUBLIC_LIBRARIES + Qt::CorePrivate + Qt::DeviceDiscoverySupportPrivate + Qt::GuiPrivate + PRECOMPILED_HEADER + "../../corelib/global/qt_pch.h" + NO_GENERATE_CPP_EXPORTS +) + +## Scopes: +##################################################################### + +qt_internal_extend_target(InputSupportPrivate CONDITION QT_FEATURE_evdev + SOURCES + evdevkeyboard/qevdevkeyboard_defaultmap_p.h + evdevkeyboard/qevdevkeyboardhandler.cpp evdevkeyboard/qevdevkeyboardhandler_p.h + evdevkeyboard/qevdevkeyboardmanager.cpp evdevkeyboard/qevdevkeyboardmanager_p.h + evdevmouse/qevdevmousehandler.cpp evdevmouse/qevdevmousehandler_p.h + evdevmouse/qevdevmousemanager.cpp evdevmouse/qevdevmousemanager_p.h + evdevtouch/qevdevtouchhandler.cpp evdevtouch/qevdevtouchhandler_p.h + evdevtouch/qevdevtouchfilter_p.h + evdevtouch/qevdevtouchmanager.cpp evdevtouch/qevdevtouchmanager_p.h + INCLUDE_DIRECTORIES + evdevtouch/../shared +) + +qt_internal_extend_target(InputSupportPrivate CONDITION QT_FEATURE_evdev AND QT_FEATURE_tabletevent + SOURCES + evdevtablet/qevdevtablethandler.cpp evdevtablet/qevdevtablethandler_p.h + evdevtablet/qevdevtabletmanager.cpp evdevtablet/qevdevtabletmanager_p.h +) + +qt_internal_extend_target(InputSupportPrivate CONDITION QT_FEATURE_evdev AND QT_FEATURE_libudev AND QT_FEATURE_tabletevent + LIBRARIES + PkgConfig::Libudev +) + +qt_internal_extend_target(InputSupportPrivate CONDITION QT_FEATURE_evdev AND QT_FEATURE_libudev + LIBRARIES + PkgConfig::Libudev +) + +qt_internal_extend_target(InputSupportPrivate CONDITION QT_FEATURE_evdev AND QT_FEATURE_mtdev + LIBRARIES + PkgConfig::Mtdev +) + +qt_internal_extend_target(InputSupportPrivate CONDITION QT_FEATURE_tslib + SOURCES + tslib/qtslib.cpp tslib/qtslib_p.h + PUBLIC_LIBRARIES + PkgConfig::Tslib +) + +qt_internal_extend_target(InputSupportPrivate CONDITION QT_FEATURE_libinput + SOURCES + libinput/qlibinputhandler.cpp libinput/qlibinputhandler_p.h + libinput/qlibinputkeyboard.cpp libinput/qlibinputkeyboard_p.h + libinput/qlibinputpointer.cpp libinput/qlibinputpointer_p.h + libinput/qlibinputtouch.cpp libinput/qlibinputtouch_p.h + INCLUDE_DIRECTORIES + libinput/../shared + LIBRARIES + Libinput::Libinput + PkgConfig::Libudev +) + +qt_internal_extend_target(InputSupportPrivate CONDITION QT_FEATURE_libinput AND QT_FEATURE_xkbcommon + LIBRARIES + XKB::XKB +) + +qt_internal_extend_target(InputSupportPrivate CONDITION QT_FEATURE_evdev OR QT_FEATURE_libinput + SOURCES + shared/devicehandlerlist_p.h + shared/qevdevutil.cpp shared/qevdevutil_p.h + shared/qoutputmapping.cpp shared/qoutputmapping_p.h +) + +qt_internal_extend_target(InputSupportPrivate CONDITION QT_FEATURE_integrityhid + SOURCES + integrityhid/qintegrityhidmanager.cpp integrityhid/qintegrityhidmanager.h + LIBRARIES + integrityhid +) diff --git a/src/platformsupport/input/evdevkeyboard/evdevkeyboard.pri b/src/platformsupport/input/evdevkeyboard/evdevkeyboard.pri deleted file mode 100644 index 445f230fa5..0000000000 --- a/src/platformsupport/input/evdevkeyboard/evdevkeyboard.pri +++ /dev/null @@ -1,11 +0,0 @@ -HEADERS += \ - $$PWD/qevdevkeyboard_defaultmap_p.h \ - $$PWD/qevdevkeyboardhandler_p.h \ - $$PWD/qevdevkeyboardmanager_p.h - -SOURCES += \ - $$PWD/qevdevkeyboardhandler.cpp \ - $$PWD/qevdevkeyboardmanager.cpp - -qtConfig(libudev): \ - QMAKE_USE_PRIVATE += libudev diff --git a/src/platformsupport/input/evdevkeyboard/qevdevkeyboard_defaultmap_p.h b/src/platformsupport/input/evdevkeyboard/qevdevkeyboard_defaultmap_p.h index 17bf0fb797..02ed8463e3 100644 --- a/src/platformsupport/input/evdevkeyboard/qevdevkeyboard_defaultmap_p.h +++ b/src/platformsupport/input/evdevkeyboard/qevdevkeyboard_defaultmap_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QEVDEVKEYBOARDHANDLER_DEFAULTMAP_P_H #define QEVDEVKEYBOARDHANDLER_DEFAULTMAP_P_H @@ -52,6 +16,7 @@ // #include "qnamespace.h" +#include "private/qglobal_p.h" #ifdef Q_OS_FREEBSD #include <dev/evdev/input.h> #else diff --git a/src/platformsupport/input/evdevkeyboard/qevdevkeyboardhandler.cpp b/src/platformsupport/input/evdevkeyboard/qevdevkeyboardhandler.cpp index ad134a825f..48fba79958 100644 --- a/src/platformsupport/input/evdevkeyboard/qevdevkeyboardhandler.cpp +++ b/src/platformsupport/input/evdevkeyboard/qevdevkeyboardhandler.cpp @@ -1,43 +1,8 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qevdevkeyboardhandler_p.h" +#include "qoutputmapping_p.h" #include <qplatformdefs.h> @@ -58,15 +23,25 @@ #include <linux/input.h> #endif +#ifndef input_event_sec +#define input_event_sec time.tv_sec +#endif + +#ifndef input_event_usec +#define input_event_usec time.tv_usec +#endif + QT_BEGIN_NAMESPACE +using namespace Qt::StringLiterals; + Q_LOGGING_CATEGORY(qLcEvdevKey, "qt.qpa.input") Q_LOGGING_CATEGORY(qLcEvdevKeyMap, "qt.qpa.input.keymap") // simple builtin US keymap #include "qevdevkeyboard_defaultmap_p.h" -void QFdContainer::reset() Q_DECL_NOTHROW +void QFdContainer::reset() noexcept { if (m_fd >= 0) qt_safe_close(m_fd); @@ -81,7 +56,7 @@ QEvdevKeyboardHandler::QEvdevKeyboardHandler(const QString &device, QFdContainer { qCDebug(qLcEvdevKey) << "Create keyboard handler with for device" << device; - setObjectName(QLatin1String("LinuxInput Keyboard Handler")); + setObjectName("LinuxInput Keyboard Handler"_L1); memset(m_locks, 0, sizeof(m_locks)); @@ -98,11 +73,12 @@ QEvdevKeyboardHandler::~QEvdevKeyboardHandler() unloadKeymap(); } -QEvdevKeyboardHandler *QEvdevKeyboardHandler::create(const QString &device, +std::unique_ptr<QEvdevKeyboardHandler> QEvdevKeyboardHandler::create(const QString &device, const QString &specification, const QString &defaultKeymapFile) { - qCDebug(qLcEvdevKey) << "Try to create keyboard handler for" << device << specification; + qCDebug(qLcEvdevKey, "Try to create keyboard handler for \"%ls\" \"%ls\"", + qUtf16Printable(device), qUtf16Printable(specification)); QString keymapFile = defaultKeymapFile; int repeatDelay = 400; @@ -111,25 +87,29 @@ QEvdevKeyboardHandler *QEvdevKeyboardHandler::create(const QString &device, bool enableCompose = false; int grab = 0; - const auto args = specification.splitRef(QLatin1Char(':')); - for (const QStringRef &arg : args) { - if (arg.startsWith(QLatin1String("keymap="))) + const auto args = QStringView{specification}.split(u':'); + for (const auto &arg : args) { + if (arg.startsWith("keymap="_L1)) keymapFile = arg.mid(7).toString(); - else if (arg == QLatin1String("disable-zap")) + else if (arg == "disable-zap"_L1) disableZap = true; - else if (arg == QLatin1String("enable-compose")) + else if (arg == "enable-compose"_L1) enableCompose = true; - else if (arg.startsWith(QLatin1String("repeat-delay="))) + else if (arg.startsWith("repeat-delay="_L1)) repeatDelay = arg.mid(13).toInt(); - else if (arg.startsWith(QLatin1String("repeat-rate="))) + else if (arg.startsWith("repeat-rate="_L1)) repeatRate = arg.mid(12).toInt(); - else if (arg.startsWith(QLatin1String("grab="))) + else if (arg.startsWith("grab="_L1)) grab = arg.mid(5).toInt(); } - qCDebug(qLcEvdevKey) << "Opening keyboard at" << device; + qCDebug(qLcEvdevKey, "Opening keyboard at %ls", qUtf16Printable(device)); - QFdContainer fd(qt_safe_open(device.toLocal8Bit().constData(), O_RDONLY | O_NDELAY, 0)); + QFdContainer fd(qt_safe_open(device.toLocal8Bit().constData(), O_RDWR | O_NDELAY, 0)); + if (fd.get() < 0) { + qCDebug(qLcEvdevKey, "Keyboard device could not be opened as read-write, trying read-only"); + fd.reset(qt_safe_open(device.toLocal8Bit().constData(), O_RDONLY | O_NDELAY, 0)); + } if (fd.get() >= 0) { ::ioctl(fd.get(), EVIOCGRAB, grab); if (repeatDelay > 0 && repeatRate > 0) { @@ -137,19 +117,22 @@ QEvdevKeyboardHandler *QEvdevKeyboardHandler::create(const QString &device, ::ioctl(fd.get(), EVIOCSREP, kbdrep); } - return new QEvdevKeyboardHandler(device, fd, disableZap, enableCompose, keymapFile); + return std::unique_ptr<QEvdevKeyboardHandler>(new QEvdevKeyboardHandler(device, fd, disableZap, enableCompose, keymapFile)); } else { - qWarning("Cannot open keyboard input device '%s': %s", qPrintable(device), strerror(errno)); - return 0; + qErrnoWarning("Cannot open keyboard input device '%ls'", qUtf16Printable(device)); + return nullptr; } } void QEvdevKeyboardHandler::switchLed(int led, bool state) { - qCDebug(qLcEvdevKey) << "switchLed" << led << state; + qCDebug(qLcEvdevKey, "switchLed %d %d", led, int(state)); + struct timeval tv; + ::gettimeofday(&tv, 0); struct ::input_event led_ie; - ::gettimeofday(&led_ie.time, 0); + led_ie.input_event_sec = tv.tv_sec; + led_ie.input_event_usec = tv.tv_usec; led_ie.type = EV_LED; led_ie.code = led; led_ie.value = state; @@ -170,7 +153,7 @@ void QEvdevKeyboardHandler::readKeycode() return; } else if (result < 0) { if (errno != EINTR && errno != EAGAIN) { - qErrnoWarning(errno, "evdevkeyboard: Could not read from input device"); + qErrnoWarning("evdevkeyboard: Could not read from input device"); // If the device got disconnected, stop reading, otherwise we get flooded // by the above error over and over again. if (errno == ENODEV) { @@ -228,9 +211,13 @@ void QEvdevKeyboardHandler::processKeyEvent(int nativecode, int unicode, int qtc if (!autoRepeat) QGuiApplicationPrivate::inputDeviceManager()->setKeyboardModifiers(QEvdevKeyboardHandler::toQtModifiers(m_modifiers)); - QWindowSystemInterface::handleExtendedKeyEvent(0, (isPress ? QEvent::KeyPress : QEvent::KeyRelease), + QWindow *window = nullptr; +#ifdef Q_OS_WEBOS + window = QOutputMapping::get()->windowForDeviceNode(m_device); +#endif + QWindowSystemInterface::handleExtendedKeyEvent(window, (isPress ? QEvent::KeyPress : QEvent::KeyRelease), qtcode, modifiers, nativecode + 8, 0, int(modifiers), - (unicode != 0xffff ) ? QString(unicode) : QString(), autoRepeat); + (unicode != 0xffff ) ? QString(QChar(unicode)) : QString(), autoRepeat); } QEvdevKeyboardHandler::KeycodeAction QEvdevKeyboardHandler::processKeycode(quint16 keycode, bool pressed, bool autorepeat) @@ -238,8 +225,8 @@ QEvdevKeyboardHandler::KeycodeAction QEvdevKeyboardHandler::processKeycode(quint KeycodeAction result = None; bool first_press = pressed && !autorepeat; - const QEvdevKeyboardMap::Mapping *map_plain = 0; - const QEvdevKeyboardMap::Mapping *map_withmod = 0; + const QEvdevKeyboardMap::Mapping *map_plain = nullptr; + const QEvdevKeyboardMap::Mapping *map_withmod = nullptr; quint8 modifiers = m_modifiers; @@ -473,7 +460,7 @@ QEvdevKeyboardHandler::KeycodeAction QEvdevKeyboardHandler::processKeycode(quint void QEvdevKeyboardHandler::unloadKeymap() { - qCDebug(qLcEvdevKey) << "Unload current keymap and restore built-in"; + qCDebug(qLcEvdevKey, "Unload current keymap and restore built-in"); if (m_keymap && m_keymap != s_keymap_default) delete [] m_keymap; @@ -517,12 +504,12 @@ void QEvdevKeyboardHandler::unloadKeymap() bool QEvdevKeyboardHandler::loadKeymap(const QString &file) { - qCDebug(qLcEvdevKey) << "Loading keymap" << file; + qCDebug(qLcEvdevKey, "Loading keymap %ls", qUtf16Printable(file)); QFile f(file); if (!f.open(QIODevice::ReadOnly)) { - qWarning("Could not open keymap file '%s'", qPrintable(file)); + qWarning("Could not open keymap file '%ls'", qUtf16Printable(file)); return false; } @@ -541,7 +528,7 @@ bool QEvdevKeyboardHandler::loadKeymap(const QString &file) ds >> qmap_magic >> qmap_version >> qmap_keymap_size >> qmap_keycompose_size; if (ds.status() != QDataStream::Ok || qmap_magic != QEvdevKeyboardMap::FileMagic || qmap_version != 1 || qmap_keymap_size == 0) { - qWarning("'%s' is not a valid .qmap keymap file", qPrintable(file)); + qWarning("'%ls' is not a valid .qmap keymap file", qUtf16Printable(file)); return false; } @@ -557,7 +544,7 @@ bool QEvdevKeyboardHandler::loadKeymap(const QString &file) delete [] qmap_keymap; delete [] qmap_keycompose; - qWarning("Keymap file '%s' can not be loaded.", qPrintable(file)); + qWarning("Keymap file '%ls' cannot be loaded.", qUtf16Printable(file)); return false; } diff --git a/src/platformsupport/input/evdevkeyboard/qevdevkeyboardhandler_p.h b/src/platformsupport/input/evdevkeyboard/qevdevkeyboardhandler_p.h index 5498a3e4f0..1d991e2ba5 100644 --- a/src/platformsupport/input/evdevkeyboard/qevdevkeyboardhandler_p.h +++ b/src/platformsupport/input/evdevkeyboard/qevdevkeyboardhandler_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2021 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QEVDEVKEYBOARDHANDLER_P_H #define QEVDEVKEYBOARDHANDLER_P_H @@ -54,6 +18,9 @@ #include <qobject.h> #include <QTimer> #include <QDataStream> +#include <private/qglobal_p.h> + +#include <memory> QT_BEGIN_NAMESPACE @@ -132,15 +99,16 @@ inline QDataStream &operator<<(QDataStream &ds, const QEvdevKeyboardMap::Composi class QFdContainer { int m_fd; - Q_DISABLE_COPY(QFdContainer); + Q_DISABLE_COPY_MOVE(QFdContainer); public: - explicit QFdContainer(int fd = -1) Q_DECL_NOTHROW : m_fd(fd) {} + Q_NODISCARD_CTOR explicit QFdContainer(int fd = -1) noexcept : m_fd(fd) {} ~QFdContainer() { reset(); } - int get() const Q_DECL_NOTHROW { return m_fd; } + int get() const noexcept { return m_fd; } - int release() Q_DECL_NOTHROW { int result = m_fd; m_fd = -1; return result; } - void reset() Q_DECL_NOTHROW; + int release() noexcept { int result = m_fd; m_fd = -1; return result; } + void reset() noexcept; + void reset(int fd) { reset(); m_fd = fd; } }; class QEvdevKeyboardHandler : public QObject @@ -168,7 +136,7 @@ public: SwitchConsoleMask = 0x0000007f }; - static QEvdevKeyboardHandler *create(const QString &device, + static std::unique_ptr<QEvdevKeyboardHandler> create(const QString &device, const QString &specification, const QString &defaultKeymapFile = QString()); diff --git a/src/platformsupport/input/evdevkeyboard/qevdevkeyboardmanager.cpp b/src/platformsupport/input/evdevkeyboard/qevdevkeyboardmanager.cpp index e1659bc0d9..43717c4e81 100644 --- a/src/platformsupport/input/evdevkeyboard/qevdevkeyboardmanager.cpp +++ b/src/platformsupport/input/evdevkeyboard/qevdevkeyboardmanager.cpp @@ -1,44 +1,10 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qevdevkeyboardmanager_p.h" +#include <QtInputSupport/private/qevdevutil_p.h> + #include <QStringList> #include <QCoreApplication> #include <QLoggingCategory> @@ -48,6 +14,8 @@ QT_BEGIN_NAMESPACE +using namespace Qt::StringLiterals; + Q_DECLARE_LOGGING_CATEGORY(qLcEvdevKey) QEvdevKeyboardManager::QEvdevKeyboardManager(const QString &key, const QString &specification, QObject *parent) @@ -61,36 +29,24 @@ QEvdevKeyboardManager::QEvdevKeyboardManager(const QString &key, const QString & if (spec.isEmpty()) spec = specification; - QStringList args = spec.split(QLatin1Char(':')); - QStringList devices; - - foreach (const QString &arg, args) { - if (arg.startsWith(QLatin1String("/dev/"))) { - // if device is specified try to use it - devices.append(arg); - args.removeAll(arg); - } - } - - // build new specification without /dev/ elements - m_spec = args.join(QLatin1Char(':')); + auto parsed = QEvdevUtil::parseSpecification(spec); + m_spec = std::move(parsed.spec); // add all keyboards for devices specified in the argument list - foreach (const QString &device, devices) + for (const QString &device : std::as_const(parsed.devices)) addKeyboard(device); - if (devices.isEmpty()) { - qCDebug(qLcEvdevKey) << "evdevkeyboard: Using device discovery"; - m_deviceDiscovery = QDeviceDiscovery::create(QDeviceDiscovery::Device_Keyboard, this); - if (m_deviceDiscovery) { + if (parsed.devices.isEmpty()) { + qCDebug(qLcEvdevKey, "evdevkeyboard: Using device discovery"); + if (auto deviceDiscovery = QDeviceDiscovery::create(QDeviceDiscovery::Device_Keyboard, this)) { // scan and add already connected keyboards - const QStringList devices = m_deviceDiscovery->scanConnectedDevices(); + const QStringList devices = deviceDiscovery->scanConnectedDevices(); for (const QString &device : devices) addKeyboard(device); - connect(m_deviceDiscovery, &QDeviceDiscovery::deviceDetected, + connect(deviceDiscovery, &QDeviceDiscovery::deviceDetected, this, &QEvdevKeyboardManager::addKeyboard); - connect(m_deviceDiscovery, &QDeviceDiscovery::deviceRemoved, + connect(deviceDiscovery, &QDeviceDiscovery::deviceRemoved, this, &QEvdevKeyboardManager::removeKeyboard); } } @@ -98,36 +54,34 @@ QEvdevKeyboardManager::QEvdevKeyboardManager(const QString &key, const QString & QEvdevKeyboardManager::~QEvdevKeyboardManager() { - qDeleteAll(m_keyboards); - m_keyboards.clear(); } void QEvdevKeyboardManager::addKeyboard(const QString &deviceNode) { - qCDebug(qLcEvdevKey) << "Adding keyboard at" << deviceNode; - QEvdevKeyboardHandler *keyboard; - keyboard = QEvdevKeyboardHandler::create(deviceNode, m_spec, m_defaultKeymapFile); + qCDebug(qLcEvdevKey, "Adding keyboard at %ls", qUtf16Printable(deviceNode)); + auto keyboard = QEvdevKeyboardHandler::create(deviceNode, m_spec, m_defaultKeymapFile); if (keyboard) { - m_keyboards.insert(deviceNode, keyboard); - QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount( - QInputDeviceManager::DeviceTypeKeyboard, m_keyboards.count()); + m_keyboards.add(deviceNode, std::move(keyboard)); + updateDeviceCount(); } else { - qWarning("Failed to open keyboard device %s", qPrintable(deviceNode)); + qWarning("Failed to open keyboard device %ls", qUtf16Printable(deviceNode)); } } void QEvdevKeyboardManager::removeKeyboard(const QString &deviceNode) { - if (m_keyboards.contains(deviceNode)) { - qCDebug(qLcEvdevKey) << "Removing keyboard at" << deviceNode; - QEvdevKeyboardHandler *keyboard = m_keyboards.value(deviceNode); - m_keyboards.remove(deviceNode); - QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount( - QInputDeviceManager::DeviceTypeKeyboard, m_keyboards.count()); - delete keyboard; + if (m_keyboards.remove(deviceNode)) { + qCDebug(qLcEvdevKey, "Removing keyboard at %ls", qUtf16Printable(deviceNode)); + updateDeviceCount(); } } +void QEvdevKeyboardManager::updateDeviceCount() +{ + QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount( + QInputDeviceManager::DeviceTypeKeyboard, m_keyboards.count()); +} + void QEvdevKeyboardManager::loadKeymap(const QString &file) { m_defaultKeymapFile = file; @@ -136,27 +90,27 @@ void QEvdevKeyboardManager::loadKeymap(const QString &file) // Restore the default, which is either the built-in keymap or // the one given in the plugin spec. QString keymapFromSpec; - const auto specs = m_spec.splitRef(QLatin1Char(':')); - for (const QStringRef &arg : specs) { - if (arg.startsWith(QLatin1String("keymap="))) + const auto specs = QStringView{m_spec}.split(u':'); + for (const auto &arg : specs) { + if (arg.startsWith("keymap="_L1)) keymapFromSpec = arg.mid(7).toString(); } - foreach (QEvdevKeyboardHandler *handler, m_keyboards) { + for (const auto &keyboard : m_keyboards) { if (keymapFromSpec.isEmpty()) - handler->unloadKeymap(); + keyboard.handler->unloadKeymap(); else - handler->loadKeymap(keymapFromSpec); + keyboard.handler->loadKeymap(keymapFromSpec); } } else { - foreach (QEvdevKeyboardHandler *handler, m_keyboards) - handler->loadKeymap(file); + for (const auto &keyboard : m_keyboards) + keyboard.handler->loadKeymap(file); } } void QEvdevKeyboardManager::switchLang() { - foreach (QEvdevKeyboardHandler *handler, m_keyboards) - handler->switchLang(); + for (const auto &keyboard : m_keyboards) + keyboard.handler->switchLang(); } QT_END_NAMESPACE diff --git a/src/platformsupport/input/evdevkeyboard/qevdevkeyboardmanager_p.h b/src/platformsupport/input/evdevkeyboard/qevdevkeyboardmanager_p.h index 326e438a7c..d3f75f8367 100644 --- a/src/platformsupport/input/evdevkeyboard/qevdevkeyboardmanager_p.h +++ b/src/platformsupport/input/evdevkeyboard/qevdevkeyboardmanager_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QEVDEVKEYBOARDMANAGER_P_H #define QEVDEVKEYBOARDMANAGER_P_H @@ -53,6 +17,7 @@ #include "qevdevkeyboardhandler_p.h" +#include <QtInputSupport/private/devicehandlerlist_p.h> #include <QtDeviceDiscoverySupport/private/qdevicediscovery_p.h> #include <QObject> @@ -64,7 +29,7 @@ QT_BEGIN_NAMESPACE class QEvdevKeyboardManager : public QObject { public: - QEvdevKeyboardManager(const QString &key, const QString &specification, QObject *parent = 0); + QEvdevKeyboardManager(const QString &key, const QString &specification, QObject *parent = nullptr); ~QEvdevKeyboardManager(); void loadKeymap(const QString &file); @@ -74,9 +39,10 @@ public: void removeKeyboard(const QString &deviceNode); private: + void updateDeviceCount(); + QString m_spec; - QHash<QString,QEvdevKeyboardHandler*> m_keyboards; - QDeviceDiscovery *m_deviceDiscovery; + QtInputSupport::DeviceHandlerList<QEvdevKeyboardHandler> m_keyboards; QString m_defaultKeymapFile; }; diff --git a/src/platformsupport/input/evdevmouse/evdevmouse.pri b/src/platformsupport/input/evdevmouse/evdevmouse.pri deleted file mode 100644 index a8c9c663f3..0000000000 --- a/src/platformsupport/input/evdevmouse/evdevmouse.pri +++ /dev/null @@ -1,11 +0,0 @@ -HEADERS += \ - $$PWD/qevdevmousehandler_p.h \ - $$PWD/qevdevmousemanager_p.h - -SOURCES += \ - $$PWD/qevdevmousehandler.cpp \ - $$PWD/qevdevmousemanager.cpp - -qtConfig(libudev): \ - QMAKE_USE_PRIVATE += libudev - diff --git a/src/platformsupport/input/evdevmouse/qevdevmousehandler.cpp b/src/platformsupport/input/evdevmouse/qevdevmousehandler.cpp index 86a4cd0076..8d98cb1e8c 100644 --- a/src/platformsupport/input/evdevmouse/qevdevmousehandler.cpp +++ b/src/platformsupport/input/evdevmouse/qevdevmousehandler.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qevdevmousehandler_p.h" @@ -64,9 +28,11 @@ QT_BEGIN_NAMESPACE +using namespace Qt::StringLiterals; + Q_LOGGING_CATEGORY(qLcEvdevMouse, "qt.qpa.input") -QEvdevMouseHandler *QEvdevMouseHandler::create(const QString &device, const QString &specification) +std::unique_ptr<QEvdevMouseHandler> QEvdevMouseHandler::create(const QString &device, const QString &specification) { qCDebug(qLcEvdevMouse) << "create mouse handler for" << device << specification; @@ -75,15 +41,15 @@ QEvdevMouseHandler *QEvdevMouseHandler::create(const QString &device, const QStr int grab = 0; bool abs = false; - const auto args = specification.splitRef(QLatin1Char(':')); - for (const QStringRef &arg : args) { - if (arg == QLatin1String("nocompress")) + const auto args = QStringView{specification}.split(u':'); + for (const auto &arg : args) { + if (arg == "nocompress"_L1) compression = false; - else if (arg.startsWith(QLatin1String("dejitter="))) + else if (arg.startsWith("dejitter="_L1)) jitterLimit = arg.mid(9).toInt(); - else if (arg.startsWith(QLatin1String("grab="))) + else if (arg.startsWith("grab="_L1)) grab = arg.mid(5).toInt(); - else if (arg == QLatin1String("abs")) + else if (arg == "abs"_L1) abs = true; } @@ -91,18 +57,17 @@ QEvdevMouseHandler *QEvdevMouseHandler::create(const QString &device, const QStr fd = qt_safe_open(device.toLocal8Bit().constData(), O_RDONLY | O_NDELAY, 0); if (fd >= 0) { ::ioctl(fd, EVIOCGRAB, grab); - return new QEvdevMouseHandler(device, fd, abs, compression, jitterLimit); + return std::unique_ptr<QEvdevMouseHandler>(new QEvdevMouseHandler(device, fd, abs, compression, jitterLimit)); } else { qErrnoWarning(errno, "Cannot open mouse input device %s", qPrintable(device)); - return 0; + return nullptr; } } QEvdevMouseHandler::QEvdevMouseHandler(const QString &device, int fd, bool abs, bool compression, int jitterLimit) - : m_device(device), m_fd(fd), m_notify(0), m_x(0), m_y(0), m_prevx(0), m_prevy(0), - m_abs(abs), m_compression(compression), m_buttons(0), m_prevInvalid(true) + : m_device(device), m_fd(fd), m_abs(abs), m_compression(compression) { - setObjectName(QLatin1String("Evdev Mouse Handler")); + setObjectName("Evdev Mouse Handler"_L1); m_jitterLimitSquared = jitterLimit * jitterLimit; @@ -114,6 +79,8 @@ QEvdevMouseHandler::QEvdevMouseHandler(const QString &device, int fd, bool abs, if (m_abs) m_abs = getHardwareMaximum(); + detectHiResWheelSupport(); + // socket notifier for events on the mouse device m_notify = new QSocketNotifier(m_fd, QSocketNotifier::Read, this); connect(m_notify, &QSocketNotifier::activated, @@ -126,6 +93,25 @@ QEvdevMouseHandler::~QEvdevMouseHandler() qt_safe_close(m_fd); } +void QEvdevMouseHandler::detectHiResWheelSupport() +{ +#if defined(REL_WHEEL_HI_RES) || defined(REL_HWHEEL_HI_RES) + // Check if we can expect hires events as we will get both + // legacy and hires event and needs to know if we should + // ignore the legacy events. + unsigned char relFeatures[(REL_MAX / 8) + 1]{}; + if (ioctl(m_fd, EVIOCGBIT(EV_REL, sizeof (relFeatures)), relFeatures) == -1) + return; + +#if defined(REL_WHEEL_HI_RES) + m_hiResWheel = TEST_BIT(relFeatures, REL_WHEEL_HI_RES); +#endif +#if defined(REL_HWHEEL_HI_RES) + m_hiResHWheel = TEST_BIT(relFeatures, REL_HWHEEL_HI_RES); +#endif +#endif +} + // Ask touch screen hardware for information on coordinate maximums // If any ioctls fail, revert to non abs mode bool QEvdevMouseHandler::getHardwareMaximum() @@ -184,7 +170,10 @@ void QEvdevMouseHandler::sendMouseEvent() m_prevInvalid = false; } - emit handleMouseEvent(x, y, m_abs, m_buttons, m_button, m_eventType); + if (m_eventType == QEvent::MouseMove) + emit handleMouseEvent(x, y, m_abs, m_buttons, Qt::NoButton, m_eventType); + else + emit handleMouseEvent(x, y, m_abs, m_buttons, m_button, m_eventType); m_prevx = m_x; m_prevy = m_y; @@ -196,7 +185,6 @@ void QEvdevMouseHandler::readMouseData() int n = 0; bool posChanged = false, btnChanged = false; bool pendingMouseEvent = false; - int eventCompressCount = 0; forever { int result = QT_READ(m_fd, reinterpret_cast<char *>(buffer) + n, sizeof(buffer) - n); @@ -244,14 +232,24 @@ void QEvdevMouseHandler::readMouseData() } else if (data->code == REL_Y) { m_y += data->value; posChanged = true; - } else if (data->code == ABS_WHEEL) { // vertical scroll + } else if (!m_hiResWheel && data->code == REL_WHEEL) { // data->value: positive == up, negative == down delta.setY(120 * data->value); emit handleWheelEvent(delta); - } else if (data->code == ABS_THROTTLE) { // horizontal scroll +#ifdef REL_WHEEL_HI_RES + } else if (data->code == REL_WHEEL_HI_RES) { + delta.setY(data->value); + emit handleWheelEvent(delta); +#endif + } else if (!m_hiResHWheel && data->code == REL_HWHEEL) { // data->value: positive == right, negative == left delta.setX(-120 * data->value); emit handleWheelEvent(delta); +#ifdef REL_HWHEEL_HI_RES + } else if (data->code == REL_HWHEEL_HI_RES) { + delta.setX(-data->value); + emit handleWheelEvent(delta); +#endif } } else if (data->type == EV_KEY && data->code == BTN_TOUCH) { // We care about touchpads only, not touchscreens -> don't map to button press. @@ -293,7 +291,6 @@ void QEvdevMouseHandler::readMouseData() posChanged = false; if (m_compression) { pendingMouseEvent = true; - eventCompressCount++; } else { sendMouseEvent(); } @@ -311,3 +308,5 @@ void QEvdevMouseHandler::readMouseData() } QT_END_NAMESPACE + +#include "moc_qevdevmousehandler_p.cpp" diff --git a/src/platformsupport/input/evdevmouse/qevdevmousehandler_p.h b/src/platformsupport/input/evdevmouse/qevdevmousehandler_p.h index c7f2b04eb2..a49ff10256 100644 --- a/src/platformsupport/input/evdevmouse/qevdevmousehandler_p.h +++ b/src/platformsupport/input/evdevmouse/qevdevmousehandler_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2020 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QEVDEVMOUSEHANDLER_P_H #define QEVDEVMOUSEHANDLER_P_H @@ -55,6 +19,9 @@ #include <QString> #include <QPoint> #include <QEvent> +#include <private/qglobal_p.h> + +#include <memory> QT_BEGIN_NAMESPACE @@ -64,7 +31,7 @@ class QEvdevMouseHandler : public QObject { Q_OBJECT public: - static QEvdevMouseHandler *create(const QString &device, const QString &specification); + static std::unique_ptr<QEvdevMouseHandler> create(const QString &device, const QString &specification); ~QEvdevMouseHandler(); void readMouseData(); @@ -79,19 +46,22 @@ private: void sendMouseEvent(); bool getHardwareMaximum(); + void detectHiResWheelSupport(); QString m_device; int m_fd; - QSocketNotifier *m_notify; - int m_x, m_y; - int m_prevx, m_prevy; + QSocketNotifier *m_notify = nullptr; + int m_x = 0, m_y = 0; + int m_prevx = 0, m_prevy = 0; bool m_abs; bool m_compression; + bool m_hiResWheel = false; + bool m_hiResHWheel = false; Qt::MouseButtons m_buttons; Qt::MouseButton m_button; QEvent::Type m_eventType; int m_jitterLimitSquared; - bool m_prevInvalid; + bool m_prevInvalid = true; int m_hardwareWidth; int m_hardwareHeight; qreal m_hardwareScalerY; diff --git a/src/platformsupport/input/evdevmouse/qevdevmousemanager.cpp b/src/platformsupport/input/evdevmouse/qevdevmousemanager.cpp index 06025c016e..55b127ef17 100644 --- a/src/platformsupport/input/evdevmouse/qevdevmousemanager.cpp +++ b/src/platformsupport/input/evdevmouse/qevdevmousemanager.cpp @@ -1,44 +1,10 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qevdevmousemanager_p.h" +#include <QtInputSupport/private/qevdevutil_p.h> + #include <QStringList> #include <QGuiApplication> #include <QScreen> @@ -51,6 +17,8 @@ QT_BEGIN_NAMESPACE +using namespace Qt::StringLiterals; + Q_DECLARE_LOGGING_CATEGORY(qLcEvdevMouse) QEvdevMouseManager::QEvdevMouseManager(const QString &key, const QString &specification, QObject *parent) @@ -63,46 +31,38 @@ QEvdevMouseManager::QEvdevMouseManager(const QString &key, const QString &specif if (spec.isEmpty()) spec = specification; - QStringList args = spec.split(QLatin1Char(':')); - QStringList devices; + auto parsed = QEvdevUtil::parseSpecification(spec); + m_spec = std::move(parsed.spec); - foreach (const QString &arg, args) { - if (arg.startsWith(QLatin1String("/dev/"))) { - // if device is specified try to use it - devices.append(arg); - args.removeAll(arg); - } else if (arg.startsWith(QLatin1String("xoffset="))) { + for (const auto &arg : std::as_const(parsed.args)) { + if (arg.startsWith("xoffset="_L1)) { m_xoffset = arg.mid(8).toInt(); - } else if (arg.startsWith(QLatin1String("yoffset="))) { + } else if (arg.startsWith("yoffset="_L1)) { m_yoffset = arg.mid(8).toInt(); } } - // build new specification without /dev/ elements - m_spec = args.join(QLatin1Char(':')); - // add all mice for devices specified in the argument list - foreach (const QString &device, devices) + for (const QString &device : std::as_const(parsed.devices)) addMouse(device); - if (devices.isEmpty()) { - qCDebug(qLcEvdevMouse) << "evdevmouse: Using device discovery"; - m_deviceDiscovery = QDeviceDiscovery::create(QDeviceDiscovery::Device_Mouse | QDeviceDiscovery::Device_Touchpad, this); - if (m_deviceDiscovery) { + if (parsed.devices.isEmpty()) { + qCDebug(qLcEvdevMouse, "evdevmouse: Using device discovery"); + if (auto deviceDiscovery = QDeviceDiscovery::create(QDeviceDiscovery::Device_Mouse | QDeviceDiscovery::Device_Touchpad, this)) { // scan and add already connected keyboards - const QStringList devices = m_deviceDiscovery->scanConnectedDevices(); + const QStringList devices = deviceDiscovery->scanConnectedDevices(); for (const QString &device : devices) addMouse(device); - connect(m_deviceDiscovery, &QDeviceDiscovery::deviceDetected, + connect(deviceDiscovery, &QDeviceDiscovery::deviceDetected, this, &QEvdevMouseManager::addMouse); - connect(m_deviceDiscovery, &QDeviceDiscovery::deviceRemoved, + connect(deviceDiscovery, &QDeviceDiscovery::deviceRemoved, this, &QEvdevMouseManager::removeMouse); } } QInputDeviceManager *manager = QGuiApplicationPrivate::inputDeviceManager(); - connect(manager, &QInputDeviceManager::cursorPositionChangeRequested, [this](const QPoint &pos) { + connect(manager, &QInputDeviceManager::cursorPositionChangeRequested, this, [this](const QPoint &pos) { m_x = pos.x(); m_y = pos.y(); clampPosition(); @@ -111,8 +71,6 @@ QEvdevMouseManager::QEvdevMouseManager(const QString &key, const QString &specif QEvdevMouseManager::~QEvdevMouseManager() { - qDeleteAll(m_mice); - m_mice.clear(); } void QEvdevMouseManager::clampPosition() @@ -159,31 +117,32 @@ void QEvdevMouseManager::handleWheelEvent(QPoint delta) void QEvdevMouseManager::addMouse(const QString &deviceNode) { - qCDebug(qLcEvdevMouse) << "Adding mouse at" << deviceNode; - QEvdevMouseHandler *handler = QEvdevMouseHandler::create(deviceNode, m_spec); + qCDebug(qLcEvdevMouse, "Adding mouse at %ls", qUtf16Printable(deviceNode)); + auto handler = QEvdevMouseHandler::create(deviceNode, m_spec); if (handler) { - connect(handler, &QEvdevMouseHandler::handleMouseEvent, + connect(handler.get(), &QEvdevMouseHandler::handleMouseEvent, this, &QEvdevMouseManager::handleMouseEvent); - connect(handler, &QEvdevMouseHandler::handleWheelEvent, + connect(handler.get(), &QEvdevMouseHandler::handleWheelEvent, this, &QEvdevMouseManager::handleWheelEvent); - m_mice.insert(deviceNode, handler); - QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount( - QInputDeviceManager::DeviceTypePointer, m_mice.count()); + m_mice.add(deviceNode, std::move(handler)); + updateDeviceCount(); } else { - qWarning("evdevmouse: Failed to open mouse device %s", qPrintable(deviceNode)); + qWarning("evdevmouse: Failed to open mouse device %ls", qUtf16Printable(deviceNode)); } } void QEvdevMouseManager::removeMouse(const QString &deviceNode) { - if (m_mice.contains(deviceNode)) { - qCDebug(qLcEvdevMouse) << "Removing mouse at" << deviceNode; - QEvdevMouseHandler *handler = m_mice.value(deviceNode); - m_mice.remove(deviceNode); - QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount( - QInputDeviceManager::DeviceTypePointer, m_mice.count()); - delete handler; + if (m_mice.remove(deviceNode)) { + qCDebug(qLcEvdevMouse, "Removing mouse at %ls", qUtf16Printable(deviceNode)); + updateDeviceCount(); } } +void QEvdevMouseManager::updateDeviceCount() +{ + QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount( + QInputDeviceManager::DeviceTypePointer, m_mice.count()); +} + QT_END_NAMESPACE diff --git a/src/platformsupport/input/evdevmouse/qevdevmousemanager_p.h b/src/platformsupport/input/evdevmouse/qevdevmousemanager_p.h index 13a8e3dec5..5467513cd4 100644 --- a/src/platformsupport/input/evdevmouse/qevdevmousemanager_p.h +++ b/src/platformsupport/input/evdevmouse/qevdevmousemanager_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QEVDEVMOUSEMANAGER_P_H #define QEVDEVMOUSEMANAGER_P_H @@ -53,6 +17,8 @@ #include "qevdevmousehandler_p.h" +#include <QtInputSupport/private/devicehandlerlist_p.h> + #include <QObject> #include <QHash> #include <QSocketNotifier> @@ -65,7 +31,7 @@ class QDeviceDiscovery; class QEvdevMouseManager : public QObject { public: - QEvdevMouseManager(const QString &key, const QString &specification, QObject *parent = 0); + QEvdevMouseManager(const QString &key, const QString &specification, QObject *parent = nullptr); ~QEvdevMouseManager(); void handleMouseEvent(int x, int y, bool abs, Qt::MouseButtons buttons, @@ -77,10 +43,10 @@ public: private: void clampPosition(); + void updateDeviceCount(); QString m_spec; - QHash<QString,QEvdevMouseHandler*> m_mice; - QDeviceDiscovery *m_deviceDiscovery; + QtInputSupport::DeviceHandlerList<QEvdevMouseHandler> m_mice; int m_x; int m_y; int m_xoffset; diff --git a/src/platformsupport/input/evdevtablet/evdevtablet.pri b/src/platformsupport/input/evdevtablet/evdevtablet.pri deleted file mode 100644 index ea1712ad2f..0000000000 --- a/src/platformsupport/input/evdevtablet/evdevtablet.pri +++ /dev/null @@ -1,10 +0,0 @@ -HEADERS += \ - $$PWD/qevdevtablethandler_p.h \ - $$PWD/qevdevtabletmanager_p.h - -SOURCES += \ - $$PWD/qevdevtablethandler.cpp \ - $$PWD/qevdevtabletmanager.cpp - -qtConfig(libudev): \ - QMAKE_USE_PRIVATE += libudev diff --git a/src/platformsupport/input/evdevtablet/qevdevtablethandler.cpp b/src/platformsupport/input/evdevtablet/qevdevtablethandler.cpp index b6051aaf3c..109ab0f212 100644 --- a/src/platformsupport/input/evdevtablet/qevdevtablethandler.cpp +++ b/src/platformsupport/input/evdevtablet/qevdevtablethandler.cpp @@ -1,47 +1,12 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qevdevtablethandler_p.h" #include <QStringList> #include <QSocketNotifier> #include <QGuiApplication> +#include <QPointingDevice> #include <QLoggingCategory> #include <QtCore/private/qcore_unix_p.h> #include <qpa/qwindowsysteminterface.h> @@ -53,6 +18,8 @@ QT_BEGIN_NAMESPACE +using namespace Qt::StringLiterals; + Q_LOGGING_CATEGORY(qLcEvdevTablet, "qt.qpa.input") class QEvdevTabletData @@ -114,10 +81,10 @@ void QEvdevTabletData::processInputEvent(input_event *ev) state.down = ev->value != 0; break; case BTN_TOOL_PEN: - state.tool = ev->value ? QTabletEvent::Pen : 0; + state.tool = ev->value ? int(QPointingDevice::PointerType::Pen) : 0; break; case BTN_TOOL_RUBBER: - state.tool = ev->value ? QTabletEvent::Eraser : 0; + state.tool = ev->value ? int(QPointingDevice::PointerType::Eraser) : 0; break; default: break; @@ -131,7 +98,7 @@ void QEvdevTabletData::processInputEvent(input_event *ev) void QEvdevTabletData::report() { if (!state.lastReportTool && state.tool) - QWindowSystemInterface::handleTabletEnterProximityEvent(QTabletEvent::Stylus, state.tool, q->deviceId()); + QWindowSystemInterface::handleTabletEnterProximityEvent(int(QInputDevice::DeviceType::Stylus), state.tool, q->deviceId()); qreal nx = (state.x - minValues.x) / qreal(maxValues.x - minValues.x); qreal ny = (state.y - minValues.y) / qreal(maxValues.y - minValues.y); @@ -150,14 +117,14 @@ void QEvdevTabletData::report() if (state.down || state.lastReportDown) { QWindowSystemInterface::handleTabletEvent(0, QPointF(), globalPos, - QTabletEvent::Stylus, pointer, + int(QInputDevice::DeviceType::Stylus), pointer, state.down ? Qt::LeftButton : Qt::NoButton, pressure, 0, 0, 0, 0, 0, q->deviceId(), qGuiApp->keyboardModifiers()); } if (state.lastReportTool && !state.tool) - QWindowSystemInterface::handleTabletLeaveProximityEvent(QTabletEvent::Stylus, state.tool, q->deviceId()); + QWindowSystemInterface::handleTabletLeaveProximityEvent(int(QInputDevice::DeviceType::Stylus), state.tool, q->deviceId()); state.lastReportDown = state.down; state.lastReportTool = state.tool; @@ -168,15 +135,15 @@ void QEvdevTabletData::report() QEvdevTabletHandler::QEvdevTabletHandler(const QString &device, const QString &spec, QObject *parent) : QObject(parent), m_fd(-1), m_device(device), m_notifier(0), d(0) { - Q_UNUSED(spec) + Q_UNUSED(spec); - setObjectName(QLatin1String("Evdev Tablet Handler")); + setObjectName("Evdev Tablet Handler"_L1); - qCDebug(qLcEvdevTablet, "evdevtablet: using %s", qPrintable(device)); + qCDebug(qLcEvdevTablet, "evdevtablet: using %ls", qUtf16Printable(device)); m_fd = QT_OPEN(device.toLocal8Bit().constData(), O_RDONLY | O_NDELAY, 0); if (m_fd < 0) { - qErrnoWarning(errno, "evdevtablet: Cannot open input device %s", qPrintable(device)); + qErrnoWarning("evdevtablet: Cannot open input device %ls", qUtf16Printable(device)); return; } @@ -184,11 +151,11 @@ QEvdevTabletHandler::QEvdevTabletHandler(const QString &device, const QString &s if (grabSuccess) ioctl(m_fd, EVIOCGRAB, (void *) 0); else - qWarning("evdevtablet: %s: The device is grabbed by another process. No events will be read.", qPrintable(device)); + qWarning("evdevtablet: %ls: The device is grabbed by another process. No events will be read.", qUtf16Printable(device)); d = new QEvdevTabletData(this); if (!queryLimits()) - qWarning("evdevtablet: %s: Unset or invalid ABS limits. Behavior will be unspecified.", qPrintable(device)); + qWarning("evdevtablet: %ls: Unset or invalid ABS limits. Behavior will be unspecified.", qUtf16Printable(device)); m_notifier = new QSocketNotifier(m_fd, QSocketNotifier::Read, this); connect(m_notifier, &QSocketNotifier::activated, this, &QEvdevTabletHandler::readData); @@ -216,32 +183,32 @@ bool QEvdevTabletHandler::queryLimits() if (ok) { d->minValues.x = absInfo.minimum; d->maxValues.x = absInfo.maximum; - qCDebug(qLcEvdevTablet, "evdevtablet: %s: min X: %d max X: %d", qPrintable(m_device), + qCDebug(qLcEvdevTablet, "evdevtablet: %ls: min X: %d max X: %d", qUtf16Printable(m_device), d->minValues.x, d->maxValues.x); } ok &= ioctl(m_fd, EVIOCGABS(ABS_Y), &absInfo) >= 0; if (ok) { d->minValues.y = absInfo.minimum; d->maxValues.y = absInfo.maximum; - qCDebug(qLcEvdevTablet, "evdevtablet: %s: min Y: %d max Y: %d", qPrintable(m_device), + qCDebug(qLcEvdevTablet, "evdevtablet: %ls: min Y: %d max Y: %d", qUtf16Printable(m_device), d->minValues.y, d->maxValues.y); } if (ioctl(m_fd, EVIOCGABS(ABS_PRESSURE), &absInfo) >= 0) { d->minValues.p = absInfo.minimum; d->maxValues.p = absInfo.maximum; - qCDebug(qLcEvdevTablet, "evdevtablet: %s: min pressure: %d max pressure: %d", qPrintable(m_device), + qCDebug(qLcEvdevTablet, "evdevtablet: %ls: min pressure: %d max pressure: %d", qUtf16Printable(m_device), d->minValues.p, d->maxValues.p); } if (ioctl(m_fd, EVIOCGABS(ABS_DISTANCE), &absInfo) >= 0) { d->minValues.d = absInfo.minimum; d->maxValues.d = absInfo.maximum; - qCDebug(qLcEvdevTablet, "evdevtablet: %s: min distance: %d max distance: %d", qPrintable(m_device), + qCDebug(qLcEvdevTablet, "evdevtablet: %ls: min distance: %d max distance: %d", qUtf16Printable(m_device), d->minValues.d, d->maxValues.d); } char name[128]; if (ioctl(m_fd, EVIOCGNAME(sizeof(name) - 1), name) >= 0) { d->devName = QString::fromLocal8Bit(name); - qCDebug(qLcEvdevTablet, "evdevtablet: %s: device name: %s", qPrintable(m_device), name); + qCDebug(qLcEvdevTablet, "evdevtablet: %ls: device name: %s", qUtf16Printable(m_device), name); } return ok; } @@ -253,11 +220,11 @@ void QEvdevTabletHandler::readData() for (; ;) { int result = QT_READ(m_fd, reinterpret_cast<char*>(buffer) + n, sizeof(buffer) - n); if (!result) { - qWarning("evdevtablet: %s: Got EOF from input device", qPrintable(m_device)); + qWarning("evdevtablet: %ls: Got EOF from input device", qUtf16Printable(m_device)); return; } else if (result < 0) { if (errno != EINTR && errno != EAGAIN) { - qErrnoWarning(errno, "evdevtablet: %s: Could not read from input device", qPrintable(m_device)); + qErrnoWarning("evdevtablet: %ls: Could not read from input device", qUtf16Printable(m_device)); if (errno == ENODEV) { // device got disconnected -> stop reading delete m_notifier; m_notifier = 0; diff --git a/src/platformsupport/input/evdevtablet/qevdevtablethandler_p.h b/src/platformsupport/input/evdevtablet/qevdevtablethandler_p.h index 66e821117a..205d629397 100644 --- a/src/platformsupport/input/evdevtablet/qevdevtablethandler_p.h +++ b/src/platformsupport/input/evdevtablet/qevdevtablethandler_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QEVDEVTABLETHANDLER_P_H #define QEVDEVTABLETHANDLER_P_H @@ -64,7 +28,7 @@ class QEvdevTabletData; class QEvdevTabletHandler : public QObject { public: - explicit QEvdevTabletHandler(const QString &device, const QString &spec = QString(), QObject *parent = 0); + explicit QEvdevTabletHandler(const QString &device, const QString &spec = QString(), QObject *parent = nullptr); ~QEvdevTabletHandler(); qint64 deviceId() const; @@ -83,7 +47,7 @@ private: class QEvdevTabletHandlerThread : public QDaemonThread { public: - explicit QEvdevTabletHandlerThread(const QString &device, const QString &spec, QObject *parent = 0); + explicit QEvdevTabletHandlerThread(const QString &device, const QString &spec, QObject *parent = nullptr); ~QEvdevTabletHandlerThread(); void run() override; QEvdevTabletHandler *handler() { return m_handler; } diff --git a/src/platformsupport/input/evdevtablet/qevdevtabletmanager.cpp b/src/platformsupport/input/evdevtablet/qevdevtabletmanager.cpp index 90949408ac..a270f9700d 100644 --- a/src/platformsupport/input/evdevtablet/qevdevtabletmanager.cpp +++ b/src/platformsupport/input/evdevtablet/qevdevtabletmanager.cpp @@ -1,45 +1,11 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qevdevtabletmanager_p.h" #include "qevdevtablethandler_p.h" +#include <QtInputSupport/private/qevdevutil_p.h> + #include <QStringList> #include <QGuiApplication> #include <QLoggingCategory> @@ -64,34 +30,23 @@ QEvdevTabletManager::QEvdevTabletManager(const QString &key, const QString &spec if (spec.isEmpty()) spec = specification; - QStringList args = spec.split(QLatin1Char(':')); - QStringList devices; - - foreach (const QString &arg, args) { - if (arg.startsWith(QLatin1String("/dev/"))) { - devices.append(arg); - args.removeAll(arg); - } - } - - // build new specification without /dev/ elements - m_spec = args.join(QLatin1Char(':')); + auto parsed = QEvdevUtil::parseSpecification(spec); + m_spec = std::move(parsed.spec); - foreach (const QString &device, devices) + for (const QString &device : std::as_const(parsed.devices)) addDevice(device); // when no devices specified, use device discovery to scan and monitor - if (devices.isEmpty()) { - qCDebug(qLcEvdevTablet) << "evdevtablet: Using device discovery"; - m_deviceDiscovery = QDeviceDiscovery::create(QDeviceDiscovery::Device_Tablet, this); - if (m_deviceDiscovery) { - const QStringList devices = m_deviceDiscovery->scanConnectedDevices(); + if (parsed.devices.isEmpty()) { + qCDebug(qLcEvdevTablet, "evdevtablet: Using device discovery"); + if (auto deviceDiscovery = QDeviceDiscovery::create(QDeviceDiscovery::Device_Tablet, this)) { + const QStringList devices = deviceDiscovery->scanConnectedDevices(); for (const QString &device : devices) addDevice(device); - connect(m_deviceDiscovery, &QDeviceDiscovery::deviceDetected, + connect(deviceDiscovery, &QDeviceDiscovery::deviceDetected, this, &QEvdevTabletManager::addDevice); - connect(m_deviceDiscovery, &QDeviceDiscovery::deviceRemoved, + connect(deviceDiscovery, &QDeviceDiscovery::deviceRemoved, this, &QEvdevTabletManager::removeDevice); } } @@ -99,33 +54,32 @@ QEvdevTabletManager::QEvdevTabletManager(const QString &key, const QString &spec QEvdevTabletManager::~QEvdevTabletManager() { - qDeleteAll(m_activeDevices); } void QEvdevTabletManager::addDevice(const QString &deviceNode) { - qCDebug(qLcEvdevTablet) << "Adding device at" << deviceNode; - QEvdevTabletHandlerThread *handler; - handler = new QEvdevTabletHandlerThread(deviceNode, m_spec); + qCDebug(qLcEvdevTablet, "Adding device at %ls", qUtf16Printable(deviceNode)); + auto handler = std::make_unique<QEvdevTabletHandlerThread>(deviceNode, m_spec); if (handler) { - m_activeDevices.insert(deviceNode, handler); - QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount( - QInputDeviceManager::DeviceTypeTablet, m_activeDevices.count()); + m_activeDevices.add(deviceNode, std::move(handler)); + updateDeviceCount(); } else { - qWarning("evdevtablet: Failed to open tablet device %s", qPrintable(deviceNode)); + qWarning("evdevtablet: Failed to open tablet device %ls", qUtf16Printable(deviceNode)); } } void QEvdevTabletManager::removeDevice(const QString &deviceNode) { - if (m_activeDevices.contains(deviceNode)) { - qCDebug(qLcEvdevTablet) << "Removing device at" << deviceNode; - QEvdevTabletHandlerThread *handler = m_activeDevices.value(deviceNode); - m_activeDevices.remove(deviceNode); - QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount( - QInputDeviceManager::DeviceTypeTablet, m_activeDevices.count()); - delete handler; + if (m_activeDevices.remove(deviceNode)) { + qCDebug(qLcEvdevTablet, "Removing device at %ls", qUtf16Printable(deviceNode)); + updateDeviceCount(); } } +void QEvdevTabletManager::updateDeviceCount() +{ + QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount( + QInputDeviceManager::DeviceTypeTablet, m_activeDevices.count()); +} + QT_END_NAMESPACE diff --git a/src/platformsupport/input/evdevtablet/qevdevtabletmanager_p.h b/src/platformsupport/input/evdevtablet/qevdevtabletmanager_p.h index cde91c55aa..08bc2cfaa4 100644 --- a/src/platformsupport/input/evdevtablet/qevdevtabletmanager_p.h +++ b/src/platformsupport/input/evdevtablet/qevdevtabletmanager_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QEVDEVTABLETMANAGER_P_H #define QEVDEVTABLETMANAGER_P_H @@ -51,6 +15,8 @@ // We mean it. // +#include <QtInputSupport/private/devicehandlerlist_p.h> + #include <QObject> #include <QHash> #include <QSocketNotifier> @@ -63,16 +29,17 @@ class QEvdevTabletHandlerThread; class QEvdevTabletManager : public QObject { public: - QEvdevTabletManager(const QString &key, const QString &spec, QObject *parent = 0); + QEvdevTabletManager(const QString &key, const QString &spec, QObject *parent = nullptr); ~QEvdevTabletManager(); void addDevice(const QString &deviceNode); void removeDevice(const QString &deviceNode); private: + void updateDeviceCount(); + QString m_spec; - QDeviceDiscovery *m_deviceDiscovery; - QHash<QString, QEvdevTabletHandlerThread *> m_activeDevices; + QtInputSupport::DeviceHandlerList<QEvdevTabletHandlerThread> m_activeDevices; }; QT_END_NAMESPACE diff --git a/src/platformsupport/input/evdevtouch/evdevtouch.pri b/src/platformsupport/input/evdevtouch/evdevtouch.pri deleted file mode 100644 index 0ad236e882..0000000000 --- a/src/platformsupport/input/evdevtouch/evdevtouch.pri +++ /dev/null @@ -1,16 +0,0 @@ -HEADERS += \ - $$PWD/qevdevtouchhandler_p.h \ - $$PWD/qevdevtouchmanager_p.h - -SOURCES += \ - $$PWD/qevdevtouchhandler.cpp \ - $$PWD/qevdevtouchmanager.cpp - -INCLUDEPATH += $$PWD/../shared - -qtConfig(libudev): \ - QMAKE_USE_PRIVATE += libudev - -qtConfig(mtdev) { - QMAKE_USE_PRIVATE += mtdev -} diff --git a/src/platformsupport/input/evdevtouch/qevdevtouchfilter_p.h b/src/platformsupport/input/evdevtouch/qevdevtouchfilter_p.h index ff6085d725..9d181dc651 100644 --- a/src/platformsupport/input/evdevtouch/qevdevtouchfilter_p.h +++ b/src/platformsupport/input/evdevtouch/qevdevtouchfilter_p.h @@ -1,43 +1,7 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <qglobal.h> +// Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com> +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include <private/qglobal_p.h> // // W A R N I N G diff --git a/src/platformsupport/input/evdevtouch/qevdevtouchhandler.cpp b/src/platformsupport/input/evdevtouch/qevdevtouchhandler.cpp index f3cc160b3e..1b0da6297b 100644 --- a/src/platformsupport/input/evdevtouch/qevdevtouchhandler.cpp +++ b/src/platformsupport/input/evdevtouch/qevdevtouchhandler.cpp @@ -1,60 +1,38 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com> +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qevdevtouchhandler_p.h" -#include "qtouchoutputmapping_p.h" +#include "qoutputmapping_p.h" #include <QStringList> #include <QHash> #include <QSocketNotifier> #include <QGuiApplication> -#include <QTouchDevice> #include <QLoggingCategory> #include <QtCore/private/qcore_unix_p.h> +#include <QtGui/qpointingdevice.h> #include <QtGui/private/qhighdpiscaling_p.h> #include <QtGui/private/qguiapplication_p.h> +#include <QtGui/private/qpointingdevice_p.h> + +#include <QtCore/qpointer.h> + +#include <mutex> + #ifdef Q_OS_FREEBSD #include <dev/evdev/input.h> #else #include <linux/input.h> #endif +#ifndef input_event_sec +#define input_event_sec time.tv_sec +#endif + +#ifndef input_event_usec +#define input_event_usec time.tv_usec +#endif + #include <math.h> #if QT_CONFIG(mtdev) @@ -65,7 +43,10 @@ extern "C" { QT_BEGIN_NAMESPACE +using namespace Qt::StringLiterals; + Q_LOGGING_CATEGORY(qLcEvdevTouch, "qt.qpa.input") +Q_LOGGING_CATEGORY(qLcEvents, "qt.qpa.input.events") /* android (and perhaps some other linux-derived stuff) don't define everything * in linux/input.h, so we'll need to do that ourselves. @@ -74,7 +55,7 @@ Q_LOGGING_CATEGORY(qLcEvdevTouch, "qt.qpa.input") #define ABS_MT_TOUCH_MAJOR 0x30 /* Major axis of touching ellipse */ #endif #ifndef ABS_MT_POSITION_X -#define ABS_MT_POSITION_X 0x35 /* Center X ellipse position */ +#define ABS_MT_POSITION_X 0x35 /* Center X ellipse position */ #endif #ifndef ABS_MT_POSITION_Y #define ABS_MT_POSITION_Y 0x36 /* Center Y ellipse position */ @@ -88,6 +69,9 @@ Q_LOGGING_CATEGORY(qLcEvdevTouch, "qt.qpa.input") #ifndef ABS_MT_TRACKING_ID #define ABS_MT_TRACKING_ID 0x39 /* Unique ID of initiated contact */ #endif +#ifndef ABS_MT_PRESSURE +#define ABS_MT_PRESSURE 0x3a +#endif #ifndef SYN_MT_REPORT #define SYN_MT_REPORT 2 #endif @@ -106,16 +90,12 @@ public: QList<QWindowSystemInterface::TouchPoint> m_lastTouchPoints; struct Contact { - int trackingId; - int x; - int y; - int maj; - int pressure; - Qt::TouchPointState state; - QTouchEvent::TouchPoint::InfoFlags flags; - Contact() : trackingId(-1), - x(0), y(0), maj(-1), pressure(0), - state(Qt::TouchPointPressed), flags(0) { } + int trackingId = -1; + int x = 0; + int y = 0; + int maj = -1; + int pressure = 0; + QEventPoint::State state = QEventPoint::State::Pressed; }; QHash<int, Contact> m_contacts; // The key is a tracking id for type A, slot number for type B. QHash<int, Contact> m_lastContacts; @@ -126,7 +106,7 @@ public: double m_lastTimeStamp; int findClosestContact(const QHash<int, Contact> &contacts, int x, int y, int *dist); - void addTouchPoint(const Contact &contact, Qt::TouchPointStates *combinedStates); + void addTouchPoint(const Contact &contact, QEventPoint::States *combinedStates); void reportPoints(); void loadMultiScreenMappings(); @@ -172,12 +152,12 @@ QEvdevTouchScreenData::QEvdevTouchScreenData(QEvdevTouchScreenHandler *q_ptr, co m_filtered(false), m_prediction(0) { for (const QString &arg : args) { - if (arg == QStringLiteral("force_window")) + if (arg == u"force_window") m_forceToActiveWindow = true; - else if (arg == QStringLiteral("filtered")) + else if (arg == u"filtered") m_filtered = true; - else if (arg.startsWith(QStringLiteral("prediction="))) - m_prediction = arg.mid(11).toInt(); + else if (const QStringView prefix = u"prediction="; arg.startsWith(prefix)) + m_prediction = QStringView(arg).mid(prefix.size()).toInt(); } } @@ -197,15 +177,15 @@ QEvdevTouchScreenHandler::QEvdevTouchScreenHandler(const QString &device, const , m_mtdev(nullptr) #endif { - setObjectName(QLatin1String("Evdev Touch Handler")); + setObjectName("Evdev Touch Handler"_L1); - const QStringList args = spec.split(QLatin1Char(':')); + const QStringList args = spec.split(u':'); int rotationAngle = 0; bool invertx = false; bool inverty = false; - for (int i = 0; i < args.count(); ++i) { - if (args.at(i).startsWith(QLatin1String("rotate"))) { - QString rotateArg = args.at(i).section(QLatin1Char('='), 1, 1); + for (int i = 0; i < args.size(); ++i) { + if (args.at(i).startsWith("rotate"_L1)) { + QString rotateArg = args.at(i).section(u'=', 1, 1); bool ok; uint argValue = rotateArg.toUInt(&ok); if (ok) { @@ -214,18 +194,19 @@ QEvdevTouchScreenHandler::QEvdevTouchScreenHandler(const QString &device, const case 180: case 270: rotationAngle = argValue; + break; default: break; } } - } else if (args.at(i) == QLatin1String("invertx")) { + } else if (args.at(i) == "invertx"_L1) { invertx = true; - } else if (args.at(i) == QLatin1String("inverty")) { + } else if (args.at(i) == "inverty"_L1) { inverty = true; } } - qCDebug(qLcEvdevTouch, "evdevtouch: Using device %s", qPrintable(device)); + qCDebug(qLcEvdevTouch, "evdevtouch: Using device %ls", qUtf16Printable(device)); m_fd = QT_OPEN(device.toLocal8Bit().constData(), O_RDONLY | O_NDELAY, 0); @@ -233,7 +214,7 @@ QEvdevTouchScreenHandler::QEvdevTouchScreenHandler(const QString &device, const m_notify = new QSocketNotifier(m_fd, QSocketNotifier::Read, this); connect(m_notify, &QSocketNotifier::activated, this, &QEvdevTouchScreenHandler::readData); } else { - qErrnoWarning(errno, "evdevtouch: Cannot open input device %s", qPrintable(device)); + qErrnoWarning("evdevtouch: Cannot open input device %ls", qUtf16Printable(device)); return; } @@ -243,6 +224,7 @@ QEvdevTouchScreenHandler::QEvdevTouchScreenHandler(const QString &device, const if (mtdeverr) { qWarning("evdevtouch: mtdev_open failed: %d", mtdeverr); QT_CLOSE(m_fd); + free(m_mtdev); return; } #endif @@ -263,8 +245,8 @@ QEvdevTouchScreenHandler::QEvdevTouchScreenHandler(const QString &device, const d->deviceNode = device; qCDebug(qLcEvdevTouch, - "evdevtouch: %s: Protocol type %c %s (%s), filtered=%s", - qPrintable(d->deviceNode), + "evdevtouch: %ls: Protocol type %c %s (%s), filtered=%s", + qUtf16Printable(d->deviceNode), d->m_typeB ? 'B' : 'A', mtdevStr, d->m_singleTouch ? "single" : "multi", d->m_filtered ? "yes" : "no"); @@ -276,7 +258,7 @@ QEvdevTouchScreenHandler::QEvdevTouchScreenHandler(const QString &device, const bool has_x_range = false, has_y_range = false; if (ioctl(m_fd, EVIOCGABS((d->m_singleTouch ? ABS_X : ABS_MT_POSITION_X)), &absInfo) >= 0) { - qCDebug(qLcEvdevTouch, "evdevtouch: %s: min X: %d max X: %d", qPrintable(device), + qCDebug(qLcEvdevTouch, "evdevtouch: %ls: min X: %d max X: %d", qUtf16Printable(device), absInfo.minimum, absInfo.maximum); d->hw_range_x_min = absInfo.minimum; d->hw_range_x_max = absInfo.maximum; @@ -284,7 +266,7 @@ QEvdevTouchScreenHandler::QEvdevTouchScreenHandler(const QString &device, const } if (ioctl(m_fd, EVIOCGABS((d->m_singleTouch ? ABS_Y : ABS_MT_POSITION_Y)), &absInfo) >= 0) { - qCDebug(qLcEvdevTouch, "evdevtouch: %s: min Y: %d max Y: %d", qPrintable(device), + qCDebug(qLcEvdevTouch, "evdevtouch: %ls: min Y: %d max Y: %d", qUtf16Printable(device), absInfo.minimum, absInfo.maximum); d->hw_range_y_min = absInfo.minimum; d->hw_range_y_max = absInfo.maximum; @@ -292,10 +274,10 @@ QEvdevTouchScreenHandler::QEvdevTouchScreenHandler(const QString &device, const } if (!has_x_range || !has_y_range) - qWarning("evdevtouch: %s: Invalid ABS limits, behavior unspecified", qPrintable(device)); + qWarning("evdevtouch: %ls: Invalid ABS limits, behavior unspecified", qUtf16Printable(device)); if (ioctl(m_fd, EVIOCGABS(ABS_PRESSURE), &absInfo) >= 0) { - qCDebug(qLcEvdevTouch, "evdevtouch: %s: min pressure: %d max pressure: %d", qPrintable(device), + qCDebug(qLcEvdevTouch, "evdevtouch: %ls: min pressure: %d max pressure: %d", qUtf16Printable(device), absInfo.minimum, absInfo.maximum); if (absInfo.maximum > absInfo.minimum) { d->hw_pressure_min = absInfo.minimum; @@ -306,11 +288,11 @@ QEvdevTouchScreenHandler::QEvdevTouchScreenHandler(const QString &device, const char name[1024]; if (ioctl(m_fd, EVIOCGNAME(sizeof(name) - 1), name) >= 0) { d->hw_name = QString::fromLocal8Bit(name); - qCDebug(qLcEvdevTouch, "evdevtouch: %s: device name: %s", qPrintable(device), name); + qCDebug(qLcEvdevTouch, "evdevtouch: %ls: device name: %s", qUtf16Printable(device), name); } // Fix up the coordinate ranges for am335x in case the kernel driver does not have them fixed. - if (d->hw_name == QLatin1String("ti-tsc")) { + if (d->hw_name == "ti-tsc"_L1) { if (d->hw_range_x_min == 0 && d->hw_range_x_max == 4095) { d->hw_range_x_min = 165; d->hw_range_x_max = 4016; @@ -338,15 +320,15 @@ QEvdevTouchScreenHandler::QEvdevTouchScreenHandler(const QString &device, const if (inverty) d->m_rotate *= QTransform::fromTranslate(0.5, 0.5).scale(1.0, -1.0).translate(-0.5, -0.5); - QTouchOutputMapping mapping; - if (mapping.load()) { - d->m_screenName = mapping.screenNameForDeviceNode(d->deviceNode); + QOutputMapping *mapping = QOutputMapping::get(); + if (mapping->load()) { + d->m_screenName = mapping->screenNameForDeviceNode(d->deviceNode); if (!d->m_screenName.isEmpty()) - qCDebug(qLcEvdevTouch, "evdevtouch: Mapping device %s to screen %s", - qPrintable(d->deviceNode), qPrintable(d->m_screenName)); + qCDebug(qLcEvdevTouch, "evdevtouch: Mapping device %ls to screen %ls", + qUtf16Printable(d->deviceNode), qUtf16Printable(d->m_screenName)); } - registerTouchDevice(); + registerPointingDevice(); } QEvdevTouchScreenHandler::~QEvdevTouchScreenHandler() @@ -363,7 +345,7 @@ QEvdevTouchScreenHandler::~QEvdevTouchScreenHandler() delete d; - unregisterTouchDevice(); + unregisterPointingDevice(); } bool QEvdevTouchScreenHandler::isFiltered() const @@ -371,7 +353,7 @@ bool QEvdevTouchScreenHandler::isFiltered() const return d && d->m_filtered; } -QTouchDevice *QEvdevTouchScreenHandler::touchDevice() const +QPointingDevice *QEvdevTouchScreenHandler::touchDevice() const { return m_device; } @@ -424,7 +406,7 @@ err: return; } else if (events < 0) { if (errno != EINTR && errno != EAGAIN) { - qErrnoWarning(errno, "evdevtouch: Could not read from input device"); + qErrnoWarning("evdevtouch: Could not read from input device"); if (errno == ENODEV) { // device got disconnected -> stop reading delete m_notify; m_notify = nullptr; @@ -432,48 +414,82 @@ err: QT_CLOSE(m_fd); m_fd = -1; - unregisterTouchDevice(); + unregisterPointingDevice(); } return; } } } -void QEvdevTouchScreenHandler::registerTouchDevice() +void QEvdevTouchScreenHandler::registerPointingDevice() { if (m_device) return; - m_device = new QTouchDevice; - m_device->setName(d->hw_name); - m_device->setType(QTouchDevice::TouchScreen); - m_device->setCapabilities(QTouchDevice::Position | QTouchDevice::Area); + static int id = 1; + QPointingDevice::Capabilities caps = QPointingDevice::Capability::Position | QPointingDevice::Capability::Area; if (d->hw_pressure_max > d->hw_pressure_min) - m_device->setCapabilities(m_device->capabilities() | QTouchDevice::Pressure); + caps.setFlag(QPointingDevice::Capability::Pressure); + + // TODO get evdev ID instead of an incremeting number; set USB ID too + m_device = new QPointingDevice(d->hw_name, id++, + QInputDevice::DeviceType::TouchScreen, QPointingDevice::PointerType::Finger, + caps, 16, 0); + + auto geom = d->screenGeometry(); + if (!geom.isNull()) + QPointingDevicePrivate::get(m_device)->setAvailableVirtualGeometry(geom); - QWindowSystemInterface::registerTouchDevice(m_device); + QWindowSystemInterface::registerInputDevice(m_device); } -void QEvdevTouchScreenHandler::unregisterTouchDevice() +/*! \internal + + QEvdevTouchScreenHandler::unregisterPointingDevice can be called by several cases. + + First of all, the case that an application is terminated, and destroy all input devices + immediately to unregister in this case. + + Secondly, the case that removing a device without touch events for the device while the + application is still running. In this case, the destructor of QEvdevTouchScreenHandler from + the connection with QDeviceDiscovery::deviceRemoved in QEvdevTouchManager calls this method. + And this method moves a device into the main thread and then deletes it later but there is no + touch events for the device so that the device would be deleted in appropriate time. + + Finally, this case is similar as the second one but with touch events, that is, a device is + removed while touch events are given to the device and the application is still running. + In this case, this method is called by readData with ENODEV error and the destructor of + QEvdevTouchScreenHandler. So in order to prevent accessing the device which is already nullptr, + check the nullity of a device first. And as same as the second case, move the device into the + main thread and then delete it later. But in this case, cannot guarantee which event is + handled first since the list or queue where posting QDeferredDeleteEvent and appending touch + events are different. + If touch events are handled first, there is no problem because the device which is used for + these events is registered. However if QDeferredDeleteEvent for deleting the device is + handled first, this may cause a crash due to using unregistered device when processing touch + events later. In order to prevent processing such touch events, check a device which is used + for touch events is registered when processing touch events. + + see QGuiApplicationPrivate::processTouchEvent(). + */ +void QEvdevTouchScreenHandler::unregisterPointingDevice() { if (!m_device) return; - // At app exit the cleanup may have already been done, avoid - // double delete by checking the list first. - if (QWindowSystemInterface::isTouchDeviceRegistered(m_device)) { - QWindowSystemInterface::unregisterTouchDevice(m_device); + if (QGuiApplication::instance()) { + m_device->moveToThread(QGuiApplication::instance()->thread()); + m_device->deleteLater(); + } else { delete m_device; } - m_device = nullptr; } -void QEvdevTouchScreenData::addTouchPoint(const Contact &contact, Qt::TouchPointStates *combinedStates) +void QEvdevTouchScreenData::addTouchPoint(const Contact &contact, QEventPoint::States *combinedStates) { QWindowSystemInterface::TouchPoint tp; tp.id = contact.trackingId; - tp.flags = contact.flags; tp.state = contact.state; *combinedStates |= tp.state; @@ -504,8 +520,8 @@ void QEvdevTouchScreenData::processInputEvent(input_event *data) m_contacts[m_currentSlot].x = m_currentData.x; if (m_typeB) { m_contacts[m_currentSlot].x = m_currentData.x; - if (m_contacts[m_currentSlot].state == Qt::TouchPointStationary) - m_contacts[m_currentSlot].state = Qt::TouchPointMoved; + if (m_contacts[m_currentSlot].state == QEventPoint::State::Stationary) + m_contacts[m_currentSlot].state = QEventPoint::State::Updated; } } else if (data->code == ABS_MT_POSITION_Y || (m_singleTouch && data->code == ABS_Y)) { m_currentData.y = qBound(hw_range_y_min, data->value, hw_range_y_max); @@ -513,26 +529,29 @@ void QEvdevTouchScreenData::processInputEvent(input_event *data) m_contacts[m_currentSlot].y = m_currentData.y; if (m_typeB) { m_contacts[m_currentSlot].y = m_currentData.y; - if (m_contacts[m_currentSlot].state == Qt::TouchPointStationary) - m_contacts[m_currentSlot].state = Qt::TouchPointMoved; + if (m_contacts[m_currentSlot].state == QEventPoint::State::Stationary) + m_contacts[m_currentSlot].state = QEventPoint::State::Updated; } } else if (data->code == ABS_MT_TRACKING_ID) { m_currentData.trackingId = data->value; if (m_typeB) { if (m_currentData.trackingId == -1) { - m_contacts[m_currentSlot].state = Qt::TouchPointReleased; + m_contacts[m_currentSlot].state = QEventPoint::State::Released; } else { - m_contacts[m_currentSlot].state = Qt::TouchPointPressed; + m_contacts[m_currentSlot].state = QEventPoint::State::Pressed; m_contacts[m_currentSlot].trackingId = m_currentData.trackingId; } } } else if (data->code == ABS_MT_TOUCH_MAJOR) { m_currentData.maj = data->value; if (data->value == 0) - m_currentData.state = Qt::TouchPointReleased; + m_currentData.state = QEventPoint::State::Released; if (m_typeB) m_contacts[m_currentSlot].maj = m_currentData.maj; - } else if (data->code == ABS_PRESSURE) { + } else if (data->code == ABS_PRESSURE || data->code == ABS_MT_PRESSURE) { + if (Q_UNLIKELY(qLcEvents().isDebugEnabled())) + qCDebug(qLcEvents, "EV_ABS code 0x%x: pressure %d; bounding to [%d,%d]", + data->code, data->value, hw_pressure_min, hw_pressure_max); m_currentData.pressure = qBound(hw_pressure_min, data->value, hw_pressure_max); if (m_typeB || m_singleTouch) m_contacts[m_currentSlot].pressure = m_currentData.pressure; @@ -542,14 +561,14 @@ void QEvdevTouchScreenData::processInputEvent(input_event *data) } else if (data->type == EV_KEY && !m_typeB) { if (data->code == BTN_TOUCH && data->value == 0) - m_contacts[m_currentSlot].state = Qt::TouchPointReleased; + m_contacts[m_currentSlot].state = QEventPoint::State::Released; } else if (data->type == EV_SYN && data->code == SYN_MT_REPORT && m_lastEventType != EV_SYN) { // If there is no tracking id, one will be generated later. // Until that use a temporary key. int key = m_currentData.trackingId; if (key == -1) - key = m_contacts.count(); + key = m_contacts.size(); m_contacts.insert(key, m_currentData); m_currentData = Contact(); @@ -560,85 +579,92 @@ void QEvdevTouchScreenData::processInputEvent(input_event *data) if (!m_contacts.isEmpty() && m_contacts.constBegin().value().trackingId == -1) assignIds(); + std::unique_lock<QMutex> locker; if (m_filtered) - m_mutex.lock(); + locker = std::unique_lock<QMutex>{m_mutex}; // update timestamps m_lastTimeStamp = m_timeStamp; - m_timeStamp = data->time.tv_sec + data->time.tv_usec / 1000000.0; + m_timeStamp = data->input_event_sec + data->input_event_usec / 1000000.0; m_lastTouchPoints = m_touchPoints; m_touchPoints.clear(); - Qt::TouchPointStates combinedStates; + QEventPoint::States combinedStates; + bool hasPressure = false; - QMutableHashIterator<int, Contact> it(m_contacts); - while (it.hasNext()) { - it.next(); + for (auto it = m_contacts.begin(), end = m_contacts.end(); it != end; /*erasing*/) { Contact &contact(it.value()); - if (!contact.state) + if (!contact.state) { + ++it; continue; + } int key = m_typeB ? it.key() : contact.trackingId; if (!m_typeB && m_lastContacts.contains(key)) { const Contact &prev(m_lastContacts.value(key)); - if (contact.state == Qt::TouchPointReleased) { + if (contact.state == QEventPoint::State::Released) { // Copy over the previous values for released points, just in case. contact.x = prev.x; contact.y = prev.y; contact.maj = prev.maj; } else { contact.state = (prev.x == contact.x && prev.y == contact.y) - ? Qt::TouchPointStationary : Qt::TouchPointMoved; + ? QEventPoint::State::Stationary : QEventPoint::State::Updated; } } // Avoid reporting a contact in released state more than once. - if (!m_typeB && contact.state == Qt::TouchPointReleased + if (!m_typeB && contact.state == QEventPoint::State::Released && !m_lastContacts.contains(key)) { - it.remove(); + it = m_contacts.erase(it); continue; } + if (contact.pressure) + hasPressure = true; + addTouchPoint(contact, &combinedStates); + ++it; } // Now look for contacts that have disappeared since the last sync. - it = m_lastContacts; - while (it.hasNext()) { - it.next(); + for (auto it = m_lastContacts.begin(), end = m_lastContacts.end(); it != end; ++it) { Contact &contact(it.value()); int key = m_typeB ? it.key() : contact.trackingId; if (m_typeB) { if (contact.trackingId != m_contacts[key].trackingId && contact.state) { - contact.state = Qt::TouchPointReleased; + contact.state = QEventPoint::State::Released; addTouchPoint(contact, &combinedStates); } } else { if (!m_contacts.contains(key)) { - contact.state = Qt::TouchPointReleased; + contact.state = QEventPoint::State::Released; addTouchPoint(contact, &combinedStates); } } } // Remove contacts that have just been reported as released. - it = m_contacts; - while (it.hasNext()) { - it.next(); + for (auto it = m_contacts.begin(), end = m_contacts.end(); it != end; /*erasing*/) { Contact &contact(it.value()); - if (!contact.state) + if (!contact.state) { + ++it; continue; + } - if (contact.state == Qt::TouchPointReleased) { - if (m_typeB) - contact.state = static_cast<Qt::TouchPointState>(0); - else - it.remove(); + if (contact.state == QEventPoint::State::Released) { + if (m_typeB) { + contact.state = QEventPoint::State::Unknown; + } else { + it = m_contacts.erase(it); + continue; + } } else { - contact.state = Qt::TouchPointStationary; + contact.state = QEventPoint::State::Stationary; } + ++it; } m_lastContacts = m_contacts; @@ -646,11 +672,8 @@ void QEvdevTouchScreenData::processInputEvent(input_event *data) m_contacts.clear(); - if (!m_touchPoints.isEmpty() && combinedStates != Qt::TouchPointStationary) + if (!m_touchPoints.isEmpty() && (hasPressure || combinedStates != QEventPoint::State::Stationary)) reportPoints(); - - if (m_filtered) - m_mutex.unlock(); } m_lastEventType = data->type; @@ -713,7 +736,7 @@ QRect QEvdevTouchScreenData::screenGeometry() const { if (m_forceToActiveWindow) { QWindow *win = QGuiApplication::focusWindow(); - return win ? QHighDpi::toNativePixels(win->geometry(), win) : QRect(); + return win ? QHighDpi::toNativeWindowGeometry(win->geometry(), win) : QRect(); } // Now it becomes tricky. Traditionally we picked the primaryScreen() @@ -721,7 +744,7 @@ QRect QEvdevTouchScreenData::screenGeometry() const // suddenly it was all broken. // // For now we only support the display configuration of the KMS/DRM - // backends of eglfs. See QTouchOutputMapping. + // backends of eglfs. See QOutputMapping. // // The good news it that once winRect refers to the correct screen // geometry in the full virtual desktop space, there is nothing else @@ -740,7 +763,7 @@ QRect QEvdevTouchScreenData::screenGeometry() const if (m_screen) screen = m_screen; } - return QHighDpi::toNativePixels(screen->geometry(), screen); + return screen ? QHighDpi::toNativePixels(screen->geometry(), screen) : QRect(); } void QEvdevTouchScreenData::reportPoints() @@ -754,7 +777,7 @@ void QEvdevTouchScreenData::reportPoints() // Map the coordinates based on the normalized position. QPA expects 'area' // to be in screen coordinates. - const int pointCount = m_touchPoints.count(); + const int pointCount = m_touchPoints.size(); for (int i = 0; i < pointCount; ++i) { QWindowSystemInterface::TouchPoint &tp(m_touchPoints[i]); @@ -772,9 +795,12 @@ void QEvdevTouchScreenData::reportPoints() // Calculate normalized pressure. if (!hw_pressure_min && !hw_pressure_max) - tp.pressure = tp.state == Qt::TouchPointReleased ? 0 : 1; + tp.pressure = tp.state == QEventPoint::State::Released ? 0 : 1; else tp.pressure = (tp.pressure - hw_pressure_min) / qreal(hw_pressure_max - hw_pressure_min); + + if (Q_UNLIKELY(qLcEvents().isDebugEnabled())) + qCDebug(qLcEvents) << "reporting" << tp; } // Let qguiapp pick the target window. @@ -815,7 +841,7 @@ void QEvdevTouchScreenHandlerThread::run() m_handler = nullptr; } -bool QEvdevTouchScreenHandlerThread::isTouchDeviceRegistered() const +bool QEvdevTouchScreenHandlerThread::isPointingDeviceRegistered() const { return m_touchDeviceRegistered; } @@ -878,7 +904,7 @@ void QEvdevTouchScreenHandlerThread::filterAndSendTouchPoints() } else { // Update our estimate for the touch rate. We're making the assumption - // that this value will be mostly accurate with the occational bump, + // that this value will be mostly accurate with the occasional bump, // so we're weighting the existing value high compared to the update. const double ratio = 0.9; m_touchRate = sqrt(m_touchRate * m_touchRate * ratio + touchDelta * touchDelta * (1.0 - ratio)); @@ -916,8 +942,8 @@ void QEvdevTouchScreenHandlerThread::filterAndSendTouchPoints() f.y.initialize(pos.y(), velocity.y()); // Make sure the first instance of a touch point we send has the // 'pressed' state. - if (tp.state != Qt::TouchPointPressed) - tp.state = Qt::TouchPointPressed; + if (tp.state != QEventPoint::State::Pressed) + tp.state = QEventPoint::State::Pressed; } tp.velocity = QVector2D(f.x.velocity() * winRect.width(), f.y.velocity() * winRect.height()); @@ -939,14 +965,14 @@ void QEvdevTouchScreenHandlerThread::filterAndSendTouchPoints() f.touchPoint = tp; // Don't store the point for future reference if it is a release. - if (tp.state != Qt::TouchPointReleased) + if (tp.state != QEventPoint::State::Released) filteredPoints[tp.id] = f; } for (QHash<int, FilteredTouchPoint>::const_iterator it = m_filteredPoints.constBegin(), end = m_filteredPoints.constEnd(); it != end; ++it) { const FilteredTouchPoint &f = it.value(); QWindowSystemInterface::TouchPoint tp = f.touchPoint; - tp.state = Qt::TouchPointReleased; + tp.state = QEventPoint::State::Released; tp.velocity = QVector2D(); points.append(tp); } @@ -960,3 +986,5 @@ void QEvdevTouchScreenHandlerThread::filterAndSendTouchPoints() QT_END_NAMESPACE + +#include "moc_qevdevtouchhandler_p.cpp" diff --git a/src/platformsupport/input/evdevtouch/qevdevtouchhandler_p.h b/src/platformsupport/input/evdevtouch/qevdevtouchhandler_p.h index 56308d0352..b7b058e8b2 100644 --- a/src/platformsupport/input/evdevtouch/qevdevtouchhandler_p.h +++ b/src/platformsupport/input/evdevtouch/qevdevtouchhandler_p.h @@ -1,42 +1,6 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com> +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QEVDEVTOUCHHANDLER_P_H #define QEVDEVTOUCHHANDLER_P_H @@ -52,10 +16,12 @@ // We mean it. // +//#include <QtGui/qpointingdevice.h> #include <QtGui/private/qtguiglobal_p.h> #include <QObject> #include <QString> #include <QList> +#include <QHash> #include <QThread> #include <QtCore/private/qthread_p.h> #include <qpa/qwindowsysteminterface.h> @@ -69,6 +35,7 @@ QT_BEGIN_NAMESPACE class QSocketNotifier; class QEvdevTouchScreenData; +class QPointingDevice; class QEvdevTouchScreenHandler : public QObject { @@ -78,7 +45,7 @@ public: explicit QEvdevTouchScreenHandler(const QString &device, const QString &spec = QString(), QObject *parent = nullptr); ~QEvdevTouchScreenHandler(); - QTouchDevice *touchDevice() const; + QPointingDevice *touchDevice() const; bool isFiltered() const; @@ -91,13 +58,13 @@ private: friend class QEvdevTouchScreenData; friend class QEvdevTouchScreenHandlerThread; - void registerTouchDevice(); - void unregisterTouchDevice(); + void registerPointingDevice(); + void unregisterPointingDevice(); QSocketNotifier *m_notify; int m_fd; QEvdevTouchScreenData *d; - QTouchDevice *m_device; + QPointingDevice *m_device; #if QT_CONFIG(mtdev) mtdev *m_mtdev; #endif @@ -111,7 +78,7 @@ public: ~QEvdevTouchScreenHandlerThread(); void run() override; - bool isTouchDeviceRegistered() const; + bool isPointingDeviceRegistered() const; bool eventFilter(QObject *object, QEvent *event) override; diff --git a/src/platformsupport/input/evdevtouch/qevdevtouchmanager.cpp b/src/platformsupport/input/evdevtouch/qevdevtouchmanager.cpp index 4cacbf03e5..f2a652c254 100644 --- a/src/platformsupport/input/evdevtouch/qevdevtouchmanager.cpp +++ b/src/platformsupport/input/evdevtouch/qevdevtouchmanager.cpp @@ -1,45 +1,11 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qevdevtouchmanager_p.h" #include "qevdevtouchhandler_p.h" +#include <QtInputSupport/private/qevdevutil_p.h> + #include <QStringList> #include <QGuiApplication> #include <QLoggingCategory> @@ -64,34 +30,23 @@ QEvdevTouchManager::QEvdevTouchManager(const QString &key, const QString &specif if (spec.isEmpty()) spec = specification; - QStringList args = spec.split(QLatin1Char(':')); - QStringList devices; - - foreach (const QString &arg, args) { - if (arg.startsWith(QLatin1String("/dev/"))) { - devices.append(arg); - args.removeAll(arg); - } - } - - // build new specification without /dev/ elements - m_spec = args.join(QLatin1Char(':')); + auto parsed = QEvdevUtil::parseSpecification(spec); + m_spec = std::move(parsed.spec); - foreach (const QString &device, devices) + for (const QString &device : std::as_const(parsed.devices)) addDevice(device); // when no devices specified, use device discovery to scan and monitor - if (devices.isEmpty()) { - qCDebug(qLcEvdevTouch) << "evdevtouch: Using device discovery"; - m_deviceDiscovery = QDeviceDiscovery::create(QDeviceDiscovery::Device_Touchpad | QDeviceDiscovery::Device_Touchscreen, this); - if (m_deviceDiscovery) { - const QStringList devices = m_deviceDiscovery->scanConnectedDevices(); + if (parsed.devices.isEmpty()) { + qCDebug(qLcEvdevTouch, "evdevtouch: Using device discovery"); + if (auto deviceDiscovery = QDeviceDiscovery::create(QDeviceDiscovery::Device_Touchpad | QDeviceDiscovery::Device_Touchscreen, this)) { + const QStringList devices = deviceDiscovery->scanConnectedDevices(); for (const QString &device : devices) addDevice(device); - connect(m_deviceDiscovery, &QDeviceDiscovery::deviceDetected, + connect(deviceDiscovery, &QDeviceDiscovery::deviceDetected, this, &QEvdevTouchManager::addDevice); - connect(m_deviceDiscovery, &QDeviceDiscovery::deviceRemoved, + connect(deviceDiscovery, &QDeviceDiscovery::deviceRemoved, this, &QEvdevTouchManager::removeDevice); } } @@ -99,30 +54,24 @@ QEvdevTouchManager::QEvdevTouchManager(const QString &key, const QString &specif QEvdevTouchManager::~QEvdevTouchManager() { - qDeleteAll(m_activeDevices); } void QEvdevTouchManager::addDevice(const QString &deviceNode) { - qCDebug(qLcEvdevTouch) << "evdevtouch: Adding device at" << deviceNode; - QEvdevTouchScreenHandlerThread *handler; - handler = new QEvdevTouchScreenHandlerThread(deviceNode, m_spec); + qCDebug(qLcEvdevTouch, "evdevtouch: Adding device at %ls", qUtf16Printable(deviceNode)); + auto handler = std::make_unique<QEvdevTouchScreenHandlerThread>(deviceNode, m_spec); if (handler) { - m_activeDevices.insert(deviceNode, handler); - connect(handler, &QEvdevTouchScreenHandlerThread::touchDeviceRegistered, this, &QEvdevTouchManager::updateInputDeviceCount); + connect(handler.get(), &QEvdevTouchScreenHandlerThread::touchDeviceRegistered, this, &QEvdevTouchManager::updateInputDeviceCount); + m_activeDevices.add(deviceNode, std::move(handler)); } else { - qWarning("evdevtouch: Failed to open touch device %s", qPrintable(deviceNode)); + qWarning("evdevtouch: Failed to open touch device %ls", qUtf16Printable(deviceNode)); } } void QEvdevTouchManager::removeDevice(const QString &deviceNode) { - if (m_activeDevices.contains(deviceNode)) { - qCDebug(qLcEvdevTouch) << "evdevtouch: Removing device at" << deviceNode; - QEvdevTouchScreenHandlerThread *handler = m_activeDevices.value(deviceNode); - m_activeDevices.remove(deviceNode); - delete handler; - + if (m_activeDevices.remove(deviceNode)) { + qCDebug(qLcEvdevTouch, "evdevtouch: Removing device at %ls", qUtf16Printable(deviceNode)); updateInputDeviceCount(); } } @@ -130,13 +79,13 @@ void QEvdevTouchManager::removeDevice(const QString &deviceNode) void QEvdevTouchManager::updateInputDeviceCount() { int registeredTouchDevices = 0; - Q_FOREACH (QEvdevTouchScreenHandlerThread *handler, m_activeDevices) { - if (handler->isTouchDeviceRegistered()) + for (const auto &device : m_activeDevices) { + if (device.handler->isPointingDeviceRegistered()) ++registeredTouchDevices; } - qCDebug(qLcEvdevTouch) << "evdevtouch: Updating QInputDeviceManager device count:" << registeredTouchDevices << " touch devices," - << m_activeDevices.count() - registeredTouchDevices << "pending handler(s)" ; + qCDebug(qLcEvdevTouch, "evdevtouch: Updating QInputDeviceManager device count: %d touch devices, %d pending handler(s)", + registeredTouchDevices, m_activeDevices.count() - registeredTouchDevices); QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount( QInputDeviceManager::DeviceTypeTouch, registeredTouchDevices); diff --git a/src/platformsupport/input/evdevtouch/qevdevtouchmanager_p.h b/src/platformsupport/input/evdevtouch/qevdevtouchmanager_p.h index e524c516f1..0bbc87ac0b 100644 --- a/src/platformsupport/input/evdevtouch/qevdevtouchmanager_p.h +++ b/src/platformsupport/input/evdevtouch/qevdevtouchmanager_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QEVDEVTOUCHMANAGER_P_H #define QEVDEVTOUCHMANAGER_P_H @@ -51,6 +15,8 @@ // We mean it. // +#include <QtInputSupport/private/devicehandlerlist_p.h> + #include <QObject> #include <QHash> #include <QSocketNotifier> @@ -63,7 +29,7 @@ class QEvdevTouchScreenHandlerThread; class QEvdevTouchManager : public QObject { public: - QEvdevTouchManager(const QString &key, const QString &spec, QObject *parent = 0); + QEvdevTouchManager(const QString &key, const QString &spec, QObject *parent = nullptr); ~QEvdevTouchManager(); void addDevice(const QString &deviceNode); @@ -73,8 +39,7 @@ public: private: QString m_spec; - QDeviceDiscovery *m_deviceDiscovery; - QHash<QString, QEvdevTouchScreenHandlerThread *> m_activeDevices; + QtInputSupport::DeviceHandlerList<QEvdevTouchScreenHandlerThread> m_activeDevices; }; QT_END_NAMESPACE diff --git a/src/platformsupport/input/input.pro b/src/platformsupport/input/input.pro deleted file mode 100644 index 3d39210b9e..0000000000 --- a/src/platformsupport/input/input.pro +++ /dev/null @@ -1,35 +0,0 @@ -TARGET = QtInputSupport -MODULE = input_support - -QT = core-private gui-private devicediscovery_support-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII -PRECOMPILED_HEADER = ../../corelib/global/qt_pch.h - -qtConfig(evdev) { - include($$PWD/evdevmouse/evdevmouse.pri) - include($$PWD/evdevkeyboard/evdevkeyboard.pri) - include($$PWD/evdevtouch/evdevtouch.pri) - qtConfig(tabletevent) { - include($$PWD/evdevtablet/evdevtablet.pri) - } -} - -qtConfig(tslib) { - include($$PWD/tslib/tslib.pri) -} - -qtConfig(libinput) { - include($$PWD/libinput/libinput.pri) -} - -qtConfig(evdev)|qtConfig(libinput) { - include($$PWD/shared/shared.pri) -} - -qtConfig(integrityhid) { - include($$PWD/integrityhid/integrityhid.pri) -} - -load(qt_module) diff --git a/src/platformsupport/input/integrityhid/integrityhid.pri b/src/platformsupport/input/integrityhid/integrityhid.pri deleted file mode 100644 index 0a6240c422..0000000000 --- a/src/platformsupport/input/integrityhid/integrityhid.pri +++ /dev/null @@ -1,7 +0,0 @@ -HEADERS += \ - $$PWD/qintegrityhidmanager.h - -SOURCES += \ - $$PWD/qintegrityhidmanager.cpp - -QMAKE_USE_PRIVATE += integrityhid diff --git a/src/platformsupport/input/integrityhid/qintegrityhidmanager.cpp b/src/platformsupport/input/integrityhid/qintegrityhidmanager.cpp index e472693077..86036d579d 100644 --- a/src/platformsupport/input/integrityhid/qintegrityhidmanager.cpp +++ b/src/platformsupport/input/integrityhid/qintegrityhidmanager.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2015 Green Hills Software -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2015 Green Hills Software +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qintegrityhidmanager.h" #include <QList> diff --git a/src/platformsupport/input/integrityhid/qintegrityhidmanager.h b/src/platformsupport/input/integrityhid/qintegrityhidmanager.h index 36d7587457..228d9ea5f3 100644 --- a/src/platformsupport/input/integrityhid/qintegrityhidmanager.h +++ b/src/platformsupport/input/integrityhid/qintegrityhidmanager.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2015 Green Hills Software -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2015 Green Hills Software +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QINTEGRITYHIDMANAGER_P_H #define QINTEGRITYHIDMANAGER_P_H @@ -52,10 +16,10 @@ class QIntegrityHIDManager : public QThread { Q_OBJECT public: - QIntegrityHIDManager(const QString &key, const QString &specification, QObject *parent = 0); + QIntegrityHIDManager(const QString &key, const QString &specification, QObject *parent = nullptr); ~QIntegrityHIDManager(); - void run(void); + void run(void) override; private: void open_devices(void); diff --git a/src/platformsupport/input/libinput/libinput.pri b/src/platformsupport/input/libinput/libinput.pri deleted file mode 100644 index 476f20c1b8..0000000000 --- a/src/platformsupport/input/libinput/libinput.pri +++ /dev/null @@ -1,17 +0,0 @@ -HEADERS += \ - $$PWD/qlibinputhandler_p.h \ - $$PWD/qlibinputpointer_p.h \ - $$PWD/qlibinputkeyboard_p.h \ - $$PWD/qlibinputtouch_p.h - -SOURCES += \ - $$PWD/qlibinputhandler.cpp \ - $$PWD/qlibinputpointer.cpp \ - $$PWD/qlibinputkeyboard.cpp \ - $$PWD/qlibinputtouch.cpp - -QMAKE_USE_PRIVATE += libudev libinput - -INCLUDEPATH += $$PWD/../shared - -qtConfig(xkbcommon): QMAKE_USE_PRIVATE += xkbcommon diff --git a/src/platformsupport/input/libinput/qlibinputhandler.cpp b/src/platformsupport/input/libinput/qlibinputhandler.cpp index e5dc182bec..ef45533f1a 100644 --- a/src/platformsupport/input/libinput/qlibinputhandler.cpp +++ b/src/platformsupport/input/libinput/qlibinputhandler.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qlibinputhandler_p.h" #include "qlibinputpointer_p.h" @@ -115,7 +79,7 @@ QLibInputHandler::QLibInputHandler(const QString &key, const QString &spec) m_touch.reset(new QLibInputTouch); QInputDeviceManager *manager = QGuiApplicationPrivate::inputDeviceManager(); - connect(manager, &QInputDeviceManager::cursorPositionChangeRequested, [this](const QPoint &pos) { + connect(manager, &QInputDeviceManager::cursorPositionChangeRequested, this, [this](const QPoint &pos) { m_pointer->setPos(pos); }); @@ -205,7 +169,14 @@ void QLibInputHandler::processEvent(libinput_event *ev) case LIBINPUT_EVENT_POINTER_MOTION: m_pointer->processMotion(libinput_event_get_pointer_event(ev)); break; + case LIBINPUT_EVENT_POINTER_MOTION_ABSOLUTE: + m_pointer->processAbsMotion(libinput_event_get_pointer_event(ev)); + break; +#if QT_CONFIG(libinput_hires_wheel_support) + case LIBINPUT_EVENT_POINTER_SCROLL_WHEEL: +#else case LIBINPUT_EVENT_POINTER_AXIS: +#endif m_pointer->processAxis(libinput_event_get_pointer_event(ev)); break; case LIBINPUT_EVENT_KEYBOARD_KEY: diff --git a/src/platformsupport/input/libinput/qlibinputhandler_p.h b/src/platformsupport/input/libinput/qlibinputhandler_p.h index ac7a267a4d..ca7926bae6 100644 --- a/src/platformsupport/input/libinput/qlibinputhandler_p.h +++ b/src/platformsupport/input/libinput/qlibinputhandler_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QLIBINPUTHANDLER_P_H #define QLIBINPUTHANDLER_P_H @@ -43,6 +7,7 @@ #include <QtCore/QObject> #include <QtCore/QScopedPointer> #include <QtCore/QMap> +#include <QtCore/private/qglobal_p.h> // // W A R N I N G diff --git a/src/platformsupport/input/libinput/qlibinputkeyboard.cpp b/src/platformsupport/input/libinput/qlibinputkeyboard.cpp index baef769bc9..25939cd510 100644 --- a/src/platformsupport/input/libinput/qlibinputkeyboard.cpp +++ b/src/platformsupport/input/libinput/qlibinputkeyboard.cpp @@ -1,44 +1,7 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qlibinputkeyboard_p.h" -#include <QtCore/QTextCodec> #include <QtCore/QLoggingCategory> #include <QtGui/private/qguiapplication_p.h> #include <QtGui/private/qinputdevicemanager_p.h> @@ -47,6 +10,7 @@ #if QT_CONFIG(xkbcommon) #include <xkbcommon/xkbcommon-keysyms.h> #include <xkbcommon/xkbcommon-names.h> +#include <QtGui/private/qxkbcommon_p.h> #endif QT_BEGIN_NAMESPACE @@ -56,88 +20,7 @@ Q_DECLARE_LOGGING_CATEGORY(qLcLibInput) const int REPEAT_DELAY = 500; const int REPEAT_RATE = 100; -#if QT_CONFIG(xkbcommon) -struct KeyTabEntry { - int xkbkey; - int qtkey; -}; - -static inline bool operator==(const KeyTabEntry &a, const KeyTabEntry &b) -{ - return a.xkbkey == b.xkbkey; -} - -static const KeyTabEntry keyTab[] = { - { XKB_KEY_Escape, Qt::Key_Escape }, - { XKB_KEY_Tab, Qt::Key_Tab }, - { XKB_KEY_ISO_Left_Tab, Qt::Key_Backtab }, - { XKB_KEY_BackSpace, Qt::Key_Backspace }, - { XKB_KEY_Return, Qt::Key_Return }, - { XKB_KEY_Insert, Qt::Key_Insert }, - { XKB_KEY_Delete, Qt::Key_Delete }, - { XKB_KEY_Clear, Qt::Key_Delete }, - { XKB_KEY_Pause, Qt::Key_Pause }, - { XKB_KEY_Print, Qt::Key_Print }, - - { XKB_KEY_Home, Qt::Key_Home }, - { XKB_KEY_End, Qt::Key_End }, - { XKB_KEY_Left, Qt::Key_Left }, - { XKB_KEY_Up, Qt::Key_Up }, - { XKB_KEY_Right, Qt::Key_Right }, - { XKB_KEY_Down, Qt::Key_Down }, - { XKB_KEY_Prior, Qt::Key_PageUp }, - { XKB_KEY_Next, Qt::Key_PageDown }, - - { XKB_KEY_Shift_L, Qt::Key_Shift }, - { XKB_KEY_Shift_R, Qt::Key_Shift }, - { XKB_KEY_Shift_Lock, Qt::Key_Shift }, - { XKB_KEY_Control_L, Qt::Key_Control }, - { XKB_KEY_Control_R, Qt::Key_Control }, - { XKB_KEY_Meta_L, Qt::Key_Meta }, - { XKB_KEY_Meta_R, Qt::Key_Meta }, - { XKB_KEY_Alt_L, Qt::Key_Alt }, - { XKB_KEY_Alt_R, Qt::Key_Alt }, - { XKB_KEY_Caps_Lock, Qt::Key_CapsLock }, - { XKB_KEY_Num_Lock, Qt::Key_NumLock }, - { XKB_KEY_Scroll_Lock, Qt::Key_ScrollLock }, - { XKB_KEY_Super_L, Qt::Key_Super_L }, - { XKB_KEY_Super_R, Qt::Key_Super_R }, - { XKB_KEY_Menu, Qt::Key_Menu }, - { XKB_KEY_Hyper_L, Qt::Key_Hyper_L }, - { XKB_KEY_Hyper_R, Qt::Key_Hyper_R }, - { XKB_KEY_Help, Qt::Key_Help }, - - { XKB_KEY_KP_Space, Qt::Key_Space }, - { XKB_KEY_KP_Tab, Qt::Key_Tab }, - { XKB_KEY_KP_Enter, Qt::Key_Enter }, - { XKB_KEY_KP_Home, Qt::Key_Home }, - { XKB_KEY_KP_Left, Qt::Key_Left }, - { XKB_KEY_KP_Up, Qt::Key_Up }, - { XKB_KEY_KP_Right, Qt::Key_Right }, - { XKB_KEY_KP_Down, Qt::Key_Down }, - { XKB_KEY_KP_Prior, Qt::Key_PageUp }, - { XKB_KEY_KP_Next, Qt::Key_PageDown }, - { XKB_KEY_KP_End, Qt::Key_End }, - { XKB_KEY_KP_Begin, Qt::Key_Clear }, - { XKB_KEY_KP_Insert, Qt::Key_Insert }, - { XKB_KEY_KP_Delete, Qt::Key_Delete }, - { XKB_KEY_KP_Equal, Qt::Key_Equal }, - { XKB_KEY_KP_Multiply, Qt::Key_Asterisk }, - { XKB_KEY_KP_Add, Qt::Key_Plus }, - { XKB_KEY_KP_Separator, Qt::Key_Comma }, - { XKB_KEY_KP_Subtract, Qt::Key_Minus }, - { XKB_KEY_KP_Decimal, Qt::Key_Period }, - { XKB_KEY_KP_Divide, Qt::Key_Slash }, -}; -#endif - QLibInputKeyboard::QLibInputKeyboard() -#if QT_CONFIG(xkbcommon) - : m_ctx(0), - m_keymap(0), - m_state(0), - m_mods(Qt::NoModifier) -#endif { #if QT_CONFIG(xkbcommon) qCDebug(qLcLibInput) << "Using xkbcommon for key mapping"; @@ -148,18 +31,14 @@ QLibInputKeyboard::QLibInputKeyboard() } m_keymap = xkb_keymap_new_from_names(m_ctx, nullptr, XKB_KEYMAP_COMPILE_NO_FLAGS); if (!m_keymap) { - qWarning("Failed to compile keymap"); + qCWarning(qLcLibInput, "Failed to compile keymap"); return; } m_state = xkb_state_new(m_keymap); if (!m_state) { - qWarning("Failed to create xkb state"); + qCWarning(qLcLibInput, "Failed to create xkb state"); return; } - m_modindex[0] = xkb_keymap_mod_get_index(m_keymap, XKB_MOD_NAME_CTRL); - m_modindex[1] = xkb_keymap_mod_get_index(m_keymap, XKB_MOD_NAME_ALT); - m_modindex[2] = xkb_keymap_mod_get_index(m_keymap, XKB_MOD_NAME_SHIFT); - m_modindex[3] = xkb_keymap_mod_get_index(m_keymap, XKB_MOD_NAME_LOGO); m_repeatTimer.setSingleShot(true); connect(&m_repeatTimer, &QTimer::timeout, this, &QLibInputKeyboard::handleRepeat); @@ -186,52 +65,33 @@ void QLibInputKeyboard::processKey(libinput_event_keyboard *e) if (!m_ctx || !m_keymap || !m_state) return; - const uint32_t k = libinput_event_keyboard_get_key(e) + 8; + const uint32_t keycode = libinput_event_keyboard_get_key(e) + 8; + const xkb_keysym_t sym = xkb_state_key_get_one_sym(m_state, keycode); const bool pressed = libinput_event_keyboard_get_key_state(e) == LIBINPUT_KEY_STATE_PRESSED; - QVarLengthArray<char, 32> chars(32); - const int size = xkb_state_key_get_utf8(m_state, k, chars.data(), chars.size()); - if (Q_UNLIKELY(size + 1 > chars.size())) { // +1 for NUL - chars.resize(size + 1); - xkb_state_key_get_utf8(m_state, k, chars.data(), chars.size()); - } - const QString text = QString::fromUtf8(chars.constData(), size); - - const xkb_keysym_t sym = xkb_state_key_get_one_sym(m_state, k); + // Modifiers here is the modifier state before the event, i.e. not + // including the current key in case it is a modifier. See the XOR + // logic in QKeyEvent::modifiers(). ### QTBUG-73826 + Qt::KeyboardModifiers modifiers = QXkbCommon::modifiers(m_state); - // mods here is the modifier state before the event, i.e. not - // including the current key in case it is a modifier. - Qt::KeyboardModifiers mods = Qt::NoModifier; - const int qtkey = keysymToQtKey(sym, &mods, text); + const QString text = QXkbCommon::lookupString(m_state, keycode); + const int qtkey = QXkbCommon::keysymToQtKey(sym, modifiers, m_state, keycode); - if (qtkey == Qt::Key_Control) - mods |= Qt::ControlModifier; - if (qtkey == Qt::Key_Alt) - mods |= Qt::AltModifier; - if (qtkey == Qt::Key_Shift) - mods |= Qt::ShiftModifier; - if (qtkey == Qt::Key_Meta) - mods |= Qt::MetaModifier; - xkb_state_update_key(m_state, k, pressed ? XKB_KEY_DOWN : XKB_KEY_UP); + xkb_state_update_key(m_state, keycode, pressed ? XKB_KEY_DOWN : XKB_KEY_UP); - if (mods != Qt::NoModifier) { - if (pressed) - m_mods |= mods; - else - m_mods &= ~mods; + Qt::KeyboardModifiers modifiersAfterStateChange = QXkbCommon::modifiers(m_state, sym); + QGuiApplicationPrivate::inputDeviceManager()->setKeyboardModifiers(modifiersAfterStateChange); - QGuiApplicationPrivate::inputDeviceManager()->setKeyboardModifiers(m_mods); - } QWindowSystemInterface::handleExtendedKeyEvent(nullptr, pressed ? QEvent::KeyPress : QEvent::KeyRelease, - qtkey, m_mods, k, sym, m_mods, text); + qtkey, modifiers, keycode, sym, modifiers, text); - if (pressed && xkb_keymap_key_repeats(m_keymap, k)) { + if (pressed && xkb_keymap_key_repeats(m_keymap, keycode)) { m_repeatData.qtkey = qtkey; - m_repeatData.mods = mods; - m_repeatData.nativeScanCode = k; + m_repeatData.mods = modifiers; + m_repeatData.nativeScanCode = keycode; m_repeatData.virtualKey = sym; - m_repeatData.nativeMods = mods; + m_repeatData.nativeMods = modifiers; m_repeatData.unicodeText = text; m_repeatData.repeatCount = 1; m_repeatTimer.setInterval(REPEAT_DELAY); @@ -256,50 +116,6 @@ void QLibInputKeyboard::handleRepeat() m_repeatTimer.setInterval(REPEAT_RATE); m_repeatTimer.start(); } - -int QLibInputKeyboard::keysymToQtKey(xkb_keysym_t key) const -{ - const size_t elemCount = sizeof(keyTab) / sizeof(KeyTabEntry); - KeyTabEntry e; - e.xkbkey = key; - const KeyTabEntry *result = std::find(keyTab, keyTab + elemCount, e); - return result != keyTab + elemCount ? result->qtkey : 0; -} - -int QLibInputKeyboard::keysymToQtKey(xkb_keysym_t keysym, Qt::KeyboardModifiers *modifiers, const QString &text) const -{ - int code = 0; -#if QT_CONFIG(textcodec) - QTextCodec *systemCodec = QTextCodec::codecForLocale(); -#endif - if (keysym < 128 || (keysym < 256 -#if QT_CONFIG(textcodec) - && systemCodec->mibEnum() == 4 -#endif - )) { - // upper-case key, if known - code = isprint((int)keysym) ? toupper((int)keysym) : 0; - } else if (keysym >= XKB_KEY_F1 && keysym <= XKB_KEY_F35) { - // function keys - code = Qt::Key_F1 + ((int)keysym - XKB_KEY_F1); - } else if (keysym >= XKB_KEY_KP_Space && keysym <= XKB_KEY_KP_9) { - if (keysym >= XKB_KEY_KP_0) { - // numeric keypad keys - code = Qt::Key_0 + ((int)keysym - XKB_KEY_KP_0); - } else { - code = keysymToQtKey(keysym); - } - *modifiers |= Qt::KeypadModifier; - } else if (text.length() == 1 && text.unicode()->unicode() > 0x1f - && text.unicode()->unicode() != 0x7f - && !(keysym >= XKB_KEY_dead_grave && keysym <= XKB_KEY_dead_longsolidusoverlay)) { - code = text.unicode()->toUpper().unicode(); - } else { - // any other keys - code = keysymToQtKey(keysym); - } - return code; -} #endif QT_END_NAMESPACE diff --git a/src/platformsupport/input/libinput/qlibinputkeyboard_p.h b/src/platformsupport/input/libinput/qlibinputkeyboard_p.h index 14ae71b545..fecbca34aa 100644 --- a/src/platformsupport/input/libinput/qlibinputkeyboard_p.h +++ b/src/platformsupport/input/libinput/qlibinputkeyboard_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QLIBINPUTKEYBOARD_P_H #define QLIBINPUTKEYBOARD_P_H @@ -79,10 +43,9 @@ private: int keysymToQtKey(xkb_keysym_t key) const; int keysymToQtKey(xkb_keysym_t keysym, Qt::KeyboardModifiers *modifiers, const QString &text) const; - xkb_context *m_ctx; - xkb_keymap *m_keymap; - xkb_state *m_state; - xkb_mod_index_t m_modindex[4]; + xkb_context *m_ctx = nullptr; + xkb_keymap *m_keymap = nullptr; + xkb_state *m_state = nullptr; QTimer m_repeatTimer; @@ -95,7 +58,6 @@ private: QString unicodeText; int repeatCount; } m_repeatData; - Qt::KeyboardModifiers m_mods; #endif }; diff --git a/src/platformsupport/input/libinput/qlibinputpointer.cpp b/src/platformsupport/input/libinput/qlibinputpointer.cpp index c54b61fc66..03351397b5 100644 --- a/src/platformsupport/input/libinput/qlibinputpointer.cpp +++ b/src/platformsupport/input/libinput/qlibinputpointer.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qlibinputpointer_p.h" #include <libinput.h> @@ -103,6 +67,24 @@ void QLibInputPointer::processMotion(libinput_event_pointer *e) Qt::NoButton, QEvent::MouseMove, mods); } +void QLibInputPointer::processAbsMotion(libinput_event_pointer *e) +{ + QScreen * const primaryScreen = QGuiApplication::primaryScreen(); + const QRect g = QHighDpi::toNativePixels(primaryScreen->virtualGeometry(), primaryScreen); + + const double x = libinput_event_pointer_get_absolute_x_transformed(e, g.width()); + const double y = libinput_event_pointer_get_absolute_y_transformed(e, g.height()); + + m_pos.setX(qBound(g.left(), qRound(g.left() + x), g.right())); + m_pos.setY(qBound(g.top(), qRound(g.top() + y), g.bottom())); + + Qt::KeyboardModifiers mods = QGuiApplicationPrivate::inputDeviceManager()->keyboardModifiers(); + + QWindowSystemInterface::handleMouseEvent(nullptr, m_pos, m_pos, m_buttons, + Qt::NoButton, QEvent::MouseMove, mods); + +} + void QLibInputPointer::processAxis(libinput_event_pointer *e) { double value; // default axis value is 15 degrees per wheel click @@ -115,16 +97,28 @@ void QLibInputPointer::processAxis(libinput_event_pointer *e) angleDelta.setX(qRound(value)); #else if (libinput_event_pointer_has_axis(e, LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL)) { +#if QT_CONFIG(libinput_hires_wheel_support) + value = libinput_event_pointer_get_scroll_value_v120(e, LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL); +#else value = libinput_event_pointer_get_axis_value(e, LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL); +#endif angleDelta.setY(qRound(value)); } if (libinput_event_pointer_has_axis(e, LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL)) { +#if QT_CONFIG(libinput_hires_wheel_support) + value = libinput_event_pointer_get_scroll_value_v120(e, LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL); +#else value = libinput_event_pointer_get_axis_value(e, LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL); +#endif angleDelta.setX(qRound(value)); } #endif - const int factor = 8; - angleDelta *= -factor; +#if QT_CONFIG(libinput_hires_wheel_support) + const int factor = -1; +#else + const int factor = -8; +#endif + angleDelta *= factor; Qt::KeyboardModifiers mods = QGuiApplicationPrivate::inputDeviceManager()->keyboardModifiers(); QWindowSystemInterface::handleWheelEvent(nullptr, m_pos, m_pos, QPoint(), angleDelta, mods); } diff --git a/src/platformsupport/input/libinput/qlibinputpointer_p.h b/src/platformsupport/input/libinput/qlibinputpointer_p.h index a7a66337f1..f1709eaa34 100644 --- a/src/platformsupport/input/libinput/qlibinputpointer_p.h +++ b/src/platformsupport/input/libinput/qlibinputpointer_p.h @@ -1,46 +1,11 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QLIBINPUTPOINTER_P_H #define QLIBINPUTPOINTER_P_H #include <QtCore/QPoint> +#include <QtCore/private/qglobal_p.h> // // W A R N I N G @@ -64,6 +29,7 @@ public: void processButton(libinput_event_pointer *e); void processMotion(libinput_event_pointer *e); + void processAbsMotion(libinput_event_pointer *e); void processAxis(libinput_event_pointer *e); void setPos(const QPoint &pos); diff --git a/src/platformsupport/input/libinput/qlibinputtouch.cpp b/src/platformsupport/input/libinput/qlibinputtouch.cpp index a65bc91c39..e3a483dc84 100644 --- a/src/platformsupport/input/libinput/qlibinputtouch.cpp +++ b/src/platformsupport/input/libinput/qlibinputtouch.cpp @@ -1,55 +1,26 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qlibinputtouch_p.h" +#include "qoutputmapping_p.h" #include <libinput.h> #include <QtGui/QGuiApplication> +#include <QtGui/QPointingDevice> #include <QtGui/QScreen> +#include <QtGui/QPointingDevice> #include <QtGui/private/qhighdpiscaling_p.h> +#include <QtGui/private/qpointingdevice_p.h> QT_BEGIN_NAMESPACE +Q_DECLARE_LOGGING_CATEGORY(qLcLibInput) +Q_LOGGING_CATEGORY(qLcLibInputEvents, "qt.qpa.input.events") + QWindowSystemInterface::TouchPoint *QLibInputTouch::DeviceState::point(int32_t slot) { const int id = qMax(0, slot); - for (int i = 0; i < m_points.count(); ++i) + for (int i = 0; i < m_points.size(); ++i) if (m_points.at(i).id == id) return &m_points[i]; @@ -62,32 +33,99 @@ QLibInputTouch::DeviceState *QLibInputTouch::deviceState(libinput_event_touch *e return &m_devState[dev]; } -static inline QPointF getPos(libinput_event_touch *e) +QRect QLibInputTouch::screenGeometry(DeviceState *state) { - // TODO Map to correct screen using QTouchOutputMapping. - // Perhaps investigate libinput_device_get_output_name as well. - // For now just use the primary screen. QScreen *screen = QGuiApplication::primaryScreen(); - const QRect geom = QHighDpi::toNativePixels(screen->geometry(), screen); + if (!state->m_screenName.isEmpty()) { + if (!m_screen) { + const QList<QScreen *> screens = QGuiApplication::screens(); + for (QScreen *s : screens) { + if (s->name() == state->m_screenName) { + m_screen = s; + break; + } + } + } + if (m_screen) + screen = m_screen; + } + return screen ? QHighDpi::toNativePixels(screen->geometry(), screen) : QRect(); +} + +QPointF QLibInputTouch::getPos(libinput_event_touch *e) +{ + DeviceState *state = deviceState(e); + QRect geom = screenGeometry(state); const double x = libinput_event_touch_get_x_transformed(e, geom.width()); const double y = libinput_event_touch_get_y_transformed(e, geom.height()); return geom.topLeft() + QPointF(x, y); } +static void setMatrix(libinput_device *dev) +{ + if (libinput_device_config_calibration_has_matrix(dev)) { + QByteArray env = qgetenv("QT_QPA_LIBINPUT_TOUCH_MATRIX"); + env = env.simplified(); + if (env.size()) { + float matrix[6]; + QList<QByteArray> list = env.split(' '); + if (list.length() != 6) { + qCWarning(qLcLibInput, "matrix length %lld wrong, should be 6", list.length()); + return; + } + for (int i = 0; i < 6; i++) { + bool ok = true; + matrix[i] = list[i].toFloat(&ok); + if (!ok) { + qCWarning(qLcLibInput, "Invalid matrix entry %d %s ", i, list[i].constData()); + return; + } + } + if (libinput_device_config_calibration_set_matrix(dev, matrix) != LIBINPUT_CONFIG_STATUS_SUCCESS) + qCWarning(qLcLibInput, "Failed to set libinput calibration matrix "); + } + } else { + qCWarning(qLcLibInput, "Touch device doesn't support matrix"); + } +} void QLibInputTouch::registerDevice(libinput_device *dev) { - QTouchDevice *&td = m_devState[dev].m_touchDevice; - td = new QTouchDevice; - td->setName(QString::fromUtf8(libinput_device_get_name(dev))); - td->setType(QTouchDevice::TouchScreen); - td->setCapabilities(QTouchDevice::Position | QTouchDevice::Area); - QWindowSystemInterface::registerTouchDevice(td); + struct udev_device *udev_device; + udev_device = libinput_device_get_udev_device(dev); + QString devNode = QString::fromUtf8(udev_device_get_devnode(udev_device)); + QString devName = QString::fromUtf8(libinput_device_get_name(dev)); + + qCDebug(qLcLibInput, "libinput: registerDevice %s - %s", + qPrintable(devNode), qPrintable(devName)); + + QOutputMapping *mapping = QOutputMapping::get(); + QRect geom; + if (mapping->load()) { + m_devState[dev].m_screenName = mapping->screenNameForDeviceNode(devNode); + if (!m_devState[dev].m_screenName.isEmpty()) { + geom = screenGeometry(&m_devState[dev]); + qCDebug(qLcLibInput) << "libinput: Mapping device" << devNode + << "to screen" << m_devState[dev].m_screenName + << "with geometry" << geom; + } + } + + QPointingDevice *&td = m_devState[dev].m_touchDevice; + td = new QPointingDevice(devName, udev_device_get_devnum(udev_device), + QInputDevice::DeviceType::TouchScreen, QPointingDevice::PointerType::Finger, + QPointingDevice::Capability::Position | QPointingDevice::Capability::Area, 16, 0); + auto devPriv = QPointingDevicePrivate::get(td); + devPriv->busId = QString::fromLocal8Bit(udev_device_get_syspath(udev_device)); // TODO is that the best to choose? + if (!geom.isNull()) + devPriv->setAvailableVirtualGeometry(geom); + QWindowSystemInterface::registerInputDevice(td); + setMatrix(dev); } void QLibInputTouch::unregisterDevice(libinput_device *dev) { Q_UNUSED(dev); - // There is no way to remove a QTouchDevice. + // There is no way to remove a QPointingDevice. } void QLibInputTouch::processTouchDown(libinput_event_touch *e) @@ -100,10 +138,11 @@ void QLibInputTouch::processTouchDown(libinput_event_touch *e) } else { QWindowSystemInterface::TouchPoint newTp; newTp.id = qMax(0, slot); - newTp.state = Qt::TouchPointPressed; + newTp.state = QEventPoint::State::Pressed; newTp.area = QRect(0, 0, 8, 8); newTp.area.moveCenter(getPos(e)); state->m_points.append(newTp); + qCDebug(qLcLibInputEvents) << "touch down" << newTp; } } @@ -113,16 +152,17 @@ void QLibInputTouch::processTouchMotion(libinput_event_touch *e) DeviceState *state = deviceState(e); QWindowSystemInterface::TouchPoint *tp = state->point(slot); if (tp) { + QEventPoint::State tmpState = QEventPoint::State::Updated; const QPointF p = getPos(e); - if (tp->area.center() != p) { + if (tp->area.center() == p) + tmpState = QEventPoint::State::Stationary; + else tp->area.moveCenter(p); - // 'down' may be followed by 'motion' within the same "frame". - // Handle this by compressing and keeping the Pressed state until the 'frame'. - if (tp->state != Qt::TouchPointPressed) - tp->state = Qt::TouchPointMoved; - } else { - tp->state = Qt::TouchPointStationary; - } + // 'down' may be followed by 'motion' within the same "frame". + // Handle this by compressing and keeping the Pressed state until the 'frame'. + if (tp->state != QEventPoint::State::Pressed && tp->state != QEventPoint::State::Released) + tp->state = tmpState; + qCDebug(qLcLibInputEvents) << "touch move" << tp; } else { qWarning("Inconsistent touch state (got 'motion' without 'down')"); } @@ -134,13 +174,16 @@ void QLibInputTouch::processTouchUp(libinput_event_touch *e) DeviceState *state = deviceState(e); QWindowSystemInterface::TouchPoint *tp = state->point(slot); if (tp) { - tp->state = Qt::TouchPointReleased; + tp->state = QEventPoint::State::Released; // There may not be a Frame event after the last Up. Work this around. - Qt::TouchPointStates s = 0; - for (int i = 0; i < state->m_points.count(); ++i) + QEventPoint::States s; + for (int i = 0; i < state->m_points.size(); ++i) s |= state->m_points.at(i).state; - if (s == Qt::TouchPointReleased) + qCDebug(qLcLibInputEvents) << "touch up" << s << tp; + if (s == QEventPoint::State::Released) processTouchFrame(e); + else + qCDebug(qLcLibInputEvents, "waiting for all points to be released"); } else { qWarning("Inconsistent touch state (got 'up' without 'down')"); } @@ -149,6 +192,7 @@ void QLibInputTouch::processTouchUp(libinput_event_touch *e) void QLibInputTouch::processTouchCancel(libinput_event_touch *e) { DeviceState *state = deviceState(e); + qCDebug(qLcLibInputEvents) << "touch cancel" << state->m_points; if (state->m_touchDevice) QWindowSystemInterface::handleTouchCancelEvent(nullptr, state->m_touchDevice, QGuiApplication::keyboardModifiers()); else @@ -162,18 +206,19 @@ void QLibInputTouch::processTouchFrame(libinput_event_touch *e) qWarning("TouchFrame without registered device"); return; } + qCDebug(qLcLibInputEvents) << "touch frame" << state->m_points; if (state->m_points.isEmpty()) return; QWindowSystemInterface::handleTouchEvent(nullptr, state->m_touchDevice, state->m_points, QGuiApplication::keyboardModifiers()); - for (int i = 0; i < state->m_points.count(); ++i) { + for (int i = 0; i < state->m_points.size(); ++i) { QWindowSystemInterface::TouchPoint &tp(state->m_points[i]); - if (tp.state == Qt::TouchPointReleased) + if (tp.state == QEventPoint::State::Released) state->m_points.removeAt(i--); - else if (tp.state == Qt::TouchPointPressed) - tp.state = Qt::TouchPointStationary; + else if (tp.state == QEventPoint::State::Pressed) + tp.state = QEventPoint::State::Stationary; } } diff --git a/src/platformsupport/input/libinput/qlibinputtouch_p.h b/src/platformsupport/input/libinput/qlibinputtouch_p.h index 6f88001d19..174795b140 100644 --- a/src/platformsupport/input/libinput/qlibinputtouch_p.h +++ b/src/platformsupport/input/libinput/qlibinputtouch_p.h @@ -1,48 +1,14 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2019 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QLIBINPUTTOUCH_P_H #define QLIBINPUTTOUCH_P_H #include <QtCore/QHash> #include <QtCore/QList> +#include <QtCore/QPointer> #include <qpa/qwindowsysteminterface.h> +#include <private/qglobal_p.h> // // W A R N I N G @@ -60,6 +26,7 @@ struct libinput_device; QT_BEGIN_NAMESPACE +class QScreen; class QLibInputTouch { public: @@ -73,15 +40,19 @@ public: private: struct DeviceState { - DeviceState() : m_touchDevice(0) { } + DeviceState() : m_touchDevice(nullptr), m_screenName() { } QWindowSystemInterface::TouchPoint *point(int32_t slot); QList<QWindowSystemInterface::TouchPoint> m_points; - QTouchDevice *m_touchDevice; + QPointingDevice *m_touchDevice; + QString m_screenName; }; DeviceState *deviceState(libinput_event_touch *e); + QRect screenGeometry(DeviceState *state); + QPointF getPos(libinput_event_touch *e); QHash<libinput_device *, DeviceState> m_devState; + mutable QPointer<QScreen> m_screen; }; QT_END_NAMESPACE diff --git a/src/platformsupport/input/shared/devicehandlerlist_p.h b/src/platformsupport/input/shared/devicehandlerlist_p.h new file mode 100644 index 0000000000..facd1946a5 --- /dev/null +++ b/src/platformsupport/input/shared/devicehandlerlist_p.h @@ -0,0 +1,60 @@ +// Copyright (C) 2019 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Marc Mutz <marc.mutz@kdab.com> +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef QTINPUTSUPPORT_DEVICEHANDLERLIST_P_H +#define QTINPUTSUPPORT_DEVICEHANDLERLIST_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include <QString> +#include <private/qglobal_p.h> + +#include <vector> +#include <memory> + +namespace QtInputSupport { + +template <typename Handler> +class DeviceHandlerList { +public: + struct Device { + QString deviceNode; + std::unique_ptr<Handler> handler; + }; + + void add(const QString &deviceNode, std::unique_ptr<Handler> handler) + { + v.push_back({deviceNode, std::move(handler)}); + } + + bool remove(const QString &deviceNode) + { + const auto deviceNodeMatches = [&] (const Device &d) { return d.deviceNode == deviceNode; }; + const auto it = std::find_if(v.cbegin(), v.cend(), deviceNodeMatches); + if (it == v.cend()) + return false; + v.erase(it); + return true; + } + + int count() const noexcept { return static_cast<int>(v.size()); } + + typename std::vector<Device>::const_iterator begin() const noexcept { return v.begin(); } + typename std::vector<Device>::const_iterator end() const noexcept { return v.end(); } + +private: + std::vector<Device> v; +}; + +} // QtInputSupport + +#endif // QTINPUTSUPPORT_DEVICEHANDLERLIST_P_H diff --git a/src/platformsupport/input/shared/qevdevutil.cpp b/src/platformsupport/input/shared/qevdevutil.cpp new file mode 100644 index 0000000000..c1ebb9ada0 --- /dev/null +++ b/src/platformsupport/input/shared/qevdevutil.cpp @@ -0,0 +1,36 @@ +// Copyright (C) 2019 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Marc Mutz <marc.mutz@kdab.com> +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qevdevutil_p.h" + +QT_BEGIN_NAMESPACE + +using namespace Qt::StringLiterals; + +namespace QEvdevUtil { + +ParsedSpecification parseSpecification(const QString &specification) +{ + ParsedSpecification result; + + result.args = QStringView{specification}.split(u':'); + + for (const auto &arg : std::as_const(result.args)) { + if (arg.startsWith("/dev/"_L1)) { + // if device is specified try to use it + result.devices.append(arg.toString()); + } else { + // build new specification without /dev/ elements + result.spec += arg + u':'; + } + } + + if (!result.spec.isEmpty()) + result.spec.chop(1); // remove trailing ':' + + return result; +} + +} // namespace QEvdevUtil + +QT_END_NAMESPACE diff --git a/src/platformsupport/input/shared/qevdevutil_p.h b/src/platformsupport/input/shared/qevdevutil_p.h new file mode 100644 index 0000000000..8533b93783 --- /dev/null +++ b/src/platformsupport/input/shared/qevdevutil_p.h @@ -0,0 +1,41 @@ +// Copyright (C) 2019 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Marc Mutz <marc.mutz@kdab.com> +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef QEVDEVUTIL_P_H +#define QEVDEVUTIL_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include <QList> +#include <QString> +#include <QStringList> +#include <QStringView> +#include <private/qglobal_p.h> + +QT_BEGIN_NAMESPACE + +namespace QEvdevUtil { + +struct ParsedSpecification +{ + QString spec; + QStringList devices; + QList<QStringView> args; +}; + +ParsedSpecification parseSpecification(const QString &specification); + +} + +QT_END_NAMESPACE + +#endif // QEVDEVUTIL_P_H diff --git a/src/platformsupport/input/shared/qoutputmapping.cpp b/src/platformsupport/input/shared/qoutputmapping.cpp new file mode 100644 index 0000000000..c8683958d3 --- /dev/null +++ b/src/platformsupport/input/shared/qoutputmapping.cpp @@ -0,0 +1,95 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qoutputmapping_p.h" +#include <QFile> +#include <QFileInfo> +#include <QVariantMap> +#include <QJsonDocument> +#include <QJsonObject> +#include <QJsonArray> + +QT_BEGIN_NAMESPACE + +using namespace Qt::StringLiterals; + +static QOutputMapping *s_outputMapping = nullptr; + +QOutputMapping *QOutputMapping::get() +{ + if (!s_outputMapping) + s_outputMapping = new QDefaultOutputMapping; + + return s_outputMapping; +} + +bool QOutputMapping::load() +{ + return false; +} + +QString QOutputMapping::screenNameForDeviceNode(const QString &deviceNode) +{ + Q_UNUSED(deviceNode); + return QString(); +} + +#ifdef Q_OS_WEBOS +QWindow *QOutputMapping::windowForDeviceNode(const QString &deviceNode) +{ + Q_UNUSED(deviceNode); + return nullptr; +} + +void QOutputMapping::set(QOutputMapping *mapping) +{ + if (s_outputMapping) + delete s_outputMapping; + + s_outputMapping = mapping; +} +#endif // Q_OS_WEBOS + +bool QDefaultOutputMapping::load() +{ + static QByteArray configFile = qgetenv("QT_QPA_EGLFS_KMS_CONFIG"); + if (configFile.isEmpty()) + return false; + + QFile file(QString::fromUtf8(configFile)); + if (!file.open(QFile::ReadOnly)) { + qWarning("touch input support: Failed to open %s", configFile.constData()); + return false; + } + + const QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); + if (!doc.isObject()) { + qWarning("touch input support: Failed to parse %s", configFile.constData()); + return false; + } + + // What we are interested is the virtualIndex and touchDevice properties for + // each element in the outputs array. + const QJsonArray outputs = doc.object().value("outputs"_L1).toArray(); + for (int i = 0; i < outputs.size(); ++i) { + const QVariantMap output = outputs.at(i).toObject().toVariantMap(); + if (!output.contains(QStringLiteral("touchDevice"))) + continue; + if (!output.contains(QStringLiteral("name"))) { + qWarning("evdevtouch: Output %d specifies touchDevice but not name, this is wrong", i); + continue; + } + QFileInfo deviceNode(output.value(QStringLiteral("touchDevice")).toString()); + const QString &screenName = output.value(QStringLiteral("name")).toString(); + m_screenTable.insert(deviceNode.canonicalFilePath(), screenName); + } + + return true; +} + +QString QDefaultOutputMapping::screenNameForDeviceNode(const QString &deviceNode) +{ + return m_screenTable.value(deviceNode); +} + +QT_END_NAMESPACE diff --git a/src/platformsupport/input/shared/qoutputmapping_p.h b/src/platformsupport/input/shared/qoutputmapping_p.h new file mode 100644 index 0000000000..b11364188d --- /dev/null +++ b/src/platformsupport/input/shared/qoutputmapping_p.h @@ -0,0 +1,53 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef QOUTPUTMAPPING_P_H +#define QOUTPUTMAPPING_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include <QString> +#include <QHash> +#include <private/qglobal_p.h> + +QT_BEGIN_NAMESPACE + +class QWindow; + +class QOutputMapping +{ +public: + virtual ~QOutputMapping() {} + + static QOutputMapping *get(); + virtual bool load(); + virtual QString screenNameForDeviceNode(const QString &deviceNode); + +#ifdef Q_OS_WEBOS + virtual QWindow *windowForDeviceNode(const QString &deviceNode); + static void set(QOutputMapping *mapping); +#endif +}; + +class QDefaultOutputMapping : public QOutputMapping +{ +public: + bool load() override; + QString screenNameForDeviceNode(const QString &deviceNode) override; + +private: + QHash<QString, QString> m_screenTable; +}; + +QT_END_NAMESPACE + +#endif // QOUTPUTMAPPING_P_H diff --git a/src/platformsupport/input/shared/qtouchoutputmapping.cpp b/src/platformsupport/input/shared/qtouchoutputmapping.cpp deleted file mode 100644 index 0a1afd4739..0000000000 --- a/src/platformsupport/input/shared/qtouchoutputmapping.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qtouchoutputmapping_p.h" -#include <QFile> -#include <QVariantMap> -#include <QJsonDocument> -#include <QJsonObject> -#include <QJsonArray> - -QT_BEGIN_NAMESPACE - -bool QTouchOutputMapping::load() -{ - static QByteArray configFile = qgetenv("QT_QPA_EGLFS_KMS_CONFIG"); - if (configFile.isEmpty()) - return false; - - QFile file(QString::fromUtf8(configFile)); - if (!file.open(QFile::ReadOnly)) { - qWarning("touch input support: Failed to open %s", configFile.constData()); - return false; - } - - const QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); - if (!doc.isObject()) { - qWarning("touch input support: Failed to parse %s", configFile.constData()); - return false; - } - - // What we are interested is the virtualIndex and touchDevice properties for - // each element in the outputs array. - const QJsonArray outputs = doc.object().value(QLatin1String("outputs")).toArray(); - for (int i = 0; i < outputs.size(); ++i) { - const QVariantMap output = outputs.at(i).toObject().toVariantMap(); - if (!output.contains(QStringLiteral("touchDevice"))) - continue; - if (!output.contains(QStringLiteral("name"))) { - qWarning("evdevtouch: Output %d specifies touchDevice but not name, this is wrong", i); - continue; - } - const QString &deviceNode = output.value(QStringLiteral("touchDevice")).toString(); - const QString &screenName = output.value(QStringLiteral("name")).toString(); - m_screenTable.insert(deviceNode, screenName); - } - - return true; -} - -QString QTouchOutputMapping::screenNameForDeviceNode(const QString &deviceNode) -{ - return m_screenTable.value(deviceNode); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/input/shared/qtouchoutputmapping_p.h b/src/platformsupport/input/shared/qtouchoutputmapping_p.h deleted file mode 100644 index 94d4dbc3b1..0000000000 --- a/src/platformsupport/input/shared/qtouchoutputmapping_p.h +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QTOUCHOUTPUTMAPPING_P_H -#define QTOUCHOUTPUTMAPPING_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QString> -#include <QHash> - -QT_BEGIN_NAMESPACE - -class QTouchOutputMapping -{ -public: - bool load(); - QString screenNameForDeviceNode(const QString &deviceNode); - -private: - QHash<QString, QString> m_screenTable; -}; - -QT_END_NAMESPACE - -#endif // QTOUCHOUTPUTMAPPING_P_H diff --git a/src/platformsupport/input/shared/shared.pri b/src/platformsupport/input/shared/shared.pri deleted file mode 100644 index 1443235244..0000000000 --- a/src/platformsupport/input/shared/shared.pri +++ /dev/null @@ -1,5 +0,0 @@ -HEADERS += \ - $$PWD/qtouchoutputmapping_p.h - -SOURCES += \ - $$PWD/qtouchoutputmapping.cpp diff --git a/src/platformsupport/input/tslib/qtslib.cpp b/src/platformsupport/input/tslib/qtslib.cpp index 7609416fea..a84cc90dc2 100644 --- a/src/platformsupport/input/tslib/qtslib.cpp +++ b/src/platformsupport/input/tslib/qtslib.cpp @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qtslib_p.h" @@ -51,44 +15,30 @@ QT_BEGIN_NAMESPACE +using namespace Qt::StringLiterals; + Q_LOGGING_CATEGORY(qLcTsLib, "qt.qpa.input") QTsLibMouseHandler::QTsLibMouseHandler(const QString &key, const QString &specification, QObject *parent) : QObject(parent), - m_notify(0), m_x(0), m_y(0), m_pressed(0), m_rawMode(false) + m_rawMode(!key.compare("TslibRaw"_L1, Qt::CaseInsensitive)) { qCDebug(qLcTsLib) << "Initializing tslib plugin" << key << specification; - setObjectName(QLatin1String("TSLib Mouse Handler")); - - QByteArray device = qgetenv("TSLIB_TSDEVICE"); - - if (specification.startsWith(QLatin1String("/dev/"))) - device = specification.toLocal8Bit(); + setObjectName("TSLib Mouse Handler"_L1); - if (device.isEmpty()) - device = QByteArrayLiteral("/dev/input/event1"); - - m_dev = ts_open(device.constData(), 1); + m_dev = ts_setup(nullptr, 1); if (!m_dev) { - qErrnoWarning(errno, "ts_open() failed"); + qErrnoWarning(errno, "ts_setup() failed"); return; } - if (ts_config(m_dev)) - qErrnoWarning(errno, "ts_config() failed"); - - m_rawMode = !key.compare(QLatin1String("TslibRaw"), Qt::CaseInsensitive); - - int fd = ts_fd(m_dev); - if (fd >= 0) { - qCDebug(qLcTsLib) << "tslib device is" << device; - m_notify = new QSocketNotifier(fd, QSocketNotifier::Read, this); - connect(m_notify, &QSocketNotifier::activated, this, &QTsLibMouseHandler::readMouseData); - } else { - qErrnoWarning(errno, "tslib: Cannot open input device %s", device.constData()); - } +#ifdef TSLIB_VERSION_EVENTPATH /* also introduced in 1.15 */ + qCDebug(qLcTsLib) << "tslib device is" << ts_get_eventpath(m_dev); +#endif + m_notify = new QSocketNotifier(ts_fd(m_dev), QSocketNotifier::Read, this); + connect(m_notify, &QSocketNotifier::activated, this, &QTsLibMouseHandler::readMouseData); } QTsLibMouseHandler::~QTsLibMouseHandler() @@ -129,9 +79,12 @@ void QTsLibMouseHandler::readMouseData() } QPoint pos(x, y); - QWindowSystemInterface::handleMouseEvent(nullptr, pos, pos, - pressed ? Qt::LeftButton : Qt::NoButton, - Qt::NoButton, QEvent::None); + Qt::MouseButton button = pressed ^ m_pressed ? Qt::LeftButton : Qt::NoButton; + Qt::MouseButtons state = pressed ? Qt::LeftButton : Qt::NoButton; + QEvent::Type type = pressed ? (m_pressed ? QEvent::MouseMove : QEvent::MouseButtonPress) + : QEvent::MouseButtonRelease; + + QWindowSystemInterface::handleMouseEvent(nullptr, pos, pos, state, button, type); m_x = x; m_y = y; @@ -140,3 +93,5 @@ void QTsLibMouseHandler::readMouseData() } QT_END_NAMESPACE + +#include "moc_qtslib_p.cpp" diff --git a/src/platformsupport/input/tslib/qtslib_p.h b/src/platformsupport/input/tslib/qtslib_p.h index 0c08fb6a3d..03514a6d5d 100644 --- a/src/platformsupport/input/tslib/qtslib_p.h +++ b/src/platformsupport/input/tslib/qtslib_p.h @@ -1,41 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2020 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QTSLIB_H #define QTSLIB_H @@ -52,6 +16,7 @@ // #include <QObject> +#include <private/qglobal_p.h> struct tsdev; @@ -64,18 +29,19 @@ class QTsLibMouseHandler : public QObject Q_OBJECT public: - QTsLibMouseHandler(const QString &key, const QString &specification, QObject *parent = 0); + QTsLibMouseHandler(const QString &key, const QString &specification, QObject *parent = nullptr); ~QTsLibMouseHandler(); private slots: void readMouseData(); private: - QSocketNotifier * m_notify; + QSocketNotifier * m_notify = nullptr; tsdev *m_dev; - int m_x, m_y; - bool m_pressed; - bool m_rawMode; + int m_x = 0; + int m_y = 0; + bool m_pressed = false; + const bool m_rawMode; }; QT_END_NAMESPACE diff --git a/src/platformsupport/input/tslib/tslib.pri b/src/platformsupport/input/tslib/tslib.pri deleted file mode 100644 index 9efd126e13..0000000000 --- a/src/platformsupport/input/tslib/tslib.pri +++ /dev/null @@ -1,7 +0,0 @@ -HEADERS += \ - $$PWD/qtslib_p.h - -SOURCES += \ - $$PWD/qtslib.cpp - -QMAKE_USE += tslib diff --git a/src/platformsupport/kmsconvenience/CMakeLists.txt b/src/platformsupport/kmsconvenience/CMakeLists.txt new file mode 100644 index 0000000000..9cd4eb1d33 --- /dev/null +++ b/src/platformsupport/kmsconvenience/CMakeLists.txt @@ -0,0 +1,23 @@ +# Copyright (C) 2022 The Qt Company Ltd. +# SPDX-License-Identifier: BSD-3-Clause + +qt_find_package(Libdrm) + +##################################################################### +## KmsSupportPrivate Module: +##################################################################### + +qt_internal_add_module(KmsSupportPrivate + CONFIG_MODULE_NAME kms_support + STATIC + INTERNAL_MODULE + SOURCES + qkmsdevice.cpp qkmsdevice_p.h + DEFINES + QT_NO_CAST_FROM_ASCII + PUBLIC_LIBRARIES + Libdrm::Libdrm + Qt::CorePrivate + Qt::GuiPrivate + NO_GENERATE_CPP_EXPORTS +) diff --git a/src/platformsupport/kmsconvenience/kmsconvenience.pro b/src/platformsupport/kmsconvenience/kmsconvenience.pro deleted file mode 100644 index 0c5a20a239..0000000000 --- a/src/platformsupport/kmsconvenience/kmsconvenience.pro +++ /dev/null @@ -1,19 +0,0 @@ -TARGET = QtKmsSupport -MODULE = kms_support - -QT = core-private gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII - -HEADERS += \ - qkmsdevice_p.h - -SOURCES += \ - qkmsdevice.cpp - -QMAKE_USE += drm - -LIBS_PRIVATE += $$QMAKE_LIBS_DYNLOAD - -load(qt_module) diff --git a/src/platformsupport/kmsconvenience/qkmsdevice.cpp b/src/platformsupport/kmsconvenience/qkmsdevice.cpp index fec59cfc7b..421e9f05c0 100644 --- a/src/platformsupport/kmsconvenience/qkmsdevice.cpp +++ b/src/platformsupport/kmsconvenience/qkmsdevice.cpp @@ -1,43 +1,7 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Copyright (C) 2016 Pelagicore AG -** Copyright (C) 2015 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2017 The Qt Company Ltd. +// Copyright (C) 2016 Pelagicore AG +// Copyright (C) 2015 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qkmsdevice_p.h" @@ -53,6 +17,8 @@ QT_BEGIN_NAMESPACE +using namespace Qt::StringLiterals; + Q_LOGGING_CATEGORY(qLcKmsDebug, "qt.qpa.eglfs.kms") enum OutputConfiguration { @@ -66,6 +32,8 @@ enum OutputConfiguration { int QKmsDevice::crtcForConnector(drmModeResPtr resources, drmModeConnectorPtr connector) { + int candidate = -1; + for (int i = 0; i < connector->count_encoders; i++) { drmModeEncoderPtr encoder = drmModeGetEncoder(m_dri_fd, connector->encoders[i]); if (!encoder) { @@ -73,19 +41,30 @@ int QKmsDevice::crtcForConnector(drmModeResPtr resources, drmModeConnectorPtr co continue; } + quint32 encoderId = encoder->encoder_id; + quint32 crtcId = encoder->crtc_id; quint32 possibleCrtcs = encoder->possible_crtcs; drmModeFreeEncoder(encoder); for (int j = 0; j < resources->count_crtcs; j++) { bool isPossible = possibleCrtcs & (1 << j); bool isAvailable = !(m_crtc_allocator & (1 << j)); - - if (isPossible && isAvailable) + // Preserve the existing CRTC -> encoder -> connector routing if + // any. It makes the initialization faster, and may be better + // since we have a very dumb picking algorithm. + bool isBestChoice = (!connector->encoder_id || + (connector->encoder_id == encoderId && + resources->crtcs[j] == crtcId)); + + if (isPossible && isAvailable && isBestChoice) { return j; + } else if (isPossible && isAvailable) { + candidate = j; + } } } - return -1; + return candidate; } static const char * const connector_type_names[] = { // must match DRM_MODE_CONNECTOR_* @@ -163,6 +142,15 @@ static bool parseModeline(const QByteArray &text, drmModeModeInfoPtr mode) return true; } +static inline void assignPlane(QKmsOutput *output, QKmsPlane *plane) +{ + if (output->eglfs_plane) + output->eglfs_plane->activeCrtcId = 0; + + plane->activeCrtcId = output->crtc_id; + output->eglfs_plane = plane; +} + QPlatformScreen *QKmsDevice::createScreenForConnector(drmModeResPtr resources, drmModeConnectorPtr connector, ScreenInfo *vinfo) @@ -212,7 +200,7 @@ QPlatformScreen *QKmsDevice::createScreenForConnector(drmModeResPtr resources, if (userConnectorConfig.contains(QStringLiteral("virtualPos"))) { const QByteArray vpos = userConnectorConfig.value(QStringLiteral("virtualPos")).toByteArray(); const QByteArrayList vposComp = vpos.split(','); - if (vposComp.count() == 2) + if (vposComp.size() == 2) vinfo->virtualPos = QPoint(vposComp[0].trimmed().toInt(), vposComp[1].trimmed().toInt()); } if (userConnectorConfig.value(QStringLiteral("primary")).toBool()) @@ -240,7 +228,7 @@ QPlatformScreen *QKmsDevice::createScreenForConnector(drmModeResPtr resources, // Get the current mode on the current crtc drmModeModeInfo crtc_mode; memset(&crtc_mode, 0, sizeof crtc_mode); - if (drmModeEncoderPtr encoder = drmModeGetEncoder(m_dri_fd, connector->connector_id)) { + if (drmModeEncoderPtr encoder = drmModeGetEncoder(m_dri_fd, connector->encoder_id)) { drmModeCrtcPtr crtc = drmModeGetCrtc(m_dri_fd, encoder->crtc_id); drmModeFreeEncoder(encoder); @@ -296,7 +284,7 @@ QPlatformScreen *QKmsDevice::createScreenForConnector(drmModeResPtr resources, if (current < 0 && crtc_mode.clock != 0) { modes << crtc_mode; - current = mode.size() - 1; + current = modes.size() - 1; } if (configuration == OutputConfigCurrent) @@ -374,30 +362,33 @@ QPlatformScreen *QKmsDevice::createScreenForConnector(drmModeResPtr resources, drmFormat = DRM_FORMAT_XRGB8888; drmFormatExplicit = false; } - qCDebug(qLcKmsDebug) << "Format is" << hex << drmFormat << dec << "requested_by_user =" << drmFormatExplicit + qCDebug(qLcKmsDebug) << "Format is" << Qt::hex << drmFormat << Qt::dec << "requested_by_user =" << drmFormatExplicit << "for output" << connectorName; const QString cloneSource = userConnectorConfig.value(QStringLiteral("clones")).toString(); if (!cloneSource.isEmpty()) qCDebug(qLcKmsDebug) << "Output" << connectorName << " clones output " << cloneSource; - const QByteArray fbsize = userConnectorConfig.value(QStringLiteral("size")).toByteArray().toLower(); QSize framebufferSize; - framebufferSize.setWidth(modes[selected_mode].hdisplay); - framebufferSize.setHeight(modes[selected_mode].vdisplay); - + bool framebufferSizeSet = false; + const QByteArray fbsize = userConnectorConfig.value(QStringLiteral("size")).toByteArray().toLower(); + if (!fbsize.isEmpty()) { + if (sscanf(fbsize.constData(), "%dx%d", &framebufferSize.rwidth(), &framebufferSize.rheight()) == 2) { #if QT_CONFIG(drm_atomic) - if (hasAtomicSupport()) { - if (sscanf(fbsize.constData(), "%dx%d", &framebufferSize.rwidth(), &framebufferSize.rheight()) != 2) { - qWarning("Framebuffer size format is invalid."); + if (hasAtomicSupport()) + framebufferSizeSet = true; +#endif + if (!framebufferSizeSet) + qWarning("Setting framebuffer size is only available with DRM atomic API"); + } else { + qWarning("Invalid framebuffer size '%s'", fbsize.constData()); } - } else { - qWarning("Setting framebuffer size is only available with DRM atomic API"); } -#else - if (fbsize.size()) - qWarning("Setting framebuffer size is only available with DRM atomic API"); -#endif + if (!framebufferSizeSet) { + framebufferSize.setWidth(modes[selected_mode].hdisplay); + framebufferSize.setHeight(modes[selected_mode].vdisplay); + } + qCDebug(qLcKmsDebug) << "Output" << connectorName << "framebuffer size is " << framebufferSize; QKmsOutput output; @@ -433,17 +424,20 @@ QPlatformScreen *QKmsDevice::createScreenForConnector(drmModeResPtr resources, #endif QString planeListStr; - for (const QKmsPlane &plane : qAsConst(m_planes)) { + for (QKmsPlane &plane : m_planes) { if (plane.possibleCrtcs & (1 << output.crtc_index)) { output.available_planes.append(plane); planeListStr.append(QString::number(plane.id)); - planeListStr.append(QLatin1Char(' ')); - if (plane.type == QKmsPlane::PrimaryPlane) - output.eglfs_plane = (QKmsPlane*)&plane; + planeListStr.append(u' '); + + // Choose the first primary plane that is not already assigned to + // another screen's associated crtc. + if (!output.eglfs_plane && plane.type == QKmsPlane::PrimaryPlane && !plane.activeCrtcId) + assignPlane(&output, &plane); } } qCDebug(qLcKmsDebug, "Output %s can use %d planes: %s", - connectorName.constData(), output.available_planes.count(), qPrintable(planeListStr)); + connectorName.constData(), int(output.available_planes.size()), qPrintable(planeListStr)); // This is for the EGLDevice/EGLStream backend. On some of those devices one // may want to target a pre-configured plane. It is probably useless for @@ -461,9 +455,11 @@ QPlatformScreen *QKmsDevice::createScreenForConnector(drmModeResPtr resources, qCDebug(qLcKmsDebug, "Forcing plane index %d, plane id %u (belongs to crtc id %u)", idx, plane->plane_id, plane->crtc_id); - for (const QKmsPlane &kmsplane : qAsConst(m_planes)) { - if (kmsplane.id == output.forced_plane_id) - output.eglfs_plane = (QKmsPlane*)&kmsplane; + for (QKmsPlane &kmsplane : m_planes) { + if (kmsplane.id == output.forced_plane_id) { + assignPlane(&output, &kmsplane); + break; + } } drmModeFreePlane(plane); @@ -474,8 +470,37 @@ QPlatformScreen *QKmsDevice::createScreenForConnector(drmModeResPtr resources, } } - if (output.eglfs_plane) - qCDebug(qLcKmsDebug, "Output eglfs plane is: %d", output.eglfs_plane->id); + // A more useful version: allows specifying "crtc_id,plane_id:crtc_id,plane_id:..." + // in order to allow overriding the plane used for a given crtc. + if (qEnvironmentVariableIsSet("QT_QPA_EGLFS_KMS_PLANES_FOR_CRTCS")) { + const QString val = qEnvironmentVariable("QT_QPA_EGLFS_KMS_PLANES_FOR_CRTCS"); + qCDebug(qLcKmsDebug, "crtc_id:plane_id override list: %s", qPrintable(val)); + const QStringList crtcPlanePairs = val.split(u':'); + for (const QString &crtcPlanePair : crtcPlanePairs) { + const QStringList values = crtcPlanePair.split(u','); + if (values.size() == 2 && uint(values[0].toInt()) == output.crtc_id) { + uint planeId = values[1].toInt(); + for (QKmsPlane &kmsplane : m_planes) { + if (kmsplane.id == planeId) { + assignPlane(&output, &kmsplane); + break; + } + } + } + } + } + + if (output.eglfs_plane) { + qCDebug(qLcKmsDebug, "Chose plane %u for output %s (crtc id %u) (may not be applicable)", + output.eglfs_plane->id, connectorName.constData(), output.crtc_id); + } + +#if QT_CONFIG(drm_atomic) + if (hasAtomicSupport() && !output.eglfs_plane) { + qCDebug(qLcKmsDebug, "No plane associated with output %s (crtc id %u) and atomic modesetting is enabled. This is bad.", + connectorName.constData(), output.crtc_id); + } +#endif m_crtc_allocator |= (1 << output.crtc_index); @@ -522,10 +547,6 @@ QKmsDevice::QKmsDevice(QKmsScreenConfig *screenConfig, const QString &path) , m_path(path) , m_dri_fd(-1) , m_has_atomic_support(false) -#if QT_CONFIG(drm_atomic) - , m_atomic_request(nullptr) - , m_previous_request(nullptr) -#endif , m_crtc_allocator(0) { if (m_path.isEmpty()) { @@ -541,7 +562,7 @@ QKmsDevice::QKmsDevice(QKmsScreenConfig *screenConfig, const QString &path) QKmsDevice::~QKmsDevice() { #if QT_CONFIG(drm_atomic) - atomicReset(); + threadLocalAtomicReset(); #endif } @@ -609,7 +630,7 @@ void QKmsDevice::createScreens() discoverPlanes(); - QVector<OrderedScreen> screens; + QList<OrderedScreen> screens; int wantedConnectorIndex = -1; bool ok; @@ -647,7 +668,7 @@ void QKmsDevice::createScreens() // The final list of screens is available, so do the second phase setup. // Hook up clone sources and targets. for (const OrderedScreen &orderedScreen : screens) { - QVector<QPlatformScreen *> screensCloningThisScreen; + QList<QPlatformScreen *> screensCloningThisScreen; for (const OrderedScreen &s : screens) { if (s.vinfo.output.clone_source == orderedScreen.vinfo.output.name) screensCloningThisScreen.append(s.screen); @@ -672,7 +693,7 @@ void QKmsDevice::createScreens() // Figure out the virtual desktop and register the screens to QPA/QGuiApplication. QPoint pos(0, 0); QList<QPlatformScreen *> siblings; - QVector<QPoint> virtualPositions; + QList<QPoint> virtualPositions; int primarySiblingIdx = -1; for (const OrderedScreen &orderedScreen : screens) { @@ -695,10 +716,11 @@ void QKmsDevice::createScreens() // virtualIndex. This is not only handy but also required since for instance // evdevtouch relies on it when performing touch device - screen mapping. if (!m_screenConfig->separateScreens()) { + qCDebug(qLcKmsDebug) << " virtual position is" << virtualPos; siblings.append(s); virtualPositions.append(virtualPos); if (orderedScreen.vinfo.isPrimary) - primarySiblingIdx = siblings.count() - 1; + primarySiblingIdx = siblings.size() - 1; } else { registerScreen(s, orderedScreen.vinfo.isPrimary, virtualPos, QList<QPlatformScreen *>() << s); } @@ -706,7 +728,7 @@ void QKmsDevice::createScreens() if (!m_screenConfig->separateScreens()) { // enable the virtual desktop - for (int i = 0; i < siblings.count(); ++i) + for (int i = 0; i < siblings.size(); ++i) registerScreen(siblings[i], i == primarySiblingIdx, virtualPositions[i], siblings); } } @@ -720,7 +742,7 @@ QPlatformScreen *QKmsDevice::createHeadlessScreen() // not all subclasses support screen cloning void QKmsDevice::registerScreenCloning(QPlatformScreen *screen, QPlatformScreen *screenThisScreenClones, - const QVector<QPlatformScreen *> &screensCloningThisScreen) + const QList<QPlatformScreen *> &screensCloningThisScreen) { Q_UNUSED(screen); Q_UNUSED(screenThisScreenClones); @@ -799,9 +821,7 @@ void QKmsDevice::discoverPlanes() for (int i = 0; i < countFormats; ++i) { uint32_t f = drmplane->formats[i]; plane.supportedFormats.append(f); - QString s; - s.sprintf("%c%c%c%c ", f, f >> 8, f >> 16, f >> 24); - formatStr += s; + formatStr += QString::asprintf("%c%c%c%c ", f, f >> 8, f >> 16, f >> 24); } qCDebug(qLcKmsDebug, "plane %d: id = %u countFormats = %d possibleCrtcs = 0x%x supported formats = %s", @@ -820,7 +840,7 @@ void QKmsDevice::discoverPlanes() plane.type = QKmsPlane::Type(value); } else if (!strcmp(prop->name, "rotation")) { plane.initialRotation = QKmsPlane::Rotations(int(value)); - plane.availableRotations = 0; + plane.availableRotations = { }; if (propTypeIs(prop, DRM_MODE_PROP_BITMASK)) { for (int i = 0; i < prop->count_enums; ++i) plane.availableRotations |= QKmsPlane::Rotation(1 << prop->enums[i].value); @@ -848,6 +868,8 @@ void QKmsDevice::discoverPlanes() plane.crtcYPropertyId = prop->prop_id; } else if (!strcasecmp(prop->name, "zpos")) { plane.zposPropertyId = prop->prop_id; + } else if (!strcasecmp(prop->name, "blend_op")) { + plane.blendOpPropertyId = prop->prop_id; } }); @@ -881,39 +903,51 @@ bool QKmsDevice::hasAtomicSupport() } #if QT_CONFIG(drm_atomic) -drmModeAtomicReq * QKmsDevice::atomic_request() +drmModeAtomicReq *QKmsDevice::threadLocalAtomicRequest() { - if (!m_atomic_request && m_has_atomic_support) - m_atomic_request = drmModeAtomicAlloc(); + if (!m_has_atomic_support) + return nullptr; - return m_atomic_request; + AtomicReqs &a(m_atomicReqs.localData()); + if (!a.request) + a.request = drmModeAtomicAlloc(); + + return a.request; } -bool QKmsDevice::atomicCommit(void *user_data) +bool QKmsDevice::threadLocalAtomicCommit(void *user_data) { - if (m_atomic_request) { - int ret = drmModeAtomicCommit(m_dri_fd, m_atomic_request, - DRM_MODE_ATOMIC_NONBLOCK | DRM_MODE_PAGE_FLIP_EVENT | DRM_MODE_ATOMIC_ALLOW_MODESET, user_data); + if (!m_has_atomic_support) + return false; - if (ret) { - qWarning("Failed to commit atomic request (code=%d)", ret); - return false; - } + AtomicReqs &a(m_atomicReqs.localData()); + if (!a.request) + return false; - m_previous_request = m_atomic_request; - m_atomic_request = nullptr; + int ret = drmModeAtomicCommit(m_dri_fd, a.request, + DRM_MODE_ATOMIC_NONBLOCK | DRM_MODE_PAGE_FLIP_EVENT | DRM_MODE_ATOMIC_ALLOW_MODESET, + user_data); - return true; + if (ret) { + qWarning("Failed to commit atomic request (code=%d)", ret); + return false; } - return false; + a.previous_request = a.request; + a.request = nullptr; + + return true; } -void QKmsDevice::atomicReset() +void QKmsDevice::threadLocalAtomicReset() { - if (m_previous_request) { - drmModeAtomicFree(m_previous_request); - m_previous_request = nullptr; + if (!m_has_atomic_support) + return; + + AtomicReqs &a(m_atomicReqs.localData()); + if (a.previous_request) { + drmModeAtomicFree(a.previous_request); + a.previous_request = nullptr; } } #endif @@ -944,7 +978,7 @@ void QKmsDevice::parseCrtcProperties(uint32_t crtcId, QKmsOutput *output) } enumerateProperties(objProps, [output](drmModePropertyPtr prop, quint64 value) { - Q_UNUSED(value) + Q_UNUSED(value); if (!strcasecmp(prop->name, "mode_id")) output->modeIdPropertyId = prop->prop_id; else if (!strcasecmp(prop->name, "active")) @@ -966,7 +1000,6 @@ QKmsScreenConfig::QKmsScreenConfig() , m_pbuffers(false) , m_virtualDesktopLayout(VirtualDesktopLayoutHorizontal) { - loadConfig(); } void QKmsScreenConfig::loadConfig() @@ -996,7 +1029,7 @@ void QKmsScreenConfig::loadConfig() const QJsonObject object = doc.object(); - const QString headlessStr = object.value(QLatin1String("headless")).toString(); + const QString headlessStr = object.value("headless"_L1).toString(); const QByteArray headless = headlessStr.toUtf8(); QSize headlessSize; if (sscanf(headless.constData(), "%dx%d", &headlessSize.rwidth(), &headlessSize.rheight()) == 2) { @@ -1006,22 +1039,22 @@ void QKmsScreenConfig::loadConfig() m_headless = false; } - m_hwCursor = object.value(QLatin1String("hwcursor")).toBool(m_hwCursor); - m_pbuffers = object.value(QLatin1String("pbuffers")).toBool(m_pbuffers); - m_devicePath = object.value(QLatin1String("device")).toString(); - m_separateScreens = object.value(QLatin1String("separateScreens")).toBool(m_separateScreens); + m_hwCursor = object.value("hwcursor"_L1).toBool(m_hwCursor); + m_pbuffers = object.value("pbuffers"_L1).toBool(m_pbuffers); + m_devicePath = object.value("device"_L1).toString(); + m_separateScreens = object.value("separateScreens"_L1).toBool(m_separateScreens); - const QString vdOriString = object.value(QLatin1String("virtualDesktopLayout")).toString(); + const QString vdOriString = object.value("virtualDesktopLayout"_L1).toString(); if (!vdOriString.isEmpty()) { - if (vdOriString == QLatin1String("horizontal")) + if (vdOriString == "horizontal"_L1) m_virtualDesktopLayout = VirtualDesktopLayoutHorizontal; - else if (vdOriString == QLatin1String("vertical")) + else if (vdOriString == "vertical"_L1) m_virtualDesktopLayout = VirtualDesktopLayoutVertical; else qCWarning(qLcKmsDebug) << "Unknown virtualDesktopOrientation value" << vdOriString; } - const QJsonArray outputs = object.value(QLatin1String("outputs")).toArray(); + const QJsonArray outputs = object.value("outputs"_L1).toArray(); for (int i = 0; i < outputs.size(); i++) { const QVariantMap outputSettings = outputs.at(i).toObject().toVariantMap(); diff --git a/src/platformsupport/kmsconvenience/qkmsdevice_p.h b/src/platformsupport/kmsconvenience/qkmsdevice_p.h index 14da6bb947..050d836cb1 100644 --- a/src/platformsupport/kmsconvenience/qkmsdevice_p.h +++ b/src/platformsupport/kmsconvenience/qkmsdevice_p.h @@ -1,43 +1,7 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Copyright (C) 2016 Pelagicore AG -** Copyright (C) 2015 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ +// Copyright (C) 2016 The Qt Company Ltd. +// Copyright (C) 2016 Pelagicore AG +// Copyright (C) 2015 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QKMSDEVICE_P_H #define QKMSDEVICE_P_H @@ -57,6 +21,7 @@ #include <qpa/qplatformscreen.h> #include <QtCore/QMap> #include <QtCore/QVariant> +#include <QtCore/QThreadStorage> #include <xf86drm.h> #include <xf86drmMode.h> @@ -65,7 +30,7 @@ #include <functional> // In less fortunate cases one may need to build on a system with dev headers -// from the dark ages. Let's pull a GL and define the missing stuff outselves. +// from the dark ages. Let's pull a GL and define the missing stuff ourselves. #ifndef DRM_PLANE_TYPE_OVERLAY #define DRM_PLANE_TYPE_OVERLAY 0 @@ -110,6 +75,7 @@ public: }; QKmsScreenConfig(); + virtual ~QKmsScreenConfig() {} QString devicePath() const { return m_devicePath; } @@ -121,10 +87,9 @@ public: VirtualDesktopLayout virtualDesktopLayout() const { return m_virtualDesktopLayout; } QMap<QString, QVariantMap> outputSettings() const { return m_outputSettings; } + virtual void loadConfig(); -private: - void loadConfig(); - +protected: QString m_devicePath; bool m_headless; QSize m_headlessSize; @@ -162,7 +127,7 @@ struct QKmsPlane int possibleCrtcs = 0; - QVector<uint32_t> supportedFormats; + QList<uint32_t> supportedFormats; Rotations initialRotation = Rotation0; Rotations availableRotations = Rotation0; @@ -178,6 +143,9 @@ struct QKmsPlane uint32_t crtcwidthPropertyId = 0; uint32_t crtcheightPropertyId = 0; uint32_t zposPropertyId = 0; + uint32_t blendOpPropertyId = 0; + + uint32_t activeCrtcId = 0; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QKmsPlane::Rotations) @@ -203,7 +171,7 @@ struct QKmsOutput uint32_t drm_format = DRM_FORMAT_XRGB8888; bool drm_format_requested_by_user = false; QString clone_source; - QVector<QKmsPlane> available_planes; + QList<QKmsPlane> available_planes; struct QKmsPlane *eglfs_plane = nullptr; QSize size; uint32_t crtcIdPropertyId = 0; @@ -238,10 +206,9 @@ public: bool hasAtomicSupport(); #if QT_CONFIG(drm_atomic) - bool atomicCommit(void *user_data); - void atomicReset(); - - drmModeAtomicReq *atomic_request(); + drmModeAtomicReq *threadLocalAtomicRequest(); + bool threadLocalAtomicCommit(void *user_data); + void threadLocalAtomicReset(); #endif void createScreens(); @@ -255,7 +222,7 @@ protected: virtual QPlatformScreen *createHeadlessScreen(); virtual void registerScreenCloning(QPlatformScreen *screen, QPlatformScreen *screenThisScreenClones, - const QVector<QPlatformScreen *> &screensCloningThisScreen); + const QList<QPlatformScreen *> &screensCloningThisScreen); virtual void registerScreen(QPlatformScreen *screen, bool isPrimary, const QPoint &virtualPos, @@ -281,12 +248,15 @@ protected: bool m_has_atomic_support; #if QT_CONFIG(drm_atomic) - drmModeAtomicReq *m_atomic_request; - drmModeAtomicReq *m_previous_request; + struct AtomicReqs { + drmModeAtomicReq *request = nullptr; + drmModeAtomicReq *previous_request = nullptr; + }; + QThreadStorage<AtomicReqs> m_atomicReqs; #endif quint32 m_crtc_allocator; - QVector<QKmsPlane> m_planes; + QList<QKmsPlane> m_planes; private: Q_DISABLE_COPY(QKmsDevice) diff --git a/src/platformsupport/linuxaccessibility/application.cpp b/src/platformsupport/linuxaccessibility/application.cpp deleted file mode 100644 index 7852e407ad..0000000000 --- a/src/platformsupport/linuxaccessibility/application.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include "application_p.h" - -#include <QtCore/qcoreapplication.h> -#include <QtDBus/qdbuspendingreply.h> -#include <qdebug.h> - -#ifndef QT_NO_ACCESSIBILITY -#include "deviceeventcontroller_adaptor.h" -#include "atspi/atspi-constants.h" - -//#define KEYBOARD_DEBUG - -QT_BEGIN_NAMESPACE - -/*! - \class QSpiApplicationAdaptor - \internal - - \brief QSpiApplicationAdaptor - - QSpiApplicationAdaptor -*/ - -QSpiApplicationAdaptor::QSpiApplicationAdaptor(const QDBusConnection &connection, QObject *parent) - : QObject(parent), dbusConnection(connection), inCapsLock(false) -{ -} - -enum QSpiKeyEventType { - QSPI_KEY_EVENT_PRESS, - QSPI_KEY_EVENT_RELEASE, - QSPI_KEY_EVENT_LAST_DEFINED -}; - -void QSpiApplicationAdaptor::sendEvents(bool active) -{ - if (active) { - qApp->installEventFilter(this); - } else { - qApp->removeEventFilter(this); - } -} - - -bool QSpiApplicationAdaptor::eventFilter(QObject *target, QEvent *event) -{ - if (!event->spontaneous()) - return false; - - switch (event->type()) { - case QEvent::WindowActivate: - emit windowActivated(target, true); - break; - case QEvent::WindowDeactivate: - emit windowActivated(target, false); - break; - case QEvent::KeyPress: - case QEvent::KeyRelease: { - QKeyEvent *keyEvent = static_cast <QKeyEvent *>(event); - QSpiDeviceEvent de; - - if (event->type() == QEvent::KeyPress) - de.type = QSPI_KEY_EVENT_PRESS; - else - de.type = QSPI_KEY_EVENT_RELEASE; - - de.id = keyEvent->nativeVirtualKey(); - de.hardwareCode = keyEvent->nativeScanCode(); - - de.timestamp = QDateTime::currentMSecsSinceEpoch(); - - if (keyEvent->key() == Qt::Key_Tab) - de.text = QStringLiteral("Tab"); - else if (keyEvent->key() == Qt::Key_Backtab) - de.text = QStringLiteral("Backtab"); - else if (keyEvent->key() == Qt::Key_Control) - de.text = QStringLiteral("Control_L"); - else if (keyEvent->key() == Qt::Key_Left) - de.text = (keyEvent->modifiers() & Qt::KeypadModifier) ? QStringLiteral("KP_Left") : QStringLiteral("Left"); - else if (keyEvent->key() == Qt::Key_Right) - de.text = (keyEvent->modifiers() & Qt::KeypadModifier) ? QStringLiteral("KP_Right") : QStringLiteral("Right"); - else if (keyEvent->key() == Qt::Key_Up) - de.text = (keyEvent->modifiers() & Qt::KeypadModifier) ? QStringLiteral("KP_Up") : QStringLiteral("Up"); - else if (keyEvent->key() == Qt::Key_Down) - de.text = (keyEvent->modifiers() & Qt::KeypadModifier) ? QStringLiteral("KP_Down") : QStringLiteral("Down"); - else if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return) - de.text = QStringLiteral("Return"); - else if (keyEvent->key() == Qt::Key_Backspace) - de.text = QStringLiteral("BackSpace"); - else if (keyEvent->key() == Qt::Key_Delete) - de.text = QStringLiteral("Delete"); - else if (keyEvent->key() == Qt::Key_PageUp) - de.text = (keyEvent->modifiers() & Qt::KeypadModifier) ? QStringLiteral("KP_Page_Up") : QStringLiteral("Page_Up"); - else if (keyEvent->key() == Qt::Key_PageDown) - de.text = (keyEvent->modifiers() & Qt::KeypadModifier) ? QStringLiteral("KP_Page_Up") : QStringLiteral("Page_Down"); - else if (keyEvent->key() == Qt::Key_Home) - de.text = (keyEvent->modifiers() & Qt::KeypadModifier) ? QStringLiteral("KP_Home") : QStringLiteral("Home"); - else if (keyEvent->key() == Qt::Key_End) - de.text = (keyEvent->modifiers() & Qt::KeypadModifier) ? QStringLiteral("KP_End") : QStringLiteral("End"); - else if (keyEvent->key() == Qt::Key_Clear && (keyEvent->modifiers() & Qt::KeypadModifier)) - de.text = QStringLiteral("KP_Begin"); // Key pad 5 - else if (keyEvent->key() == Qt::Key_Escape) - de.text = QStringLiteral("Escape"); - else if (keyEvent->key() == Qt::Key_Space) - de.text = QStringLiteral("space"); - else if (keyEvent->key() == Qt::Key_CapsLock) { - de.text = QStringLiteral("Caps_Lock"); - if (event->type() == QEvent::KeyPress) - inCapsLock = true; - else - inCapsLock = false; - } else if (keyEvent->key() == Qt::Key_NumLock) - de.text = QStringLiteral("Num_Lock"); - else if (keyEvent->key() == Qt::Key_Insert) - de.text = QStringLiteral("Insert"); - else - de.text = keyEvent->text(); - - // This is a bit dubious, Gnome uses some gtk function here. - // Long term the spec will hopefully change to just use keycodes. - de.isText = !de.text.isEmpty(); - - de.modifiers = 0; - if (!inCapsLock && keyEvent->modifiers() & Qt::ShiftModifier) - de.modifiers |= 1 << ATSPI_MODIFIER_SHIFT; - if (inCapsLock && (keyEvent->key() != Qt::Key_CapsLock)) - de.modifiers |= 1 << ATSPI_MODIFIER_SHIFTLOCK; - if ((keyEvent->modifiers() & Qt::ControlModifier) && (keyEvent->key() != Qt::Key_Control)) - de.modifiers |= 1 << ATSPI_MODIFIER_CONTROL; - if ((keyEvent->modifiers() & Qt::AltModifier) && (keyEvent->key() != Qt::Key_Alt)) - de.modifiers |= 1 << ATSPI_MODIFIER_ALT; - if ((keyEvent->modifiers() & Qt::MetaModifier) && (keyEvent->key() != Qt::Key_Meta)) - de.modifiers |= 1 << ATSPI_MODIFIER_META; - -#ifdef KEYBOARD_DEBUG - qDebug() << "Key event text:" << event->type() << de.text - << "native virtual key:" << de.id - << "hardware code/scancode:" << de.hardwareCode - << "modifiers:" << de.modifiers - << "text:" << de.text; -#endif - - QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.a11y.atspi.Registry"), - QStringLiteral("/org/a11y/atspi/registry/deviceeventcontroller"), - QStringLiteral("org.a11y.atspi.DeviceEventController"), QStringLiteral("NotifyListenersSync")); - m.setArguments(QVariantList() << QVariant::fromValue(de)); - - // FIXME: this is critical, the timeout should probably be pretty low to allow normal processing - int timeout = 100; - bool sent = dbusConnection.callWithCallback(m, this, SLOT(notifyKeyboardListenerCallback(QDBusMessage)), - SLOT(notifyKeyboardListenerError(QDBusError,QDBusMessage)), timeout); - if (sent) { - //queue the event and send it after callback - keyEvents.enqueue(QPair<QPointer<QObject>, QKeyEvent*> (QPointer<QObject>(target), copyKeyEvent(keyEvent))); - return true; - } - } - default: - break; - } - return false; -} - -QKeyEvent* QSpiApplicationAdaptor::copyKeyEvent(QKeyEvent* old) -{ - return new QKeyEvent(old->type(), old->key(), old->modifiers(), - old->nativeScanCode(), old->nativeVirtualKey(), old->nativeModifiers(), - old->text(), old->isAutoRepeat(), old->count()); -} - -void QSpiApplicationAdaptor::notifyKeyboardListenerCallback(const QDBusMessage& message) -{ - if (!keyEvents.length()) { - qWarning("QSpiApplication::notifyKeyboardListenerCallback with no queued key called"); - return; - } - Q_ASSERT(message.arguments().length() == 1); - if (message.arguments().at(0).toBool() == true) { - QPair<QPointer<QObject>, QKeyEvent*> event = keyEvents.dequeue(); - delete event.second; - } else { - QPair<QPointer<QObject>, QKeyEvent*> event = keyEvents.dequeue(); - if (event.first) - QCoreApplication::postEvent(event.first.data(), event.second); - } -} - -void QSpiApplicationAdaptor::notifyKeyboardListenerError(const QDBusError& error, const QDBusMessage& /*message*/) -{ - qWarning() << "QSpiApplication::keyEventError " << error.name() << error.message(); - while (!keyEvents.isEmpty()) { - QPair<QPointer<QObject>, QKeyEvent*> event = keyEvents.dequeue(); - if (event.first) - QCoreApplication::postEvent(event.first.data(), event.second); - } -} - -QT_END_NAMESPACE - -#endif //QT_NO_ACCESSIBILITY diff --git a/src/platformsupport/linuxaccessibility/application_p.h b/src/platformsupport/linuxaccessibility/application_p.h deleted file mode 100644 index 9c053b253c..0000000000 --- a/src/platformsupport/linuxaccessibility/application_p.h +++ /dev/null @@ -1,98 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef Q_SPI_APPLICATION_H -#define Q_SPI_APPLICATION_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qtguiglobal_p.h> -#include <QtCore/QPointer> -#include <QtCore/QQueue> -#include <QtDBus/QDBusConnection> -#include <QtGui/QAccessibleInterface> - -QT_REQUIRE_CONFIG(accessibility); - -QT_BEGIN_NAMESPACE - -/* - * Used for the root object. - * - * Uses the root object reference and reports its parent as the desktop object. - */ -class QSpiApplicationAdaptor :public QObject -{ - Q_OBJECT - -public: - QSpiApplicationAdaptor(const QDBusConnection &connection, QObject *parent); - virtual ~QSpiApplicationAdaptor() {} - void sendEvents(bool active); - -Q_SIGNALS: - void windowActivated(QObject* window, bool active); - -protected: - bool eventFilter(QObject *obj, QEvent *event); - -private Q_SLOTS: - void notifyKeyboardListenerCallback(const QDBusMessage& message); - void notifyKeyboardListenerError(const QDBusError& error, const QDBusMessage& message); - -private: - static QKeyEvent* copyKeyEvent(QKeyEvent*); - - QQueue<QPair<QPointer<QObject>, QKeyEvent*> > keyEvents; - QDBusConnection dbusConnection; - bool inCapsLock; -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/platformsupport/linuxaccessibility/atspiadaptor.cpp b/src/platformsupport/linuxaccessibility/atspiadaptor.cpp deleted file mode 100644 index 580cf0e31d..0000000000 --- a/src/platformsupport/linuxaccessibility/atspiadaptor.cpp +++ /dev/null @@ -1,2479 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "atspiadaptor_p.h" - -#include <QtGui/qwindow.h> -#include <QtGui/qguiapplication.h> -#include <qdbusmessage.h> -#include <qdbusreply.h> -#include <qclipboard.h> - -#include <QtCore/qloggingcategory.h> - -#ifndef QT_NO_ACCESSIBILITY -#include "socket_interface.h" -#include "constant_mappings_p.h" -#include <QtAccessibilitySupport/private/qaccessiblebridgeutils_p.h> - -#include "application_p.h" -/*! - \class AtSpiAdaptor - \internal - - \brief AtSpiAdaptor is the main class to forward between QAccessibleInterface and AT-SPI DBus - - AtSpiAdaptor implements the functions specified in all at-spi interfaces. - It sends notifications coming from Qt via dbus and listens to incoming dbus requests. -*/ - -QT_BEGIN_NAMESPACE - -Q_LOGGING_CATEGORY(lcAccessibilityAtspi, "qt.accessibility.atspi") -Q_LOGGING_CATEGORY(lcAccessibilityAtspiCreation, "qt.accessibility.atspi.creation") - -AtSpiAdaptor::AtSpiAdaptor(DBusConnection *connection, QObject *parent) - : QDBusVirtualObject(parent), m_dbus(connection) - , sendFocus(0) - , sendObject(0) - , sendObject_active_descendant_changed(0) - , sendObject_attributes_changed(0) - , sendObject_bounds_changed(0) - , sendObject_children_changed(0) -// , sendObject_children_changed_add(0) -// , sendObject_children_changed_remove(0) - , sendObject_column_deleted(0) - , sendObject_column_inserted(0) - , sendObject_column_reordered(0) - , sendObject_link_selected(0) - , sendObject_model_changed(0) - , sendObject_property_change(0) - , sendObject_property_change_accessible_description(0) - , sendObject_property_change_accessible_name(0) - , sendObject_property_change_accessible_parent(0) - , sendObject_property_change_accessible_role(0) - , sendObject_property_change_accessible_table_caption(0) - , sendObject_property_change_accessible_table_column_description(0) - , sendObject_property_change_accessible_table_column_header(0) - , sendObject_property_change_accessible_table_row_description(0) - , sendObject_property_change_accessible_table_row_header(0) - , sendObject_property_change_accessible_table_summary(0) - , sendObject_property_change_accessible_value(0) - , sendObject_row_deleted(0) - , sendObject_row_inserted(0) - , sendObject_row_reordered(0) - , sendObject_selection_changed(0) - , sendObject_state_changed(0) - , sendObject_text_attributes_changed(0) - , sendObject_text_bounds_changed(0) - , sendObject_text_caret_moved(0) - , sendObject_text_changed(0) -// , sendObject_text_changed_delete(0) -// , sendObject_text_changed_insert(0) - , sendObject_text_selection_changed(0) - , sendObject_value_changed(0) - , sendObject_visible_data_changed(0) - , sendWindow(0) - , sendWindow_activate(0) - , sendWindow_close(0) - , sendWindow_create(0) - , sendWindow_deactivate(0) -// , sendWindow_desktop_create(0) -// , sendWindow_desktop_destroy(0) - , sendWindow_lower(0) - , sendWindow_maximize(0) - , sendWindow_minimize(0) - , sendWindow_move(0) - , sendWindow_raise(0) - , sendWindow_reparent(0) - , sendWindow_resize(0) - , sendWindow_restore(0) - , sendWindow_restyle(0) - , sendWindow_shade(0) - , sendWindow_unshade(0) -{ - m_applicationAdaptor = new QSpiApplicationAdaptor(m_dbus->connection(), this); - connect(m_applicationAdaptor, SIGNAL(windowActivated(QObject*,bool)), this, SLOT(windowActivated(QObject*,bool))); - - updateEventListeners(); - bool success = m_dbus->connection().connect(QLatin1String("org.a11y.atspi.Registry"), QLatin1String("/org/a11y/atspi/registry"), - QLatin1String("org.a11y.atspi.Registry"), QLatin1String("EventListenerRegistered"), this, - SLOT(eventListenerRegistered(QString,QString))); - success = success && m_dbus->connection().connect(QLatin1String("org.a11y.atspi.Registry"), QLatin1String("/org/a11y/atspi/registry"), - QLatin1String("org.a11y.atspi.Registry"), QLatin1String("EventListenerDeregistered"), this, - SLOT(eventListenerDeregistered(QString,QString))); -} - -AtSpiAdaptor::~AtSpiAdaptor() -{ -} - -/*! - Provide DBus introspection. - */ -QString AtSpiAdaptor::introspect(const QString &path) const -{ - static const QLatin1String accessibleIntrospection( - " <interface name=\"org.a11y.atspi.Accessible\">\n" - " <property access=\"read\" type=\"s\" name=\"Name\"/>\n" - " <property access=\"read\" type=\"s\" name=\"Description\"/>\n" - " <property access=\"read\" type=\"(so)\" name=\"Parent\">\n" - " <annotation value=\"QSpiObjectReference\" name=\"org.qtproject.QtDBus.QtTypeName\"/>\n" - " </property>\n" - " <property access=\"read\" type=\"i\" name=\"ChildCount\"/>\n" - " <method name=\"GetChildAtIndex\">\n" - " <arg direction=\"in\" type=\"i\" name=\"index\"/>\n" - " <arg direction=\"out\" type=\"(so)\"/>\n" - " <annotation value=\"QSpiObjectReference\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetChildren\">\n" - " <arg direction=\"out\" type=\"a(so)\"/>\n" - " <annotation value=\"QSpiObjectReferenceArray\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetIndexInParent\">\n" - " <arg direction=\"out\" type=\"i\"/>\n" - " </method>\n" - " <method name=\"GetRelationSet\">\n" - " <arg direction=\"out\" type=\"a(ua(so))\"/>\n" - " <annotation value=\"QSpiRelationArray\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetRole\">\n" - " <arg direction=\"out\" type=\"u\"/>\n" - " </method>\n" - " <method name=\"GetRoleName\">\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " </method>\n" - " <method name=\"GetLocalizedRoleName\">\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " </method>\n" - " <method name=\"GetState\">\n" - " <arg direction=\"out\" type=\"au\"/>\n" - " <annotation value=\"QSpiUIntList\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetAttributes\">\n" - " <arg direction=\"out\" type=\"a{ss}\"/>\n" - " <annotation value=\"QSpiAttributeSet\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetApplication\">\n" - " <arg direction=\"out\" type=\"(so)\"/>\n" - " <annotation value=\"QSpiObjectReference\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " </interface>\n" - ); - - static const QLatin1String actionIntrospection( - " <interface name=\"org.a11y.atspi.Action\">\n" - " <property access=\"read\" type=\"i\" name=\"NActions\"/>\n" - " <method name=\"GetDescription\">\n" - " <arg direction=\"in\" type=\"i\" name=\"index\"/>\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " </method>\n" - " <method name=\"GetName\">\n" - " <arg direction=\"in\" type=\"i\" name=\"index\"/>\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " </method>\n" - " <method name=\"GetKeyBinding\">\n" - " <arg direction=\"in\" type=\"i\" name=\"index\"/>\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " </method>\n" - " <method name=\"GetActions\">\n" - " <arg direction=\"out\" type=\"a(sss)\" name=\"index\"/>\n" - " <annotation value=\"QSpiActionArray\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"DoAction\">\n" - " <arg direction=\"in\" type=\"i\" name=\"index\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " </interface>\n" - ); - - static const QLatin1String applicationIntrospection( - " <interface name=\"org.a11y.atspi.Application\">\n" - " <property access=\"read\" type=\"s\" name=\"ToolkitName\"/>\n" - " <property access=\"read\" type=\"s\" name=\"Version\"/>\n" - " <property access=\"readwrite\" type=\"i\" name=\"Id\"/>\n" - " <method name=\"GetLocale\">\n" - " <arg direction=\"in\" type=\"u\" name=\"lctype\"/>\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " </method>\n" - " <method name=\"GetApplicationBusAddress\">\n" - " <arg direction=\"out\" type=\"s\" name=\"address\"/>\n" - " </method>\n" - " </interface>\n" - ); - - static const QLatin1String componentIntrospection( - " <interface name=\"org.a11y.atspi.Component\">\n" - " <method name=\"Contains\">\n" - " <arg direction=\"in\" type=\"i\" name=\"x\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"y\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"coord_type\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"GetAccessibleAtPoint\">\n" - " <arg direction=\"in\" type=\"i\" name=\"x\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"y\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"coord_type\"/>\n" - " <arg direction=\"out\" type=\"(so)\"/>\n" - " <annotation value=\"QSpiObjectReference\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetExtents\">\n" - " <arg direction=\"in\" type=\"u\" name=\"coord_type\"/>\n" - " <arg direction=\"out\" type=\"(iiii)\"/>\n" - " <annotation value=\"QSpiRect\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetPosition\">\n" - " <arg direction=\"in\" type=\"u\" name=\"coord_type\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"x\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"y\"/>\n" - " </method>\n" - " <method name=\"GetSize\">\n" - " <arg direction=\"out\" type=\"i\" name=\"width\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"height\"/>\n" - " </method>\n" - " <method name=\"GetLayer\">\n" - " <arg direction=\"out\" type=\"u\"/>\n" - " </method>\n" - " <method name=\"GetMDIZOrder\">\n" - " <arg direction=\"out\" type=\"n\"/>\n" - " </method>\n" - " <method name=\"GrabFocus\">\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"GetAlpha\">\n" - " <arg direction=\"out\" type=\"d\"/>\n" - " </method>\n" - " <method name=\"SetExtents\">\n" - " <arg direction=\"in\" type=\"i\" name=\"x\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"y\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"width\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"height\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"coord_type\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"SetPosition\">\n" - " <arg direction=\"in\" type=\"i\" name=\"x\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"y\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"coord_type\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"SetSize\">\n" - " <arg direction=\"in\" type=\"i\" name=\"width\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"height\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " </interface>\n" - ); - - static const QLatin1String editableTextIntrospection( - " <interface name=\"org.a11y.atspi.EditableText\">\n" - " <method name=\"SetTextContents\">\n" - " <arg direction=\"in\" type=\"s\" name=\"newContents\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"InsertText\">\n" - " <arg direction=\"in\" type=\"i\" name=\"position\"/>\n" - " <arg direction=\"in\" type=\"s\" name=\"text\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"length\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"CopyText\">\n" - " <arg direction=\"in\" type=\"i\" name=\"startPos\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"endPos\"/>\n" - " </method>\n" - " <method name=\"CutText\">\n" - " <arg direction=\"in\" type=\"i\" name=\"startPos\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"endPos\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"DeleteText\">\n" - " <arg direction=\"in\" type=\"i\" name=\"startPos\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"endPos\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"PasteText\">\n" - " <arg direction=\"in\" type=\"i\" name=\"position\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " </interface>\n" - ); - - static const QLatin1String tableIntrospection( - " <interface name=\"org.a11y.atspi.Table\">\n" - " <property access=\"read\" type=\"i\" name=\"NRows\"/>\n" - " <property access=\"read\" type=\"i\" name=\"NColumns\"/>\n" - " <property access=\"read\" type=\"(so)\" name=\"Caption\">\n" - " <annotation value=\"QSpiObjectReference\" name=\"org.qtproject.QtDBus.QtTypeName\"/>\n" - " </property>\n" - " <property access=\"read\" type=\"(so)\" name=\"Summary\">\n" - " <annotation value=\"QSpiObjectReference\" name=\"org.qtproject.QtDBus.QtTypeName\"/>\n" - " </property>\n" - " <property access=\"read\" type=\"i\" name=\"NSelectedRows\"/>\n" - " <property access=\"read\" type=\"i\" name=\"NSelectedColumns\"/>\n" - " <method name=\"GetAccessibleAt\">\n" - " <arg direction=\"in\" type=\"i\" name=\"row\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"column\"/>\n" - " <arg direction=\"out\" type=\"(so)\"/>\n" - " <annotation value=\"QSpiObjectReference\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetIndexAt\">\n" - " <arg direction=\"in\" type=\"i\" name=\"row\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"column\"/>\n" - " <arg direction=\"out\" type=\"i\"/>\n" - " </method>\n" - " <method name=\"GetRowAtIndex\">\n" - " <arg direction=\"in\" type=\"i\" name=\"index\"/>\n" - " <arg direction=\"out\" type=\"i\"/>\n" - " </method>\n" - " <method name=\"GetColumnAtIndex\">\n" - " <arg direction=\"in\" type=\"i\" name=\"index\"/>\n" - " <arg direction=\"out\" type=\"i\"/>\n" - " </method>\n" - " <method name=\"GetRowDescription\">\n" - " <arg direction=\"in\" type=\"i\" name=\"row\"/>\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " </method>\n" - " <method name=\"GetColumnDescription\">\n" - " <arg direction=\"in\" type=\"i\" name=\"column\"/>\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " </method>\n" - " <method name=\"GetRowExtentAt\">\n" - " <arg direction=\"in\" type=\"i\" name=\"row\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"column\"/>\n" - " <arg direction=\"out\" type=\"i\"/>\n" - " </method>\n" - " <method name=\"GetColumnExtentAt\">\n" - " <arg direction=\"in\" type=\"i\" name=\"row\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"column\"/>\n" - " <arg direction=\"out\" type=\"i\"/>\n" - " </method>\n" - " <method name=\"GetRowHeader\">\n" - " <arg direction=\"in\" type=\"i\" name=\"row\"/>\n" - " <arg direction=\"out\" type=\"(so)\"/>\n" - " <annotation value=\"QSpiObjectReference\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetColumnHeader\">\n" - " <arg direction=\"in\" type=\"i\" name=\"column\"/>\n" - " <arg direction=\"out\" type=\"(so)\"/>\n" - " <annotation value=\"QSpiObjectReference\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetSelectedRows\">\n" - " <arg direction=\"out\" type=\"ai\"/>\n" - " <annotation value=\"QSpiIntList\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetSelectedColumns\">\n" - " <arg direction=\"out\" type=\"ai\"/>\n" - " <annotation value=\"QSpiIntList\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"IsRowSelected\">\n" - " <arg direction=\"in\" type=\"i\" name=\"row\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"IsColumnSelected\">\n" - " <arg direction=\"in\" type=\"i\" name=\"column\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"IsSelected\">\n" - " <arg direction=\"in\" type=\"i\" name=\"row\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"column\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"AddRowSelection\">\n" - " <arg direction=\"in\" type=\"i\" name=\"row\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"AddColumnSelection\">\n" - " <arg direction=\"in\" type=\"i\" name=\"column\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"RemoveRowSelection\">\n" - " <arg direction=\"in\" type=\"i\" name=\"row\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"RemoveColumnSelection\">\n" - " <arg direction=\"in\" type=\"i\" name=\"column\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"GetRowColumnExtentsAtIndex\">\n" - " <arg direction=\"in\" type=\"i\" name=\"index\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"row\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"col\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"row_extents\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"col_extents\"/>\n" - " <arg direction=\"out\" type=\"b\" name=\"is_selected\"/>\n" - " </method>\n" - " </interface>\n" - ); - - static const QLatin1String textIntrospection( - " <interface name=\"org.a11y.atspi.Text\">\n" - " <property access=\"read\" type=\"i\" name=\"CharacterCount\"/>\n" - " <property access=\"read\" type=\"i\" name=\"CaretOffset\"/>\n" - " <method name=\"GetText\">\n" - " <arg direction=\"in\" type=\"i\" name=\"startOffset\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"endOffset\"/>\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " </method>\n" - " <method name=\"SetCaretOffset\">\n" - " <arg direction=\"in\" type=\"i\" name=\"offset\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"GetTextBeforeOffset\">\n" - " <arg direction=\"in\" type=\"i\" name=\"offset\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"type\"/>\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"startOffset\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"endOffset\"/>\n" - " </method>\n" - " <method name=\"GetTextAtOffset\">\n" - " <arg direction=\"in\" type=\"i\" name=\"offset\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"type\"/>\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"startOffset\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"endOffset\"/>\n" - " </method>\n" - " <method name=\"GetTextAfterOffset\">\n" - " <arg direction=\"in\" type=\"i\" name=\"offset\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"type\"/>\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"startOffset\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"endOffset\"/>\n" - " </method>\n" - " <method name=\"GetCharacterAtOffset\">\n" - " <arg direction=\"in\" type=\"i\" name=\"offset\"/>\n" - " <arg direction=\"out\" type=\"i\"/>\n" - " </method>\n" - " <method name=\"GetAttributeValue\">\n" - " <arg direction=\"in\" type=\"i\" name=\"offset\"/>\n" - " <arg direction=\"in\" type=\"s\" name=\"attributeName\"/>\n" - " <arg direction=\"out\" type=\"s\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"startOffset\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"endOffset\"/>\n" - " <arg direction=\"out\" type=\"b\" name=\"defined\"/>\n" - " </method>\n" - " <method name=\"GetAttributes\">\n" - " <arg direction=\"in\" type=\"i\" name=\"offset\"/>\n" - " <arg direction=\"out\" type=\"a{ss}\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"startOffset\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"endOffset\"/>\n" - " <annotation value=\"QSpiAttributeSet\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetDefaultAttributes\">\n" - " <arg direction=\"out\" type=\"a{ss}\"/>\n" - " <annotation value=\"QSpiAttributeSet\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetCharacterExtents\">\n" - " <arg direction=\"in\" type=\"i\" name=\"offset\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"x\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"y\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"width\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"height\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"coordType\"/>\n" - " </method>\n" - " <method name=\"GetOffsetAtPoint\">\n" - " <arg direction=\"in\" type=\"i\" name=\"x\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"y\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"coordType\"/>\n" - " <arg direction=\"out\" type=\"i\"/>\n" - " </method>\n" - " <method name=\"GetNSelections\">\n" - " <arg direction=\"out\" type=\"i\"/>\n" - " <method name=\"GetSelection\">\n" - " <arg direction=\"in\" type=\"i\" name=\"selectionNum\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"startOffset\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"endOffset\"/>\n" - " </method>\n" - " <method name=\"AddSelection\">\n" - " <arg direction=\"in\" type=\"i\" name=\"startOffset\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"endOffset\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"RemoveSelection\">\n" - " <arg direction=\"in\" type=\"i\" name=\"selectionNum\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"SetSelection\">\n" - " <arg direction=\"in\" type=\"i\" name=\"selectionNum\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"startOffset\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"endOffset\"/>\n" - " <arg direction=\"out\" type=\"b\"/>\n" - " </method>\n" - " <method name=\"GetRangeExtents\">\n" - " <arg direction=\"in\" type=\"i\" name=\"startOffset\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"endOffset\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"x\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"y\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"width\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"height\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"coordType\"/>\n" - " </method>\n" - " <method name=\"GetBoundedRanges\">\n" - " <arg direction=\"in\" type=\"i\" name=\"x\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"y\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"width\"/>\n" - " <arg direction=\"in\" type=\"i\" name=\"height\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"coordType\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"xClipType\"/>\n" - " <arg direction=\"in\" type=\"u\" name=\"yClipType\"/>\n" - " <arg direction=\"out\" type=\"a(iisv)\"/>\n" - " <annotation value=\"QSpiRangeList\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetAttributeRun\">\n" - " <arg direction=\"in\" type=\"i\" name=\"offset\"/>\n" - " <arg direction=\"in\" type=\"b\" name=\"includeDefaults\"/>\n" - " <arg direction=\"out\" type=\"a{ss}\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"startOffset\"/>\n" - " <arg direction=\"out\" type=\"i\" name=\"endOffset\"/>\n" - " <annotation value=\"QSpiAttributeSet\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " <method name=\"GetDefaultAttributeSet\">\n" - " <arg direction=\"out\" type=\"a{ss}\"/>\n" - " <annotation value=\"QSpiAttributeSet\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" - " </method>\n" - " </interface>\n" - ); - - static const QLatin1String valueIntrospection( - " <interface name=\"org.a11y.atspi.Value\">\n" - " <property access=\"read\" type=\"d\" name=\"MinimumValue\"/>\n" - " <property access=\"read\" type=\"d\" name=\"MaximumValue\"/>\n" - " <property access=\"read\" type=\"d\" name=\"MinimumIncrement\"/>\n" - " <property access=\"readwrite\" type=\"d\" name=\"CurrentValue\"/>\n" - " <method name=\"SetCurrentValue\">\n" - " <arg direction=\"in\" type=\"d\" name=\"value\"/>\n" - " </method>\n" - " </interface>\n" - ); - - QAccessibleInterface * interface = interfaceFromPath(path); - if (!interface) { - qCDebug(lcAccessibilityAtspi) << "WARNING Qt AtSpiAdaptor: Could not find accessible on path: " << path; - return QString(); - } - - QStringList interfaces = accessibleInterfaces(interface); - - QString xml; - xml.append(accessibleIntrospection); - - if (interfaces.contains(QLatin1String(ATSPI_DBUS_INTERFACE_COMPONENT))) - xml.append(componentIntrospection); - if (interfaces.contains(QLatin1String(ATSPI_DBUS_INTERFACE_TEXT))) - xml.append(textIntrospection); - if (interfaces.contains(QLatin1String(ATSPI_DBUS_INTERFACE_EDITABLE_TEXT))) - xml.append(editableTextIntrospection); - if (interfaces.contains(QLatin1String(ATSPI_DBUS_INTERFACE_ACTION))) - xml.append(actionIntrospection); - if (interfaces.contains(QLatin1String(ATSPI_DBUS_INTERFACE_TABLE))) - xml.append(tableIntrospection); - if (interfaces.contains(QLatin1String(ATSPI_DBUS_INTERFACE_VALUE))) - xml.append(valueIntrospection); - if (path == QLatin1String(QSPI_OBJECT_PATH_ROOT)) - xml.append(applicationIntrospection); - - return xml; -} - -void AtSpiAdaptor::setBitFlag(const QString &flag) -{ - Q_ASSERT(flag.size()); - - // assume we don't get nonsense - look at first letter only - switch (flag.at(0).toLower().toLatin1()) { - case 'o': { - if (flag.size() <= 8) { // Object:: - sendObject = 1; - } else { // Object:Foo:Bar - QString right = flag.mid(7); - if (false) { - } else if (right.startsWith(QLatin1String("ActiveDescendantChanged"))) { - sendObject_active_descendant_changed = 1; - } else if (right.startsWith(QLatin1String("AttributesChanged"))) { - sendObject_attributes_changed = 1; - } else if (right.startsWith(QLatin1String("BoundsChanged"))) { - sendObject_bounds_changed = 1; - } else if (right.startsWith(QLatin1String("ChildrenChanged"))) { - sendObject_children_changed = 1; - } else if (right.startsWith(QLatin1String("ColumnDeleted"))) { - sendObject_column_deleted = 1; - } else if (right.startsWith(QLatin1String("ColumnInserted"))) { - sendObject_column_inserted = 1; - } else if (right.startsWith(QLatin1String("ColumnReordered"))) { - sendObject_column_reordered = 1; - } else if (right.startsWith(QLatin1String("LinkSelected"))) { - sendObject_link_selected = 1; - } else if (right.startsWith(QLatin1String("ModelChanged"))) { - sendObject_model_changed = 1; - } else if (right.startsWith(QLatin1String("PropertyChange"))) { - if (right == QLatin1String("PropertyChange:AccessibleDescription")) { - sendObject_property_change_accessible_description = 1; - } else if (right == QLatin1String("PropertyChange:AccessibleName")) { - sendObject_property_change_accessible_name = 1; - } else if (right == QLatin1String("PropertyChange:AccessibleParent")) { - sendObject_property_change_accessible_parent = 1; - } else if (right == QLatin1String("PropertyChange:AccessibleRole")) { - sendObject_property_change_accessible_role = 1; - } else if (right == QLatin1String("PropertyChange:TableCaption")) { - sendObject_property_change_accessible_table_caption = 1; - } else if (right == QLatin1String("PropertyChange:TableColumnDescription")) { - sendObject_property_change_accessible_table_column_description = 1; - } else if (right == QLatin1String("PropertyChange:TableColumnHeader")) { - sendObject_property_change_accessible_table_column_header = 1; - } else if (right == QLatin1String("PropertyChange:TableRowDescription")) { - sendObject_property_change_accessible_table_row_description = 1; - } else if (right == QLatin1String("PropertyChange:TableRowHeader")) { - sendObject_property_change_accessible_table_row_header = 1; - } else if (right == QLatin1String("PropertyChange:TableSummary")) { - sendObject_property_change_accessible_table_summary = 1; - } else if (right == QLatin1String("PropertyChange:AccessibleValue")) { - sendObject_property_change_accessible_value = 1; - } else { - sendObject_property_change = 1; - } - } else if (right.startsWith(QLatin1String("RowDeleted"))) { - sendObject_row_deleted = 1; - } else if (right.startsWith(QLatin1String("RowInserted"))) { - sendObject_row_inserted = 1; - } else if (right.startsWith(QLatin1String("RowReordered"))) { - sendObject_row_reordered = 1; - } else if (right.startsWith(QLatin1String("SelectionChanged"))) { - sendObject_selection_changed = 1; - } else if (right.startsWith(QLatin1String("StateChanged"))) { - sendObject_state_changed = 1; - } else if (right.startsWith(QLatin1String("TextAttributesChanged"))) { - sendObject_text_attributes_changed = 1; - } else if (right.startsWith(QLatin1String("TextBoundsChanged"))) { - sendObject_text_bounds_changed = 1; - } else if (right.startsWith(QLatin1String("TextCaretMoved"))) { - sendObject_text_caret_moved = 1; - } else if (right.startsWith(QLatin1String("TextChanged"))) { - sendObject_text_changed = 1; - } else if (right.startsWith(QLatin1String("TextSelectionChanged"))) { - sendObject_text_selection_changed = 1; - } else if (right.startsWith(QLatin1String("ValueChanged"))) { - sendObject_value_changed = 1; - } else if (right.startsWith(QLatin1String("VisibleDataChanged")) - || right.startsWith(QLatin1String("VisibledataChanged"))) { // typo in libatspi - sendObject_visible_data_changed = 1; - } else { - qCDebug(lcAccessibilityAtspi) << "WARNING: subscription string not handled:" << flag; - } - } - break; - } - case 'w': { // window - if (flag.size() <= 8) { - sendWindow = 1; - } else { // object:Foo:Bar - QString right = flag.mid(7); - if (false) { - } else if (right.startsWith(QLatin1String("Activate"))) { - sendWindow_activate = 1; - } else if (right.startsWith(QLatin1String("Close"))) { - sendWindow_close= 1; - } else if (right.startsWith(QLatin1String("Create"))) { - sendWindow_create = 1; - } else if (right.startsWith(QLatin1String("Deactivate"))) { - sendWindow_deactivate = 1; - } else if (right.startsWith(QLatin1String("Lower"))) { - sendWindow_lower = 1; - } else if (right.startsWith(QLatin1String("Maximize"))) { - sendWindow_maximize = 1; - } else if (right.startsWith(QLatin1String("Minimize"))) { - sendWindow_minimize = 1; - } else if (right.startsWith(QLatin1String("Move"))) { - sendWindow_move = 1; - } else if (right.startsWith(QLatin1String("Raise"))) { - sendWindow_raise = 1; - } else if (right.startsWith(QLatin1String("Reparent"))) { - sendWindow_reparent = 1; - } else if (right.startsWith(QLatin1String("Resize"))) { - sendWindow_resize = 1; - } else if (right.startsWith(QLatin1String("Restore"))) { - sendWindow_restore = 1; - } else if (right.startsWith(QLatin1String("Restyle"))) { - sendWindow_restyle = 1; - } else if (right.startsWith(QLatin1String("Shade"))) { - sendWindow_shade = 1; - } else if (right.startsWith(QLatin1String("Unshade"))) { - sendWindow_unshade = 1; - } else if (right.startsWith(QLatin1String("DesktopCreate"))) { - // ignore this one - } else if (right.startsWith(QLatin1String("DesktopDestroy"))) { - // ignore this one - } else { - qCDebug(lcAccessibilityAtspi) << "WARNING: subscription string not handled:" << flag; - } - } - break; - } - case 'f': { - sendFocus = 1; - break; - } - case 'd': { // document is not implemented - break; - } - case 't': { // terminal is not implemented - break; - } - case 'm': { // mouse* is handled in a different way by the gnome atspi stack - break; - } - default: - qCDebug(lcAccessibilityAtspi) << "WARNING: subscription string not handled:" << flag; - } -} - -/*! - Checks via dbus which events should be sent. - */ -void AtSpiAdaptor::updateEventListeners() -{ - QDBusMessage m = QDBusMessage::createMethodCall(QLatin1String("org.a11y.atspi.Registry"), - QLatin1String("/org/a11y/atspi/registry"), - QLatin1String("org.a11y.atspi.Registry"), QLatin1String("GetRegisteredEvents")); - QDBusReply<QSpiEventListenerArray> listenersReply = m_dbus->connection().call(m); - if (listenersReply.isValid()) { - const QSpiEventListenerArray evList = listenersReply.value(); - for (const QSpiEventListener &ev : evList) - setBitFlag(ev.eventName); - m_applicationAdaptor->sendEvents(!evList.isEmpty()); - } else { - qCDebug(lcAccessibilityAtspi) << "Could not query active accessibility event listeners."; - } -} - -void AtSpiAdaptor::eventListenerDeregistered(const QString &/*bus*/, const QString &/*path*/) -{ -// qCDebug(lcAccessibilityAtspi) << "AtSpiAdaptor::eventListenerDeregistered: " << bus << path; - updateEventListeners(); -} - -void AtSpiAdaptor::eventListenerRegistered(const QString &/*bus*/, const QString &/*path*/) -{ -// qCDebug(lcAccessibilityAtspi) << "AtSpiAdaptor::eventListenerRegistered: " << bus << path; - updateEventListeners(); -} - -/*! - This slot needs to get called when a \a window has be activated or deactivated (become focused). - When \a active is true, the window just received focus, otherwise it lost the focus. - */ -void AtSpiAdaptor::windowActivated(QObject* window, bool active) -{ - if (!(sendWindow || sendWindow_activate)) - return; - - QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(window); - Q_ASSERT(iface); - Q_ASSERT(!active || iface->isValid()); - - QString windowTitle; - // in dtor it may be invalid - if (iface->isValid()) - windowTitle = iface->text(QAccessible::Name); - - QDBusVariant data; - data.setVariant(windowTitle); - - QVariantList args = packDBusSignalArguments(QString(), 0, 0, QVariant::fromValue(data)); - - QString status = active ? QLatin1String("Activate") : QLatin1String("Deactivate"); - QString path = pathForObject(window); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_WINDOW), status, args); - - QVariantList stateArgs = packDBusSignalArguments(QLatin1String("active"), active ? 1 : 0, 0, variantForPath(path)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("StateChanged"), stateArgs); -} - -QVariantList AtSpiAdaptor::packDBusSignalArguments(const QString &type, int data1, int data2, const QVariant &variantData) const -{ - QVariantList arguments; - arguments << type << data1 << data2 << variantData - << QVariant::fromValue(QSpiObjectReference(m_dbus->connection(), QDBusObjectPath(QSPI_OBJECT_PATH_ROOT))); - return arguments; -} - -QVariant AtSpiAdaptor::variantForPath(const QString &path) const -{ - QDBusVariant data; - data.setVariant(QVariant::fromValue(QSpiObjectReference(m_dbus->connection(), QDBusObjectPath(path)))); - return QVariant::fromValue(data); -} - -bool AtSpiAdaptor::sendDBusSignal(const QString &path, const QString &interface, const QString &signalName, const QVariantList &arguments) const -{ - QDBusMessage message = QDBusMessage::createSignal(path, interface, signalName); - message.setArguments(arguments); - return m_dbus->connection().send(message); -} - -QAccessibleInterface *AtSpiAdaptor::interfaceFromPath(const QString& dbusPath) const -{ - if (dbusPath == QLatin1String(QSPI_OBJECT_PATH_ROOT)) - return QAccessible::queryAccessibleInterface(qApp); - - QStringList parts = dbusPath.split(QLatin1Char('/')); - if (parts.size() != 6) { - qCDebug(lcAccessibilityAtspi) << "invalid path: " << dbusPath; - return 0; - } - - QString objectString = parts.at(5); - QAccessible::Id id = objectString.toUInt(); - - // The id is always in the range [INT_MAX+1, UINT_MAX] - if ((int)id >= 0) - qCWarning(lcAccessibilityAtspi) << "No accessible object found for id: " << id; - - return QAccessible::accessibleInterface(id); -} - -void AtSpiAdaptor::notifyStateChange(QAccessibleInterface *interface, const QString &state, int value) -{ - QString path = pathForInterface(interface); - QVariantList stateArgs = packDBusSignalArguments(state, value, 0, variantForPath(path)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("StateChanged"), stateArgs); -} - - -/*! - This function gets called when Qt notifies about accessibility updates. -*/ -void AtSpiAdaptor::notify(QAccessibleEvent *event) -{ - switch (event->type()) { - case QAccessible::ObjectCreated: - if (sendObject || sendObject_children_changed) - notifyAboutCreation(event->accessibleInterface()); - break; - case QAccessible::ObjectShow: { - if (sendObject || sendObject_state_changed) { - notifyStateChange(event->accessibleInterface(), QLatin1String("showing"), 1); - } - break; - } - case QAccessible::ObjectHide: { - if (sendObject || sendObject_state_changed) { - notifyStateChange(event->accessibleInterface(), QLatin1String("showing"), 0); - } - break; - } - case QAccessible::ObjectDestroyed: { - if (sendObject || sendObject_state_changed) - notifyAboutDestruction(event->accessibleInterface()); - break; - } - case QAccessible::ObjectReorder: { - if (sendObject || sendObject_children_changed) - childrenChanged(event->accessibleInterface()); - break; - } - case QAccessible::NameChanged: { - if (sendObject || sendObject_property_change || sendObject_property_change_accessible_name) { - QString path = pathForInterface(event->accessibleInterface()); - QVariantList args = packDBusSignalArguments(QLatin1String("accessible-name"), 0, 0, variantForPath(path)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("PropertyChange"), args); - } - break; - } - case QAccessible::DescriptionChanged: { - if (sendObject || sendObject_property_change || sendObject_property_change_accessible_description) { - QString path = pathForInterface(event->accessibleInterface()); - QVariantList args = packDBusSignalArguments(QLatin1String("accessible-description"), 0, 0, variantForPath(path)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("PropertyChange"), args); - } - break; - } - case QAccessible::Focus: { - if (sendFocus || sendObject || sendObject_state_changed) - sendFocusChanged(event->accessibleInterface()); - break; - } - case QAccessible::TextInserted: - case QAccessible::TextRemoved: - case QAccessible::TextUpdated: { - if (sendObject || sendObject_text_changed) { - QAccessibleInterface * iface = event->accessibleInterface(); - if (!iface || !iface->textInterface()) { - qCDebug(lcAccessibilityAtspi) << "Received text event for invalid interface."; - return; - } - QString path = pathForInterface(iface); - - int changePosition = 0; - int cursorPosition = 0; - QString textRemoved; - QString textInserted; - - if (event->type() == QAccessible::TextInserted) { - QAccessibleTextInsertEvent *textEvent = static_cast<QAccessibleTextInsertEvent*>(event); - textInserted = textEvent->textInserted(); - changePosition = textEvent->changePosition(); - cursorPosition = textEvent->cursorPosition(); - } else if (event->type() == QAccessible::TextRemoved) { - QAccessibleTextRemoveEvent *textEvent = static_cast<QAccessibleTextRemoveEvent*>(event); - textRemoved = textEvent->textRemoved(); - changePosition = textEvent->changePosition(); - cursorPosition = textEvent->cursorPosition(); - } else if (event->type() == QAccessible::TextInserted) { - QAccessibleTextUpdateEvent *textEvent = static_cast<QAccessibleTextUpdateEvent*>(event); - textInserted = textEvent->textInserted(); - textRemoved = textEvent->textRemoved(); - changePosition = textEvent->changePosition(); - cursorPosition = textEvent->cursorPosition(); - } - - QDBusVariant data; - - if (!textRemoved.isEmpty()) { - data.setVariant(QVariant::fromValue(textRemoved)); - QVariantList args = packDBusSignalArguments(QLatin1String("delete"), changePosition, textRemoved.length(), QVariant::fromValue(data)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("TextChanged"), args); - } - - if (!textInserted.isEmpty()) { - data.setVariant(QVariant::fromValue(textInserted)); - QVariantList args = packDBusSignalArguments(QLatin1String("insert"), changePosition, textInserted.length(), QVariant::fromValue(data)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("TextChanged"), args); - } - - // send a cursor update - Q_UNUSED(cursorPosition) -// QDBusVariant cursorData; -// cursorData.setVariant(QVariant::fromValue(cursorPosition)); -// QVariantList args = packDBusSignalArguments(QString(), cursorPosition, 0, QVariant::fromValue(cursorData)); -// sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), -// QLatin1String("TextCaretMoved"), args); - } - break; - } - case QAccessible::TextCaretMoved: { - if (sendObject || sendObject_text_caret_moved) { - QAccessibleInterface * iface = event->accessibleInterface(); - if (!iface || !iface->textInterface()) { - qCWarning(lcAccessibilityAtspi) << "Sending TextCaretMoved from object that does not implement text interface: " << iface; - return; - } - - QString path = pathForInterface(iface); - QDBusVariant cursorData; - int pos = iface->textInterface()->cursorPosition(); - cursorData.setVariant(QVariant::fromValue(pos)); - QVariantList args = packDBusSignalArguments(QString(), pos, 0, QVariant::fromValue(cursorData)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("TextCaretMoved"), args); - } - break; - } - case QAccessible::TextSelectionChanged: { - if (sendObject || sendObject_text_selection_changed) { - QAccessibleInterface * iface = event->accessibleInterface(); - QString path = pathForInterface(iface); - QVariantList args = packDBusSignalArguments(QString(), 0, 0, QVariant::fromValue(QDBusVariant(QVariant(QString())))); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("TextSelectionChanged"), args); - } - break; - } - case QAccessible::ValueChanged: { - if (sendObject || sendObject_value_changed || sendObject_property_change_accessible_value) { - QAccessibleInterface * iface = event->accessibleInterface(); - if (!iface) { - qCWarning(lcAccessibilityAtspi) << "ValueChanged event from invalid accessible."; - return; - } - if (iface->valueInterface()) { - QString path = pathForInterface(iface); - QVariantList args = packDBusSignalArguments(QLatin1String("accessible-value"), 0, 0, variantForPath(path)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("PropertyChange"), args); - } else if (iface->role() == QAccessible::ComboBox) { - // Combo Box with AT-SPI likes to be special - // It requires a name-change to update caches and then selection-changed - QString path = pathForInterface(iface); - QVariantList args1 = packDBusSignalArguments(QLatin1String("accessible-name"), 0, 0, variantForPath(path)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("PropertyChange"), args1); - QVariantList args2 = packDBusSignalArguments(QString(), 0, 0, QVariant::fromValue(QDBusVariant(QVariant(0)))); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("SelectionChanged"), args2); - } else { - qCWarning(lcAccessibilityAtspi) << "ValueChanged event and no ValueInterface or ComboBox: " << iface; - } - } - break; - } - case QAccessible::SelectionAdd: - case QAccessible::SelectionRemove: - case QAccessible::Selection: { - QAccessibleInterface * iface = event->accessibleInterface(); - if (!iface) { - qCWarning(lcAccessibilityAtspi) << "Selection event from invalid accessible."; - return; - } - QString path = pathForInterface(iface); - int selected = iface->state().selected ? 1 : 0; - QVariantList stateArgs = packDBusSignalArguments(QLatin1String("selected"), selected, 0, variantForPath(path)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("StateChanged"), stateArgs); - break; - } - - case QAccessible::StateChanged: { - if (sendObject || sendObject_state_changed || sendWindow || sendWindow_activate) { - QAccessible::State stateChange = static_cast<QAccessibleStateChangeEvent*>(event)->changedStates(); - if (stateChange.checked) { - QAccessibleInterface * iface = event->accessibleInterface(); - if (!iface) { - qCWarning(lcAccessibilityAtspi) << "StateChanged event from invalid accessible."; - return; - } - int checked = iface->state().checked; - notifyStateChange(iface, QLatin1String("checked"), checked); - } else if (stateChange.active) { - QAccessibleInterface * iface = event->accessibleInterface(); - if (!iface || !(iface->role() == QAccessible::Window && (sendWindow || sendWindow_activate))) - return; - int isActive = iface->state().active; - QString windowTitle = iface->text(QAccessible::Name); - QDBusVariant data; - data.setVariant(windowTitle); - QVariantList args = packDBusSignalArguments(QString(), 0, 0, QVariant::fromValue(data)); - QString status = isActive ? QLatin1String("Activate") : QLatin1String("Deactivate"); - QString path = pathForInterface(iface); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_WINDOW), status, args); - notifyStateChange(iface, QLatin1String("active"), isActive); - } else if (stateChange.disabled) { - QAccessibleInterface *iface = event->accessibleInterface(); - QAccessible::State state = iface->state(); - bool enabled = !state.disabled; - - notifyStateChange(iface, QLatin1String("enabled"), enabled); - notifyStateChange(iface, QLatin1String("sensitive"), enabled); - } - } - break; - } - // For now we ignore these events - case QAccessible::TableModelChanged: - // For tables, setting manages_descendants should - // indicate to the client that it cannot cache these - // interfaces. - case QAccessible::ParentChanged: - case QAccessible::DialogStart: - case QAccessible::DialogEnd: - case QAccessible::PopupMenuStart: - case QAccessible::PopupMenuEnd: - case QAccessible::SoundPlayed: - case QAccessible::Alert: - case QAccessible::ForegroundChanged: - case QAccessible::MenuStart: - case QAccessible::MenuEnd: - case QAccessible::ContextHelpStart: - case QAccessible::ContextHelpEnd: - case QAccessible::DragDropStart: - case QAccessible::DragDropEnd: - case QAccessible::ScrollingStart: - case QAccessible::ScrollingEnd: - case QAccessible::MenuCommand: - case QAccessible::ActionChanged: - case QAccessible::ActiveDescendantChanged: - case QAccessible::AttributeChanged: - case QAccessible::DocumentContentChanged: - case QAccessible::DocumentLoadComplete: - case QAccessible::DocumentLoadStopped: - case QAccessible::DocumentReload: - case QAccessible::HyperlinkEndIndexChanged: - case QAccessible::HyperlinkNumberOfAnchorsChanged: - case QAccessible::HyperlinkSelectedLinkChanged: - case QAccessible::HypertextLinkActivated: - case QAccessible::HypertextLinkSelected: - case QAccessible::HyperlinkStartIndexChanged: - case QAccessible::HypertextChanged: - case QAccessible::HypertextNLinksChanged: - case QAccessible::ObjectAttributeChanged: - case QAccessible::PageChanged: - case QAccessible::SectionChanged: - case QAccessible::TableCaptionChanged: - case QAccessible::TableColumnDescriptionChanged: - case QAccessible::TableColumnHeaderChanged: - case QAccessible::TableRowDescriptionChanged: - case QAccessible::TableRowHeaderChanged: - case QAccessible::TableSummaryChanged: - case QAccessible::TextAttributeChanged: - case QAccessible::TextColumnChanged: - case QAccessible::VisibleDataChanged: - case QAccessible::SelectionWithin: - case QAccessible::LocationChanged: - case QAccessible::HelpChanged: - case QAccessible::DefaultActionChanged: - case QAccessible::AcceleratorChanged: - case QAccessible::InvalidEvent: - break; - } -} - -void AtSpiAdaptor::sendFocusChanged(QAccessibleInterface *interface) const -{ - static QString lastFocusPath; - // "remove" old focus - if (!lastFocusPath.isEmpty()) { - QVariantList stateArgs = packDBusSignalArguments(QLatin1String("focused"), 0, 0, variantForPath(lastFocusPath)); - sendDBusSignal(lastFocusPath, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("StateChanged"), stateArgs); - } - // send new focus - { - QString path = pathForInterface(interface); - - QVariantList stateArgs = packDBusSignalArguments(QLatin1String("focused"), 1, 0, variantForPath(path)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), - QLatin1String("StateChanged"), stateArgs); - - QVariantList focusArgs = packDBusSignalArguments(QString(), 0, 0, variantForPath(path)); - sendDBusSignal(path, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_FOCUS), - QLatin1String("Focus"), focusArgs); - lastFocusPath = path; - } -} - -void AtSpiAdaptor::childrenChanged(QAccessibleInterface *interface) const -{ - QString parentPath = pathForInterface(interface); - int childCount = interface->childCount(); - for (int i = 0; i < interface->childCount(); ++i) { - QString childPath = pathForInterface(interface->child(i)); - QVariantList args = packDBusSignalArguments(QLatin1String("add"), childCount, 0, childPath); - sendDBusSignal(parentPath, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), QLatin1String("ChildrenChanged"), args); - } -} - -void AtSpiAdaptor::notifyAboutCreation(QAccessibleInterface *interface) const -{ -// // say hello to d-bus -// cache->emitAddAccessible(accessible->getCacheItem()); - - // notify about the new child of our parent - QAccessibleInterface * parent = interface->parent(); - if (!parent) { - qCDebug(lcAccessibilityAtspi) << "AtSpiAdaptor::notifyAboutCreation: Could not find parent for " << interface->object(); - return; - } - QString path = pathForInterface(interface); - int childCount = parent->childCount(); - QString parentPath = pathForInterface(parent); - QVariantList args = packDBusSignalArguments(QLatin1String("add"), childCount, 0, variantForPath(path)); - sendDBusSignal(parentPath, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), QLatin1String("ChildrenChanged"), args); -} - -void AtSpiAdaptor::notifyAboutDestruction(QAccessibleInterface *interface) const -{ - if (!interface || !interface->isValid()) - return; - - QAccessibleInterface * parent = interface->parent(); - if (!parent) { - qCDebug(lcAccessibilityAtspi) << "AtSpiAdaptor::notifyAboutDestruction: Could not find parent for " << interface->object(); - return; - } - QString path = pathForInterface(interface); - - // this is in the destructor. we have no clue which child we used to be. - // FIXME - int childIndex = -1; - // if (child) { - // childIndex = child; - // } else { - // childIndex = parent->indexOfChild(interface); - // } - - QString parentPath = pathForInterface(parent); - QVariantList args = packDBusSignalArguments(QLatin1String("remove"), childIndex, 0, variantForPath(path)); - sendDBusSignal(parentPath, QLatin1String(ATSPI_DBUS_INTERFACE_EVENT_OBJECT), QLatin1String("ChildrenChanged"), args); -} - -/*! - Handle incoming DBus message. - This function dispatches the dbus message to the right interface handler. - */ -bool AtSpiAdaptor::handleMessage(const QDBusMessage &message, const QDBusConnection &connection) -{ - // get accessible interface - QAccessibleInterface * accessible = interfaceFromPath(message.path()); - if (!accessible) { - qCDebug(lcAccessibilityAtspi) << "WARNING Qt AtSpiAdaptor: Could not find accessible on path: " << message.path(); - return false; - } - if (!accessible->isValid()) { - qCWarning(lcAccessibilityAtspi) << "WARNING Qt AtSpiAdaptor: Accessible invalid: " << accessible << message.path(); - return false; - } - - QString interface = message.interface(); - QString function = message.member(); - - // qCDebug(lcAccessibilityAtspi) << "AtSpiAdaptor::handleMessage: " << interface << function; - - if (function == QLatin1String("Introspect")) { - //introspect(message.path()); - return false; - } - - // handle properties like regular functions - if (interface == QLatin1String("org.freedesktop.DBus.Properties")) { - interface = message.arguments().at(0).toString(); - // Get/Set + Name - function = message.member() + message.arguments().at(1).toString(); - } - - // switch interface to call - if (interface == QLatin1String(ATSPI_DBUS_INTERFACE_ACCESSIBLE)) - return accessibleInterface(accessible, function, message, connection); - if (interface == QLatin1String(ATSPI_DBUS_INTERFACE_APPLICATION)) - return applicationInterface(accessible, function, message, connection); - if (interface == QLatin1String(ATSPI_DBUS_INTERFACE_COMPONENT)) - return componentInterface(accessible, function, message, connection); - if (interface == QLatin1String(ATSPI_DBUS_INTERFACE_ACTION)) - return actionInterface(accessible, function, message, connection); - if (interface == QLatin1String(ATSPI_DBUS_INTERFACE_TEXT)) - return textInterface(accessible, function, message, connection); - if (interface == QLatin1String(ATSPI_DBUS_INTERFACE_EDITABLE_TEXT)) - return editableTextInterface(accessible, function, message, connection); - if (interface == QLatin1String(ATSPI_DBUS_INTERFACE_VALUE)) - return valueInterface(accessible, function, message, connection); - if (interface == QLatin1String(ATSPI_DBUS_INTERFACE_TABLE)) - return tableInterface(accessible, function, message, connection); - - qCDebug(lcAccessibilityAtspi) << "AtSpiAdaptor::handleMessage with unknown interface: " << message.path() << interface << function; - return false; -} - -// Application -bool AtSpiAdaptor::applicationInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection) -{ - if (message.path() != QLatin1String(ATSPI_DBUS_PATH_ROOT)) { - qCDebug(lcAccessibilityAtspi) << "WARNING Qt AtSpiAdaptor: Could not find application interface for: " << message.path() << interface; - return false; - } - - if (function == QLatin1String("SetId")) { - Q_ASSERT(message.signature() == QLatin1String("ssv")); - QVariant value = qvariant_cast<QDBusVariant>(message.arguments().at(2)).variant(); - - m_applicationId = value.toInt(); - return true; - } - if (function == QLatin1String("GetId")) { - Q_ASSERT(message.signature() == QLatin1String("ss")); - QDBusMessage reply = message.createReply(QVariant::fromValue(QDBusVariant(m_applicationId))); - return connection.send(reply); - } - if (function == QLatin1String("GetToolkitName")) { - Q_ASSERT(message.signature() == QLatin1String("ss")); - QDBusMessage reply = message.createReply(QVariant::fromValue(QDBusVariant(QLatin1String("Qt")))); - return connection.send(reply); - } - if (function == QLatin1String("GetVersion")) { - Q_ASSERT(message.signature() == QLatin1String("ss")); - QDBusMessage reply = message.createReply(QVariant::fromValue(QDBusVariant(QLatin1String(qVersion())))); - return connection.send(reply); - } - if (function == QLatin1String("GetLocale")) { - Q_ASSERT(message.signature() == QLatin1String("u")); - QDBusMessage reply = message.createReply(QVariant::fromValue(QLocale().name())); - return connection.send(reply); - } - qCDebug(lcAccessibilityAtspi) << "AtSpiAdaptor::applicationInterface " << message.path() << interface << function; - return false; -} - -/*! - Register this application as accessible on the accessibility DBus. - */ -void AtSpiAdaptor::registerApplication() -{ - OrgA11yAtspiSocketInterface *registry; - registry = new OrgA11yAtspiSocketInterface(QLatin1String(QSPI_REGISTRY_NAME), - QLatin1String(QSPI_OBJECT_PATH_ROOT), m_dbus->connection()); - - QDBusPendingReply<QSpiObjectReference> reply; - QSpiObjectReference ref = QSpiObjectReference(m_dbus->connection(), QDBusObjectPath(QSPI_OBJECT_PATH_ROOT)); - reply = registry->Embed(ref); - reply.waitForFinished(); // TODO: make this async - if (reply.isValid ()) { - const QSpiObjectReference &socket = reply.value(); - accessibilityRegistry = QSpiObjectReference(socket); - } else { - qCDebug(lcAccessibilityAtspi) << "Error in contacting registry: " - << reply.error().name() - << reply.error().message(); - } - delete registry; -} - -// Accessible -bool AtSpiAdaptor::accessibleInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection) -{ - if (function == QLatin1String("GetRole")) { - sendReply(connection, message, (uint) getRole(interface)); - } else if (function == QLatin1String("GetName")) { - sendReply(connection, message, QVariant::fromValue(QDBusVariant(interface->text(QAccessible::Name)))); - } else if (function == QLatin1String("GetRoleName")) { - sendReply(connection, message, qSpiRoleMapping[interface->role()].name()); - } else if (function == QLatin1String("GetLocalizedRoleName")) { - sendReply(connection, message, QVariant::fromValue(qSpiRoleMapping[interface->role()].localizedName())); - } else if (function == QLatin1String("GetChildCount")) { - sendReply(connection, message, QVariant::fromValue(QDBusVariant(interface->childCount()))); - } else if (function == QLatin1String("GetIndexInParent")) { - int childIndex = -1; - QAccessibleInterface * parent = interface->parent(); - if (parent) { - childIndex = parent->indexOfChild(interface); - if (childIndex < 0) { - qCDebug(lcAccessibilityAtspi) << "GetIndexInParent get invalid index: " << childIndex << interface; - } - } - sendReply(connection, message, childIndex); - } else if (function == QLatin1String("GetParent")) { - QString path; - QAccessibleInterface * parent = interface->parent(); - if (!parent) { - path = QLatin1String(ATSPI_DBUS_PATH_NULL); - } else if (parent->role() == QAccessible::Application) { - path = QLatin1String(ATSPI_DBUS_PATH_ROOT); - } else { - path = pathForInterface(parent); - } - // Parent is a property, so it needs to be wrapped inside an extra variant. - sendReply(connection, message, QVariant::fromValue( - QDBusVariant(QVariant::fromValue(QSpiObjectReference(connection, QDBusObjectPath(path)))))); - } else if (function == QLatin1String("GetChildAtIndex")) { - const int index = message.arguments().at(0).toInt(); - if (index < 0) { - sendReply(connection, message, QVariant::fromValue( - QSpiObjectReference(connection, QDBusObjectPath(ATSPI_DBUS_PATH_NULL)))); - } else { - QAccessibleInterface * childInterface = interface->child(index); - sendReply(connection, message, QVariant::fromValue( - QSpiObjectReference(connection, QDBusObjectPath(pathForInterface(childInterface))))); - } - } else if (function == QLatin1String("GetInterfaces")) { - sendReply(connection, message, accessibleInterfaces(interface)); - } else if (function == QLatin1String("GetDescription")) { - sendReply(connection, message, QVariant::fromValue(QDBusVariant(interface->text(QAccessible::Description)))); - } else if (function == QLatin1String("GetState")) { - quint64 spiState = spiStatesFromQState(interface->state()); - if (interface->tableInterface()) { - setSpiStateBit(&spiState, ATSPI_STATE_MANAGES_DESCENDANTS); - } - QAccessible::Role role = interface->role(); - if (role == QAccessible::TreeItem || - role == QAccessible::ListItem) { - /* Transient means libatspi2 will not cache items. - This is important because when adding/removing an item - the cache becomes outdated and we don't change the paths of - items in lists/trees/tables. */ - setSpiStateBit(&spiState, ATSPI_STATE_TRANSIENT); - } - sendReply(connection, message, - QVariant::fromValue(spiStateSetFromSpiStates(spiState))); - } else if (function == QLatin1String("GetAttributes")) { - sendReply(connection, message, QVariant::fromValue(QSpiAttributeSet())); - } else if (function == QLatin1String("GetRelationSet")) { - sendReply(connection, message, QVariant::fromValue(relationSet(interface, connection))); - } else if (function == QLatin1String("GetApplication")) { - sendReply(connection, message, QVariant::fromValue( - QSpiObjectReference(connection, QDBusObjectPath(QSPI_OBJECT_PATH_ROOT)))); - } else if (function == QLatin1String("GetChildren")) { - QSpiObjectReferenceArray children; - const int numChildren = interface->childCount(); - children.reserve(numChildren); - for (int i = 0; i < numChildren; ++i) { - QString childPath = pathForInterface(interface->child(i)); - QSpiObjectReference ref(connection, QDBusObjectPath(childPath)); - children << ref; - } - connection.send(message.createReply(QVariant::fromValue(children))); - } else { - qCDebug(lcAccessibilityAtspi) << "WARNING: AtSpiAdaptor::accessibleInterface does not implement " << function << message.path(); - return false; - } - return true; -} - -AtspiRole AtSpiAdaptor::getRole(QAccessibleInterface *interface) const -{ - if ((interface->role() == QAccessible::EditableText) && interface->state().passwordEdit) - return ATSPI_ROLE_PASSWORD_TEXT; - return qSpiRoleMapping[interface->role()].spiRole(); -} - -QStringList AtSpiAdaptor::accessibleInterfaces(QAccessibleInterface *interface) const -{ - QStringList ifaces; - qCDebug(lcAccessibilityAtspiCreation) << "AtSpiAdaptor::accessibleInterfaces create: " << interface->object(); - ifaces << QLatin1String(ATSPI_DBUS_INTERFACE_ACCESSIBLE); - - if ( (!interface->rect().isEmpty()) || - (interface->object() && interface->object()->isWidgetType()) || - (interface->role() == QAccessible::ListItem) || - (interface->role() == QAccessible::Cell) || - (interface->role() == QAccessible::TreeItem) || - (interface->role() == QAccessible::Row) || - (interface->object() && interface->object()->inherits("QSGItem")) - ) { - ifaces << QLatin1String(ATSPI_DBUS_INTERFACE_COMPONENT); - } else { - qCDebug(lcAccessibilityAtspiCreation) << " IS NOT a component"; - } - if (interface->role() == QAccessible::Application) - ifaces << QLatin1String(ATSPI_DBUS_INTERFACE_APPLICATION); - - if (interface->actionInterface() || interface->valueInterface()) - ifaces << QLatin1String(ATSPI_DBUS_INTERFACE_ACTION); - - if (interface->textInterface()) - ifaces << QLatin1String(ATSPI_DBUS_INTERFACE_TEXT); - - if (interface->editableTextInterface()) - ifaces << QLatin1String(ATSPI_DBUS_INTERFACE_EDITABLE_TEXT); - - if (interface->valueInterface()) - ifaces << QLatin1String(ATSPI_DBUS_INTERFACE_VALUE); - - if (interface->tableInterface()) - ifaces << QLatin1String(ATSPI_DBUS_INTERFACE_TABLE); - - return ifaces; -} - -QSpiRelationArray AtSpiAdaptor::relationSet(QAccessibleInterface *interface, const QDBusConnection &connection) const -{ - typedef QPair<QAccessibleInterface*, QAccessible::Relation> RelationPair; - const QVector<RelationPair> relationInterfaces = interface->relations(); - - QSpiRelationArray relations; - for (const RelationPair &pair : relationInterfaces) { -// FIXME: this loop seems a bit strange... "related" always have one item when we check. -//And why is it a list, when it always have one item? And it seems to assume that the QAccessible::Relation enum maps directly to AtSpi - QSpiObjectReferenceArray related; - - QDBusObjectPath path = QDBusObjectPath(pathForInterface(pair.first)); - related.append(QSpiObjectReference(connection, path)); - - if (!related.isEmpty()) - relations.append(QSpiRelationArrayEntry(qAccessibleRelationToAtSpiRelation(pair.second), related)); - } - return relations; -} - -void AtSpiAdaptor::sendReply(const QDBusConnection &connection, const QDBusMessage &message, const QVariant &argument) const -{ - QDBusMessage reply = message.createReply(argument); - connection.send(reply); -} - - -QString AtSpiAdaptor::pathForObject(QObject *object) const -{ - Q_ASSERT(object); - - if (inheritsQAction(object)) { - qCDebug(lcAccessibilityAtspi) << "AtSpiAdaptor::pathForObject: warning: creating path with QAction as object."; - } - - QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(object); - return pathForInterface(iface); -} - -QString AtSpiAdaptor::pathForInterface(QAccessibleInterface *interface) const -{ - if (!interface || !interface->isValid()) - return QLatin1String(ATSPI_DBUS_PATH_NULL); - if (interface->role() == QAccessible::Application) - return QLatin1String(QSPI_OBJECT_PATH_ROOT); - - QAccessible::Id id = QAccessible::uniqueId(interface); - Q_ASSERT((int)id < 0); - return QLatin1String(QSPI_OBJECT_PATH_PREFIX) + QString::number(id); -} - -bool AtSpiAdaptor::inheritsQAction(QObject *object) -{ - const QMetaObject *mo = object->metaObject(); - while (mo) { - const QLatin1String cn(mo->className()); - if (cn == QLatin1String("QAction")) - return true; - mo = mo->superClass(); - } - return false; -} - -// Component -static QAccessibleInterface * getWindow(QAccessibleInterface * interface) -{ - if (interface->role() == QAccessible::Window) - return interface; - - QAccessibleInterface * parent = interface->parent(); - while (parent && parent->role() != QAccessible::Window) - parent = parent->parent(); - - return parent; -} - -static QRect getRelativeRect(QAccessibleInterface *interface) -{ - QAccessibleInterface * window; - QRect wr, cr; - - cr = interface->rect(); - - window = getWindow(interface); - if (window) { - wr = window->rect(); - - cr.setX(cr.x() - wr.x()); - cr.setY(cr.x() - wr.y()); - } - return cr; -} - -bool AtSpiAdaptor::componentInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection) -{ - if (function == QLatin1String("Contains")) { - bool ret = false; - int x = message.arguments().at(0).toInt(); - int y = message.arguments().at(1).toInt(); - uint coordType = message.arguments().at(2).toUInt(); - if (coordType == ATSPI_COORD_TYPE_SCREEN) - ret = interface->rect().contains(x, y); - else - ret = getRelativeRect(interface).contains(x, y); - sendReply(connection, message, ret); - } else if (function == QLatin1String("GetAccessibleAtPoint")) { - int x = message.arguments().at(0).toInt(); - int y = message.arguments().at(1).toInt(); - uint coordType = message.arguments().at(2).toUInt(); - if (coordType == ATSPI_COORD_TYPE_WINDOW) { - QWindow * window = interface->window(); - if (window) { - x += window->position().x(); - y += window->position().y(); - } - } - - QAccessibleInterface * childInterface(interface->childAt(x, y)); - QAccessibleInterface * iface = 0; - while (childInterface) { - iface = childInterface; - childInterface = iface->childAt(x, y); - } - if (iface) { - QString path = pathForInterface(iface); - sendReply(connection, message, QVariant::fromValue( - QSpiObjectReference(connection, QDBusObjectPath(path)))); - } else { - sendReply(connection, message, QVariant::fromValue( - QSpiObjectReference(connection, QDBusObjectPath(ATSPI_DBUS_PATH_NULL)))); - } - } else if (function == QLatin1String("GetAlpha")) { - sendReply(connection, message, (double) 1.0); - } else if (function == QLatin1String("GetExtents")) { - uint coordType = message.arguments().at(0).toUInt(); - sendReply(connection, message, QVariant::fromValue(getExtents(interface, coordType))); - } else if (function == QLatin1String("GetLayer")) { - sendReply(connection, message, QVariant::fromValue((uint)1)); - } else if (function == QLatin1String("GetMDIZOrder")) { - sendReply(connection, message, QVariant::fromValue((short)0)); - } else if (function == QLatin1String("GetPosition")) { - uint coordType = message.arguments().at(0).toUInt(); - QRect rect; - if (coordType == ATSPI_COORD_TYPE_SCREEN) - rect = interface->rect(); - else - rect = getRelativeRect(interface); - QVariantList pos; - pos << rect.x() << rect.y(); - connection.send(message.createReply(pos)); - } else if (function == QLatin1String("GetSize")) { - QRect rect = interface->rect(); - QVariantList size; - size << rect.width() << rect.height(); - connection.send(message.createReply(size)); - } else if (function == QLatin1String("GrabFocus")) { - QAccessibleActionInterface *actionIface = interface->actionInterface(); - if (actionIface && actionIface->actionNames().contains(QAccessibleActionInterface::setFocusAction())) { - actionIface->doAction(QAccessibleActionInterface::setFocusAction()); - sendReply(connection, message, true); - } else { - sendReply(connection, message, false); - } - } else if (function == QLatin1String("SetExtents")) { -// int x = message.arguments().at(0).toInt(); -// int y = message.arguments().at(1).toInt(); -// int width = message.arguments().at(2).toInt(); -// int height = message.arguments().at(3).toInt(); -// uint coordinateType = message.arguments().at(4).toUInt(); - qCDebug(lcAccessibilityAtspi) << "SetExtents is not implemented."; - sendReply(connection, message, false); - } else if (function == QLatin1String("SetPosition")) { -// int x = message.arguments().at(0).toInt(); -// int y = message.arguments().at(1).toInt(); -// uint coordinateType = message.arguments().at(2).toUInt(); - qCDebug(lcAccessibilityAtspi) << "SetPosition is not implemented."; - sendReply(connection, message, false); - } else if (function == QLatin1String("SetSize")) { -// int width = message.arguments().at(0).toInt(); -// int height = message.arguments().at(1).toInt(); - qCDebug(lcAccessibilityAtspi) << "SetSize is not implemented."; - sendReply(connection, message, false); - } else { - qCDebug(lcAccessibilityAtspi) << "WARNING: AtSpiAdaptor::componentInterface does not implement " << function << message.path(); - return false; - } - return true; -} - -QRect AtSpiAdaptor::getExtents(QAccessibleInterface *interface, uint coordType) -{ - return (coordType == ATSPI_COORD_TYPE_SCREEN) ? interface->rect() : getRelativeRect(interface); -} - -// Action interface -bool AtSpiAdaptor::actionInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection) -{ - if (function == QLatin1String("GetNActions")) { - int count = QAccessibleBridgeUtils::effectiveActionNames(interface).count(); - sendReply(connection, message, QVariant::fromValue(QDBusVariant(QVariant::fromValue(count)))); - } else if (function == QLatin1String("DoAction")) { - int index = message.arguments().at(0).toInt(); - const QStringList actionNames = QAccessibleBridgeUtils::effectiveActionNames(interface); - if (index < 0 || index >= actionNames.count()) - return false; - const QString actionName = actionNames.at(index); - bool success = QAccessibleBridgeUtils::performEffectiveAction(interface, actionName); - sendReply(connection, message, success); - } else if (function == QLatin1String("GetActions")) { - sendReply(connection, message, QVariant::fromValue(getActions(interface))); - } else if (function == QLatin1String("GetName")) { - int index = message.arguments().at(0).toInt(); - const QStringList actionNames = QAccessibleBridgeUtils::effectiveActionNames(interface); - if (index < 0 || index >= actionNames.count()) - return false; - sendReply(connection, message, actionNames.at(index)); - } else if (function == QLatin1String("GetDescription")) { - int index = message.arguments().at(0).toInt(); - const QStringList actionNames = QAccessibleBridgeUtils::effectiveActionNames(interface); - if (index < 0 || index >= actionNames.count()) - return false; - QString description; - if (QAccessibleActionInterface *actionIface = interface->actionInterface()) - description = actionIface->localizedActionDescription(actionNames.at(index)); - else - description = qAccessibleLocalizedActionDescription(actionNames.at(index)); - sendReply(connection, message, description); - } else if (function == QLatin1String("GetKeyBinding")) { - int index = message.arguments().at(0).toInt(); - const QStringList actionNames = QAccessibleBridgeUtils::effectiveActionNames(interface); - if (index < 0 || index >= actionNames.count()) - return false; - QStringList keyBindings; - if (QAccessibleActionInterface *actionIface = interface->actionInterface()) - keyBindings = actionIface->keyBindingsForAction(actionNames.at(index)); - if (keyBindings.isEmpty()) { - QString acc = interface->text(QAccessible::Accelerator); - if (!acc.isEmpty()) - keyBindings.append(acc); - } - if (keyBindings.length() > 0) - sendReply(connection, message, keyBindings.join(QLatin1Char(';'))); - else - sendReply(connection, message, QString()); - } else { - qCDebug(lcAccessibilityAtspi) << "WARNING: AtSpiAdaptor::actionInterface does not implement " << function << message.path(); - return false; - } - return true; -} - -QSpiActionArray AtSpiAdaptor::getActions(QAccessibleInterface *interface) const -{ - QAccessibleActionInterface *actionInterface = interface->actionInterface(); - QSpiActionArray actions; - const QStringList actionNames = QAccessibleBridgeUtils::effectiveActionNames(interface); - actions.reserve(actionNames.size()); - for (const QString &actionName : actionNames) { - QSpiAction action; - - action.name = actionName; - if (actionInterface) { - action.description = actionInterface->localizedActionDescription(actionName); - const QStringList keyBindings = actionInterface->keyBindingsForAction(actionName); - if (!keyBindings.isEmpty()) - action.keyBinding = keyBindings.front(); - } else { - action.description = qAccessibleLocalizedActionDescription(actionName); - } - - actions.append(std::move(action)); - } - return actions; -} - -// Text interface -bool AtSpiAdaptor::textInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection) -{ - if (!interface->textInterface()) - return false; - - // properties - if (function == QLatin1String("GetCaretOffset")) { - sendReply(connection, message, QVariant::fromValue(QDBusVariant(QVariant::fromValue(interface->textInterface()->cursorPosition())))); - } else if (function == QLatin1String("GetCharacterCount")) { - sendReply(connection, message, QVariant::fromValue(QDBusVariant(QVariant::fromValue(interface->textInterface()->characterCount())))); - - // functions - } else if (function == QLatin1String("AddSelection")) { - int startOffset = message.arguments().at(0).toInt(); - int endOffset = message.arguments().at(1).toInt(); - int lastSelection = interface->textInterface()->selectionCount(); - interface->textInterface()->setSelection(lastSelection, startOffset, endOffset); - sendReply(connection, message, (interface->textInterface()->selectionCount() > lastSelection)); - } else if (function == QLatin1String("GetAttributeRun")) { - int offset = message.arguments().at(0).toInt(); - bool includeDefaults = message.arguments().at(1).toBool(); - Q_UNUSED(includeDefaults) - connection.send(message.createReply(getAttributes(interface, offset, includeDefaults))); - } else if (function == QLatin1String("GetAttributeValue")) { - int offset = message.arguments().at(0).toInt(); - QString attributeName = message.arguments().at(1).toString(); - connection.send(message.createReply(getAttributeValue(interface, offset, attributeName))); - } else if (function == QLatin1String("GetAttributes")) { - int offset = message.arguments().at(0).toInt(); - connection.send(message.createReply(getAttributes(interface, offset, true))); - } else if (function == QLatin1String("GetBoundedRanges")) { - int x = message.arguments().at(0).toInt(); - int y = message.arguments().at(1).toInt(); - int width = message.arguments().at(2).toInt(); - int height = message.arguments().at(3).toInt(); - uint coordType = message.arguments().at(4).toUInt(); - uint xClipType = message.arguments().at(5).toUInt(); - uint yClipType = message.arguments().at(6).toUInt(); - Q_UNUSED(x) Q_UNUSED (y) Q_UNUSED(width) - Q_UNUSED(height) Q_UNUSED(coordType) - Q_UNUSED(xClipType) Q_UNUSED(yClipType) - qCDebug(lcAccessibilityAtspi) << "Not implemented: QSpiAdaptor::GetBoundedRanges"; - sendReply(connection, message, QVariant::fromValue(QSpiTextRangeList())); - } else if (function == QLatin1String("GetCharacterAtOffset")) { - int offset = message.arguments().at(0).toInt(); - int start; - int end; - QString result = interface->textInterface()->textAtOffset(offset, QAccessible::CharBoundary, &start, &end); - sendReply(connection, message, (int) *(qPrintable (result))); - } else if (function == QLatin1String("GetCharacterExtents")) { - int offset = message.arguments().at(0).toInt(); - int coordType = message.arguments().at(1).toUInt(); - connection.send(message.createReply(getCharacterExtents(interface, offset, coordType))); - } else if (function == QLatin1String("GetDefaultAttributeSet") || function == QLatin1String("GetDefaultAttributes")) { - // GetDefaultAttributes is deprecated in favour of GetDefaultAttributeSet. - // Empty set seems reasonable. There is no default attribute set. - sendReply(connection, message, QVariant::fromValue(QSpiAttributeSet())); - } else if (function == QLatin1String("GetNSelections")) { - sendReply(connection, message, interface->textInterface()->selectionCount()); - } else if (function == QLatin1String("GetOffsetAtPoint")) { - qCDebug(lcAccessibilityAtspi) << message.signature(); - Q_ASSERT(!message.signature().isEmpty()); - QPoint point(message.arguments().at(0).toInt(), message.arguments().at(1).toInt()); - uint coordType = message.arguments().at(2).toUInt(); - if (coordType == ATSPI_COORD_TYPE_WINDOW) { - QWindow *win = interface->window(); - point -= QPoint(win->x(), win->y()); - } - int offset = interface->textInterface()->offsetAtPoint(point); - sendReply(connection, message, offset); - } else if (function == QLatin1String("GetRangeExtents")) { - int startOffset = message.arguments().at(0).toInt(); - int endOffset = message.arguments().at(1).toInt(); - uint coordType = message.arguments().at(2).toUInt(); - connection.send(message.createReply(getRangeExtents(interface, startOffset, endOffset, coordType))); - } else if (function == QLatin1String("GetSelection")) { - int selectionNum = message.arguments().at(0).toInt(); - int start, end; - interface->textInterface()->selection(selectionNum, &start, &end); - if (start < 0) - start = end = interface->textInterface()->cursorPosition(); - QVariantList sel; - sel << start << end; - connection.send(message.createReply(sel)); - } else if (function == QLatin1String("GetText")) { - int startOffset = message.arguments().at(0).toInt(); - int endOffset = message.arguments().at(1).toInt(); - if (endOffset == -1) // AT-SPI uses -1 to signal all characters - endOffset = interface->textInterface()->characterCount(); - sendReply(connection, message, interface->textInterface()->text(startOffset, endOffset)); - } else if (function == QLatin1String("GetTextAfterOffset")) { - int offset = message.arguments().at(0).toInt(); - int type = message.arguments().at(1).toUInt(); - int startOffset, endOffset; - QString text = interface->textInterface()->textAfterOffset(offset, qAccessibleBoundaryType(type), &startOffset, &endOffset); - QVariantList ret; - ret << text << startOffset << endOffset; - connection.send(message.createReply(ret)); - } else if (function == QLatin1String("GetTextAtOffset")) { - int offset = message.arguments().at(0).toInt(); - int type = message.arguments().at(1).toUInt(); - int startOffset, endOffset; - QString text = interface->textInterface()->textAtOffset(offset, qAccessibleBoundaryType(type), &startOffset, &endOffset); - QVariantList ret; - ret << text << startOffset << endOffset; - connection.send(message.createReply(ret)); - } else if (function == QLatin1String("GetTextBeforeOffset")) { - int offset = message.arguments().at(0).toInt(); - int type = message.arguments().at(1).toUInt(); - int startOffset, endOffset; - QString text = interface->textInterface()->textBeforeOffset(offset, qAccessibleBoundaryType(type), &startOffset, &endOffset); - QVariantList ret; - ret << text << startOffset << endOffset; - connection.send(message.createReply(ret)); - } else if (function == QLatin1String("RemoveSelection")) { - int selectionNum = message.arguments().at(0).toInt(); - interface->textInterface()->removeSelection(selectionNum); - sendReply(connection, message, true); - } else if (function == QLatin1String("SetCaretOffset")) { - int offset = message.arguments().at(0).toInt(); - interface->textInterface()->setCursorPosition(offset); - sendReply(connection, message, true); - } else if (function == QLatin1String("SetSelection")) { - int selectionNum = message.arguments().at(0).toInt(); - int startOffset = message.arguments().at(1).toInt(); - int endOffset = message.arguments().at(2).toInt(); - interface->textInterface()->setSelection(selectionNum, startOffset, endOffset); - sendReply(connection, message, true); - } else { - qCDebug(lcAccessibilityAtspi) << "WARNING: AtSpiAdaptor::textInterface does not implement " << function << message.path(); - return false; - } - return true; -} - -QAccessible::TextBoundaryType AtSpiAdaptor::qAccessibleBoundaryType(int atspiTextBoundaryType) const -{ - switch (atspiTextBoundaryType) { - case ATSPI_TEXT_BOUNDARY_CHAR: - return QAccessible::CharBoundary; - case ATSPI_TEXT_BOUNDARY_WORD_START: - case ATSPI_TEXT_BOUNDARY_WORD_END: - return QAccessible::WordBoundary; - case ATSPI_TEXT_BOUNDARY_SENTENCE_START: - case ATSPI_TEXT_BOUNDARY_SENTENCE_END: - return QAccessible::SentenceBoundary; - case ATSPI_TEXT_BOUNDARY_LINE_START: - case ATSPI_TEXT_BOUNDARY_LINE_END: - return QAccessible::LineBoundary; - } - Q_ASSERT_X(0, "", "Requested invalid boundary type."); - return QAccessible::CharBoundary; -} - -namespace -{ - struct AtSpiAttribute { - QString name; - QString value; - AtSpiAttribute(const QString &aName, const QString &aValue) : name(aName), value(aValue) {} - bool isNull() const { return name.isNull() || value.isNull(); } - }; - - QString atspiColor(const QString &ia2Color) - { - // "rgb(%u,%u,%u)" -> "%u,%u,%u" - return ia2Color.mid(4, ia2Color.length() - (4+1)); - } - - QString atspiSize(const QString &ia2Size) - { - // "%fpt" -> "%f" - return ia2Size.left(ia2Size.length() - 2); - } - - AtSpiAttribute atspiTextAttribute(const QString &ia2Name, const QString &ia2Value) - { - QString name = ia2Name; - QString value = ia2Value; - - // IAccessible2: http://www.linuxfoundation.org/collaborate/workgroups/accessibility/iaccessible2/textattributes - // ATK attribute names: https://git.gnome.org/browse/orca/tree/src/orca/text_attribute_names.py - // ATK attribute values: https://developer.gnome.org/atk/unstable/AtkText.html#AtkTextAttribute - - // https://bugzilla.gnome.org/show_bug.cgi?id=744553 "ATK docs provide no guidance for allowed values of some text attributes" - // specifically for "weight", "invalid", "language" and value range for colors - - if (ia2Name == QLatin1String("background-color")) { - name = QStringLiteral("bg-color"); - value = atspiColor(value); - } else if (ia2Name == QLatin1String("font-family")) { - name = QStringLiteral("family-name"); - } else if (ia2Name == QLatin1String("color")) { - name = QStringLiteral("fg-color"); - value = atspiColor(value); - } else if (ia2Name == QLatin1String("text-align")) { - name = QStringLiteral("justification"); - if (value == QLatin1String("justify")) { - value = QStringLiteral("fill"); - } else { - if (value != QLatin1String("left") && - value != QLatin1String("right") && - value != QLatin1String("center") - ) { - value = QString(); - qCDebug(lcAccessibilityAtspi) << "Unknown text-align attribute value \"" << value << "\" cannot be translated to AT-SPI."; - } - } - } else if (ia2Name == QLatin1String("font-size")) { - name = QStringLiteral("size"); - value = atspiSize(value); - } else if (ia2Name == QLatin1String("font-style")) { - name = QStringLiteral("style"); - if (value != QLatin1String("normal") && - value != QLatin1String("italic") && - value != QLatin1String("oblique") - ) { - value = QString(); - qCDebug(lcAccessibilityAtspi) << "Unknown font-style attribute value \"" << value << "\" cannot be translated to AT-SPI."; - } - } else if (ia2Name == QLatin1String("text-underline-type")) { - name = QStringLiteral("underline"); - if (value != QLatin1String("none") && - value != QLatin1String("single") && - value != QLatin1String("double") - ) { - value = QString(); - qCDebug(lcAccessibilityAtspi) << "Unknown text-underline-type attribute value \"" << value << "\" cannot be translated to AT-SPI."; - } - } else if (ia2Name == QLatin1String("font-weight")) { - name = QStringLiteral("weight"); - if (value == QLatin1String("normal")) - // Orca seems to accept all IAccessible2 values except for "normal" - // (on which it produces traceback and fails to read any following text attributes), - // but that is the default value, so omit it anyway - value = QString(); - } else if (ia2Name == QLatin1String("text-position")) { - name = QStringLiteral("vertical-align"); - if (value != QLatin1String("baseline") && - value != QLatin1String("super") && - value != QLatin1String("sub") - ) { - value = QString(); - qCDebug(lcAccessibilityAtspi) << "Unknown text-position attribute value \"" << value << "\" cannot be translated to AT-SPI."; - } - } else if (ia2Name == QLatin1String("writing-mode")) { - name = QStringLiteral("direction"); - if (value == QLatin1String("lr")) - value = QStringLiteral("ltr"); - else if (value == QLatin1String("rl")) - value = QStringLiteral("rtl"); - else if (value == QLatin1String("tb")) { - // IAccessible2 docs refer to XSL, which specifies "tb" is shorthand for "tb-rl"; so at least give a hint about the horizontal direction (ATK does not support vertical direction in this attribute (yet)) - value = QStringLiteral("rtl"); - qCDebug(lcAccessibilityAtspi) << "writing-mode attribute value \"tb\" translated only w.r.t. horizontal direction; vertical direction ignored"; - } else { - value = QString(); - qCDebug(lcAccessibilityAtspi) << "Unknown writing-mode attribute value \"" << value << "\" cannot be translated to AT-SPI."; - } - } else if (ia2Name == QLatin1String("language")) { - // OK - ATK has no docs on the format of the value, IAccessible2 has reasonable format - leave it at that now - } else if (ia2Name == QLatin1String("invalid")) { - // OK - ATK docs are vague but suggest they support the same range of values as IAccessible2 - } else { - // attribute we know nothing about - name = QString(); - value = QString(); - } - return AtSpiAttribute(name, value); - } -} - -// FIXME all attribute methods below should share code -QVariantList AtSpiAdaptor::getAttributes(QAccessibleInterface *interface, int offset, bool includeDefaults) const -{ - Q_UNUSED(includeDefaults); - - QSpiAttributeSet set; - int startOffset; - int endOffset; - - QString joined = interface->textInterface()->attributes(offset, &startOffset, &endOffset); - QStringList attributes = joined.split (QLatin1Char(';'), QString::SkipEmptyParts, Qt::CaseSensitive); - foreach (const QString &attr, attributes) { - QStringList items; - items = attr.split(QLatin1Char(':'), QString::SkipEmptyParts, Qt::CaseSensitive); - AtSpiAttribute attribute = atspiTextAttribute(items[0], items[1]); - if (!attribute.isNull()) - set[attribute.name] = attribute.value; - } - - QVariantList list; - list << QVariant::fromValue(set) << startOffset << endOffset; - - return list; -} - -QVariantList AtSpiAdaptor::getAttributeValue(QAccessibleInterface *interface, int offset, const QString &attributeName) const -{ - QString mapped; - QString joined; - QStringList attributes; - QSpiAttributeSet map; - int startOffset; - int endOffset; - - joined = interface->textInterface()->attributes(offset, &startOffset, &endOffset); - attributes = joined.split (QLatin1Char(';'), QString::SkipEmptyParts, Qt::CaseSensitive); - foreach (const QString& attr, attributes) { - QStringList items; - items = attr.split(QLatin1Char(':'), QString::SkipEmptyParts, Qt::CaseSensitive); - AtSpiAttribute attribute = atspiTextAttribute(items[0], items[1]); - if (!attribute.isNull()) - map[attribute.name] = attribute.value; - } - mapped = map[attributeName]; - const bool defined = !mapped.isEmpty(); - QVariantList list; - list << mapped << startOffset << endOffset << defined; - return list; -} - -QList<QVariant> AtSpiAdaptor::getCharacterExtents(QAccessibleInterface *interface, int offset, uint coordType) const -{ - QRect rect = interface->textInterface()->characterRect(offset); - - if (coordType == ATSPI_COORD_TYPE_WINDOW) - rect = translateRectToWindowCoordinates(interface, rect); - - return QList<QVariant>() << rect.x() << rect.y() << rect.width() << rect.height(); -} - -QList<QVariant> AtSpiAdaptor::getRangeExtents(QAccessibleInterface *interface, - int startOffset, int endOffset, uint coordType) const -{ - if (endOffset == -1) - endOffset = interface->textInterface()->characterCount(); - - QAccessibleTextInterface *textInterface = interface->textInterface(); - if (endOffset <= startOffset || !textInterface) - return QList<QVariant>() << -1 << -1 << 0 << 0; - - QRect rect = textInterface->characterRect(startOffset); - for (int i=startOffset + 1; i <= endOffset; i++) - rect = rect | textInterface->characterRect(i); - - // relative to window - if (coordType == ATSPI_COORD_TYPE_WINDOW) - rect = translateRectToWindowCoordinates(interface, rect); - - return QList<QVariant>() << rect.x() << rect.y() << rect.width() << rect.height(); -} - -QRect AtSpiAdaptor::translateRectToWindowCoordinates(QAccessibleInterface *interface, const QRect &rect) -{ - QAccessibleInterface * window = getWindow(interface); - if (window) - return rect.translated(-window->rect().x(), -window->rect().y()); - - return rect; -} - - -// Editable Text interface -static QString textForRange(QAccessibleInterface *accessible, int startOffset, int endOffset) -{ - if (QAccessibleTextInterface *textIface = accessible->textInterface()) { - if (endOffset == -1) - endOffset = textIface->characterCount(); - return textIface->text(startOffset, endOffset); - } - QString txt = accessible->text(QAccessible::Value); - if (endOffset == -1) - endOffset = txt.length(); - return txt.mid(startOffset, endOffset - startOffset); -} - -static void replaceTextFallback(QAccessibleInterface *accessible, long startOffset, long endOffset, const QString &txt) -{ - QString t = textForRange(accessible, 0, -1); - if (endOffset == -1) - endOffset = t.length(); - if (endOffset - startOffset == 0) - t.insert(startOffset, txt); - else - t.replace(startOffset, endOffset - startOffset, txt); - accessible->setText(QAccessible::Value, t); -} - -bool AtSpiAdaptor::editableTextInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection) -{ - if (function == QLatin1String("CopyText")) { -#ifndef QT_NO_CLIPBOARD - int startOffset = message.arguments().at(0).toInt(); - int endOffset = message.arguments().at(1).toInt(); - const QString t = textForRange(interface, startOffset, endOffset); - QGuiApplication::clipboard()->setText(t); -#endif - connection.send(message.createReply(true)); - } else if (function == QLatin1String("CutText")) { -#ifndef QT_NO_CLIPBOARD - int startOffset = message.arguments().at(0).toInt(); - int endOffset = message.arguments().at(1).toInt(); - const QString t = textForRange(interface, startOffset, endOffset); - if (QAccessibleEditableTextInterface *editableTextIface = interface->editableTextInterface()) - editableTextIface->deleteText(startOffset, endOffset); - else - replaceTextFallback(interface, startOffset, endOffset, QString()); - QGuiApplication::clipboard()->setText(t); -#endif - connection.send(message.createReply(true)); - } else if (function == QLatin1String("DeleteText")) { - int startOffset = message.arguments().at(0).toInt(); - int endOffset = message.arguments().at(1).toInt(); - if (QAccessibleEditableTextInterface *editableTextIface = interface->editableTextInterface()) - editableTextIface->deleteText(startOffset, endOffset); - else - replaceTextFallback(interface, startOffset, endOffset, QString()); - connection.send(message.createReply(true)); - } else if (function == QLatin1String("InsertText")) { - int position = message.arguments().at(0).toInt(); - QString text = message.arguments().at(1).toString(); - int length = message.arguments().at(2).toInt(); - text.resize(length); - if (QAccessibleEditableTextInterface *editableTextIface = interface->editableTextInterface()) - editableTextIface->insertText(position, text); - else - replaceTextFallback(interface, position, position, text); - connection.send(message.createReply(true)); - } else if (function == QLatin1String("PasteText")) { -#ifndef QT_NO_CLIPBOARD - int position = message.arguments().at(0).toInt(); - const QString txt = QGuiApplication::clipboard()->text(); - if (QAccessibleEditableTextInterface *editableTextIface = interface->editableTextInterface()) - editableTextIface->insertText(position, txt); - else - replaceTextFallback(interface, position, position, txt); -#endif - connection.send(message.createReply(true)); - } else if (function == QLatin1String("SetTextContents")) { - QString newContents = message.arguments().at(0).toString(); - if (QAccessibleEditableTextInterface *editableTextIface = interface->editableTextInterface()) - editableTextIface->replaceText(0, interface->textInterface()->characterCount(), newContents); - else - replaceTextFallback(interface, 0, -1, newContents); - connection.send(message.createReply(true)); - } else if (function == QLatin1String("")) { - connection.send(message.createReply()); - } else { - qCDebug(lcAccessibilityAtspi) << "WARNING: AtSpiAdaptor::editableTextInterface does not implement " << function << message.path(); - return false; - } - return true; -} - -// Value interface -bool AtSpiAdaptor::valueInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection) -{ - QAccessibleValueInterface *valueIface = interface->valueInterface(); - if (!valueIface) - return false; - - if (function == QLatin1String("SetCurrentValue")) { - QDBusVariant v = message.arguments().at(2).value<QDBusVariant>(); - double value = v.variant().toDouble(); - //Temporary fix - //See https://bugzilla.gnome.org/show_bug.cgi?id=652596 - valueIface->setCurrentValue(value); - connection.send(message.createReply()); // FIXME is the reply needed? - } else { - QVariant value; - if (function == QLatin1String("GetCurrentValue")) - value = valueIface->currentValue(); - else if (function == QLatin1String("GetMaximumValue")) - value = valueIface->maximumValue(); - else if (function == QLatin1String("GetMinimumIncrement")) - value = valueIface->minimumStepSize(); - else if (function == QLatin1String("GetMinimumValue")) - value = valueIface->minimumValue(); - else { - qCDebug(lcAccessibilityAtspi) << "WARNING: AtSpiAdaptor::valueInterface does not implement " << function << message.path(); - return false; - } - if (!value.canConvert(QVariant::Double)) { - qCDebug(lcAccessibilityAtspi) << "AtSpiAdaptor::valueInterface: Could not convert to double: " << function; - } - - // explicitly convert to dbus-variant containing one double since atspi expects that - // everything else might fail to convert back on the other end - connection.send(message.createReply( - QVariant::fromValue(QDBusVariant(QVariant::fromValue(value.toDouble()))))); - } - return true; -} - -// Table interface -bool AtSpiAdaptor::tableInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection) -{ - if (!(interface->tableInterface() || interface->tableCellInterface())) { - qCDebug(lcAccessibilityAtspi) << "WARNING Qt AtSpiAdaptor: Could not find table interface for: " << message.path() << interface; - return false; - } - - if (0) { - // properties - } else if (function == QLatin1String("GetCaption")) { - QAccessibleInterface * captionInterface= interface->tableInterface()->caption(); - if (captionInterface) { - QSpiObjectReference ref = QSpiObjectReference(connection, QDBusObjectPath(pathForInterface(captionInterface))); - sendReply(connection, message, QVariant::fromValue(ref)); - } else { - sendReply(connection, message, QVariant::fromValue( - QSpiObjectReference(connection, QDBusObjectPath(ATSPI_DBUS_PATH_NULL)))); - } - } else if (function == QLatin1String("GetNColumns")) { - connection.send(message.createReply(QVariant::fromValue(QDBusVariant( - QVariant::fromValue(interface->tableInterface()->columnCount()))))); - } else if (function == QLatin1String("GetNRows")) { - connection.send(message.createReply(QVariant::fromValue(QDBusVariant( - QVariant::fromValue(interface->tableInterface()->rowCount()))))); - } else if (function == QLatin1String("GetNSelectedColumns")) { - connection.send(message.createReply(QVariant::fromValue(QDBusVariant( - QVariant::fromValue(interface->tableInterface()->selectedColumnCount()))))); - } else if (function == QLatin1String("GetNSelectedRows")) { - connection.send(message.createReply(QVariant::fromValue(QDBusVariant( - QVariant::fromValue(interface->tableInterface()->selectedRowCount()))))); - } else if (function == QLatin1String("GetSummary")) { - QAccessibleInterface * summary = interface->tableInterface() ? interface->tableInterface()->summary() : 0; - QSpiObjectReference ref(connection, QDBusObjectPath(pathForInterface(summary))); - connection.send(message.createReply(QVariant::fromValue(QDBusVariant(QVariant::fromValue(ref))))); - } else if (function == QLatin1String("GetAccessibleAt")) { - int row = message.arguments().at(0).toInt(); - int column = message.arguments().at(1).toInt(); - if ((row < 0) || - (column < 0) || - (row >= interface->tableInterface()->rowCount()) || - (column >= interface->tableInterface()->columnCount())) { - qCDebug(lcAccessibilityAtspi) << "WARNING: invalid index for tableInterface GetAccessibleAt (" << row << ", " << column << ')'; - return false; - } - - QSpiObjectReference ref; - QAccessibleInterface * cell(interface->tableInterface()->cellAt(row, column)); - if (cell) { - ref = QSpiObjectReference(connection, QDBusObjectPath(pathForInterface(cell))); - } else { - qCDebug(lcAccessibilityAtspi) << "WARNING: no cell interface returned for " << interface->object() << row << column; - ref = QSpiObjectReference(); - } - connection.send(message.createReply(QVariant::fromValue(ref))); - - } else if (function == QLatin1String("GetIndexAt")) { - int row = message.arguments().at(0).toInt(); - int column = message.arguments().at(1).toInt(); - QAccessibleInterface *cell = interface->tableInterface()->cellAt(row, column); - if (!cell) { - qCDebug(lcAccessibilityAtspi) << "WARNING: AtSpiAdaptor::GetIndexAt(" << row << ',' << column << ") did not find a cell. " << interface; - return false; - } - int index = interface->indexOfChild(cell); - qCDebug(lcAccessibilityAtspi) << "QSpiAdaptor::GetIndexAt row:" << row << " col:" << column << " logical index:" << index; - Q_ASSERT(index > 0); - connection.send(message.createReply(index)); - } else if ((function == QLatin1String("GetColumnAtIndex")) || (function == QLatin1String("GetRowAtIndex"))) { - int index = message.arguments().at(0).toInt(); - int ret = -1; - if (index >= 0) { - QAccessibleInterface * cell = interface->child(index); - if (cell) { - if (function == QLatin1String("GetColumnAtIndex")) { - if (cell->role() == QAccessible::ColumnHeader) { - ret = index; - } else if (cell->role() == QAccessible::RowHeader) { - ret = -1; - } else { - if (!cell->tableCellInterface()) { - qCDebug(lcAccessibilityAtspi) << "WARNING: AtSpiAdaptor::" << function << " No table cell interface: " << cell; - return false; - } - ret = cell->tableCellInterface()->columnIndex(); - } - } else { - if (cell->role() == QAccessible::ColumnHeader) { - ret = -1; - } else if (cell->role() == QAccessible::RowHeader) { - ret = index % interface->tableInterface()->columnCount(); - } else { - if (!cell->tableCellInterface()) { - qCDebug(lcAccessibilityAtspi) << "WARNING: AtSpiAdaptor::" << function << " No table cell interface: " << cell; - return false; - } - ret = cell->tableCellInterface()->rowIndex(); - } - } - } else { - qCDebug(lcAccessibilityAtspi) << "WARNING: AtSpiAdaptor::" << function << " No cell at index: " << index << interface; - return false; - } - } - connection.send(message.createReply(ret)); - - } else if (function == QLatin1String("GetColumnDescription")) { - int column = message.arguments().at(0).toInt(); - connection.send(message.createReply(interface->tableInterface()->columnDescription(column))); - } else if (function == QLatin1String("GetRowDescription")) { - int row = message.arguments().at(0).toInt(); - connection.send(message.createReply(interface->tableInterface()->rowDescription(row))); - - - - } else if (function == QLatin1String("GetRowColumnExtentsAtIndex")) { - int index = message.arguments().at(0).toInt(); - bool success = false; - - int row = -1; - int col = -1; - int rowExtents = -1; - int colExtents = -1; - bool isSelected = false; - - int cols = interface->tableInterface()->columnCount(); - if (cols > 0) { - row = index / cols; - col = index % cols; - QAccessibleTableCellInterface *cell = interface->tableInterface()->cellAt(row, col)->tableCellInterface(); - if (cell) { - row = cell->rowIndex(); - col = cell->columnIndex(); - rowExtents = cell->rowExtent(); - colExtents = cell->columnExtent(); - isSelected = cell->isSelected(); - success = true; - } - } - QVariantList list; - list << success << row << col << rowExtents << colExtents << isSelected; - connection.send(message.createReply(list)); - - } else if (function == QLatin1String("GetColumnExtentAt")) { - int row = message.arguments().at(0).toInt(); - int column = message.arguments().at(1).toInt(); - connection.send(message.createReply(interface->tableInterface()->cellAt(row, column)->tableCellInterface()->columnExtent())); - - } else if (function == QLatin1String("GetRowExtentAt")) { - int row = message.arguments().at(0).toInt(); - int column = message.arguments().at(1).toInt(); - connection.send(message.createReply(interface->tableInterface()->cellAt(row, column)->tableCellInterface()->rowExtent())); - - } else if (function == QLatin1String("GetColumnHeader")) { - int column = message.arguments().at(0).toInt(); - QSpiObjectReference ref; - - QAccessibleInterface * cell(interface->tableInterface()->cellAt(0, column)); - if (cell && cell->tableCellInterface()) { - QList<QAccessibleInterface*> header = cell->tableCellInterface()->columnHeaderCells(); - if (header.size() > 0) { - ref = QSpiObjectReference(connection, QDBusObjectPath(pathForInterface(header.takeAt(0)))); - } - } - connection.send(message.createReply(QVariant::fromValue(ref))); - - } else if (function == QLatin1String("GetRowHeader")) { - int row = message.arguments().at(0).toInt(); - QSpiObjectReference ref; - QAccessibleTableCellInterface *cell = interface->tableInterface()->cellAt(row, 0)->tableCellInterface(); - if (cell) { - QList<QAccessibleInterface*> header = cell->rowHeaderCells(); - if (header.size() > 0) { - ref = QSpiObjectReference(connection, QDBusObjectPath(pathForInterface(header.takeAt(0)))); - } - } - connection.send(message.createReply(QVariant::fromValue(ref))); - - } else if (function == QLatin1String("GetSelectedColumns")) { - connection.send(message.createReply(QVariant::fromValue(interface->tableInterface()->selectedColumns()))); - } else if (function == QLatin1String("GetSelectedRows")) { - connection.send(message.createReply(QVariant::fromValue(interface->tableInterface()->selectedRows()))); - } else if (function == QLatin1String("IsColumnSelected")) { - int column = message.arguments().at(0).toInt(); - connection.send(message.createReply(interface->tableInterface()->isColumnSelected(column))); - } else if (function == QLatin1String("IsRowSelected")) { - int row = message.arguments().at(0).toInt(); - connection.send(message.createReply(interface->tableInterface()->isRowSelected(row))); - } else if (function == QLatin1String("IsSelected")) { - int row = message.arguments().at(0).toInt(); - int column = message.arguments().at(1).toInt(); - QAccessibleTableCellInterface* cell = interface->tableInterface()->cellAt(row, column)->tableCellInterface(); - connection.send(message.createReply(cell->isSelected())); - } else if (function == QLatin1String("AddColumnSelection")) { - int column = message.arguments().at(0).toInt(); - connection.send(message.createReply(interface->tableInterface()->selectColumn(column))); - } else if (function == QLatin1String("AddRowSelection")) { - int row = message.arguments().at(0).toInt(); - connection.send(message.createReply(interface->tableInterface()->selectRow(row))); - } else if (function == QLatin1String("RemoveColumnSelection")) { - int column = message.arguments().at(0).toInt(); - connection.send(message.createReply(interface->tableInterface()->unselectColumn(column))); - } else if (function == QLatin1String("RemoveRowSelection")) { - int row = message.arguments().at(0).toInt(); - connection.send(message.createReply(interface->tableInterface()->unselectRow(row))); - } else { - qCDebug(lcAccessibilityAtspi) << "WARNING: AtSpiAdaptor::tableInterface does not implement " << function << message.path(); - return false; - } - return true; -} - -QT_END_NAMESPACE -#endif //QT_NO_ACCESSIBILITY diff --git a/src/platformsupport/linuxaccessibility/atspiadaptor_p.h b/src/platformsupport/linuxaccessibility/atspiadaptor_p.h deleted file mode 100644 index b5704f53ad..0000000000 --- a/src/platformsupport/linuxaccessibility/atspiadaptor_p.h +++ /dev/null @@ -1,228 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#ifndef ATSPIADAPTOR_H -#define ATSPIADAPTOR_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <atspi/atspi-constants.h> - -#include <QtGui/private/qtguiglobal_p.h> -#include <QtCore/qsharedpointer.h> -#include <QtDBus/qdbusvirtualobject.h> -#include <QtGui/qaccessible.h> - -#include "dbusconnection_p.h" -#include "struct_marshallers_p.h" - -QT_REQUIRE_CONFIG(accessibility); - -QT_BEGIN_NAMESPACE - -class QAccessibleInterface; -class QSpiAccessibleInterface; -class QSpiApplicationAdaptor; - - -class AtSpiAdaptor :public QDBusVirtualObject -{ - Q_OBJECT - -public: - explicit AtSpiAdaptor(DBusConnection *connection, QObject *parent = 0); - ~AtSpiAdaptor(); - - void registerApplication(); - QString introspect(const QString &path) const; - bool handleMessage(const QDBusMessage &message, const QDBusConnection &connection); - void notify(QAccessibleEvent *event); - - void init(); - void checkInitializedAndEnabled(); -public Q_SLOTS: - void eventListenerRegistered(const QString &bus, const QString &path); - void eventListenerDeregistered(const QString &bus, const QString &path); - void windowActivated(QObject* window, bool active); - -private: - void updateEventListeners(); - void setBitFlag(const QString &flag); - - // sending messages - QVariantList packDBusSignalArguments(const QString &type, int data1, int data2, const QVariant &variantData) const; - bool sendDBusSignal(const QString &path, const QString &interface, const QString &name, const QVariantList &arguments) const; - QVariant variantForPath(const QString &path) const; - - void sendFocusChanged(QAccessibleInterface *interface) const; - void notifyAboutCreation(QAccessibleInterface *interface) const; - void notifyAboutDestruction(QAccessibleInterface *interface) const; - void childrenChanged(QAccessibleInterface *interface) const; - - // handlers for the different accessible interfaces - bool applicationInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection); - bool accessibleInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection); - bool componentInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection); - bool actionInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection); - bool textInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection); - bool editableTextInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection); - bool valueInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection); - bool tableInterface(QAccessibleInterface *interface, const QString &function, const QDBusMessage &message, const QDBusConnection &connection); - - void sendReply(const QDBusConnection &connection, const QDBusMessage &message, const QVariant &argument) const; - - QAccessibleInterface *interfaceFromPath(const QString& dbusPath) const; - QString pathForInterface(QAccessibleInterface *interface) const; - QString pathForObject(QObject *object) const; - - void notifyStateChange(QAccessibleInterface *interface, const QString& state, int value); - - // accessible helper functions - AtspiRole getRole(QAccessibleInterface *interface) const; - QSpiRelationArray relationSet(QAccessibleInterface *interface, const QDBusConnection &connection) const; - QStringList accessibleInterfaces(QAccessibleInterface *interface) const; - - // component helper functions - static QRect getExtents(QAccessibleInterface *interface, uint coordType); - static QRect translateRectToWindowCoordinates(QAccessibleInterface *interface, const QRect &rect); - - // action helper functions - QSpiActionArray getActions(QAccessibleInterface *interface) const; - - // text helper functions - QVariantList getAttributes(QAccessibleInterface *, int offset, bool includeDefaults) const; - QVariantList getAttributeValue(QAccessibleInterface *, int offset, const QString &attributeName) const; - QList<QVariant> getCharacterExtents(QAccessibleInterface *, int offset, uint coordType) const; - QList<QVariant> getRangeExtents(QAccessibleInterface *, int startOffset, int endOffset, uint coordType) const; - QAccessible::TextBoundaryType qAccessibleBoundaryType(int atspiTextBoundaryType) const; - static bool inheritsQAction(QObject *object); - - // private vars - QSpiObjectReference accessibilityRegistry; - DBusConnection *m_dbus; - QSpiApplicationAdaptor *m_applicationAdaptor; - - /// Assigned from the accessibility registry. - int m_applicationId; - - // Bit fields - which updates to send - - // AT-SPI has some events that we do not care about: - // document - // document-load-complete - // document-load-stopped - // document-reload - uint sendFocus : 1; - // mouse abs/rel/button - - // all of object - uint sendObject : 1; - uint sendObject_active_descendant_changed : 1; - uint sendObject_attributes_changed : 1; - uint sendObject_bounds_changed : 1; - uint sendObject_children_changed : 1; -// uint sendObject_children_changed_add : 1; -// uint sendObject_children_changed_remove : 1; - uint sendObject_column_deleted : 1; - uint sendObject_column_inserted : 1; - uint sendObject_column_reordered : 1; - uint sendObject_link_selected : 1; - uint sendObject_model_changed : 1; - uint sendObject_property_change : 1; - uint sendObject_property_change_accessible_description : 1; - uint sendObject_property_change_accessible_name : 1; - uint sendObject_property_change_accessible_parent : 1; - uint sendObject_property_change_accessible_role : 1; - uint sendObject_property_change_accessible_table_caption : 1; - uint sendObject_property_change_accessible_table_column_description : 1; - uint sendObject_property_change_accessible_table_column_header : 1; - uint sendObject_property_change_accessible_table_row_description : 1; - uint sendObject_property_change_accessible_table_row_header : 1; - uint sendObject_property_change_accessible_table_summary : 1; - uint sendObject_property_change_accessible_value : 1; - uint sendObject_row_deleted : 1; - uint sendObject_row_inserted : 1; - uint sendObject_row_reordered : 1; - uint sendObject_selection_changed : 1; - uint sendObject_state_changed : 1; - uint sendObject_text_attributes_changed : 1; - uint sendObject_text_bounds_changed : 1; - uint sendObject_text_caret_moved : 1; - uint sendObject_text_changed : 1; -// uint sendObject_text_changed_delete : 1; -// uint sendObject_text_changed_insert : 1; - uint sendObject_text_selection_changed : 1; - uint sendObject_value_changed : 1; - uint sendObject_visible_data_changed : 1; - - // we don't implement terminal - // terminal-application_changed/charwidth_changed/columncount_changed/line_changed/linecount_changed - uint sendWindow : 1; - uint sendWindow_activate : 1; - uint sendWindow_close: 1; - uint sendWindow_create : 1; - uint sendWindow_deactivate : 1; -// uint sendWindow_desktop_create : 1; -// uint sendWindow_desktop_destroy : 1; - uint sendWindow_lower : 1; - uint sendWindow_maximize : 1; - uint sendWindow_minimize : 1; - uint sendWindow_move : 1; - uint sendWindow_raise : 1; - uint sendWindow_reparent : 1; - uint sendWindow_resize : 1; - uint sendWindow_restore : 1; - uint sendWindow_restyle : 1; - uint sendWindow_shade : 1; - uint sendWindow_unshade : 1; -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/platformsupport/linuxaccessibility/bridge.cpp b/src/platformsupport/linuxaccessibility/bridge.cpp deleted file mode 100644 index fdc8cd3198..0000000000 --- a/src/platformsupport/linuxaccessibility/bridge.cpp +++ /dev/null @@ -1,286 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include "bridge_p.h" - -#include <atspi/atspi-constants.h> -#include <qstring.h> - -#include "atspiadaptor_p.h" - -#include "cache_p.h" -#include "constant_mappings_p.h" -#include "dbusconnection_p.h" -#include "struct_marshallers_p.h" - -#ifndef QT_NO_ACCESSIBILITY -#include "deviceeventcontroller_adaptor.h" - -QT_BEGIN_NAMESPACE - -/*! - \class QSpiAccessibleBridge - \internal -*/ - -QSpiAccessibleBridge::QSpiAccessibleBridge() - : cache(0), dec(0), dbusAdaptor(0) -{ - dbusConnection = new DBusConnection(); - connect(dbusConnection, SIGNAL(enabledChanged(bool)), this, SLOT(enabledChanged(bool))); -} - -void QSpiAccessibleBridge::enabledChanged(bool enabled) -{ - setActive(enabled); - updateStatus(); -} - -QSpiAccessibleBridge::~QSpiAccessibleBridge() -{ - delete dbusConnection; -} // Qt currently doesn't delete plugins. - -QDBusConnection QSpiAccessibleBridge::dBusConnection() const -{ - return dbusConnection->connection(); -} - -void QSpiAccessibleBridge::updateStatus() -{ - // create the adaptor to handle everything if we are in enabled state - if (!dbusAdaptor && isActive()) { - qSpiInitializeStructTypes(); - initializeConstantMappings(); - - cache = new QSpiDBusCache(dbusConnection->connection(), this); - dec = new DeviceEventControllerAdaptor(this); - - dbusConnection->connection().registerObject(QLatin1String(ATSPI_DBUS_PATH_DEC), this, QDBusConnection::ExportAdaptors); - - dbusAdaptor = new AtSpiAdaptor(dbusConnection, this); - dbusConnection->connection().registerVirtualObject(QLatin1String(QSPI_OBJECT_PATH_ACCESSIBLE), dbusAdaptor, QDBusConnection::SubPath); - dbusAdaptor->registerApplication(); - } -} - -void QSpiAccessibleBridge::notifyAccessibilityUpdate(QAccessibleEvent *event) -{ - if (!dbusAdaptor) - return; - if (isActive() && event->accessibleInterface()) - dbusAdaptor->notify(event); -} - -struct RoleMapping { - QAccessible::Role role; - AtspiRole spiRole; - const char *name; -}; - -static RoleMapping map[] = { - //: Role of an accessible object - the object is in an invalid state or could not be constructed - { QAccessible::NoRole, ATSPI_ROLE_INVALID, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "invalid role") }, - //: Role of an accessible object - { QAccessible::TitleBar, ATSPI_ROLE_TEXT, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "title bar") }, - //: Role of an accessible object - { QAccessible::MenuBar, ATSPI_ROLE_MENU_BAR, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "menu bar") }, - //: Role of an accessible object - { QAccessible::ScrollBar, ATSPI_ROLE_SCROLL_BAR, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "scroll bar") }, - //: Role of an accessible object - the grip is usually used for resizing another object - { QAccessible::Grip, ATSPI_ROLE_UNKNOWN, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "grip") }, - //: Role of an accessible object - { QAccessible::Sound, ATSPI_ROLE_UNKNOWN, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "sound") }, - //: Role of an accessible object - { QAccessible::Cursor, ATSPI_ROLE_UNKNOWN, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "cursor") }, - //: Role of an accessible object - { QAccessible::Caret, ATSPI_ROLE_UNKNOWN, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "text caret") }, - //: Role of an accessible object - { QAccessible::AlertMessage, ATSPI_ROLE_ALERT, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "alert message") }, - //: Role of an accessible object: a window with frame and title - { QAccessible::Window, ATSPI_ROLE_FRAME, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "frame") }, - //: Role of an accessible object - { QAccessible::Client, ATSPI_ROLE_FILLER, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "filler") }, - //: Role of an accessible object - { QAccessible::PopupMenu, ATSPI_ROLE_POPUP_MENU, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "popup menu") }, - //: Role of an accessible object - { QAccessible::MenuItem, ATSPI_ROLE_MENU_ITEM, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "menu item") }, - //: Role of an accessible object - { QAccessible::ToolTip, ATSPI_ROLE_TOOL_TIP, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "tool tip") }, - //: Role of an accessible object - { QAccessible::Application, ATSPI_ROLE_APPLICATION, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "application") }, - //: Role of an accessible object - { QAccessible::Document, ATSPI_ROLE_DOCUMENT_FRAME, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "document") }, - //: Role of an accessible object - { QAccessible::Pane, ATSPI_ROLE_PANEL, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "panel") }, - //: Role of an accessible object - { QAccessible::Chart, ATSPI_ROLE_CHART, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "chart") }, - //: Role of an accessible object - { QAccessible::Dialog, ATSPI_ROLE_DIALOG, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "dialog") }, - //: Role of an accessible object - { QAccessible::Border, ATSPI_ROLE_FRAME, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "frame") }, - //: Role of an accessible object - { QAccessible::Grouping, ATSPI_ROLE_PANEL, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "panel") }, - //: Role of an accessible object - { QAccessible::Separator, ATSPI_ROLE_SEPARATOR, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "separator") }, - //: Role of an accessible object - { QAccessible::ToolBar, ATSPI_ROLE_TOOL_BAR, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "tool bar") }, - //: Role of an accessible object - { QAccessible::StatusBar, ATSPI_ROLE_STATUS_BAR, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "status bar") }, - //: Role of an accessible object - { QAccessible::Table, ATSPI_ROLE_TABLE, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "table") }, - //: Role of an accessible object - part of a table - { QAccessible::ColumnHeader, ATSPI_ROLE_TABLE_COLUMN_HEADER, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "column header") }, - //: Role of an accessible object - part of a table - { QAccessible::RowHeader, ATSPI_ROLE_TABLE_ROW_HEADER, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "row header") }, - //: Role of an accessible object - part of a table - { QAccessible::Column, ATSPI_ROLE_TABLE_CELL, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "column") }, - //: Role of an accessible object - part of a table - { QAccessible::Row, ATSPI_ROLE_TABLE_ROW, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "row") }, - //: Role of an accessible object - part of a table - { QAccessible::Cell, ATSPI_ROLE_TABLE_CELL, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "cell") }, - //: Role of an accessible object - { QAccessible::Link, ATSPI_ROLE_LINK, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "link") }, - //: Role of an accessible object - { QAccessible::HelpBalloon, ATSPI_ROLE_DIALOG, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "help balloon") }, - //: Role of an accessible object - a helper dialog - { QAccessible::Assistant, ATSPI_ROLE_DIALOG, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "assistant") }, - //: Role of an accessible object - { QAccessible::List, ATSPI_ROLE_LIST, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "list") }, - //: Role of an accessible object - { QAccessible::ListItem, ATSPI_ROLE_LIST_ITEM, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "list item") }, - //: Role of an accessible object - { QAccessible::Tree, ATSPI_ROLE_TREE, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "tree") }, - //: Role of an accessible object - { QAccessible::TreeItem, ATSPI_ROLE_TABLE_CELL, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "tree item") }, - //: Role of an accessible object - { QAccessible::PageTab, ATSPI_ROLE_PAGE_TAB, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "page tab") }, - //: Role of an accessible object - { QAccessible::PropertyPage, ATSPI_ROLE_PAGE_TAB, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "property page") }, - //: Role of an accessible object - { QAccessible::Indicator, ATSPI_ROLE_UNKNOWN, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "indicator") }, - //: Role of an accessible object - { QAccessible::Graphic, ATSPI_ROLE_IMAGE, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "graphic") }, - //: Role of an accessible object - { QAccessible::StaticText, ATSPI_ROLE_LABEL, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "label") }, - //: Role of an accessible object - { QAccessible::EditableText, ATSPI_ROLE_TEXT, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "text") }, - //: Role of an accessible object - { QAccessible::PushButton, ATSPI_ROLE_PUSH_BUTTON, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "push button") }, - //: Role of an accessible object - { QAccessible::CheckBox, ATSPI_ROLE_CHECK_BOX, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "check box") }, - //: Role of an accessible object - { QAccessible::RadioButton, ATSPI_ROLE_RADIO_BUTTON, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "radio button") }, - //: Role of an accessible object - { QAccessible::ComboBox, ATSPI_ROLE_COMBO_BOX, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "combo box") }, - //: Role of an accessible object - { QAccessible::ProgressBar, ATSPI_ROLE_PROGRESS_BAR, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "progress bar") }, - //: Role of an accessible object - { QAccessible::Dial, ATSPI_ROLE_DIAL, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "dial") }, - //: Role of an accessible object - { QAccessible::HotkeyField, ATSPI_ROLE_TEXT, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "hotkey field") }, - //: Role of an accessible object - { QAccessible::Slider, ATSPI_ROLE_SLIDER, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "slider") }, - //: Role of an accessible object - { QAccessible::SpinBox, ATSPI_ROLE_SPIN_BUTTON, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "spin box") }, - //: Role of an accessible object - { QAccessible::Canvas, ATSPI_ROLE_CANVAS, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "canvas") }, - //: Role of an accessible object - { QAccessible::Animation, ATSPI_ROLE_ANIMATION, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "animation") }, - //: Role of an accessible object - { QAccessible::Equation, ATSPI_ROLE_TEXT, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "equation") }, - //: Role of an accessible object - { QAccessible::ButtonDropDown, ATSPI_ROLE_PUSH_BUTTON, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "button with drop down") }, - //: Role of an accessible object - { QAccessible::ButtonMenu, ATSPI_ROLE_PUSH_BUTTON, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "button menu") }, - //: Role of an accessible object - a button that expands a grid. - { QAccessible::ButtonDropGrid, ATSPI_ROLE_PUSH_BUTTON, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "button with drop down grid") }, - //: Role of an accessible object - blank space between other objects. - { QAccessible::Whitespace, ATSPI_ROLE_FILLER, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "space") }, - //: Role of an accessible object - { QAccessible::PageTabList, ATSPI_ROLE_PAGE_TAB_LIST, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "page tab list") }, - //: Role of an accessible object - { QAccessible::Clock, ATSPI_ROLE_UNKNOWN, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "clock") }, - //: Role of an accessible object - { QAccessible::Splitter, ATSPI_ROLE_SPLIT_PANE, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "splitter") }, - //: Role of an accessible object - { QAccessible::LayeredPane, ATSPI_ROLE_LAYERED_PANE, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "layered pane") }, - //: Role of an accessible object - { QAccessible::WebDocument, ATSPI_ROLE_DOCUMENT_WEB, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "web document") }, - //: Role of an accessible object - { QAccessible::Paragraph, ATSPI_ROLE_PARAGRAPH, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "paragraph") }, - //: Role of an accessible object - { QAccessible::Section, ATSPI_ROLE_SECTION, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "section") }, - //: Role of an accessible object - { QAccessible::ColorChooser, ATSPI_ROLE_COLOR_CHOOSER, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "color chooser") }, - //: Role of an accessible object - { QAccessible::Footer, ATSPI_ROLE_FOOTER, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "footer") }, - //: Role of an accessible object - { QAccessible::Form, ATSPI_ROLE_FORM, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "form") }, - //: Role of an accessible object - { QAccessible::Heading, ATSPI_ROLE_HEADING, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "heading") }, - //: Role of an accessible object - { QAccessible::Note, ATSPI_ROLE_COMMENT, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "note") }, - //: Role of an accessible object - { QAccessible::ComplementaryContent, ATSPI_ROLE_SECTION, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "complementary content") }, - //: Role of an accessible object - { QAccessible::Terminal, ATSPI_ROLE_TERMINAL, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "terminal") }, - //: Role of an accessible object - { QAccessible::Desktop, ATSPI_ROLE_DESKTOP_FRAME, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "desktop") }, - //: Role of an accessible object - { QAccessible::Notification, ATSPI_ROLE_NOTIFICATION, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "notification") }, - //: Role of an accessible object - { QAccessible::UserRole, ATSPI_ROLE_UNKNOWN, QT_TRANSLATE_NOOP("QSpiAccessibleBridge", "unknown") } -}; - -void QSpiAccessibleBridge::initializeConstantMappings() -{ - for (uint i = 0; i < sizeof(map) / sizeof(RoleMapping); ++i) - qSpiRoleMapping.insert(map[i].role, RoleNames(map[i].spiRole, QLatin1String(map[i].name), tr(map[i].name))); - - // -1 because we have button duplicated, as PushButton and Button. - Q_ASSERT_X(qSpiRoleMapping.size() == - QAccessible::staticMetaObject.enumerator( - QAccessible::staticMetaObject.indexOfEnumerator("Role")).keyCount() - 1, - "", "Handle all QAccessible::Role members in qSpiRoleMapping"); -} - -QT_END_NAMESPACE -#endif //QT_NO_ACCESSIBILITY diff --git a/src/platformsupport/linuxaccessibility/bridge_p.h b/src/platformsupport/linuxaccessibility/bridge_p.h deleted file mode 100644 index c48bbd3710..0000000000 --- a/src/platformsupport/linuxaccessibility/bridge_p.h +++ /dev/null @@ -1,95 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#ifndef QSPIACCESSIBLEBRIDGE_H -#define QSPIACCESSIBLEBRIDGE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qtguiglobal_p.h> -#include <QtDBus/qdbusconnection.h> -#include <qpa/qplatformaccessibility.h> - -class DeviceEventControllerAdaptor; - -QT_REQUIRE_CONFIG(accessibility); - -QT_BEGIN_NAMESPACE - -class DBusConnection; -class QSpiDBusCache; -class AtSpiAdaptor; - -class QSpiAccessibleBridge: public QObject, public QPlatformAccessibility -{ - Q_OBJECT -public: - QSpiAccessibleBridge(); - - virtual ~QSpiAccessibleBridge(); - - void notifyAccessibilityUpdate(QAccessibleEvent *event) override; - QDBusConnection dBusConnection() const; - -public Q_SLOTS: - void enabledChanged(bool enabled); - -private: - void initializeConstantMappings(); - void updateStatus(); - - QSpiDBusCache *cache; - DeviceEventControllerAdaptor *dec; - AtSpiAdaptor *dbusAdaptor; - DBusConnection* dbusConnection; -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/platformsupport/linuxaccessibility/cache.cpp b/src/platformsupport/linuxaccessibility/cache.cpp deleted file mode 100644 index fe4d1e26f9..0000000000 --- a/src/platformsupport/linuxaccessibility/cache.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include "cache_p.h" -#include "bridge_p.h" - -#ifndef QT_NO_ACCESSIBILITY -#include "cache_adaptor.h" - -#define QSPI_OBJECT_PATH_CACHE "/org/a11y/atspi/cache" - -QT_BEGIN_NAMESPACE - -/*! - \class QSpiDBusCache - \internal - \brief This class is responsible for the AT-SPI cache interface. - - The idea behind the cache is that starting an application would - result in many dbus calls. The way GTK/Gail/ATK work is that - they create accessibles for all objects on startup. - In order to avoid querying all the objects individually via DBus - they get sent by using the GetItems call of the cache. - - Additionally the AddAccessible and RemoveAccessible signals - are responsible for adding/removing objects from the cache. - - Currently the Qt bridge chooses to ignore these. -*/ - -QSpiDBusCache::QSpiDBusCache(QDBusConnection c, QObject* parent) - : QObject(parent) -{ - new CacheAdaptor(this); - c.registerObject(QLatin1String(QSPI_OBJECT_PATH_CACHE), this, QDBusConnection::ExportAdaptors); -} - -void QSpiDBusCache::emitAddAccessible(const QSpiAccessibleCacheItem& item) -{ - emit AddAccessible(item); -} - -void QSpiDBusCache::emitRemoveAccessible(const QSpiObjectReference& item) -{ - emit RemoveAccessible(item); -} - -QSpiAccessibleCacheArray QSpiDBusCache::GetItems() -{ - return QSpiAccessibleCacheArray(); -} - -QT_END_NAMESPACE -#endif //QT_NO_ACCESSIBILITY diff --git a/src/platformsupport/linuxaccessibility/cache_p.h b/src/platformsupport/linuxaccessibility/cache_p.h deleted file mode 100644 index e8529b779b..0000000000 --- a/src/platformsupport/linuxaccessibility/cache_p.h +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#ifndef Q_SPI_CACHE_H -#define Q_SPI_CACHE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qtguiglobal_p.h> -#include <QtCore/QObject> -#include "struct_marshallers_p.h" - -QT_REQUIRE_CONFIG(accessibility); - -QT_BEGIN_NAMESPACE - -class QSpiDBusCache : public QObject -{ - Q_OBJECT - -public: - explicit QSpiDBusCache(QDBusConnection c, QObject* parent = 0); - void emitAddAccessible(const QSpiAccessibleCacheItem& item); - void emitRemoveAccessible(const QSpiObjectReference& item); - -Q_SIGNALS: - void AddAccessible(const QSpiAccessibleCacheItem &nodeAdded); - void RemoveAccessible(const QSpiObjectReference &nodeRemoved); - -public Q_SLOTS: - QSpiAccessibleCacheArray GetItems(); -}; - -QT_END_NAMESPACE - -#endif /* Q_SPI_CACHE_H */ diff --git a/src/platformsupport/linuxaccessibility/constant_mappings.cpp b/src/platformsupport/linuxaccessibility/constant_mappings.cpp deleted file mode 100644 index fce2919e73..0000000000 --- a/src/platformsupport/linuxaccessibility/constant_mappings.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include "constant_mappings_p.h" - -#include <qobject.h> -#include <qdebug.h> - -// FIXME the assignment of roles is quite arbitrary, at some point go through this list and sort and check that it makes sense -// "calendar" "check menu item" "color chooser" "column header" "dateeditor" "desktop icon" "desktop frame" -// "directory pane" "drawing area" "file chooser" "fontchooser" "frame" "glass pane" "html container" "icon" -// "internal frame" "option pane" "password text" "radio menu item" "root pane" "row header" "scroll pane" -// "tear off menu item" "terminal" "toggle button" "tree table" "unknown" "viewport" "header" "footer" "paragraph" -// "ruler" "autocomplete" "edit bar" "embedded component" "entry" "caption" -// "heading" "page" "section" "redundant object" "form" "input method window" "menu" - -#ifndef QT_NO_ACCESSIBILITY -QT_BEGIN_NAMESPACE - -QHash <QAccessible::Role, RoleNames> qSpiRoleMapping; - -quint64 spiStatesFromQState(QAccessible::State state) -{ - quint64 spiState = 0; - - if (state.active) - setSpiStateBit(&spiState, ATSPI_STATE_ACTIVE); - if (state.editable) - setSpiStateBit(&spiState, ATSPI_STATE_EDITABLE); - if (!state.disabled) { - setSpiStateBit(&spiState, ATSPI_STATE_ENABLED); - setSpiStateBit(&spiState, ATSPI_STATE_SENSITIVE); - } - if (state.selected) - setSpiStateBit(&spiState, ATSPI_STATE_SELECTED); - if (state.focused) - setSpiStateBit(&spiState, ATSPI_STATE_FOCUSED); - if (state.pressed) - setSpiStateBit(&spiState, ATSPI_STATE_PRESSED); - if (state.checked) - setSpiStateBit(&spiState, ATSPI_STATE_CHECKED); - if (state.checkStateMixed) - setSpiStateBit(&spiState, ATSPI_STATE_INDETERMINATE); - if (state.readOnly) - setSpiStateBit(&spiState, ATSPI_STATE_READ_ONLY); - // if (state.HotTracked) - if (state.defaultButton) - setSpiStateBit(&spiState, ATSPI_STATE_IS_DEFAULT); - if (state.expandable) - setSpiStateBit(&spiState, ATSPI_STATE_EXPANDABLE); - if (state.expanded) - setSpiStateBit(&spiState, ATSPI_STATE_EXPANDED); - if (state.collapsed) - setSpiStateBit(&spiState, ATSPI_STATE_COLLAPSED); - if (state.busy) - setSpiStateBit(&spiState, ATSPI_STATE_BUSY); - if (state.marqueed || state.animated) - setSpiStateBit(&spiState, ATSPI_STATE_ANIMATED); - if (!state.invisible && !state.offscreen) { - setSpiStateBit(&spiState, ATSPI_STATE_SHOWING); - setSpiStateBit(&spiState, ATSPI_STATE_VISIBLE); - } - if (state.sizeable) - setSpiStateBit(&spiState, ATSPI_STATE_RESIZABLE); - // if (state.Movable) - // if (state.SelfVoicing) - if (state.focusable) - setSpiStateBit(&spiState, ATSPI_STATE_FOCUSABLE); - if (state.selectable) - setSpiStateBit(&spiState, ATSPI_STATE_SELECTABLE); - // if (state.Linked) - if (state.traversed) - setSpiStateBit(&spiState, ATSPI_STATE_VISITED); - if (state.multiSelectable) - setSpiStateBit(&spiState, ATSPI_STATE_MULTISELECTABLE); - if (state.extSelectable) - setSpiStateBit(&spiState, ATSPI_STATE_SELECTABLE); - // if (state.Protected) - // if (state.HasPopup) - if (state.modal) - setSpiStateBit(&spiState, ATSPI_STATE_MODAL); - if (state.multiLine) - setSpiStateBit(&spiState, ATSPI_STATE_MULTI_LINE); - - return spiState; -} - -QSpiUIntList spiStateSetFromSpiStates(quint64 states) -{ - uint low = states & 0xFFFFFFFF; - uint high = (states >> 32) & 0xFFFFFFFF; - - QSpiUIntList stateList; - stateList.append(low); - stateList.append(high); - return stateList; -} - -AtspiRelationType qAccessibleRelationToAtSpiRelation(QAccessible::Relation relation) -{ - switch (relation) { - case QAccessible::Label: - return ATSPI_RELATION_LABELLED_BY; - case QAccessible::Labelled: - return ATSPI_RELATION_LABEL_FOR; - case QAccessible::Controller: - return ATSPI_RELATION_CONTROLLED_BY; - case QAccessible::Controlled: - return ATSPI_RELATION_CONTROLLER_FOR; - default: - qWarning() << "Cannot return AT-SPI relation for:" << relation; - } - return ATSPI_RELATION_NULL; -} - -QT_END_NAMESPACE -#endif //QT_NO_ACCESSIBILITY diff --git a/src/platformsupport/linuxaccessibility/constant_mappings_p.h b/src/platformsupport/linuxaccessibility/constant_mappings_p.h deleted file mode 100644 index 4da818c8c1..0000000000 --- a/src/platformsupport/linuxaccessibility/constant_mappings_p.h +++ /dev/null @@ -1,146 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -/* - * This file contains AT-SPI constants and mappings between QAccessible - * and AT-SPI constants such as 'role' and 'state' enumerations. - */ - -#ifndef Q_SPI_CONSTANT_MAPPINGS_H -#define Q_SPI_CONSTANT_MAPPINGS_H - -#include "struct_marshallers_p.h" - -#include <QtGui/private/qtguiglobal_p.h> -#include <QtGui/QAccessible> -#include <atspi/atspi-constants.h> - -QT_REQUIRE_CONFIG(accessibility); - -// interface names from at-spi2-core/atspi/atspi-misc-private.h -#define ATSPI_DBUS_NAME_REGISTRY "org.a11y.atspi.Registry" -#define ATSPI_DBUS_PATH_REGISTRY "/org/a11y/atspi/registry" -#define ATSPI_DBUS_INTERFACE_REGISTRY "org.a11y.atspi.Registry" - -#define ATSPI_DBUS_PATH_ROOT "/org/a11y/atspi/accessible/root" - -#define ATSPI_DBUS_PATH_DEC "/org/a11y/atspi/registry/deviceeventcontroller" -#define ATSPI_DBUS_INTERFACE_DEC "org.a11y.atspi.DeviceEventController" -#define ATSPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER "org.a11y.atspi.DeviceEventListener" - -#define ATSPI_DBUS_INTERFACE_CACHE "org.a11y.atspi.Cache" -#define ATSPI_DBUS_INTERFACE_ACCESSIBLE "org.a11y.atspi.Accessible" -#define ATSPI_DBUS_INTERFACE_ACTION "org.a11y.atspi.Action" -#define ATSPI_DBUS_INTERFACE_APPLICATION "org.a11y.atspi.Application" -#define ATSPI_DBUS_INTERFACE_COLLECTION "org.a11y.atspi.Collection" -#define ATSPI_DBUS_INTERFACE_COMPONENT "org.a11y.atspi.Component" -#define ATSPI_DBUS_INTERFACE_DOCUMENT "org.a11y.atspi.Document" -#define ATSPI_DBUS_INTERFACE_EDITABLE_TEXT "org.a11y.atspi.EditableText" -#define ATSPI_DBUS_INTERFACE_EVENT_KEYBOARD "org.a11y.atspi.Event.Keyboard" -#define ATSPI_DBUS_INTERFACE_EVENT_MOUSE "org.a11y.atspi.Event.Mouse" -#define ATSPI_DBUS_INTERFACE_EVENT_OBJECT "org.a11y.atspi.Event.Object" -#define ATSPI_DBUS_INTERFACE_HYPERLINK "org.a11y.atspi.Hyperlink" -#define ATSPI_DBUS_INTERFACE_HYPERTEXT "org.a11y.atspi.Hypertext" -#define ATSPI_DBUS_INTERFACE_IMAGE "org.a11y.atspi.Image" -#define ATSPI_DBUS_INTERFACE_SELECTION "org.a11y.atspi.Selection" -#define ATSPI_DBUS_INTERFACE_TABLE "org.a11y.atspi.Table" -#define ATSPI_DBUS_INTERFACE_TEXT "org.a11y.atspi.Text" -#define ATSPI_DBUS_INTERFACE_VALUE "org.a11y.atspi.Value" -#define ATSPI_DBUS_INTERFACE_SOCKET "org.a11y.atspi.Socket" - -// missing from at-spi2-core: -#define ATSPI_DBUS_INTERFACE_EVENT_WINDOW "org.a11y.atspi.Event.Window" -#define ATSPI_DBUS_INTERFACE_EVENT_FOCUS "org.a11y.atspi.Event.Focus" - -#define QSPI_OBJECT_PATH_ACCESSIBLE "/org/a11y/atspi/accessible" -#define QSPI_OBJECT_PATH_PREFIX "/org/a11y/atspi/accessible/" -#define QSPI_OBJECT_PATH_ROOT QSPI_OBJECT_PATH_PREFIX "root" - -#define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry" - -QT_BEGIN_NAMESPACE - -struct RoleNames { - RoleNames() {} - RoleNames(AtspiRole r, const QString& n, const QString& ln) - :m_spiRole(r), m_name(n), m_localizedName(ln) - {} - - AtspiRole spiRole() const {return m_spiRole;} - QString name() const {return m_name;} - QString localizedName() const {return m_localizedName;} - -private: - AtspiRole m_spiRole; - QString m_name; - QString m_localizedName; -}; - -extern QHash <QAccessible::Role, RoleNames> qSpiRoleMapping; -extern QHash <int, AtspiStateType> qSpiStateMapping; - -inline void setSpiStateBit(quint64* state, AtspiStateType spiState) -{ - *state |= quint64(1) << spiState; -} - -inline void unsetSpiStateBit(quint64* state, AtspiStateType spiState) -{ - *state &= ~(quint64(1) << spiState); -} - -quint64 spiStatesFromQState(QAccessible::State state); -QSpiUIntList spiStateSetFromSpiStates(quint64 states); - -AtspiRelationType qAccessibleRelationToAtSpiRelation(QAccessible::Relation relation); - -QT_END_NAMESPACE - -#endif /* Q_SPI_CONSTANT_MAPPINGS_H */ diff --git a/src/platformsupport/linuxaccessibility/dbusconnection.cpp b/src/platformsupport/linuxaccessibility/dbusconnection.cpp deleted file mode 100644 index cacbfdae9f..0000000000 --- a/src/platformsupport/linuxaccessibility/dbusconnection.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - - -#include "dbusconnection_p.h" - -#include <QtDBus/QDBusMessage> -#include <QtDBus/QDBusServiceWatcher> -#include <qdebug.h> - -#include <QDBusConnectionInterface> -#include "bus_interface.h" - -#include <QtGui/qguiapplication.h> -#include <qpa/qplatformnativeinterface.h> - -QT_BEGIN_NAMESPACE - -/* note: do not change these to QStringLiteral; - we are unloaded before QtDBus is done using the strings. - */ -#define A11Y_SERVICE QLatin1String("org.a11y.Bus") -#define A11Y_PATH QLatin1String("/org/a11y/bus") - -/*! - \class DBusConnection - \internal - \brief Connects to the accessibility dbus. - - This is usually a different bus from the session bus. -*/ -DBusConnection::DBusConnection(QObject *parent) - : QObject(parent), m_a11yConnection(QString()), m_enabled(false) -{ - // Start monitoring if "org.a11y.Bus" is registered as DBus service. - QDBusConnection c = QDBusConnection::sessionBus(); - if (!c.isConnected()) { - return; - } - - dbusWatcher = new QDBusServiceWatcher(A11Y_SERVICE, c, QDBusServiceWatcher::WatchForRegistration, this); - connect(dbusWatcher, SIGNAL(serviceRegistered(QString)), this, SLOT(serviceRegistered())); - - // If it is registered already, setup a11y right away - if (c.interface()->isServiceRegistered(A11Y_SERVICE)) - serviceRegistered(); - - // In addition try if there is an xatom exposing the bus address, this allows applications run as root to work - QString address = getAddressFromXCB(); - if (!address.isEmpty()) { - m_enabled = true; - connectA11yBus(address); - } -} - -QString DBusConnection::getAddressFromXCB() -{ - QGuiApplication *app = qobject_cast<QGuiApplication *>(QCoreApplication::instance()); - if (!app) - return QString(); - QPlatformNativeInterface *platformNativeInterface = app->platformNativeInterface(); - QByteArray *addressByteArray = reinterpret_cast<QByteArray*>( - platformNativeInterface->nativeResourceForIntegration(QByteArrayLiteral("AtspiBus"))); - if (addressByteArray) { - QString address = QString::fromLatin1(*addressByteArray); - delete addressByteArray; - return address; - } - return QString(); -} - -// We have the a11y registry on the session bus. -// Subscribe to updates about a11y enabled state. -// Find out the bus address -void DBusConnection::serviceRegistered() -{ - // listen to enabled changes - QDBusConnection c = QDBusConnection::sessionBus(); - OrgA11yStatusInterface *a11yStatus = new OrgA11yStatusInterface(A11Y_SERVICE, A11Y_PATH, c, this); - - //The variable was introduced because on some embedded platforms there are custom accessibility - //clients which don't set Status.ScreenReaderEnabled to true. The variable is also useful for - //debugging. - static const bool a11yAlwaysOn = qEnvironmentVariableIsSet("QT_LINUX_ACCESSIBILITY_ALWAYS_ON"); - - // a11yStatus->isEnabled() returns always true (since Gnome 3.6) - bool enabled = a11yAlwaysOn || a11yStatus->screenReaderEnabled(); - - if (enabled != m_enabled) { - m_enabled = enabled; - if (m_a11yConnection.isConnected()) { - emit enabledChanged(m_enabled); - } else { - QDBusConnection c = QDBusConnection::sessionBus(); - QDBusMessage m = QDBusMessage::createMethodCall(QLatin1String("org.a11y.Bus"), - QLatin1String("/org/a11y/bus"), - QLatin1String("org.a11y.Bus"), QLatin1String("GetAddress")); - c.callWithCallback(m, this, SLOT(connectA11yBus(QString)), SLOT(dbusError(QDBusError))); - } - } - - // connect(a11yStatus, ); QtDbus doesn't support notifications for property changes yet -} - -void DBusConnection::serviceUnregistered() -{ - emit enabledChanged(false); -} - -void DBusConnection::connectA11yBus(const QString &address) -{ - if (address.isEmpty()) { - qWarning("Could not find Accessibility DBus address."); - return; - } - m_a11yConnection = QDBusConnection(QDBusConnection::connectToBus(address, QLatin1String("a11y"))); - - if (m_enabled) - emit enabledChanged(true); -} - -void DBusConnection::dbusError(const QDBusError &error) -{ - qWarning() << "Accessibility encountered a DBus error:" << error; -} - -/*! - Returns the DBus connection that got established. - Or an invalid connection if not yet connected. -*/ -QDBusConnection DBusConnection::connection() const -{ - return m_a11yConnection; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/linuxaccessibility/dbusconnection_p.h b/src/platformsupport/linuxaccessibility/dbusconnection_p.h deleted file mode 100644 index 4030fabc22..0000000000 --- a/src/platformsupport/linuxaccessibility/dbusconnection_p.h +++ /dev/null @@ -1,94 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#ifndef DBUSCONNECTION_H -#define DBUSCONNECTION_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/QString> -#include <QtDBus/QDBusConnection> -#include <QtDBus/QDBusVariant> - -QT_BEGIN_NAMESPACE - -class QDBusServiceWatcher; - -class DBusConnection : public QObject -{ - Q_OBJECT - -public: - DBusConnection(QObject *parent = 0); - QDBusConnection connection() const; - bool isEnabled() const { return m_enabled; } - -Q_SIGNALS: - // Emitted when the global accessibility status changes to enabled - void enabledChanged(bool enabled); - -private Q_SLOTS: - QString getAddressFromXCB(); - void serviceRegistered(); - void serviceUnregistered(); - void connectA11yBus(const QString &address); - - void dbusError(const QDBusError &error); - -private: - QString getAccessibilityBusAddress() const; - - QDBusServiceWatcher *dbusWatcher; - QDBusConnection m_a11yConnection; - bool m_enabled; -}; - -QT_END_NAMESPACE - -#endif // DBUSCONNECTION_H diff --git a/src/platformsupport/linuxaccessibility/dbusxml/Bus.xml b/src/platformsupport/linuxaccessibility/dbusxml/Bus.xml deleted file mode 100644 index 5a33e335a1..0000000000 --- a/src/platformsupport/linuxaccessibility/dbusxml/Bus.xml +++ /dev/null @@ -1,17 +0,0 @@ -<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" - "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> -<node> - <interface name="org.a11y.Status"> - <property type="b" name="IsEnabled" access="readwrite"> - </property> - <property type="b" name="ScreenReaderEnabled" access="readwrite"> - </property> - </interface> - <interface name="org.a11y.Bus"> - <method name="GetAddress"> - <arg type="s" name="address" direction="out"> - </arg> - </method> - </interface> -</node> - diff --git a/src/platformsupport/linuxaccessibility/dbusxml/Cache.xml b/src/platformsupport/linuxaccessibility/dbusxml/Cache.xml deleted file mode 100644 index 01c52810ac..0000000000 --- a/src/platformsupport/linuxaccessibility/dbusxml/Cache.xml +++ /dev/null @@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<node name="/node"> -<interface name="org.a11y.atspi.Cache"> - - <method name="GetItems"> - <arg name="nodes" type="a((so)(so)a(so)assusau)" direction="out"/> - <annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiAccessibleCacheArray"/> - </method> - - <signal name="AddAccessible"> - <arg name="nodeAdded" type="((so)(so)a(so)assusau)"/> - <annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiAccessibleCacheItem"/> - </signal> - - <signal name="RemoveAccessible"> - <arg name="nodeRemoved" type="(so)"/> - <annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/> - </signal> - -</interface> -</node> diff --git a/src/platformsupport/linuxaccessibility/dbusxml/DeviceEventController.xml b/src/platformsupport/linuxaccessibility/dbusxml/DeviceEventController.xml deleted file mode 100644 index d4c26ef7e7..0000000000 --- a/src/platformsupport/linuxaccessibility/dbusxml/DeviceEventController.xml +++ /dev/null @@ -1,66 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<node name="/node"> -<interface name="org.a11y.atspi.DeviceEventController"> - -<!-- - <method name="RegisterKeystrokeListener"> - <arg direction="in" name="listener" type="o"/> - <arg direction="in" name="keys" type="a(iisi)"> - <annotation name="com.trolltech.QtDBus.QtTypeName.In1" value="QSpiKeyTypeArray"/> - </arg> - <arg direction="in" name="mask" type="u"/> - <arg direction="in" name="type" type="au"> - <annotation name="com.trolltech.QtDBus.QtTypeName.In3" value="QSpiEventTypeArray"/> - </arg> - <arg direction="in" name="mode" type="(bbb)"> - <annotation name="com.trolltech.QtDBus.QtTypeName.In4" value="QSpiEventMode"/> - </arg> - <arg direction="out" type="b"/> - </method> - - <method name="DeregisterKeystrokeListener"> - <arg direction="in" name="listener" type="o"/> - <arg direction="in" name="keys" type="a(iisi)"> - <annotation name="com.trolltech.QtDBus.QtTypeName.In1" value="QSpiKeyTypeArray"/> - </arg> - <arg direction="in" name="mask" type="u"/> - <arg direction="in" name="type" type="u"/> - </method> - - <method name="RegisterDeviceEventListener"> - <arg direction="in" name="listener" type="o"/> - <arg direction="in" name="types" type="u"/> - <arg direction="out" type="b"/> - </method> - - <method name="DeregisterDeviceEventListener"> - <arg direction="in" name="listener" type="o"/> - <arg direction="in" name="types" type="u"/> - </method> - - <method name="GenerateKeyboardEvent"> - <arg direction="in" name="keycode" type="i"/> - <arg direction="in" name="keystring" type="s"/> - <arg direction="in" name="type" type="u"/> - </method> - - <method name="GenerateMouseEvent"> - <arg direction="in" name="x" type="i"/> - <arg direction="in" name="y" type="i"/> - <arg direction="in" name="eventName" type="s"/> - </method> ---> - - <method name="NotifyListenersSync"> - <arg direction="in" name="event" type="(uinnisb)"/> - <arg direction="out" type="b"/> - <annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiDeviceEvent"/> - </method> - - <method name="NotifyListenersAsync"> - <arg direction="in" name="event" type="(uinnisb)"/> - <annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiDeviceEvent"/> - </method> - -</interface> -</node> diff --git a/src/platformsupport/linuxaccessibility/dbusxml/Socket.xml b/src/platformsupport/linuxaccessibility/dbusxml/Socket.xml deleted file mode 100644 index 75ec99f994..0000000000 --- a/src/platformsupport/linuxaccessibility/dbusxml/Socket.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<node name="/node"> -<interface name="org.a11y.atspi.Socket"> - - <method name="Embed"> - <arg direction="in" name="plug" type="(so)"/> - <annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiObjectReference"/> - <arg direction="out" name="socket" type="(so)"/> - <annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QSpiObjectReference"/> - </method> - - <method name="Unembed"> - <arg direction="in" name="plug" type="(so)"/> - <annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiObjectReference"/> - </method> - - <signal name="Available"> - <arg direction="in" name="socket" type="(so)"/> - <annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QSpiObjectReference"/> - </method> - -</interface> -</node> diff --git a/src/platformsupport/linuxaccessibility/linuxaccessibility.pro b/src/platformsupport/linuxaccessibility/linuxaccessibility.pro deleted file mode 100644 index d6689c0fa3..0000000000 --- a/src/platformsupport/linuxaccessibility/linuxaccessibility.pro +++ /dev/null @@ -1,36 +0,0 @@ -TARGET = QtLinuxAccessibilitySupport -MODULE = linuxaccessibility_support - -QT = core-private dbus gui-private accessibility_support-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII -PRECOMPILED_HEADER = ../../corelib/global/qt_pch.h - -DBUS_ADAPTORS = $$PWD/dbusxml/Cache.xml $$PWD/dbusxml/DeviceEventController.xml -QDBUSXML2CPP_ADAPTOR_HEADER_FLAGS = -i struct_marshallers_p.h - -DBUS_INTERFACES = $$PWD/dbusxml/Socket.xml $$PWD/dbusxml/Bus.xml -QDBUSXML2CPP_INTERFACE_HEADER_FLAGS = -i struct_marshallers_p.h - -QMAKE_USE += atspi/nolink - -HEADERS += \ - application_p.h \ - bridge_p.h \ - cache_p.h \ - struct_marshallers_p.h \ - constant_mappings_p.h \ - dbusconnection_p.h \ - atspiadaptor_p.h - -SOURCES += \ - application.cpp \ - bridge.cpp \ - cache.cpp \ - struct_marshallers.cpp \ - constant_mappings.cpp \ - dbusconnection.cpp \ - atspiadaptor.cpp - -load(qt_module) diff --git a/src/platformsupport/linuxaccessibility/struct_marshallers.cpp b/src/platformsupport/linuxaccessibility/struct_marshallers.cpp deleted file mode 100644 index 9bbaf23332..0000000000 --- a/src/platformsupport/linuxaccessibility/struct_marshallers.cpp +++ /dev/null @@ -1,237 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include "struct_marshallers_p.h" - -#include <atspi/atspi-constants.h> -#include <QtCore/qdebug.h> -#include <QtDBus/qdbusmetatype.h> - -#include "bridge_p.h" - -#ifndef QT_NO_ACCESSIBILITY -QT_BEGIN_NAMESPACE - -QSpiObjectReference::QSpiObjectReference() - : path(QDBusObjectPath(ATSPI_DBUS_PATH_NULL)) -{} - -/* QSpiAccessibleCacheArray */ -/*---------------------------------------------------------------------------*/ - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiAccessibleCacheItem &item) -{ - argument.beginStructure(); - argument << item.path; - argument << item.application; - argument << item.parent; - argument << item.children; - argument << item.supportedInterfaces; - argument << item.name; - argument << item.role; - argument << item.description; - argument << item.state; - argument.endStructure(); - return argument; -} - -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiAccessibleCacheItem &item) -{ - argument.beginStructure(); - argument >> item.path; - argument >> item.application; - argument >> item.parent; - argument >> item.children; - argument >> item.supportedInterfaces; - argument >> item.name; - argument >> item.role; - argument >> item.description; - argument >> item.state; - argument.endStructure(); - return argument; -} - -/* QSpiObjectReference */ -/*---------------------------------------------------------------------------*/ - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiObjectReference &address) -{ - argument.beginStructure(); - argument << address.service; - argument << address.path; - argument.endStructure(); - return argument; -} - -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiObjectReference &address) -{ - argument.beginStructure(); - argument >> address.service; - argument >> address.path; - argument.endStructure(); - return argument; -} - -/* QSpiAction */ -/*---------------------------------------------------------------------------*/ - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiAction &action) -{ - argument.beginStructure(); - argument << action.name; - argument << action.description; - argument << action.keyBinding; - argument.endStructure(); - return argument; -} - -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiAction &action) -{ - argument.beginStructure(); - argument >> action.name; - argument >> action.description; - argument >> action.keyBinding; - argument.endStructure(); - return argument; -} - - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiEventListener &ev) -{ - argument.beginStructure(); - argument << ev.listenerAddress; - argument << ev.eventName; - argument.endStructure(); - return argument; -} - -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiEventListener &ev) -{ - argument.beginStructure(); - argument >> ev.listenerAddress; - argument >> ev.eventName; - argument.endStructure(); - return argument; -} - -/* QSpiAppUpdate */ -/*---------------------------------------------------------------------------*/ - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiAppUpdate &update) { - argument.beginStructure(); - argument << update.type << update.address; - argument.endStructure(); - return argument; -} - -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiAppUpdate &update) { - argument.beginStructure(); - argument >> update.type >> update.address; - argument.endStructure(); - return argument; -} - -/* QSpiRelationArrayEntry */ -/*---------------------------------------------------------------------------*/ - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiRelationArrayEntry &entry) { - argument.beginStructure(); - argument << entry.first << entry.second; - argument.endStructure(); - return argument; -} - -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiRelationArrayEntry &entry) { - argument.beginStructure(); - argument >> entry.first >> entry.second; - argument.endStructure(); - return argument; -} - -/* QSpiDeviceEvent */ -/*---------------------------------------------------------------------------*/ - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiDeviceEvent &event) { - argument.beginStructure(); - argument << event.type - << event.id - << event.hardwareCode - << event.modifiers - << event.timestamp - << event.text - << event.isText; - argument.endStructure(); - return argument; -} - -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiDeviceEvent &event) { - argument.beginStructure(); - argument >> event.type - >> event.id - >> event.hardwareCode - >> event.modifiers - >> event.timestamp - >> event.text - >> event.isText; - argument.endStructure(); - return argument; -} - -void qSpiInitializeStructTypes() -{ - qDBusRegisterMetaType<QSpiIntList>(); - qDBusRegisterMetaType<QSpiUIntList>(); - qDBusRegisterMetaType<QSpiAccessibleCacheItem>(); - qDBusRegisterMetaType<QSpiAccessibleCacheArray>(); - qDBusRegisterMetaType<QSpiObjectReference>(); - qDBusRegisterMetaType<QSpiObjectReferenceArray>(); - qDBusRegisterMetaType<QSpiAttributeSet>(); - qDBusRegisterMetaType<QSpiAction>(); - qDBusRegisterMetaType<QSpiActionArray>(); - qDBusRegisterMetaType<QSpiEventListener>(); - qDBusRegisterMetaType<QSpiEventListenerArray>(); - qDBusRegisterMetaType<QSpiDeviceEvent>(); - qDBusRegisterMetaType<QSpiAppUpdate>(); - qDBusRegisterMetaType<QSpiRelationArrayEntry>(); - qDBusRegisterMetaType<QSpiRelationArray>(); -} - -QT_END_NAMESPACE -#endif //QT_NO_ACCESSIBILITY diff --git a/src/platformsupport/linuxaccessibility/struct_marshallers_p.h b/src/platformsupport/linuxaccessibility/struct_marshallers_p.h deleted file mode 100644 index c8cc05ab5b..0000000000 --- a/src/platformsupport/linuxaccessibility/struct_marshallers_p.h +++ /dev/null @@ -1,197 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#ifndef Q_SPI_STRUCT_MARSHALLERS_H -#define Q_SPI_STRUCT_MARSHALLERS_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qtguiglobal_p.h> -#include <QtCore/qvector.h> -#include <QtCore/qpair.h> -#include <QtDBus/QDBusArgument> -#include <QtDBus/QDBusConnection> -#include <QtDBus/QDBusObjectPath> - -QT_REQUIRE_CONFIG(accessibility); - -QT_BEGIN_NAMESPACE - -typedef QVector<int> QSpiIntList; -typedef QVector<uint> QSpiUIntList; - -// FIXME: make this copy on write -struct QSpiObjectReference -{ - QString service; - QDBusObjectPath path; - - QSpiObjectReference(); - QSpiObjectReference(const QDBusConnection& connection, const QDBusObjectPath& path) - : service(connection.baseService()), path(path) {} -}; -Q_DECLARE_TYPEINFO(QSpiObjectReference, Q_MOVABLE_TYPE); // QDBusObjectPath is movable, even though it - // cannot be marked that way until Qt 6 - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiObjectReference &address); -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiObjectReference &address); - -typedef QVector<QSpiObjectReference> QSpiObjectReferenceArray; - -struct QSpiAccessibleCacheItem -{ - QSpiObjectReference path; - QSpiObjectReference application; - QSpiObjectReference parent; - QSpiObjectReferenceArray children; - QStringList supportedInterfaces; - QString name; - uint role; - QString description; - QSpiUIntList state; -}; -Q_DECLARE_TYPEINFO(QSpiAccessibleCacheItem, Q_MOVABLE_TYPE); - -typedef QVector<QSpiAccessibleCacheItem> QSpiAccessibleCacheArray; - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiAccessibleCacheItem &item); -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiAccessibleCacheItem &item); - -struct QSpiAction -{ - QString name; - QString description; - QString keyBinding; -}; -Q_DECLARE_TYPEINFO(QSpiAction, Q_MOVABLE_TYPE); - -typedef QVector<QSpiAction> QSpiActionArray; - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiAction &action); -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiAction &action); - -struct QSpiEventListener -{ - QString listenerAddress; - QString eventName; -}; -Q_DECLARE_TYPEINFO(QSpiEventListener, Q_MOVABLE_TYPE); - -typedef QVector<QSpiEventListener> QSpiEventListenerArray; - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiEventListener &action); -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiEventListener &action); - -typedef QPair<unsigned int, QSpiObjectReferenceArray> QSpiRelationArrayEntry; -typedef QVector<QSpiRelationArrayEntry> QSpiRelationArray; - -//a(iisv) -struct QSpiTextRange { - int startOffset; - int endOffset; - QString contents; - QVariant v; -}; -Q_DECLARE_TYPEINFO(QSpiTextRange, Q_MOVABLE_TYPE); - -typedef QVector<QSpiTextRange> QSpiTextRangeList; -typedef QMap <QString, QString> QSpiAttributeSet; - -enum QSpiAppUpdateType { - QSPI_APP_UPDATE_ADDED = 0, - QSPI_APP_UPDATE_REMOVED = 1 -}; -Q_DECLARE_TYPEINFO(QSpiAppUpdateType, Q_PRIMITIVE_TYPE); - -struct QSpiAppUpdate { - int type; /* Is an application added or removed */ - QString address; /* D-Bus address of application added or removed */ -}; -Q_DECLARE_TYPEINFO(QSpiAppUpdate, Q_MOVABLE_TYPE); - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiAppUpdate &update); -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiAppUpdate &update); - -struct QSpiDeviceEvent { - unsigned int type; - int id; - int hardwareCode; - int modifiers; - int timestamp; - QString text; - bool isText; -}; -Q_DECLARE_TYPEINFO(QSpiDeviceEvent, Q_MOVABLE_TYPE); - -QDBusArgument &operator<<(QDBusArgument &argument, const QSpiDeviceEvent &event); -const QDBusArgument &operator>>(const QDBusArgument &argument, QSpiDeviceEvent &event); - -void qSpiInitializeStructTypes(); - -QT_END_NAMESPACE - -Q_DECLARE_METATYPE(QSpiIntList) -Q_DECLARE_METATYPE(QSpiUIntList) -Q_DECLARE_METATYPE(QSpiObjectReference) -Q_DECLARE_METATYPE(QSpiObjectReferenceArray) -Q_DECLARE_METATYPE(QSpiAccessibleCacheItem) -Q_DECLARE_METATYPE(QSpiAccessibleCacheArray) -Q_DECLARE_METATYPE(QSpiAction) -Q_DECLARE_METATYPE(QSpiActionArray) -Q_DECLARE_METATYPE(QSpiEventListener) -Q_DECLARE_METATYPE(QSpiEventListenerArray) -Q_DECLARE_METATYPE(QSpiRelationArrayEntry) -Q_DECLARE_METATYPE(QSpiRelationArray) -Q_DECLARE_METATYPE(QSpiTextRange) -Q_DECLARE_METATYPE(QSpiTextRangeList) -Q_DECLARE_METATYPE(QSpiAttributeSet) -Q_DECLARE_METATYPE(QSpiAppUpdate) -Q_DECLARE_METATYPE(QSpiDeviceEvent) - -#endif /* Q_SPI_STRUCT_MARSHALLERS_H */ diff --git a/src/platformsupport/platformcompositor/platformcompositor.pro b/src/platformsupport/platformcompositor/platformcompositor.pro deleted file mode 100644 index 81c31571d0..0000000000 --- a/src/platformsupport/platformcompositor/platformcompositor.pro +++ /dev/null @@ -1,17 +0,0 @@ -TARGET = QtPlatformCompositorSupport -MODULE = platformcompositor_support - -QT = core-private gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII - -SOURCES += \ - qopenglcompositor.cpp \ - qopenglcompositorbackingstore.cpp - -HEADERS += \ - qopenglcompositor_p.h \ - qopenglcompositorbackingstore_p.h - -load(qt_module) diff --git a/src/platformsupport/platformcompositor/qopenglcompositor.cpp b/src/platformsupport/platformcompositor/qopenglcompositor.cpp deleted file mode 100644 index 635bf0107f..0000000000 --- a/src/platformsupport/platformcompositor/qopenglcompositor.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtGui/QOpenGLContext> -#include <QtGui/QOpenGLFramebufferObject> -#include <QtGui/QWindow> -#include <qpa/qplatformbackingstore.h> - -#include "qopenglcompositor_p.h" - -QT_BEGIN_NAMESPACE - -/*! - \class QOpenGLCompositor - \brief A generic OpenGL-based compositor - \since 5.4 - \internal - \ingroup qpa - - This class provides a lightweight compositor that maintains the - basic stacking order of windows and composites them by drawing - textured quads via OpenGL. - - It it meant to be used by platform plugins that run without a - windowing system. - - It is up to the platform plugin to manage the lifetime of the - compositor (instance(), destroy()), set the correct destination - context and window as early as possible (setTarget()), - register the composited windows as they are shown, activated, - raised and lowered (addWindow(), moveToTop(), etc.), and to - schedule repaints (update()). - - \note To get support for QWidget-based windows, just use - QOpenGLCompositorBackingStore. It will automatically create - textures from the raster-rendered content and trigger the - necessary repaints. - */ - -static QOpenGLCompositor *compositor = 0; - -QOpenGLCompositor::QOpenGLCompositor() - : m_context(0), - m_targetWindow(0), - m_rotation(0) -{ - Q_ASSERT(!compositor); - m_updateTimer.setSingleShot(true); - m_updateTimer.setInterval(0); - connect(&m_updateTimer, SIGNAL(timeout()), SLOT(handleRenderAllRequest())); -} - -QOpenGLCompositor::~QOpenGLCompositor() -{ - Q_ASSERT(compositor == this); - m_blitter.destroy(); - compositor = 0; -} - -void QOpenGLCompositor::setTarget(QOpenGLContext *context, QWindow *targetWindow, - const QRect &nativeTargetGeometry) -{ - m_context = context; - m_targetWindow = targetWindow; - m_nativeTargetGeometry = nativeTargetGeometry; -} - -void QOpenGLCompositor::setRotation(int degrees) -{ - m_rotation = degrees; - m_rotationMatrix.setToIdentity(); - m_rotationMatrix.rotate(degrees, 0, 0, 1); -} - -void QOpenGLCompositor::update() -{ - if (!m_updateTimer.isActive()) - m_updateTimer.start(); -} - -QImage QOpenGLCompositor::grab() -{ - Q_ASSERT(m_context && m_targetWindow); - m_context->makeCurrent(m_targetWindow); - QScopedPointer<QOpenGLFramebufferObject> fbo(new QOpenGLFramebufferObject(m_nativeTargetGeometry.size())); - renderAll(fbo.data()); - return fbo->toImage(); -} - -void QOpenGLCompositor::handleRenderAllRequest() -{ - Q_ASSERT(m_context && m_targetWindow); - m_context->makeCurrent(m_targetWindow); - renderAll(0); -} - -void QOpenGLCompositor::renderAll(QOpenGLFramebufferObject *fbo) -{ - if (fbo) - fbo->bind(); - - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); - glViewport(0, 0, m_nativeTargetGeometry.width(), m_nativeTargetGeometry.height()); - - if (!m_blitter.isCreated()) - m_blitter.create(); - - m_blitter.bind(); - - for (int i = 0; i < m_windows.size(); ++i) - m_windows.at(i)->beginCompositing(); - - for (int i = 0; i < m_windows.size(); ++i) - render(m_windows.at(i)); - - m_blitter.release(); - if (!fbo) - m_context->swapBuffers(m_targetWindow); - else - fbo->release(); - - for (int i = 0; i < m_windows.size(); ++i) - m_windows.at(i)->endCompositing(); -} - -struct BlendStateBinder -{ - BlendStateBinder() : m_blend(false) { - glDisable(GL_BLEND); - } - void set(bool blend) { - if (blend != m_blend) { - if (blend) { - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } else { - glDisable(GL_BLEND); - } - m_blend = blend; - } - } - ~BlendStateBinder() { - if (m_blend) - glDisable(GL_BLEND); - } - bool m_blend; -}; - -static inline QRect toBottomLeftRect(const QRect &topLeftRect, int windowHeight) -{ - return QRect(topLeftRect.x(), windowHeight - topLeftRect.bottomRight().y() - 1, - topLeftRect.width(), topLeftRect.height()); -} - -static void clippedBlit(const QPlatformTextureList *textures, int idx, const QRect &sourceWindowRect, - const QRect &targetWindowRect, - QOpenGLTextureBlitter *blitter, QMatrix4x4 *rotationMatrix) -{ - const QRect clipRect = textures->clipRect(idx); - if (clipRect.isEmpty()) - return; - - const QRect rectInWindow = textures->geometry(idx).translated(sourceWindowRect.topLeft()); - const QRect clippedRectInWindow = rectInWindow & clipRect.translated(rectInWindow.topLeft()); - const QRect srcRect = toBottomLeftRect(clipRect, rectInWindow.height()); - - QMatrix4x4 target = QOpenGLTextureBlitter::targetTransform(clippedRectInWindow, targetWindowRect); - if (rotationMatrix) - target = *rotationMatrix * target; - - const QMatrix3x3 source = QOpenGLTextureBlitter::sourceTransform(srcRect, rectInWindow.size(), - QOpenGLTextureBlitter::OriginBottomLeft); - - blitter->blit(textures->textureId(idx), target, source); -} - -void QOpenGLCompositor::render(QOpenGLCompositorWindow *window) -{ - const QPlatformTextureList *textures = window->textures(); - if (!textures) - return; - - const QRect targetWindowRect(QPoint(0, 0), m_targetWindow->geometry().size()); - float currentOpacity = 1.0f; - BlendStateBinder blend; - const QRect sourceWindowRect = window->sourceWindow()->geometry(); - for (int i = 0; i < textures->count(); ++i) { - uint textureId = textures->textureId(i); - const float opacity = window->sourceWindow()->opacity(); - if (opacity != currentOpacity) { - currentOpacity = opacity; - m_blitter.setOpacity(currentOpacity); - } - - if (textures->count() > 1 && i == textures->count() - 1) { - // Backingstore for a widget with QOpenGLWidget subwidgets - blend.set(true); - QMatrix4x4 target = QOpenGLTextureBlitter::targetTransform(textures->geometry(i), targetWindowRect); - if (m_rotation) - target = m_rotationMatrix * target; - m_blitter.blit(textureId, target, QOpenGLTextureBlitter::OriginTopLeft); - } else if (textures->count() == 1) { - // A regular QWidget window - const bool translucent = window->sourceWindow()->requestedFormat().alphaBufferSize() > 0; - blend.set(translucent); - QMatrix4x4 target = QOpenGLTextureBlitter::targetTransform(textures->geometry(i), targetWindowRect); - if (m_rotation) - target = m_rotationMatrix * target; - m_blitter.blit(textureId, target, QOpenGLTextureBlitter::OriginTopLeft); - } else if (!textures->flags(i).testFlag(QPlatformTextureList::StacksOnTop)) { - // Texture from an FBO belonging to a QOpenGLWidget or QQuickWidget - blend.set(false); - clippedBlit(textures, i, sourceWindowRect, targetWindowRect, &m_blitter, m_rotation ? &m_rotationMatrix : nullptr); - } - } - - for (int i = 0; i < textures->count(); ++i) { - if (textures->flags(i).testFlag(QPlatformTextureList::StacksOnTop)) { - blend.set(true); - clippedBlit(textures, i, sourceWindowRect, targetWindowRect, &m_blitter, m_rotation ? &m_rotationMatrix : nullptr); - } - } - - m_blitter.setOpacity(1.0f); -} - -QOpenGLCompositor *QOpenGLCompositor::instance() -{ - if (!compositor) - compositor = new QOpenGLCompositor; - return compositor; -} - -void QOpenGLCompositor::destroy() -{ - delete compositor; - compositor = 0; -} - -void QOpenGLCompositor::addWindow(QOpenGLCompositorWindow *window) -{ - if (!m_windows.contains(window)) { - m_windows.append(window); - emit topWindowChanged(window); - } -} - -void QOpenGLCompositor::removeWindow(QOpenGLCompositorWindow *window) -{ - m_windows.removeOne(window); - if (!m_windows.isEmpty()) - emit topWindowChanged(m_windows.last()); -} - -void QOpenGLCompositor::moveToTop(QOpenGLCompositorWindow *window) -{ - m_windows.removeOne(window); - m_windows.append(window); - emit topWindowChanged(window); -} - -void QOpenGLCompositor::changeWindowIndex(QOpenGLCompositorWindow *window, int newIdx) -{ - int idx = m_windows.indexOf(window); - if (idx != -1 && idx != newIdx) { - m_windows.move(idx, newIdx); - if (newIdx == m_windows.size() - 1) - emit topWindowChanged(m_windows.last()); - } -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/platformcompositor/qopenglcompositor_p.h b/src/platformsupport/platformcompositor/qopenglcompositor_p.h deleted file mode 100644 index 41a3288240..0000000000 --- a/src/platformsupport/platformcompositor/qopenglcompositor_p.h +++ /dev/null @@ -1,122 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QOPENGLCOMPOSITOR_H -#define QOPENGLCOMPOSITOR_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/QTimer> -#include <QtGui/QOpenGLTextureBlitter> -#include <QtGui/QMatrix4x4> - -QT_BEGIN_NAMESPACE - -class QOpenGLContext; -class QOpenGLFramebufferObject; -class QWindow; -class QPlatformTextureList; - -class QOpenGLCompositorWindow -{ -public: - virtual ~QOpenGLCompositorWindow() { } - virtual QWindow *sourceWindow() const = 0; - virtual const QPlatformTextureList *textures() const = 0; - virtual void beginCompositing() { } - virtual void endCompositing() { } -}; - -class QOpenGLCompositor : public QObject -{ - Q_OBJECT - -public: - static QOpenGLCompositor *instance(); - static void destroy(); - - void setTarget(QOpenGLContext *context, QWindow *window, const QRect &nativeTargetGeometry); - void setRotation(int degrees); - QOpenGLContext *context() const { return m_context; } - QWindow *targetWindow() const { return m_targetWindow; } - - void update(); - QImage grab(); - - QList<QOpenGLCompositorWindow *> windows() const { return m_windows; } - void addWindow(QOpenGLCompositorWindow *window); - void removeWindow(QOpenGLCompositorWindow *window); - void moveToTop(QOpenGLCompositorWindow *window); - void changeWindowIndex(QOpenGLCompositorWindow *window, int newIdx); - -signals: - void topWindowChanged(QOpenGLCompositorWindow *window); - -private slots: - void handleRenderAllRequest(); - -private: - QOpenGLCompositor(); - ~QOpenGLCompositor(); - - void renderAll(QOpenGLFramebufferObject *fbo); - void render(QOpenGLCompositorWindow *window); - - QOpenGLContext *m_context; - QWindow *m_targetWindow; - QRect m_nativeTargetGeometry; - int m_rotation; - QMatrix4x4 m_rotationMatrix; - QTimer m_updateTimer; - QOpenGLTextureBlitter m_blitter; - QList<QOpenGLCompositorWindow *> m_windows; -}; - -QT_END_NAMESPACE - -#endif // QOPENGLCOMPOSITOR_H diff --git a/src/platformsupport/platformcompositor/qopenglcompositorbackingstore.cpp b/src/platformsupport/platformcompositor/qopenglcompositorbackingstore.cpp deleted file mode 100644 index 40400e2a19..0000000000 --- a/src/platformsupport/platformcompositor/qopenglcompositorbackingstore.cpp +++ /dev/null @@ -1,292 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtGui/QOpenGLContext> -#include <QtGui/QWindow> -#include <QtGui/QPainter> -#include <QtGui/QOffscreenSurface> -#include <qpa/qplatformbackingstore.h> -#include <private/qwindow_p.h> - -#include "qopenglcompositorbackingstore_p.h" -#include "qopenglcompositor_p.h" - -#ifndef GL_UNPACK_ROW_LENGTH -#define GL_UNPACK_ROW_LENGTH 0x0CF2 -#endif - -QT_BEGIN_NAMESPACE - -/*! - \class QOpenGLCompositorBackingStore - \brief A backing store implementation for OpenGL - \since 5.4 - \internal - \ingroup qpa - - This implementation uploads raster-rendered widget windows into - textures. It is meant to be used with QOpenGLCompositor that - composites the textures onto a single native window using OpenGL. - This means that multiple top-level widgets are supported without - creating actual native windows for each of them. - - \note It is important to call notifyComposited() from the - corresponding platform window's endCompositing() callback - (inherited from QOpenGLCompositorWindow). - - \note When implementing QOpenGLCompositorWindow::textures() for - windows of type RasterSurface or RasterGLSurface, simply return - the list provided by this class' textures(). -*/ - -QOpenGLCompositorBackingStore::QOpenGLCompositorBackingStore(QWindow *window) - : QPlatformBackingStore(window), - m_window(window), - m_bsTexture(0), - m_bsTextureContext(0), - m_textures(new QPlatformTextureList), - m_lockedWidgetTextures(0) -{ -} - -QOpenGLCompositorBackingStore::~QOpenGLCompositorBackingStore() -{ - if (m_bsTexture) { - QOpenGLContext *ctx = QOpenGLContext::currentContext(); - // With render-to-texture-widgets QWidget makes sure the TLW's shareContext() is - // made current before destroying backingstores. That is however not the case for - // windows with regular widgets only. - QScopedPointer<QOffscreenSurface> tempSurface; - if (!ctx) { - ctx = QOpenGLCompositor::instance()->context(); - tempSurface.reset(new QOffscreenSurface); - tempSurface->setFormat(ctx->format()); - tempSurface->create(); - ctx->makeCurrent(tempSurface.data()); - } - - if (m_bsTextureContext && ctx->shareGroup() == m_bsTextureContext->shareGroup()) - glDeleteTextures(1, &m_bsTexture); - else - qWarning("QOpenGLCompositorBackingStore: Texture is not valid in the current context"); - - if (tempSurface) - ctx->doneCurrent(); - } - - delete m_textures; // this does not actually own any GL resources -} - -QPaintDevice *QOpenGLCompositorBackingStore::paintDevice() -{ - return &m_image; -} - -void QOpenGLCompositorBackingStore::updateTexture() -{ - if (!m_bsTexture) { - m_bsTextureContext = QOpenGLContext::currentContext(); - Q_ASSERT(m_bsTextureContext); - glGenTextures(1, &m_bsTexture); - glBindTexture(GL_TEXTURE_2D, m_bsTexture); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_image.width(), m_image.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); - } else { - glBindTexture(GL_TEXTURE_2D, m_bsTexture); - } - - if (!m_dirty.isNull()) { - QRegion fixed; - QRect imageRect = m_image.rect(); - - QOpenGLContext *ctx = QOpenGLContext::currentContext(); - if (!ctx->isOpenGLES() || ctx->format().majorVersion() >= 3) { - for (const QRect &rect : m_dirty) { - QRect r = imageRect & rect; - glPixelStorei(GL_UNPACK_ROW_LENGTH, m_image.width()); - glTexSubImage2D(GL_TEXTURE_2D, 0, r.x(), r.y(), r.width(), r.height(), GL_RGBA, GL_UNSIGNED_BYTE, - m_image.constScanLine(r.y()) + r.x() * 4); - glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); - } - } else { - for (const QRect &rect : m_dirty) { - // intersect with image rect to be sure - QRect r = imageRect & rect; - - // if the rect is wide enough it's cheaper to just - // extend it instead of doing an image copy - if (r.width() >= imageRect.width() / 2) { - r.setX(0); - r.setWidth(imageRect.width()); - } - - fixed |= r; - } - for (const QRect &rect : fixed) { - // if the sub-rect is full-width we can pass the image data directly to - // OpenGL instead of copying, since there's no gap between scanlines - if (rect.width() == imageRect.width()) { - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE, - m_image.constScanLine(rect.y())); - } else { - glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE, - m_image.copy(rect).constBits()); - } - } - } - - m_dirty = QRegion(); - } -} - -void QOpenGLCompositorBackingStore::flush(QWindow *window, const QRegion ®ion, const QPoint &offset) -{ - // Called for ordinary raster windows. - - Q_UNUSED(region); - Q_UNUSED(offset); - - QOpenGLCompositor *compositor = QOpenGLCompositor::instance(); - QOpenGLContext *dstCtx = compositor->context(); - Q_ASSERT(dstCtx); - - QWindow *dstWin = compositor->targetWindow(); - if (!dstWin) - return; - - dstCtx->makeCurrent(dstWin); - updateTexture(); - m_textures->clear(); - m_textures->appendTexture(nullptr, m_bsTexture, window->geometry()); - - compositor->update(); -} - -void QOpenGLCompositorBackingStore::composeAndFlush(QWindow *window, const QRegion ®ion, const QPoint &offset, - QPlatformTextureList *textures, - bool translucentBackground) -{ - // QOpenGLWidget/QQuickWidget content provided as textures. The raster content goes on top. - - Q_UNUSED(region); - Q_UNUSED(offset); - Q_UNUSED(translucentBackground); - - QOpenGLCompositor *compositor = QOpenGLCompositor::instance(); - QOpenGLContext *dstCtx = compositor->context(); - Q_ASSERT(dstCtx); // setTarget() must have been called before, e.g. from QEGLFSWindow - - // The compositor's context and the context to which QOpenGLWidget/QQuickWidget - // textures belong are not the same. They share resources, though. - Q_ASSERT(qt_window_private(window)->shareContext()->shareGroup() == dstCtx->shareGroup()); - - QWindow *dstWin = compositor->targetWindow(); - if (!dstWin) - return; - - dstCtx->makeCurrent(dstWin); - - QWindowPrivate::get(window)->lastComposeTime.start(); - - m_textures->clear(); - for (int i = 0; i < textures->count(); ++i) - m_textures->appendTexture(textures->source(i), textures->textureId(i), textures->geometry(i), - textures->clipRect(i), textures->flags(i)); - - updateTexture(); - m_textures->appendTexture(nullptr, m_bsTexture, window->geometry()); - - textures->lock(true); - m_lockedWidgetTextures = textures; - - compositor->update(); -} - -void QOpenGLCompositorBackingStore::notifyComposited() -{ - if (m_lockedWidgetTextures) { - QPlatformTextureList *textureList = m_lockedWidgetTextures; - m_lockedWidgetTextures = 0; // may reenter so null before unlocking - textureList->lock(false); - } -} - -void QOpenGLCompositorBackingStore::beginPaint(const QRegion ®ion) -{ - m_dirty |= region; - - if (m_image.hasAlphaChannel()) { - QPainter p(&m_image); - p.setCompositionMode(QPainter::CompositionMode_Source); - for (const QRect &r : region) - p.fillRect(r, Qt::transparent); - } -} - -void QOpenGLCompositorBackingStore::resize(const QSize &size, const QRegion &staticContents) -{ - Q_UNUSED(staticContents); - - QOpenGLCompositor *compositor = QOpenGLCompositor::instance(); - QOpenGLContext *dstCtx = compositor->context(); - QWindow *dstWin = compositor->targetWindow(); - if (!dstWin) - return; - - m_image = QImage(size, QImage::Format_RGBA8888); - - m_window->create(); - - dstCtx->makeCurrent(dstWin); - if (m_bsTexture) { - glDeleteTextures(1, &m_bsTexture); - m_bsTexture = 0; - m_bsTextureContext = nullptr; - } -} - -QImage QOpenGLCompositorBackingStore::toImage() const -{ - return m_image; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/platformcompositor/qopenglcompositorbackingstore_p.h b/src/platformsupport/platformcompositor/qopenglcompositorbackingstore_p.h deleted file mode 100644 index d88738ea8f..0000000000 --- a/src/platformsupport/platformcompositor/qopenglcompositorbackingstore_p.h +++ /dev/null @@ -1,99 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QOPENGLCOMPOSITORBACKINGSTORE_H -#define QOPENGLCOMPOSITORBACKINGSTORE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <qpa/qplatformbackingstore.h> -#include <QImage> -#include <QRegion> - -QT_BEGIN_NAMESPACE - -class QOpenGLContext; -class QPlatformTextureList; - -class QOpenGLCompositorBackingStore : public QPlatformBackingStore -{ -public: - QOpenGLCompositorBackingStore(QWindow *window); - ~QOpenGLCompositorBackingStore(); - - QPaintDevice *paintDevice() override; - - void beginPaint(const QRegion ®ion) override; - - void flush(QWindow *window, const QRegion ®ion, const QPoint &offset) override; - void resize(const QSize &size, const QRegion &staticContents) override; - - QImage toImage() const override; - void composeAndFlush(QWindow *window, const QRegion ®ion, const QPoint &offset, - QPlatformTextureList *textures, - bool translucentBackground) override; - - const QPlatformTextureList *textures() const { return m_textures; } - - void notifyComposited(); - -private: - void updateTexture(); - - QWindow *m_window; - QImage m_image; - QRegion m_dirty; - uint m_bsTexture; - QOpenGLContext *m_bsTextureContext; - QPlatformTextureList *m_textures; - QPlatformTextureList *m_lockedWidgetTextures; -}; - -QT_END_NAMESPACE - -#endif // QOPENGLCOMPOSITORBACKINGSTORE_H diff --git a/src/platformsupport/platformsupport.pro b/src/platformsupport/platformsupport.pro deleted file mode 100644 index 6d4f1b93bd..0000000000 --- a/src/platformsupport/platformsupport.pro +++ /dev/null @@ -1,47 +0,0 @@ -TEMPLATE = subdirs -QT_FOR_CONFIG += gui-private - -SUBDIRS = \ - edid \ - eventdispatchers \ - devicediscovery \ - fbconvenience \ - themes - -qtConfig(freetype)|darwin|win32: \ - SUBDIRS += fontdatabases - -qtConfig(evdev)|qtConfig(tslib)|qtConfig(libinput)|qtConfig(integrityhid) { - SUBDIRS += input - input.depends += devicediscovery -} - -if(unix:!uikit)|qtConfig(xcb): \ - SUBDIRS += services - -qtConfig(opengl): \ - SUBDIRS += platformcompositor -qtConfig(egl): \ - SUBDIRS += eglconvenience -qtConfig(xlib):qtConfig(opengl):!qtConfig(opengles2): \ - SUBDIRS += glxconvenience -qtConfig(kms): \ - SUBDIRS += kmsconvenience - -qtConfig(accessibility) { - SUBDIRS += accessibility - qtConfig(accessibility-atspi-bridge) { - SUBDIRS += linuxaccessibility - linuxaccessibility.depends += accessibility - } - win32:!winrt: SUBDIRS += windowsuiautomation -} - -darwin { - SUBDIRS += \ - clipboard \ - graphics -} - -qtConfig(vulkan): \ - SUBDIRS += vkconvenience diff --git a/src/platformsupport/services/genericunix/genericunix.pri b/src/platformsupport/services/genericunix/genericunix.pri deleted file mode 100644 index 6afafa31d0..0000000000 --- a/src/platformsupport/services/genericunix/genericunix.pri +++ /dev/null @@ -1,2 +0,0 @@ -HEADERS += $$PWD/qgenericunixservices_p.h -SOURCES += $$PWD/qgenericunixservices.cpp diff --git a/src/platformsupport/services/genericunix/qgenericunixservices.cpp b/src/platformsupport/services/genericunix/qgenericunixservices.cpp deleted file mode 100644 index 734bdcaf75..0000000000 --- a/src/platformsupport/services/genericunix/qgenericunixservices.cpp +++ /dev/null @@ -1,369 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qgenericunixservices_p.h" -#include <QtGui/private/qtguiglobal_p.h> - -#include <QtCore/QDebug> -#include <QtCore/QFile> -#if QT_CONFIG(process) -# include <QtCore/QProcess> -#endif -#if QT_CONFIG(settings) -#include <QtCore/QSettings> -#endif -#include <QtCore/QStandardPaths> -#include <QtCore/QUrl> - -#if QT_CONFIG(dbus) -// These QtCore includes are needed for xdg-desktop-portal support -#include <QtCore/private/qcore_unix_p.h> - -#include <QtCore/QFileInfo> -#include <QtCore/QUrlQuery> - -#include <QtDBus/QDBusConnection> -#include <QtDBus/QDBusMessage> -#include <QtDBus/QDBusPendingCall> -#include <QtDBus/QDBusPendingCallWatcher> -#include <QtDBus/QDBusPendingReply> -#include <QtDBus/QDBusUnixFileDescriptor> - -#include <fcntl.h> - -#endif // QT_CONFIG(dbus) - -#include <stdlib.h> - -QT_BEGIN_NAMESPACE - -#if QT_CONFIG(multiprocess) - -enum { debug = 0 }; - -static inline QByteArray detectDesktopEnvironment() -{ - const QByteArray xdgCurrentDesktop = qgetenv("XDG_CURRENT_DESKTOP"); - if (!xdgCurrentDesktop.isEmpty()) - return xdgCurrentDesktop.toUpper(); // KDE, GNOME, UNITY, LXDE, MATE, XFCE... - - // Classic fallbacks - if (!qEnvironmentVariableIsEmpty("KDE_FULL_SESSION")) - return QByteArrayLiteral("KDE"); - if (!qEnvironmentVariableIsEmpty("GNOME_DESKTOP_SESSION_ID")) - return QByteArrayLiteral("GNOME"); - - // Fallback to checking $DESKTOP_SESSION (unreliable) - QByteArray desktopSession = qgetenv("DESKTOP_SESSION"); - - // This can be a path in /usr/share/xsessions - int slash = desktopSession.lastIndexOf('/'); - if (slash != -1) { -#if QT_CONFIG(settings) - QSettings desktopFile(QFile::decodeName(desktopSession + ".desktop"), QSettings::IniFormat); - desktopFile.beginGroup(QStringLiteral("Desktop Entry")); - QByteArray desktopName = desktopFile.value(QStringLiteral("DesktopNames")).toByteArray(); - if (!desktopName.isEmpty()) - return desktopName; -#endif - - // try decoding just the basename - desktopSession = desktopSession.mid(slash + 1); - } - - if (desktopSession == "gnome") - return QByteArrayLiteral("GNOME"); - else if (desktopSession == "xfce") - return QByteArrayLiteral("XFCE"); - else if (desktopSession == "kde") - return QByteArrayLiteral("KDE"); - - return QByteArrayLiteral("UNKNOWN"); -} - -static inline bool checkExecutable(const QString &candidate, QString *result) -{ - *result = QStandardPaths::findExecutable(candidate); - return !result->isEmpty(); -} - -static inline bool detectWebBrowser(const QByteArray &desktop, - bool checkBrowserVariable, - QString *browser) -{ - const char *browsers[] = {"google-chrome", "firefox", "mozilla", "opera"}; - - browser->clear(); - if (checkExecutable(QStringLiteral("xdg-open"), browser)) - return true; - - if (checkBrowserVariable) { - QByteArray browserVariable = qgetenv("DEFAULT_BROWSER"); - if (browserVariable.isEmpty()) - browserVariable = qgetenv("BROWSER"); - if (!browserVariable.isEmpty() && checkExecutable(QString::fromLocal8Bit(browserVariable), browser)) - return true; - } - - if (desktop == QByteArray("KDE")) { - // Konqueror launcher - if (checkExecutable(QStringLiteral("kfmclient"), browser)) { - browser->append(QLatin1String(" exec")); - return true; - } - } else if (desktop == QByteArray("GNOME")) { - if (checkExecutable(QStringLiteral("gnome-open"), browser)) - return true; - } - - for (size_t i = 0; i < sizeof(browsers)/sizeof(char *); ++i) - if (checkExecutable(QLatin1String(browsers[i]), browser)) - return true; - return false; -} - -static inline bool launch(const QString &launcher, const QUrl &url) -{ - const QString command = launcher + QLatin1Char(' ') + QLatin1String(url.toEncoded()); - if (debug) - qDebug("Launching %s", qPrintable(command)); -#if !QT_CONFIG(process) - const bool ok = ::system(qPrintable(command + QLatin1String(" &"))); -#else - const bool ok = QProcess::startDetached(command); -#endif - if (!ok) - qWarning("Launch failed (%s)", qPrintable(command)); - return ok; -} - -#if QT_CONFIG(dbus) -static inline bool checkNeedPortalSupport() -{ - return !QStandardPaths::locate(QStandardPaths::RuntimeLocation, QLatin1String("flatpak-info")).isEmpty() || qEnvironmentVariableIsSet("SNAP"); -} - -static inline bool isPortalReturnPermanent(const QDBusError &error) -{ - // A service unknown error isn't permanent, it just indicates that we - // should fall back to the regular way. This check includes - // QDBusError::NoError. - return error.type() != QDBusError::ServiceUnknown; -} - -static inline QDBusMessage xdgDesktopPortalOpenFile(const QUrl &url) -{ - // DBus signature: - // OpenFile (IN s parent_window, - // IN h fd, - // IN a{sv} options, - // OUT o handle) - // Options: - // handle_token (s) - A string that will be used as the last element of the @handle. - // writable (b) - Whether to allow the chosen application to write to the file. - -#ifdef O_PATH - const int fd = qt_safe_open(QFile::encodeName(url.toLocalFile()), O_PATH); - if (fd != -1) { - QDBusMessage message = QDBusMessage::createMethodCall(QLatin1String("org.freedesktop.portal.Desktop"), - QLatin1String("/org/freedesktop/portal/desktop"), - QLatin1String("org.freedesktop.portal.OpenURI"), - QLatin1String("OpenFile")); - - QDBusUnixFileDescriptor descriptor; - descriptor.giveFileDescriptor(fd); - - // FIXME parent_window_id and handle writable option - message << QString() << QVariant::fromValue(descriptor) << QVariantMap(); - - return QDBusConnection::sessionBus().call(message); - } -#else - Q_UNUSED(url) -#endif - - return QDBusMessage::createError(QDBusError::InternalError, qt_error_string()); -} - -static inline QDBusMessage xdgDesktopPortalOpenUrl(const QUrl &url) -{ - // DBus signature: - // OpenURI (IN s parent_window, - // IN s uri, - // IN a{sv} options, - // OUT o handle) - // Options: - // handle_token (s) - A string that will be used as the last element of the @handle. - // writable (b) - Whether to allow the chosen application to write to the file. - // This key only takes effect the uri points to a local file that is exported in the document portal, - // and the chosen application is sandboxed itself. - - QDBusMessage message = QDBusMessage::createMethodCall(QLatin1String("org.freedesktop.portal.Desktop"), - QLatin1String("/org/freedesktop/portal/desktop"), - QLatin1String("org.freedesktop.portal.OpenURI"), - QLatin1String("OpenURI")); - // FIXME parent_window_id and handle writable option - message << QString() << url.toString() << QVariantMap(); - - return QDBusConnection::sessionBus().call(message); -} - -static inline QDBusMessage xdgDesktopPortalSendEmail(const QUrl &url) -{ - // DBus signature: - // ComposeEmail (IN s parent_window, - // IN a{sv} options, - // OUT o handle) - // Options: - // address (s) - The email address to send to. - // subject (s) - The subject for the email. - // body (s) - The body for the email. - // attachment_fds (ah) - File descriptors for files to attach. - - QUrlQuery urlQuery(url); - QVariantMap options; - options.insert(QLatin1String("address"), url.path()); - options.insert(QLatin1String("subject"), urlQuery.queryItemValue(QLatin1String("subject"))); - options.insert(QLatin1String("body"), urlQuery.queryItemValue(QLatin1String("body"))); - - // O_PATH seems to be present since Linux 2.6.39, which is not case of RHEL 6 -#ifdef O_PATH - QList<QDBusUnixFileDescriptor> attachments; - const QStringList attachmentUris = urlQuery.allQueryItemValues(QLatin1String("attachment")); - - for (const QString &attachmentUri : attachmentUris) { - const int fd = qt_safe_open(QFile::encodeName(attachmentUri), O_PATH); - if (fd != -1) { - QDBusUnixFileDescriptor descriptor(fd); - attachments << descriptor; - qt_safe_close(fd); - } - } - - options.insert(QLatin1String("attachment_fds"), QVariant::fromValue(attachments)); -#endif - - QDBusMessage message = QDBusMessage::createMethodCall(QLatin1String("org.freedesktop.portal.Desktop"), - QLatin1String("/org/freedesktop/portal/desktop"), - QLatin1String("org.freedesktop.portal.Email"), - QLatin1String("ComposeEmail")); - - // FIXME parent_window_id - message << QString() << options; - - return QDBusConnection::sessionBus().call(message); -} -#endif // QT_CONFIG(dbus) - -QByteArray QGenericUnixServices::desktopEnvironment() const -{ - static const QByteArray result = detectDesktopEnvironment(); - return result; -} - -bool QGenericUnixServices::openUrl(const QUrl &url) -{ - if (url.scheme() == QLatin1String("mailto")) { -#if QT_CONFIG(dbus) - if (checkNeedPortalSupport()) { - QDBusError error = xdgDesktopPortalSendEmail(url); - if (isPortalReturnPermanent(error)) - return !error.isValid(); - - // service not running, fall back - } -#endif - return openDocument(url); - } - -#if QT_CONFIG(dbus) - if (checkNeedPortalSupport()) { - QDBusError error = xdgDesktopPortalOpenUrl(url); - if (isPortalReturnPermanent(error)) - return !error.isValid(); - } -#endif - - if (m_webBrowser.isEmpty() && !detectWebBrowser(desktopEnvironment(), true, &m_webBrowser)) { - qWarning("Unable to detect a web browser to launch '%s'", qPrintable(url.toString())); - return false; - } - return launch(m_webBrowser, url); -} - -bool QGenericUnixServices::openDocument(const QUrl &url) -{ -#if QT_CONFIG(dbus) - if (checkNeedPortalSupport()) { - QDBusError error = xdgDesktopPortalOpenFile(url); - if (isPortalReturnPermanent(error)) - return !error.isValid(); - } -#endif - - if (m_documentLauncher.isEmpty() && !detectWebBrowser(desktopEnvironment(), false, &m_documentLauncher)) { - qWarning("Unable to detect a launcher for '%s'", qPrintable(url.toString())); - return false; - } - return launch(m_documentLauncher, url); -} - -#else -QByteArray QGenericUnixServices::desktopEnvironment() const -{ - return QByteArrayLiteral("UNKNOWN"); -} - -bool QGenericUnixServices::openUrl(const QUrl &url) -{ - Q_UNUSED(url) - qWarning("openUrl() not supported on this platform"); - return false; -} - -bool QGenericUnixServices::openDocument(const QUrl &url) -{ - Q_UNUSED(url) - qWarning("openDocument() not supported on this platform"); - return false; -} - -#endif // QT_NO_MULTIPROCESS - -QT_END_NAMESPACE diff --git a/src/platformsupport/services/genericunix/qgenericunixservices_p.h b/src/platformsupport/services/genericunix/qgenericunixservices_p.h deleted file mode 100644 index 8ac3de6f03..0000000000 --- a/src/platformsupport/services/genericunix/qgenericunixservices_p.h +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QGENERICUNIXDESKTOPSERVICES_H -#define QGENERICUNIXDESKTOPSERVICES_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <qpa/qplatformservices.h> -#include <QtCore/QString> - -QT_BEGIN_NAMESPACE - -class QGenericUnixServices : public QPlatformServices -{ -public: - QGenericUnixServices() {} - - QByteArray desktopEnvironment() const override; - - bool openUrl(const QUrl &url) override; - bool openDocument(const QUrl &url) override; - -private: - QString m_webBrowser; - QString m_documentLauncher; -}; - -QT_END_NAMESPACE - -#endif // QGENERICUNIXDESKTOPSERVICES_H diff --git a/src/platformsupport/services/services.pro b/src/platformsupport/services/services.pro deleted file mode 100644 index 7ff5e8e179..0000000000 --- a/src/platformsupport/services/services.pro +++ /dev/null @@ -1,14 +0,0 @@ -TARGET = QtServiceSupport -MODULE = service_support - -QT = core-private gui-private -qtConfig(dbus): QT += dbus - -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII -PRECOMPILED_HEADER = ../../corelib/global/qt_pch.h - -include($$PWD/genericunix/genericunix.pri) - -load(qt_module) diff --git a/src/platformsupport/themes/genericunix/dbusmenu/dbusmenu.pri b/src/platformsupport/themes/genericunix/dbusmenu/dbusmenu.pri deleted file mode 100644 index 662ebfdae6..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/dbusmenu.pri +++ /dev/null @@ -1,19 +0,0 @@ -QT_FOR_PRIVATE += dbus - -INCLUDEPATH += $$PWD - -HEADERS += \ - $$PWD/qdbusmenuadaptor_p.h \ - $$PWD/qdbusmenutypes_p.h \ - $$PWD/qdbusmenuconnection_p.h \ - $$PWD/qdbusmenubar_p.h \ - $$PWD/qdbusmenuregistrarproxy_p.h \ - $$PWD/qdbusplatformmenu_p.h \ - -SOURCES += \ - $$PWD/qdbusmenuadaptor.cpp \ - $$PWD/qdbusmenutypes.cpp \ - $$PWD/qdbusmenuconnection.cpp \ - $$PWD/qdbusmenubar.cpp \ - $$PWD/qdbusmenuregistrarproxy.cpp \ - $$PWD/qdbusplatformmenu.cpp \ diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuadaptor.cpp b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuadaptor.cpp deleted file mode 100644 index eabb4b4122..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuadaptor.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/* - This file was originally created by qdbusxml2cpp version 0.8 - Command line was: - qdbusxml2cpp -a dbusmenu ../../3rdparty/dbus-ifaces/dbus-menu.xml - - However it is maintained manually. -*/ - -#include "qdbusmenuadaptor_p.h" -#include "qdbusplatformmenu_p.h" -#include <QtCore/QMetaObject> -#include <QtCore/QByteArray> -#include <QtCore/QList> -#include <QtCore/QMap> -#include <QtCore/QString> -#include <QtCore/QStringList> -#include <QtCore/QVariant> - -QT_BEGIN_NAMESPACE - -QDBusMenuAdaptor::QDBusMenuAdaptor(QDBusPlatformMenu *topLevelMenu) - : QDBusAbstractAdaptor(topLevelMenu) - , m_topLevelMenu(topLevelMenu) -{ - setAutoRelaySignals(true); -} - -QDBusMenuAdaptor::~QDBusMenuAdaptor() -{ -} - -QString QDBusMenuAdaptor::status() const -{ - qCDebug(qLcMenu); - return QLatin1String("normal"); -} - -QString QDBusMenuAdaptor::textDirection() const -{ - return QLocale().textDirection() == Qt::RightToLeft ? QLatin1String("rtl") : QLatin1String("ltr"); -} - -uint QDBusMenuAdaptor::version() const -{ - return 4; -} - -bool QDBusMenuAdaptor::AboutToShow(int id) -{ - qCDebug(qLcMenu) << id; - if (id == 0) { - emit m_topLevelMenu->aboutToShow(); - } else { - QDBusPlatformMenuItem *item = QDBusPlatformMenuItem::byId(id); - if (item) { - const QDBusPlatformMenu *menu = static_cast<const QDBusPlatformMenu *>(item->menu()); - if (menu) - emit const_cast<QDBusPlatformMenu *>(menu)->aboutToShow(); - } - } - return false; // updateNeeded (we don't know that, so false) -} - -QList<int> QDBusMenuAdaptor::AboutToShowGroup(const QList<int> &ids, QList<int> &idErrors) -{ - qCDebug(qLcMenu) << ids; - Q_UNUSED(idErrors) - idErrors.clear(); - for (int id : ids) - AboutToShow(id); - return QList<int>(); // updatesNeeded -} - -void QDBusMenuAdaptor::Event(int id, const QString &eventId, const QDBusVariant &data, uint timestamp) -{ - Q_UNUSED(data) - Q_UNUSED(timestamp) - QDBusPlatformMenuItem *item = QDBusPlatformMenuItem::byId(id); - qCDebug(qLcMenu) << id << (item ? item->text() : QLatin1String("")) << eventId; - if (item && eventId == QLatin1String("clicked")) - item->trigger(); - if (item && eventId == QLatin1String("hovered")) - emit item->hovered(); - if (eventId == QLatin1String("closed")) { - // There is no explicit AboutToHide method, so map closed event to aboutToHide method - const QDBusPlatformMenu *menu = nullptr; - if (item) - menu = static_cast<const QDBusPlatformMenu *>(item->menu()); - else if (id == 0) - menu = m_topLevelMenu; - if (menu) - emit const_cast<QDBusPlatformMenu *>(menu)->aboutToHide(); - } -} - -QList<int> QDBusMenuAdaptor::EventGroup(const QDBusMenuEventList &events) -{ - for (const QDBusMenuEvent &ev : events) - Event(ev.m_id, ev.m_eventId, ev.m_data, ev.m_timestamp); - return QList<int>(); // idErrors -} - -QDBusMenuItemList QDBusMenuAdaptor::GetGroupProperties(const QList<int> &ids, const QStringList &propertyNames) -{ - qCDebug(qLcMenu) << ids << propertyNames << "=>" << QDBusMenuItem::items(ids, propertyNames); - return QDBusMenuItem::items(ids, propertyNames); -} - -uint QDBusMenuAdaptor::GetLayout(int parentId, int recursionDepth, const QStringList &propertyNames, QDBusMenuLayoutItem &layout) -{ - uint ret = layout.populate(parentId, recursionDepth, propertyNames, m_topLevelMenu); - qCDebug(qLcMenu) << parentId << "depth" << recursionDepth << propertyNames << layout.m_id << layout.m_properties << "revision" << ret << layout; - return ret; -} - -QDBusVariant QDBusMenuAdaptor::GetProperty(int id, const QString &name) -{ - qCDebug(qLcMenu) << id << name; - // handle method call com.canonical.dbusmenu.GetProperty - QDBusVariant value; - return value; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuadaptor_p.h b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuadaptor_p.h deleted file mode 100644 index 6612f019a7..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuadaptor_p.h +++ /dev/null @@ -1,182 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtDBus module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/* - This file was originally created by qdbusxml2cpp version 0.8 - Command line was: - qdbusxml2cpp -a dbusmenu ../../3rdparty/dbus-ifaces/dbus-menu.xml - - However it is maintained manually. - - It is also not part of the public API. This header file may change from - version to version without notice, or even be removed. -*/ - -#ifndef DBUSMENUADAPTOR_H -#define DBUSMENUADAPTOR_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/QObject> -#include <QtDBus/QtDBus> -#include "qdbusmenutypes_p.h" - -QT_BEGIN_NAMESPACE - -/* - * Adaptor class for interface com.canonical.dbusmenu - */ -class QDBusMenuAdaptor: public QDBusAbstractAdaptor -{ - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "com.canonical.dbusmenu") - Q_CLASSINFO("D-Bus Introspection", "" -" <interface name=\"com.canonical.dbusmenu\">\n" -" <property access=\"read\" type=\"u\" name=\"Version\">\n" -" </property>\n" -" <property access=\"read\" type=\"s\" name=\"TextDirection\">\n" -" </property>\n" -" <property access=\"read\" type=\"s\" name=\"Status\">\n" -" </property>\n" -" <property access=\"read\" type=\"as\" name=\"IconThemePath\">\n" -" </property>\n" -" <method name=\"GetLayout\">\n" -" <annotation value=\"QDBusMenuLayoutItem\" name=\"org.qtproject.QtDBus.QtTypeName.Out1\"/>\n" -" <arg direction=\"in\" type=\"i\" name=\"parentId\"/>\n" -" <arg direction=\"in\" type=\"i\" name=\"recursionDepth\"/>\n" -" <arg direction=\"in\" type=\"as\" name=\"propertyNames\"/>\n" -" <arg direction=\"out\" type=\"u\" name=\"revision\"/>\n" -" <arg direction=\"out\" type=\"(ia{sv}av)\" name=\"layout\"/>\n" -" </method>\n" -" <method name=\"GetGroupProperties\">\n" -" <annotation value=\"QList<int>\" name=\"org.qtproject.QtDBus.QtTypeName.In0\"/>\n" -" <annotation value=\"QDBusMenuItemList\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" -" <arg direction=\"in\" type=\"ai\" name=\"ids\"/>\n" -" <arg direction=\"in\" type=\"as\" name=\"propertyNames\"/>\n" -" <arg direction=\"out\" type=\"a(ia{sv})\" name=\"properties\"/>\n" -" </method>\n" -" <method name=\"GetProperty\">\n" -" <arg direction=\"in\" type=\"i\" name=\"id\"/>\n" -" <arg direction=\"in\" type=\"s\" name=\"name\"/>\n" -" <arg direction=\"out\" type=\"v\" name=\"value\"/>\n" -" </method>\n" -" <method name=\"Event\">\n" -" <arg direction=\"in\" type=\"i\" name=\"id\"/>\n" -" <arg direction=\"in\" type=\"s\" name=\"eventId\"/>\n" -" <arg direction=\"in\" type=\"v\" name=\"data\"/>\n" -" <arg direction=\"in\" type=\"u\" name=\"timestamp\"/>\n" -" </method>\n" -" <method name=\"EventGroup\">\n" -" <annotation value=\"QList<QDBusMenuEvent>\" name=\"org.qtproject.QtDBus.QtTypeName.In0\"/>\n" -" <annotation value=\"QList<int>\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" -" <arg direction=\"in\" type=\"a(isvu)\" name=\"events\"/>\n" -" <arg direction=\"out\" type=\"ai\" name=\"idErrors\"/>\n" -" </method>\n" -" <method name=\"AboutToShow\">\n" -" <arg direction=\"in\" type=\"i\" name=\"id\"/>\n" -" <arg direction=\"out\" type=\"b\" name=\"needUpdate\"/>\n" -" </method>\n" -" <method name=\"AboutToShowGroup\">\n" -" <annotation value=\"QList<int>\" name=\"org.qtproject.QtDBus.QtTypeName.In0\"/>\n" -" <annotation value=\"QList<int>\" name=\"org.qtproject.QtDBus.QtTypeName.Out0\"/>\n" -" <annotation value=\"QList<int>\" name=\"org.qtproject.QtDBus.QtTypeName.Out1\"/>\n" -" <arg direction=\"in\" type=\"ai\" name=\"ids\"/>\n" -" <arg direction=\"out\" type=\"ai\" name=\"updatesNeeded\"/>\n" -" <arg direction=\"out\" type=\"ai\" name=\"idErrors\"/>\n" -" </method>\n" -" <signal name=\"ItemsPropertiesUpdated\">\n" -" <annotation value=\"QDBusMenuItemList\" name=\"org.qtproject.QtDBus.QtTypeName.In0\"/>\n" -" <annotation value=\"QDBusMenuItemKeysList\" name=\"org.qtproject.QtDBus.QtTypeName.In1\"/>\n" -" <arg direction=\"out\" type=\"a(ia{sv})\" name=\"updatedProps\"/>\n" -" <arg direction=\"out\" type=\"a(ias)\" name=\"removedProps\"/>\n" -" </signal>\n" -" <signal name=\"LayoutUpdated\">\n" -" <arg direction=\"out\" type=\"u\" name=\"revision\"/>\n" -" <arg direction=\"out\" type=\"i\" name=\"parent\"/>\n" -" </signal>\n" -" <signal name=\"ItemActivationRequested\">\n" -" <arg direction=\"out\" type=\"i\" name=\"id\"/>\n" -" <arg direction=\"out\" type=\"u\" name=\"timestamp\"/>\n" -" </signal>\n" -" </interface>\n" - "") -public: - QDBusMenuAdaptor(QDBusPlatformMenu *topLevelMenu); - virtual ~QDBusMenuAdaptor(); - -public: // PROPERTIES - Q_PROPERTY(QString Status READ status) - QString status() const; - - Q_PROPERTY(QString TextDirection READ textDirection) - QString textDirection() const; - - Q_PROPERTY(uint Version READ version) - uint version() const; - -public Q_SLOTS: // METHODS - bool AboutToShow(int id); - QList<int> AboutToShowGroup(const QList<int> &ids, QList<int> &idErrors); - void Event(int id, const QString &eventId, const QDBusVariant &data, uint timestamp); - QList<int> EventGroup(const QDBusMenuEventList &events); - QDBusMenuItemList GetGroupProperties(const QList<int> &ids, const QStringList &propertyNames); - uint GetLayout(int parentId, int recursionDepth, const QStringList &propertyNames, QDBusMenuLayoutItem &layout); - QDBusVariant GetProperty(int id, const QString &name); - -Q_SIGNALS: // SIGNALS - void ItemActivationRequested(int id, uint timestamp); - void ItemsPropertiesUpdated(const QDBusMenuItemList &updatedProps, const QDBusMenuItemKeysList &removedProps); - void LayoutUpdated(uint revision, int parent); - -private: - QDBusPlatformMenu *m_topLevelMenu; -}; - -QT_END_NAMESPACE - -#endif // DBUSMENUADAPTOR_H diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenubar.cpp b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenubar.cpp deleted file mode 100644 index b13c875854..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenubar.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Dmitry Shachnev <mitya57@gmail.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qdbusmenubar_p.h" -#include "qdbusmenuregistrarproxy_p.h" - -QT_BEGIN_NAMESPACE - -/* note: do not change these to QStringLiteral; - we are unloaded before QtDBus is done using the strings. - */ -#define REGISTRAR_SERVICE QLatin1String("com.canonical.AppMenu.Registrar") -#define REGISTRAR_PATH QLatin1String("/com/canonical/AppMenu/Registrar") - -QDBusMenuBar::QDBusMenuBar() - : QPlatformMenuBar() - , m_menu(new QDBusPlatformMenu()) - , m_menuAdaptor(new QDBusMenuAdaptor(m_menu)) - , m_windowId(0) -{ - QDBusMenuItem::registerDBusTypes(); - connect(m_menu, &QDBusPlatformMenu::propertiesUpdated, - m_menuAdaptor, &QDBusMenuAdaptor::ItemsPropertiesUpdated); - connect(m_menu, &QDBusPlatformMenu::updated, - m_menuAdaptor, &QDBusMenuAdaptor::LayoutUpdated); - connect(m_menu, &QDBusPlatformMenu::popupRequested, - m_menuAdaptor, &QDBusMenuAdaptor::ItemActivationRequested); -} - -QDBusMenuBar::~QDBusMenuBar() -{ - unregisterMenuBar(); - delete m_menuAdaptor; - delete m_menu; - qDeleteAll(m_menuItems); -} - -QDBusPlatformMenuItem *QDBusMenuBar::menuItemForMenu(QPlatformMenu *menu) -{ - if (!menu) - return nullptr; - quintptr tag = menu->tag(); - const auto it = m_menuItems.constFind(tag); - if (it != m_menuItems.cend()) { - return *it; - } else { - QDBusPlatformMenuItem *item = new QDBusPlatformMenuItem; - updateMenuItem(item, menu); - m_menuItems.insert(tag, item); - return item; - } -} - -void QDBusMenuBar::updateMenuItem(QDBusPlatformMenuItem *item, QPlatformMenu *menu) -{ - const QDBusPlatformMenu *ourMenu = qobject_cast<const QDBusPlatformMenu *>(menu); - item->setText(ourMenu->text()); - item->setIcon(ourMenu->icon()); - item->setEnabled(ourMenu->isEnabled()); - item->setVisible(ourMenu->isVisible()); - item->setMenu(menu); -} - -void QDBusMenuBar::insertMenu(QPlatformMenu *menu, QPlatformMenu *before) -{ - QDBusPlatformMenuItem *menuItem = menuItemForMenu(menu); - QDBusPlatformMenuItem *beforeItem = menuItemForMenu(before); - m_menu->insertMenuItem(menuItem, beforeItem); - m_menu->emitUpdated(); -} - -void QDBusMenuBar::removeMenu(QPlatformMenu *menu) -{ - QDBusPlatformMenuItem *menuItem = menuItemForMenu(menu); - m_menu->removeMenuItem(menuItem); - m_menu->emitUpdated(); -} - -void QDBusMenuBar::syncMenu(QPlatformMenu *menu) -{ - QDBusPlatformMenuItem *menuItem = menuItemForMenu(menu); - updateMenuItem(menuItem, menu); -} - -void QDBusMenuBar::handleReparent(QWindow *newParentWindow) -{ - if (newParentWindow) { - unregisterMenuBar(); - m_windowId = newParentWindow->winId(); - registerMenuBar(); - } -} - -QPlatformMenu *QDBusMenuBar::menuForTag(quintptr tag) const -{ - QDBusPlatformMenuItem *menuItem = m_menuItems.value(tag); - if (menuItem) - return const_cast<QPlatformMenu *>(menuItem->menu()); - return nullptr; -} - -QPlatformMenu *QDBusMenuBar::createMenu() const -{ - return new QDBusPlatformMenu; -} - -void QDBusMenuBar::registerMenuBar() -{ - static uint menuBarId = 0; - - QDBusConnection connection = QDBusConnection::sessionBus(); - m_objectPath = QStringLiteral("/MenuBar/%1").arg(++menuBarId); - if (!connection.registerObject(m_objectPath, m_menu)) - return; - - QDBusMenuRegistrarInterface registrar(REGISTRAR_SERVICE, REGISTRAR_PATH, connection, this); - QDBusPendingReply<> r = registrar.RegisterWindow(m_windowId, QDBusObjectPath(m_objectPath)); - r.waitForFinished(); - if (r.isError()) { - qWarning("Failed to register window menu, reason: %s (\"%s\")", - qUtf8Printable(r.error().name()), qUtf8Printable(r.error().message())); - connection.unregisterObject(m_objectPath); - } -} - -void QDBusMenuBar::unregisterMenuBar() -{ - QDBusConnection connection = QDBusConnection::sessionBus(); - - if (m_windowId) { - QDBusMenuRegistrarInterface registrar(REGISTRAR_SERVICE, REGISTRAR_PATH, connection, this); - QDBusPendingReply<> r = registrar.UnregisterWindow(m_windowId); - r.waitForFinished(); - if (r.isError()) - qWarning("Failed to unregister window menu, reason: %s (\"%s\")", - qUtf8Printable(r.error().name()), qUtf8Printable(r.error().message())); - } - - if (!m_objectPath.isEmpty()) - connection.unregisterObject(m_objectPath); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenubar_p.h b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenubar_p.h deleted file mode 100644 index 364e7da4b6..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenubar_p.h +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Dmitry Shachnev <mitya57@gmail.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QDBUSMENUBAR_P_H -#define QDBUSMENUBAR_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <private/qdbusplatformmenu_p.h> -#include <private/qdbusmenuadaptor_p.h> -#include <QtCore/QHash> -#include <QtCore/QString> -#include <QtGui/QWindow> - -QT_BEGIN_NAMESPACE - -class QDBusMenuBar : public QPlatformMenuBar -{ - Q_OBJECT - -public: - QDBusMenuBar(); - virtual ~QDBusMenuBar(); - - void insertMenu(QPlatformMenu *menu, QPlatformMenu *before) override; - void removeMenu(QPlatformMenu *menu) override; - void syncMenu(QPlatformMenu *menu) override; - void handleReparent(QWindow *newParentWindow) override; - QPlatformMenu *menuForTag(quintptr tag) const override; - QPlatformMenu *createMenu() const override; - -private: - QDBusPlatformMenu *m_menu; - QDBusMenuAdaptor *m_menuAdaptor; - QHash<quintptr, QDBusPlatformMenuItem *> m_menuItems; - uint m_windowId; - QString m_objectPath; - - QDBusPlatformMenuItem *menuItemForMenu(QPlatformMenu *menu); - static void updateMenuItem(QDBusPlatformMenuItem *item, QPlatformMenu *menu); - void registerMenuBar(); - void unregisterMenuBar(); -}; - -QT_END_NAMESPACE - -#endif // QDBUSMENUBAR_P_H diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuconnection.cpp b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuconnection.cpp deleted file mode 100644 index 09470bccc6..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuconnection.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtGui/qtgui-config.h> - -#ifndef QT_NO_SYSTEMTRAYICON -#include "qdbustrayicon_p.h" -#endif -#include "qdbusmenuconnection_p.h" -#include "qdbusmenuadaptor_p.h" -#include "qdbusplatformmenu_p.h" - -#include <QtDBus/QDBusMessage> -#include <QtDBus/QDBusServiceWatcher> -#include <QtDBus/QDBusConnectionInterface> -#include <qdebug.h> -#include <qcoreapplication.h> - -QT_BEGIN_NAMESPACE - -Q_DECLARE_LOGGING_CATEGORY(qLcMenu) - -const QString StatusNotifierWatcherService = QLatin1String("org.kde.StatusNotifierWatcher"); -const QString StatusNotifierWatcherPath = QLatin1String("/StatusNotifierWatcher"); -const QString StatusNotifierItemPath = QLatin1String("/StatusNotifierItem"); -const QString MenuBarPath = QLatin1String("/MenuBar"); - -/*! - \class QDBusMenuConnection - \internal - A D-Bus connection which is used for both menu and tray icon services. - Connects to the session bus and registers with the respective watcher services. -*/ -QDBusMenuConnection::QDBusMenuConnection(QObject *parent, const QString &serviceName) - : QObject(parent) - , m_connection(serviceName.isNull() ? QDBusConnection::sessionBus() - : QDBusConnection::connectToBus(QDBusConnection::SessionBus, serviceName)) - , m_dbusWatcher(new QDBusServiceWatcher(StatusNotifierWatcherService, m_connection, QDBusServiceWatcher::WatchForRegistration, this)) - , m_statusNotifierHostRegistered(false) -{ -#ifndef QT_NO_SYSTEMTRAYICON - QDBusInterface systrayHost(StatusNotifierWatcherService, StatusNotifierWatcherPath, StatusNotifierWatcherService, m_connection); - if (systrayHost.isValid() && systrayHost.property("IsStatusNotifierHostRegistered").toBool()) - m_statusNotifierHostRegistered = true; - else - qCDebug(qLcMenu) << "StatusNotifierHost is not registered"; -#endif -} - -void QDBusMenuConnection::dbusError(const QDBusError &error) -{ - qWarning() << "QDBusTrayIcon encountered a D-Bus error:" << error; -} - -#ifndef QT_NO_SYSTEMTRAYICON -bool QDBusMenuConnection::registerTrayIconMenu(QDBusTrayIcon *item) -{ - bool success = connection().registerObject(MenuBarPath, item->menu()); - if (!success) // success == false is normal, because the object may be already registered - qCDebug(qLcMenu) << "failed to register" << item->instanceId() << MenuBarPath; - return success; -} - -void QDBusMenuConnection::unregisterTrayIconMenu(QDBusTrayIcon *item) -{ - if (item->menu()) - connection().unregisterObject(MenuBarPath); -} - -bool QDBusMenuConnection::registerTrayIcon(QDBusTrayIcon *item) -{ - bool success = connection().registerService(item->instanceId()); - if (!success) { - qWarning() << "failed to register service" << item->instanceId(); - return false; - } - - success = connection().registerObject(StatusNotifierItemPath, item); - if (!success) { - unregisterTrayIcon(item); - qWarning() << "failed to register" << item->instanceId() << StatusNotifierItemPath; - return false; - } - - if (item->menu()) - registerTrayIconMenu(item); - - return registerTrayIconWithWatcher(item); -} - -bool QDBusMenuConnection::registerTrayIconWithWatcher(QDBusTrayIcon *item) -{ - QDBusMessage registerMethod = QDBusMessage::createMethodCall( - StatusNotifierWatcherService, StatusNotifierWatcherPath, StatusNotifierWatcherService, - QLatin1String("RegisterStatusNotifierItem")); - registerMethod.setArguments(QVariantList() << item->instanceId()); - return m_connection.callWithCallback(registerMethod, this, SIGNAL(trayIconRegistered()), SLOT(dbusError(QDBusError))); -} - -bool QDBusMenuConnection::unregisterTrayIcon(QDBusTrayIcon *item) -{ - unregisterTrayIconMenu(item); - connection().unregisterObject(StatusNotifierItemPath); - bool success = connection().unregisterService(item->instanceId()); - if (!success) - qWarning() << "failed to unregister service" << item->instanceId(); - return success; -} -#endif // QT_NO_SYSTEMTRAYICON - -QT_END_NAMESPACE diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuconnection_p.h b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuconnection_p.h deleted file mode 100644 index 7959f0c28a..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuconnection_p.h +++ /dev/null @@ -1,100 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef DBUSCONNECTION_H -#define DBUSCONNECTION_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/QString> -#include <QtDBus/QDBusConnection> -#include <QtDBus/QDBusVariant> - -#include <QtGui/qtgui-config.h> - -QT_BEGIN_NAMESPACE - -class QDBusServiceWatcher; -#ifndef QT_NO_SYSTEMTRAYICON -class QDBusTrayIcon; -#endif // QT_NO_SYSTEMTRAYICON - -class QDBusMenuConnection : public QObject -{ - Q_OBJECT - -public: - QDBusMenuConnection(QObject *parent = 0, const QString &serviceName = QString()); - QDBusConnection connection() const { return m_connection; } - QDBusServiceWatcher *dbusWatcher() const { return m_dbusWatcher; } - bool isStatusNotifierHostRegistered() const { return m_statusNotifierHostRegistered; } -#ifndef QT_NO_SYSTEMTRAYICON - bool registerTrayIconMenu(QDBusTrayIcon *item); - void unregisterTrayIconMenu(QDBusTrayIcon *item); - bool registerTrayIcon(QDBusTrayIcon *item); - bool registerTrayIconWithWatcher(QDBusTrayIcon *item); - bool unregisterTrayIcon(QDBusTrayIcon *item); -#endif // QT_NO_SYSTEMTRAYICON - -Q_SIGNALS: -#ifndef QT_NO_SYSTEMTRAYICON - void trayIconRegistered(); -#endif // QT_NO_SYSTEMTRAYICON - -private Q_SLOTS: - void dbusError(const QDBusError &error); - -private: - QDBusConnection m_connection; - QDBusServiceWatcher *m_dbusWatcher; - bool m_statusNotifierHostRegistered; -}; - -QT_END_NAMESPACE - -#endif // DBUSCONNECTION_H diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuregistrarproxy.cpp b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuregistrarproxy.cpp deleted file mode 100644 index c59b5a675e..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuregistrarproxy.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Dmitry Shachnev <mitya57@gmail.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/* - * This file was originally created by qdbusxml2cpp version 0.8 - * Command line was: qdbusxml2cpp -p qdbusmenuregistrarproxy ../../3rdparty/dbus-ifaces/com.canonical.AppMenu.Registrar.xml - * - * However it is maintained manually. - */ - -#include "qdbusmenuregistrarproxy_p.h" - -QT_BEGIN_NAMESPACE - -/* - * Implementation of interface class QDBusMenuRegistrarInterface - */ - -QDBusMenuRegistrarInterface::QDBusMenuRegistrarInterface(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : QDBusAbstractInterface(service, path, staticInterfaceName(), connection, parent) -{ -} - -QDBusMenuRegistrarInterface::~QDBusMenuRegistrarInterface() -{ -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuregistrarproxy_p.h b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuregistrarproxy_p.h deleted file mode 100644 index c92de0a140..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenuregistrarproxy_p.h +++ /dev/null @@ -1,127 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Dmitry Shachnev <mitya57@gmail.com> -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/* - * This file was originally created by qdbusxml2cpp version 0.8 - * Command line was: qdbusxml2cpp -p qdbusmenuregistrarproxy ../../3rdparty/dbus-ifaces/com.canonical.AppMenu.Registrar.xml - * - * However it is maintained manually. - */ - -#ifndef QDBUSMENUREGISTRARPROXY_P_H -#define QDBUSMENUREGISTRARPROXY_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/QObject> -#include <QtCore/QByteArray> -#include <QtCore/QList> -#include <QtCore/QString> -#include <QtCore/QVariant> -#include <QtDBus/QDBusAbstractInterface> -#include <QtDBus/QDBusConnection> -#include <QtDBus/QDBusReply> - -QT_BEGIN_NAMESPACE - -/* - * Proxy class for interface com.canonical.AppMenu.Registrar - */ -class QDBusMenuRegistrarInterface : public QDBusAbstractInterface -{ - Q_OBJECT -public: - static inline const char *staticInterfaceName() - { - return "com.canonical.AppMenu.Registrar"; - } - -public: - explicit QDBusMenuRegistrarInterface(const QString &service, - const QString &path, - const QDBusConnection &connection, - QObject *parent = nullptr); - - ~QDBusMenuRegistrarInterface(); - -public Q_SLOTS: // METHODS - QDBusPendingReply<QString, QDBusObjectPath> GetMenuForWindow(uint windowId) - { - QList<QVariant> argumentList; - argumentList << QVariant::fromValue(windowId); - return asyncCallWithArgumentList(QStringLiteral("GetMenuForWindow"), argumentList); - } - QDBusReply<QString> GetMenuForWindow(uint windowId, QDBusObjectPath &menuObjectPath) - { - QList<QVariant> argumentList; - argumentList << QVariant::fromValue(windowId); - QDBusMessage reply = callWithArgumentList(QDBus::Block, QStringLiteral("GetMenuForWindow"), argumentList); - QList<QVariant> arguments = reply.arguments(); - if (reply.type() == QDBusMessage::ReplyMessage && arguments.count() == 2) - menuObjectPath = qdbus_cast<QDBusObjectPath>(arguments.at(1)); - return reply; - } - - QDBusPendingReply<> RegisterWindow(uint windowId, const QDBusObjectPath &menuObjectPath) - { - QList<QVariant> argumentList; - argumentList << QVariant::fromValue(windowId) << QVariant::fromValue(menuObjectPath); - return asyncCallWithArgumentList(QStringLiteral("RegisterWindow"), argumentList); - } - - QDBusPendingReply<> UnregisterWindow(uint windowId) - { - QList<QVariant> argumentList; - argumentList << QVariant::fromValue(windowId); - return asyncCallWithArgumentList(QStringLiteral("UnregisterWindow"), argumentList); - } -}; - -QT_END_NAMESPACE - -#endif // QDBUSMENUREGISTRARPROXY_P_H diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenutypes.cpp b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenutypes.cpp deleted file mode 100644 index 82a13d2fa0..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenutypes.cpp +++ /dev/null @@ -1,301 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qdbusmenutypes_p.h" - -#include <QDBusConnection> -#include <QDBusMetaType> -#include <QImage> -#include <QIcon> -#include <QImage> -#include <QPixmap> -#include <QDebug> -#include <QtEndian> -#include <QBuffer> -#include <private/qkeysequence_p.h> -#include <qpa/qplatformmenu.h> -#include "qdbusplatformmenu_p.h" - -QT_BEGIN_NAMESPACE - -const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuItem &item) -{ - arg.beginStructure(); - arg << item.m_id << item.m_properties; - arg.endStructure(); - return arg; -} - -const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuItem &item) -{ - arg.beginStructure(); - arg >> item.m_id >> item.m_properties; - arg.endStructure(); - return arg; -} - -const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuItemKeys &keys) -{ - arg.beginStructure(); - arg << keys.id << keys.properties; - arg.endStructure(); - return arg; -} - -const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuItemKeys &keys) -{ - arg.beginStructure(); - arg >> keys.id >> keys.properties; - arg.endStructure(); - return arg; -} - -uint QDBusMenuLayoutItem::populate(int id, int depth, const QStringList &propertyNames, const QDBusPlatformMenu *topLevelMenu) -{ - qCDebug(qLcMenu) << id << "depth" << depth << propertyNames; - m_id = id; - if (id == 0) { - m_properties.insert(QLatin1String("children-display"), QLatin1String("submenu")); - if (topLevelMenu) - populate(topLevelMenu, depth, propertyNames); - return 1; // revision - } - - QDBusPlatformMenuItem *item = QDBusPlatformMenuItem::byId(id); - if (item) { - const QDBusPlatformMenu *menu = static_cast<const QDBusPlatformMenu *>(item->menu()); - - if (menu) { - if (depth != 0) - populate(menu, depth, propertyNames); - return menu->revision(); - } - } - - return 1; // revision -} - -void QDBusMenuLayoutItem::populate(const QDBusPlatformMenu *menu, int depth, const QStringList &propertyNames) -{ - const auto items = menu->items(); - for (QDBusPlatformMenuItem *item : items) { - QDBusMenuLayoutItem child; - child.populate(item, depth - 1, propertyNames); - m_children << child; - } -} - -void QDBusMenuLayoutItem::populate(const QDBusPlatformMenuItem *item, int depth, const QStringList &propertyNames) -{ - m_id = item->dbusID(); - QDBusMenuItem proxy(item); - m_properties = proxy.m_properties; - - const QDBusPlatformMenu *menu = static_cast<const QDBusPlatformMenu *>(item->menu()); - if (depth != 0 && menu) - populate(menu, depth, propertyNames); -} - -const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuLayoutItem &item) -{ - arg.beginStructure(); - arg << item.m_id << item.m_properties; - arg.beginArray(qMetaTypeId<QDBusVariant>()); - for (const QDBusMenuLayoutItem &child : item.m_children) - arg << QDBusVariant(QVariant::fromValue<QDBusMenuLayoutItem>(child)); - arg.endArray(); - arg.endStructure(); - return arg; -} - -const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuLayoutItem &item) -{ - arg.beginStructure(); - arg >> item.m_id >> item.m_properties; - arg.beginArray(); - while (!arg.atEnd()) { - QDBusVariant dbusVariant; - arg >> dbusVariant; - QDBusArgument childArgument = dbusVariant.variant().value<QDBusArgument>(); - - QDBusMenuLayoutItem child; - childArgument >> child; - item.m_children.append(child); - } - arg.endArray(); - arg.endStructure(); - return arg; -} - -void QDBusMenuItem::registerDBusTypes() -{ - qDBusRegisterMetaType<QDBusMenuItem>(); - qDBusRegisterMetaType<QDBusMenuItemList>(); - qDBusRegisterMetaType<QDBusMenuItemKeys>(); - qDBusRegisterMetaType<QDBusMenuItemKeysList>(); - qDBusRegisterMetaType<QDBusMenuLayoutItem>(); - qDBusRegisterMetaType<QDBusMenuLayoutItemList>(); - qDBusRegisterMetaType<QDBusMenuEvent>(); - qDBusRegisterMetaType<QDBusMenuEventList>(); - qDBusRegisterMetaType<QDBusMenuShortcut>(); -} - -QDBusMenuItem::QDBusMenuItem(const QDBusPlatformMenuItem *item) - : m_id(item->dbusID()) -{ - if (item->isSeparator()) { - m_properties.insert(QLatin1String("type"), QLatin1String("separator")); - } else { - m_properties.insert(QLatin1String("label"), convertMnemonic(item->text())); - if (item->menu()) - m_properties.insert(QLatin1String("children-display"), QLatin1String("submenu")); - m_properties.insert(QLatin1String("enabled"), item->isEnabled()); - if (item->isCheckable()) { - QString toggleType = item->hasExclusiveGroup() ? QLatin1String("radio") : QLatin1String("checkmark"); - m_properties.insert(QLatin1String("toggle-type"), toggleType); - m_properties.insert(QLatin1String("toggle-state"), item->isChecked() ? 1 : 0); - } -#ifndef QT_NO_SHORTCUT - const QKeySequence &scut = item->shortcut(); - if (!scut.isEmpty()) { - QDBusMenuShortcut shortcut = convertKeySequence(scut); - m_properties.insert(QLatin1String("shortcut"), QVariant::fromValue(shortcut)); - } -#endif - const QIcon &icon = item->icon(); - if (!icon.name().isEmpty()) { - m_properties.insert(QLatin1String("icon-name"), icon.name()); - } else if (!icon.isNull()) { - QBuffer buf; - icon.pixmap(16).save(&buf, "PNG"); - m_properties.insert(QLatin1String("icon-data"), buf.data()); - } - } - m_properties.insert(QLatin1String("visible"), item->isVisible()); -} - -QDBusMenuItemList QDBusMenuItem::items(const QList<int> &ids, const QStringList &propertyNames) -{ - Q_UNUSED(propertyNames) - QDBusMenuItemList ret; - const QList<const QDBusPlatformMenuItem *> items = QDBusPlatformMenuItem::byIds(ids); - ret.reserve(items.size()); - for (const QDBusPlatformMenuItem *item : items) - ret << QDBusMenuItem(item); - return ret; -} - -QString QDBusMenuItem::convertMnemonic(const QString &label) -{ - // convert only the first occurrence of ampersand which is not at the end - // dbusmenu uses underscore instead of ampersand - int idx = label.indexOf(QLatin1Char('&')); - if (idx < 0 || idx == label.length() - 1) - return label; - QString ret(label); - ret[idx] = QLatin1Char('_'); - return ret; -} - -#ifndef QT_NO_SHORTCUT -QDBusMenuShortcut QDBusMenuItem::convertKeySequence(const QKeySequence &sequence) -{ - QDBusMenuShortcut shortcut; - for (int i = 0; i < sequence.count(); ++i) { - QStringList tokens; - int key = sequence[i]; - if (key & Qt::MetaModifier) - tokens << QStringLiteral("Super"); - if (key & Qt::ControlModifier) - tokens << QStringLiteral("Control"); - if (key & Qt::AltModifier) - tokens << QStringLiteral("Alt"); - if (key & Qt::ShiftModifier) - tokens << QStringLiteral("Shift"); - if (key & Qt::KeypadModifier) - tokens << QStringLiteral("Num"); - - QString keyName = QKeySequencePrivate::keyName(key, QKeySequence::PortableText); - if (keyName == QLatin1String("+")) - tokens << QStringLiteral("plus"); - else if (keyName == QLatin1String("-")) - tokens << QStringLiteral("minus"); - else - tokens << keyName; - shortcut << tokens; - } - return shortcut; -} -#endif - -const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuEvent &ev) -{ - arg.beginStructure(); - arg << ev.m_id << ev.m_eventId << ev.m_data << ev.m_timestamp; - arg.endStructure(); - return arg; -} - -const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuEvent &ev) -{ - arg.beginStructure(); - arg >> ev.m_id >> ev.m_eventId >> ev.m_data >> ev.m_timestamp; - arg.endStructure(); - return arg; -} - -#ifndef QT_NO_DEBUG_STREAM -QDebug operator<<(QDebug d, const QDBusMenuItem &item) -{ - QDebugStateSaver saver(d); - d.nospace(); - d << "QDBusMenuItem(id=" << item.m_id << ", properties=" << item.m_properties << ')'; - return d; -} - -QDebug operator<<(QDebug d, const QDBusMenuLayoutItem &item) -{ - QDebugStateSaver saver(d); - d.nospace(); - d << "QDBusMenuLayoutItem(id=" << item.m_id << ", properties=" << item.m_properties << ", " << item.m_children.count() << " children)"; - return d; -} -#endif - -QT_END_NAMESPACE diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenutypes_p.h b/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenutypes_p.h deleted file mode 100644 index fd6727d3be..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusmenutypes_p.h +++ /dev/null @@ -1,155 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QDBUSMENUTYPES_H -#define QDBUSMENUTYPES_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QObject> -#include <QString> -#include <QDBusArgument> -#include <QDBusConnection> -#include <QDBusObjectPath> -#include <QPixmap> - -QT_BEGIN_NAMESPACE - -class QDBusPlatformMenu; -class QDBusPlatformMenuItem; -class QDBusMenuItem; -typedef QVector<QDBusMenuItem> QDBusMenuItemList; -typedef QVector<QStringList> QDBusMenuShortcut; - -class QDBusMenuItem -{ -public: - QDBusMenuItem() { } - QDBusMenuItem(const QDBusPlatformMenuItem *item); - - static QDBusMenuItemList items(const QList<int> &ids, const QStringList &propertyNames); - static QString convertMnemonic(const QString &label); -#ifndef QT_NO_SHORTCUT - static QDBusMenuShortcut convertKeySequence(const QKeySequence &sequence); -#endif - static void registerDBusTypes(); - - int m_id; - QVariantMap m_properties; -}; -Q_DECLARE_TYPEINFO(QDBusMenuItem, Q_MOVABLE_TYPE); - -const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuItem &item); -const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuItem &item); - -class QDBusMenuItemKeys -{ -public: - - int id; - QStringList properties; -}; -Q_DECLARE_TYPEINFO(QDBusMenuItemKeys, Q_MOVABLE_TYPE); - -const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuItemKeys &keys); -const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuItemKeys &keys); - -typedef QVector<QDBusMenuItemKeys> QDBusMenuItemKeysList; - -class QDBusMenuLayoutItem -{ -public: - uint populate(int id, int depth, const QStringList &propertyNames, const QDBusPlatformMenu *topLevelMenu); - void populate(const QDBusPlatformMenu *menu, int depth, const QStringList &propertyNames); - void populate(const QDBusPlatformMenuItem *item, int depth, const QStringList &propertyNames); - - int m_id; - QVariantMap m_properties; - QVector<QDBusMenuLayoutItem> m_children; -}; -Q_DECLARE_TYPEINFO(QDBusMenuLayoutItem, Q_MOVABLE_TYPE); - -const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuLayoutItem &); -const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuLayoutItem &item); - -typedef QVector<QDBusMenuLayoutItem> QDBusMenuLayoutItemList; - -class QDBusMenuEvent -{ -public: - int m_id; - QString m_eventId; - QDBusVariant m_data; - uint m_timestamp; -}; -Q_DECLARE_TYPEINFO(QDBusMenuEvent, Q_MOVABLE_TYPE); // QDBusVariant is movable, even though it cannot - // be marked as such until Qt 6. - -const QDBusArgument &operator<<(QDBusArgument &arg, const QDBusMenuEvent &ev); -const QDBusArgument &operator>>(const QDBusArgument &arg, QDBusMenuEvent &ev); - -typedef QVector<QDBusMenuEvent> QDBusMenuEventList; - -#ifndef QT_NO_DEBUG_STREAM -QDebug operator<<(QDebug d, const QDBusMenuItem &item); -QDebug operator<<(QDebug d, const QDBusMenuLayoutItem &item); -#endif - -QT_END_NAMESPACE - -Q_DECLARE_METATYPE(QDBusMenuItem) -Q_DECLARE_METATYPE(QDBusMenuItemList) -Q_DECLARE_METATYPE(QDBusMenuItemKeys) -Q_DECLARE_METATYPE(QDBusMenuItemKeysList) -Q_DECLARE_METATYPE(QDBusMenuLayoutItem) -Q_DECLARE_METATYPE(QDBusMenuLayoutItemList) -Q_DECLARE_METATYPE(QDBusMenuEvent) -Q_DECLARE_METATYPE(QDBusMenuEventList) -Q_DECLARE_METATYPE(QDBusMenuShortcut) - -#endif diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusplatformmenu.cpp b/src/platformsupport/themes/genericunix/dbusmenu/qdbusplatformmenu.cpp deleted file mode 100644 index fc1b37f2f2..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusplatformmenu.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qdbusplatformmenu_p.h" - -#include <QDateTime> -#include <QDebug> -#include <QWindow> - -QT_BEGIN_NAMESPACE - -Q_LOGGING_CATEGORY(qLcMenu, "qt.qpa.menu") - -static int nextDBusID = 1; -QHash<int, QDBusPlatformMenuItem *> menuItemsByID; - -QDBusPlatformMenuItem::QDBusPlatformMenuItem() - : m_subMenu(nullptr) - , m_role(NoRole) - , m_isEnabled(true) - , m_isVisible(true) - , m_isSeparator(false) - , m_isCheckable(false) - , m_isChecked(false) - , m_hasExclusiveGroup(false) - , m_dbusID(nextDBusID++) -{ - menuItemsByID.insert(m_dbusID, this); -} - -QDBusPlatformMenuItem::~QDBusPlatformMenuItem() -{ - menuItemsByID.remove(m_dbusID); - if (m_subMenu) - static_cast<QDBusPlatformMenu *>(m_subMenu)->setContainingMenuItem(nullptr); -} - -void QDBusPlatformMenuItem::setText(const QString &text) -{ - qCDebug(qLcMenu) << m_dbusID << text; - m_text = text; -} - -void QDBusPlatformMenuItem::setIcon(const QIcon &icon) -{ - m_icon = icon; -} - -/*! - Set a submenu under this menu item. -*/ -void QDBusPlatformMenuItem::setMenu(QPlatformMenu *menu) -{ - if (m_subMenu) - static_cast<QDBusPlatformMenu *>(m_subMenu)->setContainingMenuItem(nullptr); - m_subMenu = menu; - if (menu) - static_cast<QDBusPlatformMenu *>(menu)->setContainingMenuItem(this); -} - -void QDBusPlatformMenuItem::setEnabled(bool enabled) -{ - m_isEnabled = enabled; -} - -void QDBusPlatformMenuItem::setVisible(bool isVisible) -{ - m_isVisible = isVisible; -} - -void QDBusPlatformMenuItem::setIsSeparator(bool isSeparator) -{ - m_isSeparator = isSeparator; -} - -void QDBusPlatformMenuItem::setRole(QPlatformMenuItem::MenuRole role) -{ - m_role = role; -} - -void QDBusPlatformMenuItem::setCheckable(bool checkable) -{ - m_isCheckable = checkable; -} - -void QDBusPlatformMenuItem::setChecked(bool isChecked) -{ - m_isChecked = isChecked; -} - -void QDBusPlatformMenuItem::setHasExclusiveGroup(bool hasExclusiveGroup) -{ - m_hasExclusiveGroup = hasExclusiveGroup; -} - -#ifndef QT_NO_SHORTCUT -void QDBusPlatformMenuItem::setShortcut(const QKeySequence &shortcut) -{ - m_shortcut = shortcut; -} -#endif - -void QDBusPlatformMenuItem::trigger() -{ - emit activated(); -} - -QDBusPlatformMenuItem *QDBusPlatformMenuItem::byId(int id) -{ - // We need to check contains because otherwise QHash would insert - // a default-constructed nullptr value into menuItemsByID - if (menuItemsByID.contains(id)) - return menuItemsByID[id]; - return nullptr; -} - -QList<const QDBusPlatformMenuItem *> QDBusPlatformMenuItem::byIds(const QList<int> &ids) -{ - QList<const QDBusPlatformMenuItem *> ret; - for (int id : ids) { - if (menuItemsByID.contains(id)) - ret << menuItemsByID[id]; - } - return ret; -} - - -QDBusPlatformMenu::QDBusPlatformMenu() - : m_isEnabled(true) - , m_isVisible(true) - , m_revision(1) - , m_containingMenuItem(nullptr) -{ -} - -QDBusPlatformMenu::~QDBusPlatformMenu() -{ - if (m_containingMenuItem) - m_containingMenuItem->setMenu(nullptr); -} - -void QDBusPlatformMenu::insertMenuItem(QPlatformMenuItem *menuItem, QPlatformMenuItem *before) -{ - QDBusPlatformMenuItem *item = static_cast<QDBusPlatformMenuItem *>(menuItem); - QDBusPlatformMenuItem *beforeItem = static_cast<QDBusPlatformMenuItem *>(before); - int idx = m_items.indexOf(beforeItem); - qCDebug(qLcMenu) << item->dbusID() << item->text(); - if (idx < 0) - m_items.append(item); - else - m_items.insert(idx, item); - m_itemsByTag.insert(item->tag(), item); - if (item->menu()) - syncSubMenu(static_cast<const QDBusPlatformMenu *>(item->menu())); - emitUpdated(); -} - -void QDBusPlatformMenu::removeMenuItem(QPlatformMenuItem *menuItem) -{ - QDBusPlatformMenuItem *item = static_cast<QDBusPlatformMenuItem *>(menuItem); - m_items.removeAll(item); - m_itemsByTag.remove(menuItem->tag()); - if (item->menu()) { - // disconnect from the signals we connected to in syncSubMenu() - const QDBusPlatformMenu *menu = static_cast<const QDBusPlatformMenu *>(item->menu()); - disconnect(menu, &QDBusPlatformMenu::propertiesUpdated, - this, &QDBusPlatformMenu::propertiesUpdated); - disconnect(menu, &QDBusPlatformMenu::updated, - this, &QDBusPlatformMenu::updated); - disconnect(menu, &QDBusPlatformMenu::popupRequested, - this, &QDBusPlatformMenu::popupRequested); - } - emitUpdated(); -} - -void QDBusPlatformMenu::syncSubMenu(const QDBusPlatformMenu *menu) -{ - // The adaptor is only connected to the propertiesUpdated signal of the top-level - // menu, so the submenus should transfer their signals to their parents. - connect(menu, &QDBusPlatformMenu::propertiesUpdated, - this, &QDBusPlatformMenu::propertiesUpdated, Qt::UniqueConnection); - connect(menu, &QDBusPlatformMenu::updated, - this, &QDBusPlatformMenu::updated, Qt::UniqueConnection); - connect(menu, &QDBusPlatformMenu::popupRequested, - this, &QDBusPlatformMenu::popupRequested, Qt::UniqueConnection); -} - -void QDBusPlatformMenu::syncMenuItem(QPlatformMenuItem *menuItem) -{ - QDBusPlatformMenuItem *item = static_cast<QDBusPlatformMenuItem *>(menuItem); - // if a submenu was added to this item, we need to connect to its signals - if (item->menu()) - syncSubMenu(static_cast<const QDBusPlatformMenu *>(item->menu())); - // TODO keep around copies of the QDBusMenuLayoutItems so they can be updated? - // or eliminate them by putting dbus streaming operators in this class instead? - // or somehow tell the dbusmenu client that something has changed, so it will ask for properties again - QDBusMenuItemList updated; - QDBusMenuItemKeysList removed; - updated << QDBusMenuItem(item); - qCDebug(qLcMenu) << updated; - emit propertiesUpdated(updated, removed); -} - -void QDBusPlatformMenu::emitUpdated() -{ - if (m_containingMenuItem) - emit updated(++m_revision, m_containingMenuItem->dbusID()); - else - emit updated(++m_revision, 0); -} - -void QDBusPlatformMenu::setText(const QString &text) -{ - m_text = text; -} - -void QDBusPlatformMenu::setIcon(const QIcon &icon) -{ - m_icon = icon; -} - -void QDBusPlatformMenu::setEnabled(bool enabled) -{ - m_isEnabled = enabled; -} - -void QDBusPlatformMenu::setVisible(bool isVisible) -{ - m_isVisible = isVisible; -} - -void QDBusPlatformMenu::setContainingMenuItem(QDBusPlatformMenuItem *item) -{ - m_containingMenuItem = item; -} - -void QDBusPlatformMenu::showPopup(const QWindow *parentWindow, const QRect &targetRect, const QPlatformMenuItem *item) -{ - Q_UNUSED(parentWindow); - Q_UNUSED(targetRect); - Q_UNUSED(item); - setVisible(true); - emit popupRequested(m_containingMenuItem->dbusID(), QDateTime::currentMSecsSinceEpoch()); -} - -QPlatformMenuItem *QDBusPlatformMenu::menuItemAt(int position) const -{ - return m_items.value(position); -} - -QPlatformMenuItem *QDBusPlatformMenu::menuItemForTag(quintptr tag) const -{ - return m_itemsByTag[tag]; -} - -const QList<QDBusPlatformMenuItem *> QDBusPlatformMenu::items() const -{ - return m_items; -} - -QPlatformMenuItem *QDBusPlatformMenu::createMenuItem() const -{ - QDBusPlatformMenuItem *ret = new QDBusPlatformMenuItem(); - return ret; -} - -QPlatformMenu *QDBusPlatformMenu::createSubMenu() const -{ - return new QDBusPlatformMenu; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/themes/genericunix/dbusmenu/qdbusplatformmenu_p.h b/src/platformsupport/themes/genericunix/dbusmenu/qdbusplatformmenu_p.h deleted file mode 100644 index 8a31f82fb0..0000000000 --- a/src/platformsupport/themes/genericunix/dbusmenu/qdbusplatformmenu_p.h +++ /dev/null @@ -1,189 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QDBUSPLATFORMMENU_H -#define QDBUSPLATFORMMENU_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// -// -// W A R N I N G -// ------------- -// -// This file is part of the DBus menu support and is not meant to be used -// in applications. Usage of this API may make your code -// source and binary incompatible with future versions of Qt. -// - -#include <qpa/qplatformmenu.h> -#include <QLoggingCategory> -#include "qdbusmenutypes_p.h" - -QT_BEGIN_NAMESPACE -Q_DECLARE_LOGGING_CATEGORY(qLcMenu) - -class QDBusPlatformMenu; - -class QDBusPlatformMenuItem : public QPlatformMenuItem -{ - Q_OBJECT - -public: - QDBusPlatformMenuItem(); - ~QDBusPlatformMenuItem(); - - const QString text() const { return m_text; } - void setText(const QString &text) override; - QIcon icon() const { return m_icon; } - void setIcon(const QIcon &icon) override; - const QPlatformMenu *menu() const { return m_subMenu; } - void setMenu(QPlatformMenu *menu) override; - bool isEnabled() const { return m_isEnabled; } - void setEnabled(bool enabled) override; - bool isVisible() const { return m_isVisible; } - void setVisible(bool isVisible) override; - bool isSeparator() const { return m_isSeparator; } - void setIsSeparator(bool isSeparator) override; - void setFont(const QFont &font) override { Q_UNUSED(font); } - void setRole(MenuRole role) override; - bool isCheckable() const { return m_isCheckable; } - void setCheckable(bool checkable) override; - bool isChecked() const { return m_isChecked; } - void setChecked(bool isChecked) override; - bool hasExclusiveGroup() const { return m_hasExclusiveGroup; } - void setHasExclusiveGroup(bool hasExclusiveGroup) override; -#ifndef QT_NO_SHORTCUT - QKeySequence shortcut() const { return m_shortcut; } - void setShortcut(const QKeySequence& shortcut) override; -#endif - void setIconSize(int size) override { Q_UNUSED(size); } - void setNativeContents(WId item) override { Q_UNUSED(item); } - - int dbusID() const { return m_dbusID; } - - void trigger(); - - static QDBusPlatformMenuItem *byId(int id); - static QList<const QDBusPlatformMenuItem *> byIds(const QList<int> &ids); - -private: - QString m_text; - QIcon m_icon; - QPlatformMenu *m_subMenu; - MenuRole m_role : 4; - bool m_isEnabled : 1; - bool m_isVisible : 1; - bool m_isSeparator : 1; - bool m_isCheckable : 1; - bool m_isChecked : 1; - bool m_hasExclusiveGroup : 1; - short /*unused*/ : 6; - short m_dbusID : 16; - QKeySequence m_shortcut; -}; - -class QDBusPlatformMenu : public QPlatformMenu -{ - Q_OBJECT - -public: - QDBusPlatformMenu(); - ~QDBusPlatformMenu(); - void insertMenuItem(QPlatformMenuItem *menuItem, QPlatformMenuItem *before) override; - void removeMenuItem(QPlatformMenuItem *menuItem) override; - void syncSubMenu(const QDBusPlatformMenu *menu); - void syncMenuItem(QPlatformMenuItem *menuItem) override; - void syncSeparatorsCollapsible(bool enable) override { Q_UNUSED(enable); } - - const QString text() const { return m_text; } - void setText(const QString &text) override; - QIcon icon() const { return m_icon; } - void setIcon(const QIcon &icon) override; - bool isEnabled() const override { return m_isEnabled; } - void setEnabled(bool enabled) override; - bool isVisible() const { return m_isVisible; } - void setVisible(bool visible) override; - void setMinimumWidth(int width) override { Q_UNUSED(width); } - void setFont(const QFont &font) override { Q_UNUSED(font); } - void setMenuType(MenuType type) override { Q_UNUSED(type); } - void setContainingMenuItem(QDBusPlatformMenuItem *item); - - void showPopup(const QWindow *parentWindow, const QRect &targetRect, const QPlatformMenuItem *item) override; - - void dismiss() override { } // Closes this and all its related menu popups - - QPlatformMenuItem *menuItemAt(int position) const override; - QPlatformMenuItem *menuItemForTag(quintptr tag) const override; - const QList<QDBusPlatformMenuItem *> items() const; - - QPlatformMenuItem *createMenuItem() const override; - QPlatformMenu *createSubMenu() const override; - - uint revision() const { return m_revision; } - - void emitUpdated(); - -signals: - void updated(uint revision, int dbusId); - void propertiesUpdated(QDBusMenuItemList updatedProps, QDBusMenuItemKeysList removedProps); - void popupRequested(int id, uint timestamp); - -private: - QString m_text; - QIcon m_icon; - bool m_isEnabled; - bool m_isVisible; - uint m_revision; - QHash<quintptr, QDBusPlatformMenuItem *> m_itemsByTag; - QList<QDBusPlatformMenuItem *> m_items; - QDBusPlatformMenuItem *m_containingMenuItem; -}; - -QT_END_NAMESPACE - -#endif - diff --git a/src/platformsupport/themes/genericunix/dbustray/dbustray.pri b/src/platformsupport/themes/genericunix/dbustray/dbustray.pri deleted file mode 100644 index f703e24ba9..0000000000 --- a/src/platformsupport/themes/genericunix/dbustray/dbustray.pri +++ /dev/null @@ -1,15 +0,0 @@ -QT_FOR_PRIVATE += dbus - -INCLUDEPATH += $$PWD - -HEADERS += \ - $$PWD/qdbustrayicon_p.h \ - $$PWD/qdbustraytypes_p.h \ - $$PWD/qstatusnotifieritemadaptor_p.h \ - $$PWD/qxdgnotificationproxy_p.h \ - -SOURCES += \ - $$PWD/qdbustrayicon.cpp \ - $$PWD/qdbustraytypes.cpp \ - $$PWD/qstatusnotifieritemadaptor.cpp \ - $$PWD/qxdgnotificationproxy.cpp \ diff --git a/src/platformsupport/themes/genericunix/dbustray/qdbustrayicon.cpp b/src/platformsupport/themes/genericunix/dbustray/qdbustrayicon.cpp deleted file mode 100644 index e81d272d4f..0000000000 --- a/src/platformsupport/themes/genericunix/dbustray/qdbustrayicon.cpp +++ /dev/null @@ -1,353 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qdbustrayicon_p.h" - -#ifndef QT_NO_SYSTEMTRAYICON - -#include "qdbusmenuconnection_p.h" -#include "qstatusnotifieritemadaptor_p.h" -#include "qdbusmenuadaptor_p.h" -#include "qdbusplatformmenu_p.h" -#include "qxdgnotificationproxy_p.h" - -#include <qpa/qplatformmenu.h> -#include <qstring.h> -#include <qdebug.h> -#include <qrect.h> -#include <qloggingcategory.h> -#include <qpa/qplatformintegration.h> -#include <qpa/qplatformservices.h> -#include <qdbusconnectioninterface.h> -#include <private/qlockfile_p.h> -#include <private/qguiapplication_p.h> - -// Defined in Windows headers which get included by qlockfile_p.h -#undef interface - -QT_BEGIN_NAMESPACE - -Q_LOGGING_CATEGORY(qLcTray, "qt.qpa.tray") - -static QString iconTempPath() -{ - QString tempPath = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation); - if (!tempPath.isEmpty()) - return tempPath; - - tempPath = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation); - - if (!tempPath.isEmpty()) { - QDir tempDir(tempPath); - if (tempDir.exists()) - return tempPath; - - if (tempDir.mkpath(QStringLiteral("."))) { - const QFile::Permissions permissions = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner; - if (QFile(tempPath).setPermissions(permissions)) - return tempPath; - } - } - - return QDir::tempPath(); -} - -static const QString KDEItemFormat = QStringLiteral("org.kde.StatusNotifierItem-%1-%2"); -static const QString KDEWatcherService = QStringLiteral("org.kde.StatusNotifierWatcher"); -static const QString XdgNotificationService = QStringLiteral("org.freedesktop.Notifications"); -static const QString XdgNotificationPath = QStringLiteral("/org/freedesktop/Notifications"); -static const QString DefaultAction = QStringLiteral("default"); -static int instanceCount = 0; - -static inline QString tempFileTemplate() -{ - static const QString TempFileTemplate = iconTempPath() + QLatin1String("/qt-trayicon-XXXXXX.png"); - return TempFileTemplate; -} - -/*! - \class QDBusTrayIcon - \internal -*/ - -QDBusTrayIcon::QDBusTrayIcon() - : m_dbusConnection(nullptr) - , m_adaptor(new QStatusNotifierItemAdaptor(this)) - , m_menuAdaptor(nullptr) - , m_menu(nullptr) - , m_notifier(nullptr) - , m_instanceId(KDEItemFormat.arg(QCoreApplication::applicationPid()).arg(++instanceCount)) - , m_category(QStringLiteral("ApplicationStatus")) - , m_defaultStatus(QStringLiteral("Active")) // be visible all the time. QSystemTrayIcon has no API to control this. - , m_status(m_defaultStatus) - , m_tempIcon(nullptr) - , m_tempAttentionIcon(nullptr) - , m_registered(false) -{ - qCDebug(qLcTray); - if (instanceCount == 1) { - QDBusMenuItem::registerDBusTypes(); - qDBusRegisterMetaType<QXdgDBusImageStruct>(); - qDBusRegisterMetaType<QXdgDBusImageVector>(); - qDBusRegisterMetaType<QXdgDBusToolTipStruct>(); - } - connect(this, SIGNAL(statusChanged(QString)), m_adaptor, SIGNAL(NewStatus(QString))); - connect(this, SIGNAL(tooltipChanged()), m_adaptor, SIGNAL(NewToolTip())); - connect(this, SIGNAL(iconChanged()), m_adaptor, SIGNAL(NewIcon())); - connect(this, SIGNAL(attention()), m_adaptor, SIGNAL(NewAttentionIcon())); - connect(this, SIGNAL(menuChanged()), m_adaptor, SIGNAL(NewMenu())); - connect(this, SIGNAL(attention()), m_adaptor, SIGNAL(NewTitle())); - connect(&m_attentionTimer, SIGNAL(timeout()), this, SLOT(attentionTimerExpired())); - m_attentionTimer.setSingleShot(true); -} - -QDBusTrayIcon::~QDBusTrayIcon() -{ -} - -void QDBusTrayIcon::init() -{ - qCDebug(qLcTray) << "registering" << m_instanceId; - m_registered = dBusConnection()->registerTrayIcon(this); - QObject::connect(dBusConnection()->dbusWatcher(), &QDBusServiceWatcher::serviceRegistered, - this, &QDBusTrayIcon::watcherServiceRegistered); -} - -void QDBusTrayIcon::cleanup() -{ - qCDebug(qLcTray) << "unregistering" << m_instanceId; - if (m_registered) - dBusConnection()->unregisterTrayIcon(this); - delete m_dbusConnection; - m_dbusConnection = nullptr; - delete m_notifier; - m_notifier = nullptr; - m_registered = false; -} - -void QDBusTrayIcon::watcherServiceRegistered(const QString &serviceName) -{ - Q_UNUSED(serviceName); - // We have the icon registered, but the watcher has restarted or - // changed, so we need to tell it about our icon again - if (m_registered) - dBusConnection()->registerTrayIconWithWatcher(this); -} - -void QDBusTrayIcon::attentionTimerExpired() -{ - m_messageTitle = QString(); - m_message = QString(); - m_attentionIcon = QIcon(); - emit attention(); - emit tooltipChanged(); - setStatus(m_defaultStatus); -} - -void QDBusTrayIcon::setStatus(const QString &status) -{ - qCDebug(qLcTray) << status; - if (m_status == status) - return; - m_status = status; - emit statusChanged(m_status); -} - -QTemporaryFile *QDBusTrayIcon::tempIcon(const QIcon &icon) -{ - // Hack for indicator-application, which doesn't handle icons sent across D-Bus: - // save the icon to a temp file and set the icon name to that filename. - static bool necessity_checked = false; - static bool necessary = false; - if (!necessity_checked) { - QDBusConnection session = QDBusConnection::sessionBus(); - uint pid = session.interface()->servicePid(KDEWatcherService).value(); - QString processName = QLockFilePrivate::processNameByPid(pid); - necessary = processName.endsWith(QLatin1String("indicator-application-service")); - if (!necessary && QGuiApplication::desktopSettingsAware()) { - // Accessing to process name might be not allowed if the application - // is confined, thus we can just rely on the current desktop in use - const QPlatformServices *services = QGuiApplicationPrivate::platformIntegration()->services(); - necessary = services->desktopEnvironment().split(':').contains("UNITY"); - } - necessity_checked = true; - } - if (!necessary) - return nullptr; - qreal dpr = qGuiApp->devicePixelRatio(); - QTemporaryFile *ret = new QTemporaryFile(tempFileTemplate(), this); - ret->open(); - icon.pixmap(QSize(22 * dpr, 22 * dpr)).save(ret); - ret->close(); - return ret; -} - -QDBusMenuConnection * QDBusTrayIcon::dBusConnection() -{ - if (!m_dbusConnection) { - m_dbusConnection = new QDBusMenuConnection(this, m_instanceId); - m_notifier = new QXdgNotificationInterface(XdgNotificationService, - XdgNotificationPath, m_dbusConnection->connection(), this); - connect(m_notifier, SIGNAL(NotificationClosed(uint,uint)), this, SLOT(notificationClosed(uint,uint))); - connect(m_notifier, SIGNAL(ActionInvoked(uint,QString)), this, SLOT(actionInvoked(uint,QString))); - } - return m_dbusConnection; -} - -void QDBusTrayIcon::updateIcon(const QIcon &icon) -{ - m_iconName = icon.name(); - m_icon = icon; - if (m_iconName.isEmpty()) { - if (m_tempIcon) - delete m_tempIcon; - m_tempIcon = tempIcon(icon); - if (m_tempIcon) - m_iconName = m_tempIcon->fileName(); - } - qCDebug(qLcTray) << m_iconName << icon.availableSizes(); - emit iconChanged(); -} - -void QDBusTrayIcon::updateToolTip(const QString &tooltip) -{ - qCDebug(qLcTray) << tooltip; - m_tooltip = tooltip; - emit tooltipChanged(); -} - -QPlatformMenu *QDBusTrayIcon::createMenu() const -{ - return new QDBusPlatformMenu(); -} - -void QDBusTrayIcon::updateMenu(QPlatformMenu * menu) -{ - qCDebug(qLcTray) << menu; - QDBusPlatformMenu *newMenu = qobject_cast<QDBusPlatformMenu *>(menu); - if (m_menu != newMenu) { - if (m_menu) { - dBusConnection()->unregisterTrayIconMenu(this); - delete m_menuAdaptor; - } - m_menu = newMenu; - m_menuAdaptor = new QDBusMenuAdaptor(m_menu); - // TODO connect(m_menu, , m_menuAdaptor, SIGNAL(ItemActivationRequested(int,uint))); - connect(m_menu, SIGNAL(propertiesUpdated(QDBusMenuItemList,QDBusMenuItemKeysList)), - m_menuAdaptor, SIGNAL(ItemsPropertiesUpdated(QDBusMenuItemList,QDBusMenuItemKeysList))); - connect(m_menu, SIGNAL(updated(uint,int)), - m_menuAdaptor, SIGNAL(LayoutUpdated(uint,int))); - dBusConnection()->registerTrayIconMenu(this); - emit menuChanged(); - } -} - -void QDBusTrayIcon::showMessage(const QString &title, const QString &msg, const QIcon &icon, - QPlatformSystemTrayIcon::MessageIcon iconType, int msecs) -{ - m_messageTitle = title; - m_message = msg; - m_attentionIcon = icon; - QStringList notificationActions; - switch (iconType) { - case Information: - m_attentionIconName = QStringLiteral("dialog-information"); - break; - case Warning: - m_attentionIconName = QStringLiteral("dialog-warning"); - break; - case Critical: - m_attentionIconName = QStringLiteral("dialog-error"); - // If there are actions, the desktop notification may appear as a message dialog - // with button(s), which will interrupt the user and require a response. - // That is an optional feature in implementations of org.freedesktop.Notifications - notificationActions << DefaultAction << tr("OK"); - break; - default: - m_attentionIconName.clear(); - break; - } - if (m_attentionIconName.isEmpty()) { - if (m_tempAttentionIcon) - delete m_tempAttentionIcon; - m_tempAttentionIcon = tempIcon(icon); - if (m_tempAttentionIcon) - m_attentionIconName = m_tempAttentionIcon->fileName(); - } - qCDebug(qLcTray) << title << msg << - QPlatformSystemTrayIcon::metaObject()->enumerator( - QPlatformSystemTrayIcon::staticMetaObject.indexOfEnumerator("MessageIcon")).valueToKey(iconType) - << m_attentionIconName << msecs; - setStatus(QStringLiteral("NeedsAttention")); - m_attentionTimer.start(msecs); - emit tooltipChanged(); - emit attention(); - - // Desktop notification - QVariantMap hints; - // urgency levels according to https://developer.gnome.org/notification-spec/#urgency-levels - // 0 low, 1 normal, 2 critical - int urgency = static_cast<int>(iconType) - 1; - if (urgency < 0) // no icon - urgency = 0; - hints.insert(QLatin1String("urgency"), QVariant(urgency)); - m_notifier->notify(QCoreApplication::applicationName(), 0, - m_attentionIconName, title, msg, notificationActions, hints, msecs); -} - -void QDBusTrayIcon::actionInvoked(uint id, const QString &action) -{ - qCDebug(qLcTray) << id << action; - emit messageClicked(); -} - -void QDBusTrayIcon::notificationClosed(uint id, uint reason) -{ - qCDebug(qLcTray) << id << reason; -} - -bool QDBusTrayIcon::isSystemTrayAvailable() const -{ - QDBusMenuConnection * conn = const_cast<QDBusTrayIcon *>(this)->dBusConnection(); - qCDebug(qLcTray) << conn->isStatusNotifierHostRegistered(); - return conn->isStatusNotifierHostRegistered(); -} - -QT_END_NAMESPACE -#endif //QT_NO_SYSTEMTRAYICON diff --git a/src/platformsupport/themes/genericunix/dbustray/qdbustrayicon_p.h b/src/platformsupport/themes/genericunix/dbustray/qdbustrayicon_p.h deleted file mode 100644 index 7034a7edb4..0000000000 --- a/src/platformsupport/themes/genericunix/dbustray/qdbustrayicon_p.h +++ /dev/null @@ -1,167 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#ifndef QDBUSTRAYICON_H -#define QDBUSTRAYICON_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qtguiglobal_p.h> - -QT_REQUIRE_CONFIG(systemtrayicon); - -#include <QIcon> -#include <QTemporaryFile> -#include <QTimer> -#include "QtGui/qpa/qplatformsystemtrayicon.h" -#include "private/qdbusmenuconnection_p.h" - -QT_BEGIN_NAMESPACE - -class QStatusNotifierItemAdaptor; -class QDBusMenuAdaptor; -class QDBusPlatformMenu; -class QXdgNotificationInterface; - -class QDBusTrayIcon: public QPlatformSystemTrayIcon -{ - Q_OBJECT - Q_PROPERTY(QString category READ category NOTIFY categoryChanged) - Q_PROPERTY(QString status READ status NOTIFY statusChanged) - Q_PROPERTY(QString tooltip READ tooltip NOTIFY tooltipChanged) - Q_PROPERTY(QString iconName READ iconName NOTIFY iconChanged) - Q_PROPERTY(QIcon icon READ icon NOTIFY iconChanged) - Q_PROPERTY(bool isRequestingAttention READ isRequestingAttention NOTIFY attention) - Q_PROPERTY(QString attentionTitle READ attentionTitle NOTIFY attention) - Q_PROPERTY(QString attentionMessage READ attentionMessage NOTIFY attention) - Q_PROPERTY(QString attentionIconName READ attentionIconName NOTIFY attention) - Q_PROPERTY(QIcon attentionIcon READ attentionIcon NOTIFY attention) - Q_PROPERTY(QDBusPlatformMenu *menu READ menu NOTIFY menuChanged) - -public: - QDBusTrayIcon(); - - virtual ~QDBusTrayIcon(); - - QDBusMenuConnection * dBusConnection(); - - void init() override; - void cleanup() override; - void updateIcon(const QIcon &icon) override; - void updateToolTip(const QString &tooltip) override; - void updateMenu(QPlatformMenu *menu) override; - QPlatformMenu *createMenu() const override; - void showMessage(const QString &title, const QString &msg, - const QIcon &icon, MessageIcon iconType, int msecs) override; - - bool isSystemTrayAvailable() const override; - bool supportsMessages() const override { return true; } - QRect geometry() const override { return QRect(); } - - QString category() const { return m_category; } - QString status() const { return m_status; } - QString tooltip() const { return m_tooltip; } - - QString iconName() const { return m_iconName; } - const QIcon & icon() const { return m_icon; } - - bool isRequestingAttention() const { return m_attentionTimer.isActive(); } - QString attentionTitle() const { return m_messageTitle; } - QString attentionMessage() const { return m_message; } - QString attentionIconName() const { return m_attentionIconName; } - const QIcon & attentionIcon() const { return m_attentionIcon; } - - QString instanceId() const { return m_instanceId; } - - QDBusPlatformMenu *menu() { return m_menu; } - -signals: - void categoryChanged(); - void statusChanged(QString arg); - void tooltipChanged(); - void iconChanged(); - void attention(); - void menuChanged(); - -private Q_SLOTS: - void attentionTimerExpired(); - void actionInvoked(uint id, const QString &action); - void notificationClosed(uint id, uint reason); - void watcherServiceRegistered(const QString &serviceName); - -private: - void setStatus(const QString &status); - QTemporaryFile *tempIcon(const QIcon &icon); - -private: - QDBusMenuConnection* m_dbusConnection; - QStatusNotifierItemAdaptor *m_adaptor; - QDBusMenuAdaptor *m_menuAdaptor; - QDBusPlatformMenu *m_menu; - QXdgNotificationInterface *m_notifier; - QString m_instanceId; - QString m_category; - QString m_defaultStatus; - QString m_status; - QString m_tooltip; - QString m_messageTitle; - QString m_message; - QIcon m_icon; - QTemporaryFile *m_tempIcon; - QString m_iconName; - QIcon m_attentionIcon; - QTemporaryFile *m_tempAttentionIcon; - QString m_attentionIconName; - QTimer m_attentionTimer; - bool m_registered; -}; - -QT_END_NAMESPACE - -#endif // QDBUSTRAYICON_H diff --git a/src/platformsupport/themes/genericunix/dbustray/qdbustraytypes.cpp b/src/platformsupport/themes/genericunix/dbustray/qdbustraytypes.cpp deleted file mode 100644 index fc49fcbea9..0000000000 --- a/src/platformsupport/themes/genericunix/dbustray/qdbustraytypes.cpp +++ /dev/null @@ -1,212 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Marco Martin <notmart@gmail.com> -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT_NO_SYSTEMTRAYICON - -#include "qdbustraytypes_p.h" - -#include <QDBusConnection> -#include <QDBusMetaType> -#include <QImage> -#include <QIcon> -#include <QImage> -#include <QPixmap> -#include <QDebug> -#include <QtEndian> -#include <QPainter> -#include <QGuiApplication> -#include <qpa/qplatformmenu.h> -#include "qdbusplatformmenu_p.h" - -QT_BEGIN_NAMESPACE - -static const int IconSizeLimit = 64; -static const int IconNormalSmallSize = 22; -static const int IconNormalMediumSize = 64; - -QXdgDBusImageVector iconToQXdgDBusImageVector(const QIcon &icon) -{ - QXdgDBusImageVector ret; - QList<QSize> sizes = icon.availableSizes(); - - // Omit any size larger than 64 px, to save D-Bus bandwidth; - // ensure that 22px or smaller exists, because it's a common size; - // and ensure that something between 22px and 64px exists, for better scaling to other sizes. - bool hasSmallIcon = false; - bool hasMediumIcon = false; - qreal dpr = qGuiApp->devicePixelRatio(); - QList<QSize> toRemove; - Q_FOREACH (const QSize &size, sizes) { - int maxSize = qMax(size.width(), size.height()); - if (maxSize <= IconNormalSmallSize * dpr) - hasSmallIcon = true; - else if (maxSize <= IconNormalMediumSize * dpr) - hasMediumIcon = true; - else if (maxSize > IconSizeLimit * dpr) - toRemove << size; - } - Q_FOREACH (const QSize &size, toRemove) - sizes.removeOne(size); - if (!hasSmallIcon) - sizes.append(QSize(IconNormalSmallSize * dpr, IconNormalSmallSize * dpr)); - if (!hasMediumIcon) - sizes.append(QSize(IconNormalMediumSize * dpr, IconNormalMediumSize * dpr)); - - ret.reserve(sizes.size()); - foreach (QSize size, sizes) { - // Protocol specifies ARGB32 format in network byte order - QImage im = icon.pixmap(size).toImage().convertToFormat(QImage::Format_ARGB32); - // letterbox if necessary to make it square - if (im.height() != im.width()) { - int maxSize = qMax(im.width(), im.height()); - QImage padded(maxSize, maxSize, QImage::Format_ARGB32); - padded.fill(Qt::transparent); - QPainter painter(&padded); - painter.drawImage((maxSize - im.width()) / 2, (maxSize - im.height()) / 2, im); - im = padded; - } - // copy and endian-convert - QXdgDBusImageStruct kim(im.width(), im.height()); - const uchar *end = im.constBits() + im.sizeInBytes(); - uchar *dest = reinterpret_cast<uchar *>(kim.data.data()); - for (const uchar *src = im.constBits(); src < end; src += 4, dest += 4) - qToUnaligned(qToBigEndian<quint32>(qFromUnaligned<quint32>(src)), dest); - - ret << kim; - } - return ret; -} - -// Marshall the ImageStruct data into a D-Bus argument -const QDBusArgument &operator<<(QDBusArgument &argument, const QXdgDBusImageStruct &icon) -{ - argument.beginStructure(); - argument << icon.width; - argument << icon.height; - argument << icon.data; - argument.endStructure(); - return argument; -} - -// Retrieve the ImageStruct data from the D-Bus argument -const QDBusArgument &operator>>(const QDBusArgument &argument, QXdgDBusImageStruct &icon) -{ - qint32 width; - qint32 height; - QByteArray data; - - argument.beginStructure(); - argument >> width; - argument >> height; - argument >> data; - argument.endStructure(); - - icon.width = width; - icon.height = height; - icon.data = data; - - return argument; -} - -// Marshall the ImageVector data into a D-Bus argument -const QDBusArgument &operator<<(QDBusArgument &argument, const QXdgDBusImageVector &iconVector) -{ - argument.beginArray(qMetaTypeId<QXdgDBusImageStruct>()); - for (int i = 0; i < iconVector.size(); ++i) { - argument << iconVector[i]; - } - argument.endArray(); - return argument; -} - -// Retrieve the ImageVector data from the D-Bus argument -const QDBusArgument &operator>>(const QDBusArgument &argument, QXdgDBusImageVector &iconVector) -{ - argument.beginArray(); - iconVector.clear(); - - while (!argument.atEnd()) { - QXdgDBusImageStruct element; - argument >> element; - iconVector.append(element); - } - - argument.endArray(); - - return argument; -} - -// Marshall the ToolTipStruct data into a D-Bus argument -const QDBusArgument &operator<<(QDBusArgument &argument, const QXdgDBusToolTipStruct &toolTip) -{ - argument.beginStructure(); - argument << toolTip.icon; - argument << toolTip.image; - argument << toolTip.title; - argument << toolTip.subTitle; - argument.endStructure(); - return argument; -} - -// Retrieve the ToolTipStruct data from the D-Bus argument -const QDBusArgument &operator>>(const QDBusArgument &argument, QXdgDBusToolTipStruct &toolTip) -{ - QString icon; - QXdgDBusImageVector image; - QString title; - QString subTitle; - - argument.beginStructure(); - argument >> icon; - argument >> image; - argument >> title; - argument >> subTitle; - argument.endStructure(); - - toolTip.icon = icon; - toolTip.image = image; - toolTip.title = title; - toolTip.subTitle = subTitle; - - return argument; -} - -QT_END_NAMESPACE -#endif // QT_NO_SYSTEMTRAYICON diff --git a/src/platformsupport/themes/genericunix/dbustray/qdbustraytypes_p.h b/src/platformsupport/themes/genericunix/dbustray/qdbustraytypes_p.h deleted file mode 100644 index 3f75555579..0000000000 --- a/src/platformsupport/themes/genericunix/dbustray/qdbustraytypes_p.h +++ /dev/null @@ -1,109 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Marco Martin <notmart@gmail.com> -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QDBUSTRAYTYPES_P_H -#define QDBUSTRAYTYPES_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qtguiglobal_p.h> - -QT_REQUIRE_CONFIG(systemtrayicon); - -#include <QObject> -#include <QString> -#include <QDBusArgument> -#include <QDBusConnection> -#include <QDBusObjectPath> -#include <QPixmap> - -QT_BEGIN_NAMESPACE - -// Custom message type to send icons across D-Bus -struct QXdgDBusImageStruct -{ - QXdgDBusImageStruct() { } - QXdgDBusImageStruct(int w, int h) - : width(w), height(h), data(width * height * 4, 0) { } - int width; - int height; - QByteArray data; -}; -Q_DECLARE_TYPEINFO(QXdgDBusImageStruct, Q_MOVABLE_TYPE); - -typedef QVector<QXdgDBusImageStruct> QXdgDBusImageVector; - -QXdgDBusImageVector iconToQXdgDBusImageVector(const QIcon &icon); - -// Custom message type to send tooltips across D-Bus -struct QXdgDBusToolTipStruct -{ - QString icon; - QXdgDBusImageVector image; - QString title; - QString subTitle; -}; -Q_DECLARE_TYPEINFO(QXdgDBusToolTipStruct, Q_MOVABLE_TYPE); - -const QDBusArgument &operator<<(QDBusArgument &argument, const QXdgDBusImageStruct &icon); -const QDBusArgument &operator>>(const QDBusArgument &argument, QXdgDBusImageStruct &icon); - -const QDBusArgument &operator<<(QDBusArgument &argument, const QXdgDBusImageVector &iconVector); -const QDBusArgument &operator>>(const QDBusArgument &argument, QXdgDBusImageVector &iconVector); - -const QDBusArgument &operator<<(QDBusArgument &argument, const QXdgDBusToolTipStruct &toolTip); -const QDBusArgument &operator>>(const QDBusArgument &argument, QXdgDBusToolTipStruct &toolTip); - -QT_END_NAMESPACE - -Q_DECLARE_METATYPE(QXdgDBusImageStruct) -Q_DECLARE_METATYPE(QXdgDBusImageVector) -Q_DECLARE_METATYPE(QXdgDBusToolTipStruct) - -#endif // QDBUSTRAYTYPES_P_H diff --git a/src/platformsupport/themes/genericunix/dbustray/qstatusnotifieritemadaptor.cpp b/src/platformsupport/themes/genericunix/dbustray/qstatusnotifieritemadaptor.cpp deleted file mode 100644 index d3c5454f01..0000000000 --- a/src/platformsupport/themes/genericunix/dbustray/qstatusnotifieritemadaptor.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/* - This file was originally created by qdbusxml2cpp version 0.8 - Command line was: - qdbusxml2cpp -a statusnotifieritem ../../3rdparty/dbus-ifaces/org.kde.StatusNotifierItem.xml - - However it is maintained manually, because this adapter needs to do - significant interface adaptation, and can do it more efficiently using the - QDBusTrayIcon API directly rather than via QObject::property() and - QMetaObject::invokeMethod(). -*/ - -#include "qstatusnotifieritemadaptor_p.h" - -#ifndef QT_NO_SYSTEMTRAYICON - -#include "qdbustrayicon_p.h" - -QT_BEGIN_NAMESPACE - -Q_DECLARE_LOGGING_CATEGORY(qLcMenu) -Q_DECLARE_LOGGING_CATEGORY(qLcTray) - -QStatusNotifierItemAdaptor::QStatusNotifierItemAdaptor(QDBusTrayIcon *parent) - : QDBusAbstractAdaptor(parent), m_trayIcon(parent) -{ - setAutoRelaySignals(true); -} - -QStatusNotifierItemAdaptor::~QStatusNotifierItemAdaptor() -{ -} - -QString QStatusNotifierItemAdaptor::attentionIconName() const -{ - return m_trayIcon->attentionIconName(); -} - -QXdgDBusImageVector QStatusNotifierItemAdaptor::attentionIconPixmap() const -{ - return iconToQXdgDBusImageVector(m_trayIcon->attentionIcon()); -} - -QString QStatusNotifierItemAdaptor::attentionMovieName() const -{ - return QString(); -} - -QString QStatusNotifierItemAdaptor::category() const -{ - return m_trayIcon->category(); -} - -QString QStatusNotifierItemAdaptor::iconName() const -{ - return m_trayIcon->iconName(); -} - -QXdgDBusImageVector QStatusNotifierItemAdaptor::iconPixmap() const -{ - return iconToQXdgDBusImageVector(m_trayIcon->icon()); -} - -QString QStatusNotifierItemAdaptor::id() const -{ - // from the API docs: "a name that should be unique for this application and - // consistent between sessions, such as the application name itself" - return QCoreApplication::applicationName(); -} - -bool QStatusNotifierItemAdaptor::itemIsMenu() const -{ - // From KDE docs: if this is true, the item only supports the context menu, - // so the visualization should prefer sending ContextMenu() instead of Activate(). - // But QSystemTrayIcon doesn't have such a setting: it will emit activated() - // and the application is free to use it or ignore it; we don't know whether it will. - return false; -} - -QDBusObjectPath QStatusNotifierItemAdaptor::menu() const -{ - return QDBusObjectPath(m_trayIcon->menu() ? "/MenuBar" : "/NO_DBUSMENU"); -} - -QString QStatusNotifierItemAdaptor::overlayIconName() const -{ - return QString(); -} - -QXdgDBusImageVector QStatusNotifierItemAdaptor::overlayIconPixmap() const -{ - QXdgDBusImageVector ret; // empty vector - return ret; -} - -QString QStatusNotifierItemAdaptor::status() const -{ - return m_trayIcon->status(); -} - -QString QStatusNotifierItemAdaptor::title() const -{ - // Shown e.g. when the icon is hidden, in the popup showing all hidden items. - // Since QSystemTrayIcon doesn't have this property, the application name - // is the best information we have available. - return QCoreApplication::applicationName(); -} - -QXdgDBusToolTipStruct QStatusNotifierItemAdaptor::toolTip() const -{ - QXdgDBusToolTipStruct ret; - if (m_trayIcon->isRequestingAttention()) { - ret.title = m_trayIcon->attentionTitle(); - ret.subTitle = m_trayIcon->attentionMessage(); - ret.icon = m_trayIcon->attentionIconName(); - } else { - ret.title = m_trayIcon->tooltip(); - } - return ret; -} - -void QStatusNotifierItemAdaptor::Activate(int x, int y) -{ - qCDebug(qLcTray) << x << y; - emit m_trayIcon->activated(QPlatformSystemTrayIcon::Trigger); -} - -void QStatusNotifierItemAdaptor::ContextMenu(int x, int y) -{ - qCDebug(qLcTray) << x << y; - emit m_trayIcon->activated(QPlatformSystemTrayIcon::Context); -} - -void QStatusNotifierItemAdaptor::Scroll(int w, const QString &s) -{ - qCDebug(qLcTray) << w << s; - // unsupported -} - -void QStatusNotifierItemAdaptor::SecondaryActivate(int x, int y) -{ - qCDebug(qLcTray) << x << y; - emit m_trayIcon->activated(QPlatformSystemTrayIcon::MiddleClick); -} - -QT_END_NAMESPACE - -#endif // QT_NO_SYSTEMTRAYICON diff --git a/src/platformsupport/themes/genericunix/dbustray/qstatusnotifieritemadaptor_p.h b/src/platformsupport/themes/genericunix/dbustray/qstatusnotifieritemadaptor_p.h deleted file mode 100644 index f2bb156b1d..0000000000 --- a/src/platformsupport/themes/genericunix/dbustray/qstatusnotifieritemadaptor_p.h +++ /dev/null @@ -1,206 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/* - This file was originally created by qdbusxml2cpp version 0.8 - Command line was: - qdbusxml2cpp -a statusnotifieritem ../../3rdparty/dbus-ifaces/org.kde.StatusNotifierItem.xml - - However it is maintained manually. - - It is also not part of the public API. This header file may change from - version to version without notice, or even be removed. -*/ - -#ifndef QSTATUSNOTIFIERITEMADAPTER_P_H -#define QSTATUSNOTIFIERITEMADAPTER_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qtguiglobal_p.h> - -QT_REQUIRE_CONFIG(systemtrayicon); - -#include <QtCore/QObject> -#include <QtDBus/QtDBus> - -#include "qdbustraytypes_p.h" - -QT_BEGIN_NAMESPACE -class QDBusTrayIcon; - -/* - Adaptor class for interface org.kde.StatusNotifierItem - see http://www.freedesktop.org/wiki/Specifications/StatusNotifierItem/ - (also http://www.notmart.org/misc/statusnotifieritem/) -*/ -class QStatusNotifierItemAdaptor: public QDBusAbstractAdaptor -{ - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "org.kde.StatusNotifierItem") - Q_CLASSINFO("D-Bus Introspection", "" -" <interface name=\"org.kde.StatusNotifierItem\">\n" -" <property access=\"read\" type=\"s\" name=\"Category\"/>\n" -" <property access=\"read\" type=\"s\" name=\"Id\"/>\n" -" <property access=\"read\" type=\"s\" name=\"Title\"/>\n" -" <property access=\"read\" type=\"s\" name=\"Status\"/>\n" -" <property access=\"read\" type=\"i\" name=\"WindowId\"/>\n" -" <property access=\"read\" type=\"s\" name=\"IconThemePath\"/>\n" -" <property access=\"read\" type=\"o\" name=\"Menu\"/>\n" -" <property access=\"read\" type=\"b\" name=\"ItemIsMenu\"/>\n" -" <property access=\"read\" type=\"s\" name=\"IconName\"/>\n" -" <property access=\"read\" type=\"a(iiay)\" name=\"IconPixmap\">\n" -" <annotation value=\"QXdgDBusImageVector\" name=\"org.qtproject.QtDBus.QtTypeName\"/>\n" -" </property>\n" -" <property access=\"read\" type=\"s\" name=\"OverlayIconName\"/>\n" -" <property access=\"read\" type=\"a(iiay)\" name=\"OverlayIconPixmap\">\n" -" <annotation value=\"QXdgDBusImageVector\" name=\"org.qtproject.QtDBus.QtTypeName\"/>\n" -" </property>\n" -" <property access=\"read\" type=\"s\" name=\"AttentionIconName\"/>\n" -" <property access=\"read\" type=\"a(iiay)\" name=\"AttentionIconPixmap\">\n" -" <annotation value=\"QXdgDBusImageVector\" name=\"org.qtproject.QtDBus.QtTypeName\"/>\n" -" </property>\n" -" <property access=\"read\" type=\"s\" name=\"AttentionMovieName\"/>\n" -" <property access=\"read\" type=\"(sa(iiay)ss)\" name=\"ToolTip\">\n" -" <annotation value=\"QXdgDBusToolTipStruct\" name=\"org.qtproject.QtDBus.QtTypeName\"/>\n" -" </property>\n" -" <method name=\"ContextMenu\">\n" -" <arg direction=\"in\" type=\"i\" name=\"x\"/>\n" -" <arg direction=\"in\" type=\"i\" name=\"y\"/>\n" -" </method>\n" -" <method name=\"Activate\">\n" -" <arg direction=\"in\" type=\"i\" name=\"x\"/>\n" -" <arg direction=\"in\" type=\"i\" name=\"y\"/>\n" -" </method>\n" -" <method name=\"SecondaryActivate\">\n" -" <arg direction=\"in\" type=\"i\" name=\"x\"/>\n" -" <arg direction=\"in\" type=\"i\" name=\"y\"/>\n" -" </method>\n" -" <method name=\"Scroll\">\n" -" <arg direction=\"in\" type=\"i\" name=\"delta\"/>\n" -" <arg direction=\"in\" type=\"s\" name=\"orientation\"/>\n" -" </method>\n" -" <signal name=\"NewTitle\"/>\n" -" <signal name=\"NewIcon\"/>\n" -" <signal name=\"NewAttentionIcon\"/>\n" -" <signal name=\"NewOverlayIcon\"/>\n" -" <signal name=\"NewMenu\"/>\n" -" <signal name=\"NewToolTip\"/>\n" -" <signal name=\"NewStatus\">\n" -" <arg type=\"s\" name=\"status\"/>\n" -" </signal>\n" -" </interface>\n" - "") -public: - QStatusNotifierItemAdaptor(QDBusTrayIcon *parent); - virtual ~QStatusNotifierItemAdaptor(); - -public: // PROPERTIES - Q_PROPERTY(QString AttentionIconName READ attentionIconName) - QString attentionIconName() const; - - Q_PROPERTY(QXdgDBusImageVector AttentionIconPixmap READ attentionIconPixmap) - QXdgDBusImageVector attentionIconPixmap() const; - - Q_PROPERTY(QString AttentionMovieName READ attentionMovieName) - QString attentionMovieName() const; - - Q_PROPERTY(QString Category READ category) - QString category() const; - - Q_PROPERTY(QString IconName READ iconName) - QString iconName() const; - - Q_PROPERTY(QXdgDBusImageVector IconPixmap READ iconPixmap) - QXdgDBusImageVector iconPixmap() const; - - Q_PROPERTY(QString Id READ id) - QString id() const; - - Q_PROPERTY(bool ItemIsMenu READ itemIsMenu) - bool itemIsMenu() const; - - Q_PROPERTY(QDBusObjectPath Menu READ menu) - QDBusObjectPath menu() const; - - Q_PROPERTY(QString OverlayIconName READ overlayIconName) - QString overlayIconName() const; - - Q_PROPERTY(QXdgDBusImageVector OverlayIconPixmap READ overlayIconPixmap) - QXdgDBusImageVector overlayIconPixmap() const; - - Q_PROPERTY(QString Status READ status) - QString status() const; - - Q_PROPERTY(QString Title READ title) - QString title() const; - - Q_PROPERTY(QXdgDBusToolTipStruct ToolTip READ toolTip) - QXdgDBusToolTipStruct toolTip() const; - -public Q_SLOTS: // METHODS - void Activate(int x, int y); - void ContextMenu(int x, int y); - void Scroll(int delta, const QString &orientation); - void SecondaryActivate(int x, int y); -Q_SIGNALS: // SIGNALS - void NewAttentionIcon(); - void NewIcon(); - void NewOverlayIcon(); - void NewMenu(); - void NewStatus(const QString &status); - void NewTitle(); - void NewToolTip(); - -private: - QDBusTrayIcon *m_trayIcon; -}; - -QT_END_NAMESPACE - -#endif // QSTATUSNOTIFIERITEMADAPTER_P_H diff --git a/src/platformsupport/themes/genericunix/dbustray/qxdgnotificationproxy.cpp b/src/platformsupport/themes/genericunix/dbustray/qxdgnotificationproxy.cpp deleted file mode 100644 index ef2aa799c8..0000000000 --- a/src/platformsupport/themes/genericunix/dbustray/qxdgnotificationproxy.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qxdgnotificationproxy_p.h" - -QT_BEGIN_NAMESPACE - -QXdgNotificationInterface::QXdgNotificationInterface(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : QDBusAbstractInterface(service, path, staticInterfaceName(), connection, parent) -{ -} - -QXdgNotificationInterface::~QXdgNotificationInterface() -{ -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/themes/genericunix/dbustray/qxdgnotificationproxy_p.h b/src/platformsupport/themes/genericunix/dbustray/qxdgnotificationproxy_p.h deleted file mode 100644 index 03899723ab..0000000000 --- a/src/platformsupport/themes/genericunix/dbustray/qxdgnotificationproxy_p.h +++ /dev/null @@ -1,152 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/* - This file was originally created by qdbusxml2cpp version 0.8 - Command line was: - qdbusxml2cpp -p qxdgnotificationproxy ../../3rdparty/dbus-ifaces/org.freedesktop.Notifications.xml - - However it is maintained manually. - - It is also not part of the public API. This header file may change from - version to version without notice, or even be removed. -*/ - -#ifndef QXDGNOTIFICATIONPROXY_P_H -#define QXDGNOTIFICATIONPROXY_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/QObject> -#include <QtCore/QByteArray> -#include <QtCore/QList> -#include <QtCore/QMap> -#include <QtCore/QString> -#include <QtCore/QStringList> -#include <QtCore/QVariant> -#include <QtDBus/QtDBus> - -QT_BEGIN_NAMESPACE - -Q_DECLARE_LOGGING_CATEGORY(qLcTray) - -/* - * Proxy class for interface org.freedesktop.Notifications - */ -class QXdgNotificationInterface: public QDBusAbstractInterface -{ - Q_OBJECT -public: - static inline const char *staticInterfaceName() - { return "org.freedesktop.Notifications"; } - -public: - QXdgNotificationInterface(const QString &service, const QString &path, - const QDBusConnection &connection, QObject *parent = 0); - - ~QXdgNotificationInterface(); - -public Q_SLOTS: // METHODS - inline QDBusPendingReply<> closeNotification(uint id) - { - QList<QVariant> argumentList; - argumentList << QVariant::fromValue(id); - return asyncCallWithArgumentList(QStringLiteral("CloseNotification"), argumentList); - } - - inline QDBusPendingReply<QStringList> getCapabilities() - { - QList<QVariant> argumentList; - return asyncCallWithArgumentList(QStringLiteral("GetCapabilities"), argumentList); - } - - inline QDBusPendingReply<QString, QString, QString, QString> getServerInformation() - { - QList<QVariant> argumentList; - return asyncCallWithArgumentList(QStringLiteral("GetServerInformation"), argumentList); - } - inline QDBusReply<QString> getServerInformation(QString &vendor, QString &version, QString &specVersion) - { - QList<QVariant> argumentList; - QDBusMessage reply = callWithArgumentList(QDBus::Block, QStringLiteral("GetServerInformation"), argumentList); - if (reply.type() == QDBusMessage::ReplyMessage && reply.arguments().count() == 4) { - vendor = qdbus_cast<QString>(reply.arguments().at(1)); - version = qdbus_cast<QString>(reply.arguments().at(2)); - specVersion = qdbus_cast<QString>(reply.arguments().at(3)); - } - return reply; - } - - // see https://developer.gnome.org/notification-spec/#basic-design - inline QDBusPendingReply<uint> notify(const QString &appName, uint replacesId, const QString &appIcon, - const QString &summary, const QString &body, const QStringList &actions, - const QVariantMap &hints, int timeout) - { - qCDebug(qLcTray) << appName << replacesId << appIcon << summary << body << actions << hints << timeout; - QList<QVariant> argumentList; - argumentList << QVariant::fromValue(appName) << QVariant::fromValue(replacesId) << - QVariant::fromValue(appIcon) << QVariant::fromValue(summary) << - QVariant::fromValue(body) << QVariant::fromValue(actions) << - QVariant::fromValue(hints) << QVariant::fromValue(timeout); - return asyncCallWithArgumentList(QStringLiteral("Notify"), argumentList); - } - -Q_SIGNALS: - void ActionInvoked(uint id, const QString &action_key); - void NotificationClosed(uint id, uint reason); -}; - -namespace org { - namespace freedesktop { - typedef ::QXdgNotificationInterface Notifications; - } -} - -QT_END_NAMESPACE - -#endif diff --git a/src/platformsupport/themes/genericunix/genericunix.pri b/src/platformsupport/themes/genericunix/genericunix.pri deleted file mode 100644 index 11da533bc4..0000000000 --- a/src/platformsupport/themes/genericunix/genericunix.pri +++ /dev/null @@ -1,10 +0,0 @@ -HEADERS += $$PWD/qgenericunixthemes_p.h -SOURCES += $$PWD/qgenericunixthemes.cpp - -qtConfig(dbus) { - include(dbusmenu/dbusmenu.pri) - - qtConfig(systemtrayicon) { - include(dbustray/dbustray.pri) - } -} diff --git a/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp b/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp deleted file mode 100644 index 6db25a90da..0000000000 --- a/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp +++ /dev/null @@ -1,890 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qgenericunixthemes_p.h" - -#include "qpa/qplatformtheme_p.h" - -#include <QtGui/QPalette> -#include <QtGui/QFont> -#include <QtGui/QGuiApplication> -#include <QtCore/QDir> -#include <QtCore/QFileInfo> -#include <QtCore/QFile> -#include <QtCore/QDebug> -#include <QtCore/QHash> -#if QT_CONFIG(mimetype) -#include <QtCore/QMimeDatabase> -#endif -#include <QtCore/QLoggingCategory> -#if QT_CONFIG(settings) -#include <QtCore/QSettings> -#endif -#include <QtCore/QVariant> -#include <QtCore/QStandardPaths> -#include <QtCore/QStringList> -#include <private/qguiapplication_p.h> -#include <qpa/qplatformintegration.h> -#include <qpa/qplatformservices.h> -#include <qpa/qplatformdialoghelper.h> -#ifndef QT_NO_DBUS -#include "qdbusplatformmenu_p.h" -#include "qdbusmenubar_p.h" -#endif -#if !defined(QT_NO_DBUS) && !defined(QT_NO_SYSTEMTRAYICON) -#include "qdbustrayicon_p.h" -#endif - -#include <algorithm> - -QT_BEGIN_NAMESPACE - -Q_DECLARE_LOGGING_CATEGORY(qLcTray) -Q_LOGGING_CATEGORY(lcQpaFonts, "qt.qpa.fonts") - -ResourceHelper::ResourceHelper() -{ - std::fill(palettes, palettes + QPlatformTheme::NPalettes, static_cast<QPalette *>(0)); - std::fill(fonts, fonts + QPlatformTheme::NFonts, static_cast<QFont *>(0)); -} - -void ResourceHelper::clear() -{ - qDeleteAll(palettes, palettes + QPlatformTheme::NPalettes); - qDeleteAll(fonts, fonts + QPlatformTheme::NFonts); - std::fill(palettes, palettes + QPlatformTheme::NPalettes, static_cast<QPalette *>(0)); - std::fill(fonts, fonts + QPlatformTheme::NFonts, static_cast<QFont *>(0)); -} - -const char *QGenericUnixTheme::name = "generic"; - -// Default system font, corresponding to the value returned by 4.8 for -// XRender/FontConfig which we can now assume as default. -static const char defaultSystemFontNameC[] = "Sans Serif"; -static const char defaultFixedFontNameC[] = "monospace"; -enum { defaultSystemFontSize = 9 }; - -#if !defined(QT_NO_DBUS) && !defined(QT_NO_SYSTEMTRAYICON) -static bool isDBusTrayAvailable() { - static bool dbusTrayAvailable = false; - static bool dbusTrayAvailableKnown = false; - if (!dbusTrayAvailableKnown) { - QDBusMenuConnection conn; - if (conn.isStatusNotifierHostRegistered()) - dbusTrayAvailable = true; - dbusTrayAvailableKnown = true; - qCDebug(qLcTray) << "D-Bus tray available:" << dbusTrayAvailable; - } - return dbusTrayAvailable; -} -#endif - -#ifndef QT_NO_DBUS -static bool checkDBusGlobalMenuAvailable() -{ - const QDBusConnection connection = QDBusConnection::sessionBus(); - static const QString registrarService = QStringLiteral("com.canonical.AppMenu.Registrar"); - if (const auto iface = connection.interface()) - return iface->isServiceRegistered(registrarService); - return false; -} - -static bool isDBusGlobalMenuAvailable() -{ - static bool dbusGlobalMenuAvailable = checkDBusGlobalMenuAvailable(); - return dbusGlobalMenuAvailable; -} -#endif - -class QGenericUnixThemePrivate : public QPlatformThemePrivate -{ -public: - QGenericUnixThemePrivate() - : QPlatformThemePrivate() - , systemFont(QLatin1String(defaultSystemFontNameC), defaultSystemFontSize) - , fixedFont(QLatin1String(defaultFixedFontNameC), systemFont.pointSize()) - { - fixedFont.setStyleHint(QFont::TypeWriter); - qCDebug(lcQpaFonts) << "default fonts: system" << systemFont << "fixed" << fixedFont; - } - - const QFont systemFont; - QFont fixedFont; -}; - -QGenericUnixTheme::QGenericUnixTheme() - : QPlatformTheme(new QGenericUnixThemePrivate()) -{ -} - -const QFont *QGenericUnixTheme::font(Font type) const -{ - Q_D(const QGenericUnixTheme); - switch (type) { - case QPlatformTheme::SystemFont: - return &d->systemFont; - case QPlatformTheme::FixedFont: - return &d->fixedFont; - default: - return 0; - } -} - -// Helper to return the icon theme paths from XDG. -QStringList QGenericUnixTheme::xdgIconThemePaths() -{ - QStringList paths; - // Add home directory first in search path - const QFileInfo homeIconDir(QDir::homePath() + QLatin1String("/.icons")); - if (homeIconDir.isDir()) - paths.prepend(homeIconDir.absoluteFilePath()); - - QString xdgDirString = QFile::decodeName(qgetenv("XDG_DATA_DIRS")); - if (xdgDirString.isEmpty()) - xdgDirString = QLatin1String("/usr/local/share/:/usr/share/"); - const auto xdgDirs = xdgDirString.splitRef(QLatin1Char(':')); - for (const QStringRef &xdgDir : xdgDirs) { - const QFileInfo xdgIconsDir(xdgDir + QLatin1String("/icons")); - if (xdgIconsDir.isDir()) - paths.append(xdgIconsDir.absoluteFilePath()); - } - - return paths; -} - -QStringList QGenericUnixTheme::iconFallbackPaths() -{ - QStringList paths; - const QFileInfo pixmapsIconsDir(QStringLiteral("/usr/share/pixmaps")); - if (pixmapsIconsDir.isDir()) - paths.append(pixmapsIconsDir.absoluteFilePath()); - - return paths; -} - -#ifndef QT_NO_DBUS -QPlatformMenuBar *QGenericUnixTheme::createPlatformMenuBar() const -{ - if (isDBusGlobalMenuAvailable()) - return new QDBusMenuBar(); - return nullptr; -} -#endif - -#if !defined(QT_NO_DBUS) && !defined(QT_NO_SYSTEMTRAYICON) -QPlatformSystemTrayIcon *QGenericUnixTheme::createPlatformSystemTrayIcon() const -{ - if (isDBusTrayAvailable()) - return new QDBusTrayIcon(); - return nullptr; -} -#endif - -QVariant QGenericUnixTheme::themeHint(ThemeHint hint) const -{ - switch (hint) { - case QPlatformTheme::SystemIconFallbackThemeName: - return QVariant(QString(QStringLiteral("hicolor"))); - case QPlatformTheme::IconThemeSearchPaths: - return xdgIconThemePaths(); - case QPlatformTheme::IconFallbackSearchPaths: - return iconFallbackPaths(); - case QPlatformTheme::DialogButtonBoxButtonsHaveIcons: - return QVariant(true); - case QPlatformTheme::StyleNames: { - QStringList styleNames; - styleNames << QStringLiteral("Fusion") << QStringLiteral("Windows"); - return QVariant(styleNames); - } - case QPlatformTheme::KeyboardScheme: - return QVariant(int(X11KeyboardScheme)); - case QPlatformTheme::UiEffects: - return QVariant(int(HoverEffect)); - default: - break; - } - return QPlatformTheme::themeHint(hint); -} - -// Helper functions for implementing QPlatformTheme::fileIcon() for XDG icon themes. -static QList<QSize> availableXdgFileIconSizes() -{ - return QIcon::fromTheme(QStringLiteral("inode-directory")).availableSizes(); -} - -#if QT_CONFIG(mimetype) -static QIcon xdgFileIcon(const QFileInfo &fileInfo) -{ - QMimeDatabase mimeDatabase; - QMimeType mimeType = mimeDatabase.mimeTypeForFile(fileInfo); - if (!mimeType.isValid()) - return QIcon(); - const QString &iconName = mimeType.iconName(); - if (!iconName.isEmpty()) { - const QIcon icon = QIcon::fromTheme(iconName); - if (!icon.isNull()) - return icon; - } - const QString &genericIconName = mimeType.genericIconName(); - return genericIconName.isEmpty() ? QIcon() : QIcon::fromTheme(genericIconName); -} -#endif - -#if QT_CONFIG(settings) -class QKdeThemePrivate : public QPlatformThemePrivate -{ -public: - QKdeThemePrivate(const QStringList &kdeDirs, int kdeVersion) - : kdeDirs(kdeDirs) - , kdeVersion(kdeVersion) - { } - - static QString kdeGlobals(const QString &kdeDir, int kdeVersion) - { - if (kdeVersion > 4) - return kdeDir + QLatin1String("/kdeglobals"); - return kdeDir + QLatin1String("/share/config/kdeglobals"); - } - - void refresh(); - static QVariant readKdeSetting(const QString &key, const QStringList &kdeDirs, int kdeVersion, QHash<QString, QSettings*> &kdeSettings); - static void readKdeSystemPalette(const QStringList &kdeDirs, int kdeVersion, QHash<QString, QSettings*> &kdeSettings, QPalette *pal); - static QFont *kdeFont(const QVariant &fontValue); - static QStringList kdeIconThemeSearchPaths(const QStringList &kdeDirs); - - const QStringList kdeDirs; - const int kdeVersion; - - ResourceHelper resources; - QString iconThemeName; - QString iconFallbackThemeName; - QStringList styleNames; - int toolButtonStyle = Qt::ToolButtonTextBesideIcon; - int toolBarIconSize = 0; - bool singleClick = true; - bool showIconsOnPushButtons = true; - int wheelScrollLines = 3; - int doubleClickInterval = 400; - int startDragDist = 10; - int startDragTime = 500; - int cursorBlinkRate = 1000; -}; - -void QKdeThemePrivate::refresh() -{ - resources.clear(); - - toolButtonStyle = Qt::ToolButtonTextBesideIcon; - toolBarIconSize = 0; - styleNames.clear(); - if (kdeVersion >= 5) - styleNames << QStringLiteral("breeze"); - styleNames << QStringLiteral("Oxygen") << QStringLiteral("fusion") << QStringLiteral("windows"); - if (kdeVersion >= 5) - iconFallbackThemeName = iconThemeName = QStringLiteral("breeze"); - else - iconFallbackThemeName = iconThemeName = QStringLiteral("oxygen"); - - QHash<QString, QSettings*> kdeSettings; - - QPalette systemPalette = QPalette(); - readKdeSystemPalette(kdeDirs, kdeVersion, kdeSettings, &systemPalette); - resources.palettes[QPlatformTheme::SystemPalette] = new QPalette(systemPalette); - //## TODO tooltip color - - const QVariant styleValue = readKdeSetting(QStringLiteral("widgetStyle"), kdeDirs, kdeVersion, kdeSettings); - if (styleValue.isValid()) { - const QString style = styleValue.toString(); - if (style != styleNames.front()) - styleNames.push_front(style); - } - - const QVariant singleClickValue = readKdeSetting(QStringLiteral("KDE/SingleClick"), kdeDirs, kdeVersion, kdeSettings); - if (singleClickValue.isValid()) - singleClick = singleClickValue.toBool(); - - const QVariant showIconsOnPushButtonsValue = readKdeSetting(QStringLiteral("KDE/ShowIconsOnPushButtons"), kdeDirs, kdeVersion, kdeSettings); - if (showIconsOnPushButtonsValue.isValid()) - showIconsOnPushButtons = showIconsOnPushButtonsValue.toBool(); - - const QVariant themeValue = readKdeSetting(QStringLiteral("Icons/Theme"), kdeDirs, kdeVersion, kdeSettings); - if (themeValue.isValid()) - iconThemeName = themeValue.toString(); - - const QVariant toolBarIconSizeValue = readKdeSetting(QStringLiteral("ToolbarIcons/Size"), kdeDirs, kdeVersion, kdeSettings); - if (toolBarIconSizeValue.isValid()) - toolBarIconSize = toolBarIconSizeValue.toInt(); - - const QVariant toolbarStyleValue = readKdeSetting(QStringLiteral("Toolbar style/ToolButtonStyle"), kdeDirs, kdeVersion, kdeSettings); - if (toolbarStyleValue.isValid()) { - const QString toolBarStyle = toolbarStyleValue.toString(); - if (toolBarStyle == QLatin1String("TextBesideIcon")) - toolButtonStyle = Qt::ToolButtonTextBesideIcon; - else if (toolBarStyle == QLatin1String("TextOnly")) - toolButtonStyle = Qt::ToolButtonTextOnly; - else if (toolBarStyle == QLatin1String("TextUnderIcon")) - toolButtonStyle = Qt::ToolButtonTextUnderIcon; - } - - const QVariant wheelScrollLinesValue = readKdeSetting(QStringLiteral("KDE/WheelScrollLines"), kdeDirs, kdeVersion, kdeSettings); - if (wheelScrollLinesValue.isValid()) - wheelScrollLines = wheelScrollLinesValue.toInt(); - - const QVariant doubleClickIntervalValue = readKdeSetting(QStringLiteral("KDE/DoubleClickInterval"), kdeDirs, kdeVersion, kdeSettings); - if (doubleClickIntervalValue.isValid()) - doubleClickInterval = doubleClickIntervalValue.toInt(); - - const QVariant startDragDistValue = readKdeSetting(QStringLiteral("KDE/StartDragDist"), kdeDirs, kdeVersion, kdeSettings); - if (startDragDistValue.isValid()) - startDragDist = startDragDistValue.toInt(); - - const QVariant startDragTimeValue = readKdeSetting(QStringLiteral("KDE/StartDragTime"), kdeDirs, kdeVersion, kdeSettings); - if (startDragTimeValue.isValid()) - startDragTime = startDragTimeValue.toInt(); - - const QVariant cursorBlinkRateValue = readKdeSetting(QStringLiteral("KDE/CursorBlinkRate"), kdeDirs, kdeVersion, kdeSettings); - if (cursorBlinkRateValue.isValid()) { - cursorBlinkRate = cursorBlinkRateValue.toInt(); - cursorBlinkRate = cursorBlinkRate > 0 ? qBound(200, cursorBlinkRate, 2000) : 0; - } - - // Read system font, ignore 'smallestReadableFont' - if (QFont *systemFont = kdeFont(readKdeSetting(QStringLiteral("font"), kdeDirs, kdeVersion, kdeSettings))) - resources.fonts[QPlatformTheme::SystemFont] = systemFont; - else - resources.fonts[QPlatformTheme::SystemFont] = new QFont(QLatin1String(defaultSystemFontNameC), defaultSystemFontSize); - - if (QFont *fixedFont = kdeFont(readKdeSetting(QStringLiteral("fixed"), kdeDirs, kdeVersion, kdeSettings))) { - resources.fonts[QPlatformTheme::FixedFont] = fixedFont; - } else { - fixedFont = new QFont(QLatin1String(defaultFixedFontNameC), defaultSystemFontSize); - fixedFont->setStyleHint(QFont::TypeWriter); - resources.fonts[QPlatformTheme::FixedFont] = fixedFont; - } - - if (QFont *menuFont = kdeFont(readKdeSetting(QStringLiteral("menuFont"), kdeDirs, kdeVersion, kdeSettings))) { - resources.fonts[QPlatformTheme::MenuFont] = menuFont; - resources.fonts[QPlatformTheme::MenuBarFont] = new QFont(*menuFont); - } - - if (QFont *toolBarFont = kdeFont(readKdeSetting(QStringLiteral("toolBarFont"), kdeDirs, kdeVersion, kdeSettings))) - resources.fonts[QPlatformTheme::ToolButtonFont] = toolBarFont; - - qCDebug(lcQpaFonts) << "default fonts: system" << resources.fonts[QPlatformTheme::SystemFont] - << "fixed" << resources.fonts[QPlatformTheme::FixedFont]; - qDeleteAll(kdeSettings); -} - -QVariant QKdeThemePrivate::readKdeSetting(const QString &key, const QStringList &kdeDirs, int kdeVersion, QHash<QString, QSettings*> &kdeSettings) -{ - for (const QString &kdeDir : kdeDirs) { - QSettings *settings = kdeSettings.value(kdeDir); - if (!settings) { - const QString kdeGlobalsPath = kdeGlobals(kdeDir, kdeVersion); - if (QFileInfo(kdeGlobalsPath).isReadable()) { - settings = new QSettings(kdeGlobalsPath, QSettings::IniFormat); - kdeSettings.insert(kdeDir, settings); - } - } - if (settings) { - const QVariant value = settings->value(key); - if (value.isValid()) - return value; - } - } - return QVariant(); -} - -// Reads the color from the KDE configuration, and store it in the -// palette with the given color role if found. -static inline bool kdeColor(QPalette *pal, QPalette::ColorRole role, const QVariant &value) -{ - if (!value.isValid()) - return false; - const QStringList values = value.toStringList(); - if (values.size() != 3) - return false; - pal->setBrush(role, QColor(values.at(0).toInt(), values.at(1).toInt(), values.at(2).toInt())); - return true; -} - -void QKdeThemePrivate::readKdeSystemPalette(const QStringList &kdeDirs, int kdeVersion, QHash<QString, QSettings*> &kdeSettings, QPalette *pal) -{ - if (!kdeColor(pal, QPalette::Button, readKdeSetting(QStringLiteral("Colors:Button/BackgroundNormal"), kdeDirs, kdeVersion, kdeSettings))) { - // kcolorscheme.cpp: SetDefaultColors - const QColor defaultWindowBackground(214, 210, 208); - const QColor defaultButtonBackground(223, 220, 217); - *pal = QPalette(defaultButtonBackground, defaultWindowBackground); - return; - } - - kdeColor(pal, QPalette::Window, readKdeSetting(QStringLiteral("Colors:Window/BackgroundNormal"), kdeDirs, kdeVersion, kdeSettings)); - kdeColor(pal, QPalette::Text, readKdeSetting(QStringLiteral("Colors:View/ForegroundNormal"), kdeDirs, kdeVersion, kdeSettings)); - kdeColor(pal, QPalette::WindowText, readKdeSetting(QStringLiteral("Colors:Window/ForegroundNormal"), kdeDirs, kdeVersion, kdeSettings)); - kdeColor(pal, QPalette::Base, readKdeSetting(QStringLiteral("Colors:View/BackgroundNormal"), kdeDirs, kdeVersion, kdeSettings)); - kdeColor(pal, QPalette::Highlight, readKdeSetting(QStringLiteral("Colors:Selection/BackgroundNormal"), kdeDirs, kdeVersion, kdeSettings)); - kdeColor(pal, QPalette::HighlightedText, readKdeSetting(QStringLiteral("Colors:Selection/ForegroundNormal"), kdeDirs, kdeVersion, kdeSettings)); - kdeColor(pal, QPalette::AlternateBase, readKdeSetting(QStringLiteral("Colors:View/BackgroundAlternate"), kdeDirs, kdeVersion, kdeSettings)); - kdeColor(pal, QPalette::ButtonText, readKdeSetting(QStringLiteral("Colors:Button/ForegroundNormal"), kdeDirs, kdeVersion, kdeSettings)); - kdeColor(pal, QPalette::Link, readKdeSetting(QStringLiteral("Colors:View/ForegroundLink"), kdeDirs, kdeVersion, kdeSettings)); - kdeColor(pal, QPalette::LinkVisited, readKdeSetting(QStringLiteral("Colors:View/ForegroundVisited"), kdeDirs, kdeVersion, kdeSettings)); - kdeColor(pal, QPalette::ToolTipBase, readKdeSetting(QStringLiteral("Colors:Tooltip/BackgroundNormal"), kdeDirs, kdeVersion, kdeSettings)); - kdeColor(pal, QPalette::ToolTipText, readKdeSetting(QStringLiteral("Colors:Tooltip/ForegroundNormal"), kdeDirs, kdeVersion, kdeSettings)); - - // The above code sets _all_ color roles to "normal" colors. In KDE, the disabled - // color roles are calculated by applying various effects described in kdeglobals. - // We use a bit simpler approach here, similar logic than in qt_palette_from_color(). - const QColor button = pal->color(QPalette::Button); - int h, s, v; - button.getHsv(&h, &s, &v); - - const QBrush whiteBrush = QBrush(Qt::white); - const QBrush buttonBrush = QBrush(button); - const QBrush buttonBrushDark = QBrush(button.darker(v > 128 ? 200 : 50)); - const QBrush buttonBrushDark150 = QBrush(button.darker(v > 128 ? 150 : 75)); - const QBrush buttonBrushLight150 = QBrush(button.lighter(v > 128 ? 150 : 75)); - const QBrush buttonBrushLight = QBrush(button.lighter(v > 128 ? 200 : 50)); - - pal->setBrush(QPalette::Disabled, QPalette::WindowText, buttonBrushDark); - pal->setBrush(QPalette::Disabled, QPalette::ButtonText, buttonBrushDark); - pal->setBrush(QPalette::Disabled, QPalette::Button, buttonBrush); - pal->setBrush(QPalette::Disabled, QPalette::Text, buttonBrushDark); - pal->setBrush(QPalette::Disabled, QPalette::BrightText, whiteBrush); - pal->setBrush(QPalette::Disabled, QPalette::Base, buttonBrush); - pal->setBrush(QPalette::Disabled, QPalette::Window, buttonBrush); - pal->setBrush(QPalette::Disabled, QPalette::Highlight, buttonBrushDark150); - pal->setBrush(QPalette::Disabled, QPalette::HighlightedText, buttonBrushLight150); - - // set calculated colors for all groups - pal->setBrush(QPalette::Light, buttonBrushLight); - pal->setBrush(QPalette::Midlight, buttonBrushLight150); - pal->setBrush(QPalette::Mid, buttonBrushDark150); - pal->setBrush(QPalette::Dark, buttonBrushDark); -} - -/*! - \class QKdeTheme - \brief QKdeTheme is a theme implementation for the KDE desktop (version 4 or higher). - \since 5.0 - \internal - \ingroup qpa -*/ - -const char *QKdeTheme::name = "kde"; - -QKdeTheme::QKdeTheme(const QStringList& kdeDirs, int kdeVersion) - : QPlatformTheme(new QKdeThemePrivate(kdeDirs,kdeVersion)) -{ - d_func()->refresh(); -} - -QFont *QKdeThemePrivate::kdeFont(const QVariant &fontValue) -{ - if (fontValue.isValid()) { - // Read font value: Might be a QStringList as KDE stores fonts without quotes. - // Also retrieve the family for the constructor since we cannot use the - // default constructor of QFont, which accesses QGuiApplication::systemFont() - // causing recursion. - QString fontDescription; - QString fontFamily; - if (fontValue.type() == QVariant::StringList) { - const QStringList list = fontValue.toStringList(); - if (!list.isEmpty()) { - fontFamily = list.first(); - fontDescription = list.join(QLatin1Char(',')); - } - } else { - fontDescription = fontFamily = fontValue.toString(); - } - if (!fontDescription.isEmpty()) { - QFont font(fontFamily); - if (font.fromString(fontDescription)) - return new QFont(font); - } - } - return 0; -} - - -QStringList QKdeThemePrivate::kdeIconThemeSearchPaths(const QStringList &kdeDirs) -{ - QStringList paths = QGenericUnixTheme::xdgIconThemePaths(); - const QString iconPath = QStringLiteral("/share/icons"); - for (const QString &candidate : kdeDirs) { - const QFileInfo fi(candidate + iconPath); - if (fi.isDir()) - paths.append(fi.absoluteFilePath()); - } - return paths; -} - -QVariant QKdeTheme::themeHint(QPlatformTheme::ThemeHint hint) const -{ - Q_D(const QKdeTheme); - switch (hint) { - case QPlatformTheme::UseFullScreenForPopupMenu: - return QVariant(true); - case QPlatformTheme::DialogButtonBoxButtonsHaveIcons: - return QVariant(d->showIconsOnPushButtons); - case QPlatformTheme::DialogButtonBoxLayout: - return QVariant(QPlatformDialogHelper::KdeLayout); - case QPlatformTheme::ToolButtonStyle: - return QVariant(d->toolButtonStyle); - case QPlatformTheme::ToolBarIconSize: - return QVariant(d->toolBarIconSize); - case QPlatformTheme::SystemIconThemeName: - return QVariant(d->iconThemeName); - case QPlatformTheme::SystemIconFallbackThemeName: - return QVariant(d->iconFallbackThemeName); - case QPlatformTheme::IconThemeSearchPaths: - return QVariant(d->kdeIconThemeSearchPaths(d->kdeDirs)); - case QPlatformTheme::IconPixmapSizes: - return QVariant::fromValue(availableXdgFileIconSizes()); - case QPlatformTheme::StyleNames: - return QVariant(d->styleNames); - case QPlatformTheme::KeyboardScheme: - return QVariant(int(KdeKeyboardScheme)); - case QPlatformTheme::ItemViewActivateItemOnSingleClick: - return QVariant(d->singleClick); - case QPlatformTheme::WheelScrollLines: - return QVariant(d->wheelScrollLines); - case QPlatformTheme::MouseDoubleClickInterval: - return QVariant(d->doubleClickInterval); - case QPlatformTheme::StartDragTime: - return QVariant(d->startDragTime); - case QPlatformTheme::StartDragDistance: - return QVariant(d->startDragDist); - case QPlatformTheme::CursorFlashTime: - return QVariant(d->cursorBlinkRate); - case QPlatformTheme::UiEffects: - return QVariant(int(HoverEffect)); - default: - break; - } - return QPlatformTheme::themeHint(hint); -} - -QIcon QKdeTheme::fileIcon(const QFileInfo &fileInfo, QPlatformTheme::IconOptions) const -{ -#if QT_CONFIG(mimetype) - return xdgFileIcon(fileInfo); -#else - Q_UNUSED(fileInfo); - return QIcon(); -#endif -} - -const QPalette *QKdeTheme::palette(Palette type) const -{ - Q_D(const QKdeTheme); - return d->resources.palettes[type]; -} - -const QFont *QKdeTheme::font(Font type) const -{ - Q_D(const QKdeTheme); - return d->resources.fonts[type]; -} - -QPlatformTheme *QKdeTheme::createKdeTheme() -{ - const QByteArray kdeVersionBA = qgetenv("KDE_SESSION_VERSION"); - const int kdeVersion = kdeVersionBA.toInt(); - if (kdeVersion < 4) - return 0; - - if (kdeVersion > 4) - // Plasma 5 follows XDG spec - // but uses the same config file format: - return new QKdeTheme(QStandardPaths::standardLocations(QStandardPaths::GenericConfigLocation), kdeVersion); - - // Determine KDE prefixes in the following priority order: - // - KDEHOME and KDEDIRS environment variables - // - ~/.kde(<version>) - // - read prefixes from /etc/kde<version>rc - // - fallback to /etc/kde<version> - - QStringList kdeDirs; - const QString kdeHomePathVar = QFile::decodeName(qgetenv("KDEHOME")); - if (!kdeHomePathVar.isEmpty()) - kdeDirs += kdeHomePathVar; - - const QString kdeDirsVar = QFile::decodeName(qgetenv("KDEDIRS")); - if (!kdeDirsVar.isEmpty()) - kdeDirs += kdeDirsVar.split(QLatin1Char(':'), QString::SkipEmptyParts); - - const QString kdeVersionHomePath = QDir::homePath() + QLatin1String("/.kde") + QLatin1String(kdeVersionBA); - if (QFileInfo(kdeVersionHomePath).isDir()) - kdeDirs += kdeVersionHomePath; - - const QString kdeHomePath = QDir::homePath() + QLatin1String("/.kde"); - if (QFileInfo(kdeHomePath).isDir()) - kdeDirs += kdeHomePath; - - const QString kdeRcPath = QLatin1String("/etc/kde") + QLatin1String(kdeVersionBA) + QLatin1String("rc"); - if (QFileInfo(kdeRcPath).isReadable()) { - QSettings kdeSettings(kdeRcPath, QSettings::IniFormat); - kdeSettings.beginGroup(QStringLiteral("Directories-default")); - kdeDirs += kdeSettings.value(QStringLiteral("prefixes")).toStringList(); - } - - const QString kdeVersionPrefix = QLatin1String("/etc/kde") + QLatin1String(kdeVersionBA); - if (QFileInfo(kdeVersionPrefix).isDir()) - kdeDirs += kdeVersionPrefix; - - kdeDirs.removeDuplicates(); - if (kdeDirs.isEmpty()) { - qWarning("Unable to determine KDE dirs"); - return 0; - } - - return new QKdeTheme(kdeDirs, kdeVersion); -} - -#ifndef QT_NO_DBUS -QPlatformMenuBar *QKdeTheme::createPlatformMenuBar() const -{ - if (isDBusGlobalMenuAvailable()) - return new QDBusMenuBar(); - return nullptr; -} -#endif - -#if !defined(QT_NO_DBUS) && !defined(QT_NO_SYSTEMTRAYICON) -QPlatformSystemTrayIcon *QKdeTheme::createPlatformSystemTrayIcon() const -{ - if (isDBusTrayAvailable()) - return new QDBusTrayIcon(); - return nullptr; -} -#endif - -#endif // settings - -/*! - \class QGnomeTheme - \brief QGnomeTheme is a theme implementation for the Gnome desktop. - \since 5.0 - \internal - \ingroup qpa -*/ - -const char *QGnomeTheme::name = "gnome"; - -class QGnomeThemePrivate : public QPlatformThemePrivate -{ -public: - QGnomeThemePrivate() : systemFont(nullptr), fixedFont(nullptr) {} - ~QGnomeThemePrivate() { delete systemFont; delete fixedFont; } - - void configureFonts(const QString >kFontName) const - { - Q_ASSERT(!systemFont); - const int split = gtkFontName.lastIndexOf(QChar::Space); - float size = gtkFontName.midRef(split + 1).toFloat(); - QString fontName = gtkFontName.left(split); - - systemFont = new QFont(fontName, size); - fixedFont = new QFont(QLatin1String(defaultFixedFontNameC), systemFont->pointSize()); - fixedFont->setStyleHint(QFont::TypeWriter); - qCDebug(lcQpaFonts) << "default fonts: system" << systemFont << "fixed" << fixedFont; - } - - mutable QFont *systemFont; - mutable QFont *fixedFont; -}; - -QGnomeTheme::QGnomeTheme() - : QPlatformTheme(new QGnomeThemePrivate()) -{ -} - -QVariant QGnomeTheme::themeHint(QPlatformTheme::ThemeHint hint) const -{ - switch (hint) { - case QPlatformTheme::DialogButtonBoxButtonsHaveIcons: - return QVariant(true); - case QPlatformTheme::DialogButtonBoxLayout: - return QVariant(QPlatformDialogHelper::GnomeLayout); - case QPlatformTheme::SystemIconThemeName: - return QVariant(QStringLiteral("Adwaita")); - case QPlatformTheme::SystemIconFallbackThemeName: - return QVariant(QStringLiteral("gnome")); - case QPlatformTheme::IconThemeSearchPaths: - return QVariant(QGenericUnixTheme::xdgIconThemePaths()); - case QPlatformTheme::IconPixmapSizes: - return QVariant::fromValue(availableXdgFileIconSizes()); - case QPlatformTheme::StyleNames: { - QStringList styleNames; - styleNames << QStringLiteral("fusion") << QStringLiteral("windows"); - return QVariant(styleNames); - } - case QPlatformTheme::KeyboardScheme: - return QVariant(int(GnomeKeyboardScheme)); - case QPlatformTheme::PasswordMaskCharacter: - return QVariant(QChar(0x2022)); - case QPlatformTheme::UiEffects: - return QVariant(int(HoverEffect)); - default: - break; - } - return QPlatformTheme::themeHint(hint); -} - -QIcon QGnomeTheme::fileIcon(const QFileInfo &fileInfo, QPlatformTheme::IconOptions) const -{ -#if QT_CONFIG(mimetype) - return xdgFileIcon(fileInfo); -#else - Q_UNUSED(fileInfo); - return QIcon(); -#endif -} - -const QFont *QGnomeTheme::font(Font type) const -{ - Q_D(const QGnomeTheme); - if (!d->systemFont) - d->configureFonts(gtkFontName()); - switch (type) { - case QPlatformTheme::SystemFont: - return d->systemFont; - case QPlatformTheme::FixedFont: - return d->fixedFont; - default: - return 0; - } -} - -QString QGnomeTheme::gtkFontName() const -{ - return QStringLiteral("%1 %2").arg(QLatin1String(defaultSystemFontNameC)).arg(defaultSystemFontSize); -} - -#ifndef QT_NO_DBUS -QPlatformMenuBar *QGnomeTheme::createPlatformMenuBar() const -{ - if (isDBusGlobalMenuAvailable()) - return new QDBusMenuBar(); - return nullptr; -} -#endif - -#if !defined(QT_NO_DBUS) && !defined(QT_NO_SYSTEMTRAYICON) -QPlatformSystemTrayIcon *QGnomeTheme::createPlatformSystemTrayIcon() const -{ - if (isDBusTrayAvailable()) - return new QDBusTrayIcon(); - return nullptr; -} -#endif - -QString QGnomeTheme::standardButtonText(int button) const -{ - switch (button) { - case QPlatformDialogHelper::Ok: - return QCoreApplication::translate("QGnomeTheme", "&OK"); - case QPlatformDialogHelper::Save: - return QCoreApplication::translate("QGnomeTheme", "&Save"); - case QPlatformDialogHelper::Cancel: - return QCoreApplication::translate("QGnomeTheme", "&Cancel"); - case QPlatformDialogHelper::Close: - return QCoreApplication::translate("QGnomeTheme", "&Close"); - case QPlatformDialogHelper::Discard: - return QCoreApplication::translate("QGnomeTheme", "Close without Saving"); - default: - break; - } - return QPlatformTheme::standardButtonText(button); -} - -/*! - \brief Creates a UNIX theme according to the detected desktop environment. -*/ - -QPlatformTheme *QGenericUnixTheme::createUnixTheme(const QString &name) -{ - if (name == QLatin1String(QGenericUnixTheme::name)) - return new QGenericUnixTheme; -#if QT_CONFIG(settings) - if (name == QLatin1String(QKdeTheme::name)) - if (QPlatformTheme *kdeTheme = QKdeTheme::createKdeTheme()) - return kdeTheme; -#endif - if (name == QLatin1String(QGnomeTheme::name)) - return new QGnomeTheme; - return nullptr; -} - -QStringList QGenericUnixTheme::themeNames() -{ - QStringList result; - if (QGuiApplication::desktopSettingsAware()) { - const QByteArray desktopEnvironment = QGuiApplicationPrivate::platformIntegration()->services()->desktopEnvironment(); - QList<QByteArray> gtkBasedEnvironments; - gtkBasedEnvironments << "GNOME" - << "X-CINNAMON" - << "UNITY" - << "MATE" - << "XFCE" - << "LXDE"; - const QList<QByteArray> desktopNames = desktopEnvironment.split(':'); - for (const QByteArray &desktopName : desktopNames) { - if (desktopEnvironment == "KDE") { -#if QT_CONFIG(settings) - result.push_back(QLatin1String(QKdeTheme::name)); -#endif - } else if (gtkBasedEnvironments.contains(desktopName)) { - // prefer the GTK3 theme implementation with native dialogs etc. - result.push_back(QStringLiteral("gtk3")); - // fallback to the generic Gnome theme if loading the GTK3 theme fails - result.push_back(QLatin1String(QGnomeTheme::name)); - } else { - // unknown, but lowercase the name (our standard practice) and - // remove any "x-" prefix - QString s = QString::fromLatin1(desktopName.toLower()); - result.push_back(s.startsWith(QLatin1String("x-")) ? s.mid(2) : s); - } - } - } // desktopSettingsAware - result.append(QLatin1String(QGenericUnixTheme::name)); - return result; -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/themes/genericunix/qgenericunixthemes_p.h b/src/platformsupport/themes/genericunix/qgenericunixthemes_p.h deleted file mode 100644 index a5963b79ea..0000000000 --- a/src/platformsupport/themes/genericunix/qgenericunixthemes_p.h +++ /dev/null @@ -1,156 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QGENERICUNIXTHEMES_H -#define QGENERICUNIXTHEMES_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <qpa/qplatformtheme.h> -#include <QtCore/QString> -#include <QtCore/QStringList> -#include <QtGui/QFont> - -QT_BEGIN_NAMESPACE - -class ResourceHelper -{ -public: - ResourceHelper(); - ~ResourceHelper() { clear(); } - - void clear(); - - QPalette *palettes[QPlatformTheme::NPalettes]; - QFont *fonts[QPlatformTheme::NFonts]; -}; - -class QGenericUnixThemePrivate; - -class QGenericUnixTheme : public QPlatformTheme -{ - Q_DECLARE_PRIVATE(QGenericUnixTheme) -public: - QGenericUnixTheme(); - - static QPlatformTheme *createUnixTheme(const QString &name); - static QStringList themeNames(); - - const QFont *font(Font type) const override; - QVariant themeHint(ThemeHint hint) const override; - - static QStringList xdgIconThemePaths(); - static QStringList iconFallbackPaths(); -#ifndef QT_NO_DBUS - QPlatformMenuBar *createPlatformMenuBar() const override; -#endif -#if !defined(QT_NO_DBUS) && !defined(QT_NO_SYSTEMTRAYICON) - QPlatformSystemTrayIcon *createPlatformSystemTrayIcon() const override; -#endif - - static const char *name; -}; - -#if QT_CONFIG(settings) -class QKdeThemePrivate; - -class QKdeTheme : public QPlatformTheme -{ - Q_DECLARE_PRIVATE(QKdeTheme) -public: - QKdeTheme(const QStringList& kdeDirs, int kdeVersion); - - static QPlatformTheme *createKdeTheme(); - QVariant themeHint(ThemeHint hint) const override; - - QIcon fileIcon(const QFileInfo &fileInfo, - QPlatformTheme::IconOptions iconOptions = 0) const override; - - const QPalette *palette(Palette type = SystemPalette) const override; - - const QFont *font(Font type) const override; -#ifndef QT_NO_DBUS - QPlatformMenuBar *createPlatformMenuBar() const override; -#endif -#if !defined(QT_NO_DBUS) && !defined(QT_NO_SYSTEMTRAYICON) - QPlatformSystemTrayIcon *createPlatformSystemTrayIcon() const override; -#endif - - static const char *name; -}; -#endif // settings - -class QGnomeThemePrivate; - -class QGnomeTheme : public QPlatformTheme -{ - Q_DECLARE_PRIVATE(QGnomeTheme) -public: - QGnomeTheme(); - QVariant themeHint(ThemeHint hint) const override; - QIcon fileIcon(const QFileInfo &fileInfo, - QPlatformTheme::IconOptions = 0) const override; - const QFont *font(Font type) const override; - QString standardButtonText(int button) const override; - - virtual QString gtkFontName() const; -#ifndef QT_NO_DBUS - QPlatformMenuBar *createPlatformMenuBar() const override; -#endif -#if !defined(QT_NO_DBUS) && !defined(QT_NO_SYSTEMTRAYICON) - QPlatformSystemTrayIcon *createPlatformSystemTrayIcon() const override; -#endif - - static const char *name; -}; - -QPlatformTheme *qt_createUnixTheme(); - -QT_END_NAMESPACE - -#endif // QGENERICUNIXTHEMES_H diff --git a/src/platformsupport/themes/qabstractfileiconengine.cpp b/src/platformsupport/themes/qabstractfileiconengine.cpp deleted file mode 100644 index 192ed00510..0000000000 --- a/src/platformsupport/themes/qabstractfileiconengine.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qabstractfileiconengine_p.h" - -#include <qpixmapcache.h> - -QT_BEGIN_NAMESPACE - -/*! - \class QAbstractFileIconEngine - \brief Helper base class for retrieving icons for files for usage by QFileIconProvider and related. - - Reimplement availableSizes() and new virtual filePixmap() and return icons created - with this engine from QPlatformTheme::fileIcon(). - - Note: The class internally caches pixmaps for files by suffix (with the exception - of some files on Windows), but not for directories (since directory icons may have - overlay icons on Windows). You might want to cache pixmaps for directories - in your implementation. - - \since 5.8 - \internal - \sa QFileIconProvider::DontUseCustomDirectoryIcons, QPlatformTheme - \ingroup qpa -*/ -QPixmap QAbstractFileIconEngine::pixmap(const QSize &size, QIcon::Mode mode, - QIcon::State state) -{ - Q_UNUSED(mode); - Q_UNUSED(state); - - if (!size.isValid()) - return QPixmap(); - - QString key = cacheKey(); - if (key.isEmpty()) - return filePixmap(size, mode, state); - - key += QLatin1Char('_') + QString::number(size.width()); - - QPixmap result; - if (!QPixmapCache::find(key, result)) { - result = filePixmap(size, mode, state); - if (!result.isNull()) - QPixmapCache::insert(key, result); - } - - return result; -} - -QSize QAbstractFileIconEngine::actualSize(const QSize &size, QIcon::Mode mode, - QIcon::State state) -{ - const QList<QSize> &sizes = availableSizes(mode, state); - const int numberSizes = sizes.length(); - if (numberSizes == 0) - return QSize(); - - // Find the smallest available size whose area is still larger than the input - // size. Otherwise, use the largest area available size. (We don't assume the - // platform theme sizes are sorted, hence the extra logic.) - const int sizeArea = size.width() * size.height(); - QSize actualSize = sizes.first(); - int actualArea = actualSize.width() * actualSize.height(); - for (int i = 1; i < numberSizes; ++i) { - const QSize &s = sizes.at(i); - const int a = s.width() * s.height(); - if ((sizeArea <= a && a < actualArea) || (actualArea < sizeArea && actualArea < a)) { - actualSize = s; - actualArea = a; - } - } - - if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height())) - actualSize.scale(size, Qt::KeepAspectRatio); - - return actualSize; -} - -/* Reimplement to return a cache key for the entry. An empty result indicates - * the icon should not be cached (for example, directory icons having custom icons). */ -QString QAbstractFileIconEngine::cacheKey() const -{ - if (!m_fileInfo.isFile() || m_fileInfo.isSymLink() || m_fileInfo.isExecutable()) - return QString(); - - const QString &suffix = m_fileInfo.suffix(); - return QLatin1String("qt_.") - + (suffix.isEmpty() ? m_fileInfo.fileName() : suffix); // handle "Makefile" ;) -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/themes/qabstractfileiconengine_p.h b/src/platformsupport/themes/qabstractfileiconengine_p.h deleted file mode 100644 index ce38cf262e..0000000000 --- a/src/platformsupport/themes/qabstractfileiconengine_p.h +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QABSTRACTFILEICONENGINE_P_H -#define QABSTRACTFILEICONENGINE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/qfileinfo.h> -#include <private/qicon_p.h> -#include <qpa/qplatformtheme.h> - -QT_BEGIN_NAMESPACE - -class QAbstractFileIconEngine : public QPixmapIconEngine -{ -public: - explicit QAbstractFileIconEngine(const QFileInfo &info, QPlatformTheme::IconOptions opts) - : QPixmapIconEngine(), m_fileInfo(info), m_options(opts) {} - - QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State) override; - QSize actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state) override; - - QFileInfo fileInfo() const { return m_fileInfo; } - QPlatformTheme::IconOptions options() const { return m_options; } - - // Helper to convert a sequence of ints to a list of QSize - template <class It> static QList<QSize> toSizeList(It i1, It i2); - -protected: - virtual QPixmap filePixmap(const QSize &size, QIcon::Mode mode, QIcon::State) = 0; - virtual QString cacheKey() const; - -private: - const QFileInfo m_fileInfo; - const QPlatformTheme::IconOptions m_options; -}; - -template <class It> -inline QList<QSize> QAbstractFileIconEngine::toSizeList(It i1, It i2) -{ - QList<QSize> result; - result.reserve(int(i2 - i1)); - for ( ; i1 != i2; ++i1) - result.append(QSize(*i1, *i1)); - return result; -} - -QT_END_NAMESPACE - -#endif // QABSTRACTFILEICONENGINE_P_H diff --git a/src/platformsupport/themes/themes.pro b/src/platformsupport/themes/themes.pro deleted file mode 100644 index 668a843473..0000000000 --- a/src/platformsupport/themes/themes.pro +++ /dev/null @@ -1,18 +0,0 @@ -TARGET = QtThemeSupport -MODULE = theme_support - -QT = core-private gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII - -if(unix:!uikit)|qtConfig(xcb): \ - include($$PWD/genericunix/genericunix.pri) - -HEADERS += \ - qabstractfileiconengine_p.h - -SOURCES += \ - qabstractfileiconengine.cpp - -load(qt_module) diff --git a/src/platformsupport/vkconvenience/qbasicvulkanplatforminstance.cpp b/src/platformsupport/vkconvenience/qbasicvulkanplatforminstance.cpp deleted file mode 100644 index b9c5669b3f..0000000000 --- a/src/platformsupport/vkconvenience/qbasicvulkanplatforminstance.cpp +++ /dev/null @@ -1,383 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qbasicvulkanplatforminstance_p.h" -#include <QLibrary> -#include <QCoreApplication> -#include <QVector> -#include <QLoggingCategory> - -QT_BEGIN_NAMESPACE - -Q_LOGGING_CATEGORY(lcPlatVk, "qt.vulkan") - -/*! - \class QBasicPlatformVulkanInstance - \brief A generic platform Vulkan instance implementation. - \since 5.10 - \internal - \ingroup qpa - - Implements QPlatformVulkanInstance, serving as a base for platform-specific - implementations. The library loading and any WSI-specifics are excluded. - - Subclasses are expected to call init() from their constructor and - initInstance() from their createOrAdoptInstance() implementation. - */ - -QBasicPlatformVulkanInstance::QBasicPlatformVulkanInstance() - : m_vkInst(VK_NULL_HANDLE), - m_vkGetInstanceProcAddr(nullptr), - m_ownsVkInst(false), - m_errorCode(VK_SUCCESS), - m_debugCallback(0) -{ -} - -QBasicPlatformVulkanInstance::~QBasicPlatformVulkanInstance() -{ - if (!m_vkInst) - return; - - if (m_debugCallback && m_vkDestroyDebugReportCallbackEXT) - m_vkDestroyDebugReportCallbackEXT(m_vkInst, m_debugCallback, nullptr); - - if (m_ownsVkInst) - m_vkDestroyInstance(m_vkInst, nullptr); -} - -void QBasicPlatformVulkanInstance::loadVulkanLibrary(const QString &defaultLibraryName) -{ - if (qEnvironmentVariableIsSet("QT_VULKAN_LIB")) - m_vulkanLib.setFileName(QString::fromUtf8(qgetenv("QT_VULKAN_LIB"))); - else - m_vulkanLib.setFileName(defaultLibraryName); - - if (!m_vulkanLib.load()) { - qWarning("Failed to load %s: %s", qPrintable(m_vulkanLib.fileName()), qPrintable(m_vulkanLib.errorString())); - return; - } - - init(&m_vulkanLib); -} - -void QBasicPlatformVulkanInstance::init(QLibrary *lib) -{ - if (m_vkGetInstanceProcAddr) - return; - - qCDebug(lcPlatVk, "Vulkan init (%s)", qPrintable(lib->fileName())); - - // While not strictly required with every implementation, try to follow the spec - // and do not rely on core functions being exported. - // - // 1. dlsym vkGetInstanceProcAddr - // 2. with a special null instance resolve vkCreateInstance and vkEnumerateInstance* - // 3. all other core functions are resolved with the created instance - - m_vkGetInstanceProcAddr = reinterpret_cast<PFN_vkGetInstanceProcAddr>(lib->resolve("vkGetInstanceProcAddr")); - if (!m_vkGetInstanceProcAddr) { - qWarning("Failed to find vkGetInstanceProcAddr"); - return; - } - - m_vkCreateInstance = reinterpret_cast<PFN_vkCreateInstance>(m_vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkCreateInstance")); - if (!m_vkCreateInstance) { - qWarning("Failed to find vkCreateInstance"); - return; - } - m_vkEnumerateInstanceLayerProperties = reinterpret_cast<PFN_vkEnumerateInstanceLayerProperties>( - m_vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkEnumerateInstanceLayerProperties")); - if (!m_vkEnumerateInstanceLayerProperties) { - qWarning("Failed to find vkEnumerateInstanceLayerProperties"); - return; - } - m_vkEnumerateInstanceExtensionProperties = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>( - m_vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties")); - if (!m_vkEnumerateInstanceExtensionProperties) { - qWarning("Failed to find vkEnumerateInstanceExtensionProperties"); - return; - } - - uint32_t layerCount = 0; - m_vkEnumerateInstanceLayerProperties(&layerCount, nullptr); - if (layerCount) { - QVector<VkLayerProperties> layerProps(layerCount); - m_vkEnumerateInstanceLayerProperties(&layerCount, layerProps.data()); - m_supportedLayers.reserve(layerCount); - for (const VkLayerProperties &p : qAsConst(layerProps)) { - QVulkanLayer layer; - layer.name = p.layerName; - layer.version = p.implementationVersion; - layer.specVersion = QVersionNumber(VK_VERSION_MAJOR(p.specVersion), - VK_VERSION_MINOR(p.specVersion), - VK_VERSION_PATCH(p.specVersion)); - layer.description = p.description; - m_supportedLayers.append(layer); - } - } - qCDebug(lcPlatVk) << "Supported Vulkan instance layers:" << m_supportedLayers; - - uint32_t extCount = 0; - m_vkEnumerateInstanceExtensionProperties(nullptr, &extCount, nullptr); - if (extCount) { - QVector<VkExtensionProperties> extProps(extCount); - m_vkEnumerateInstanceExtensionProperties(nullptr, &extCount, extProps.data()); - m_supportedExtensions.reserve(extCount); - for (const VkExtensionProperties &p : qAsConst(extProps)) { - QVulkanExtension ext; - ext.name = p.extensionName; - ext.version = p.specVersion; - m_supportedExtensions.append(ext); - } - } - qDebug(lcPlatVk) << "Supported Vulkan instance extensions:" << m_supportedExtensions; -} - -QVulkanInfoVector<QVulkanLayer> QBasicPlatformVulkanInstance::supportedLayers() const -{ - return m_supportedLayers; -} - -QVulkanInfoVector<QVulkanExtension> QBasicPlatformVulkanInstance::supportedExtensions() const -{ - return m_supportedExtensions; -} - -void QBasicPlatformVulkanInstance::initInstance(QVulkanInstance *instance, const QByteArrayList &extraExts) -{ - if (!m_vkGetInstanceProcAddr) { - qWarning("initInstance: No Vulkan library available"); - return; - } - - m_vkInst = instance->vkInstance(); // when non-null we are adopting an existing instance - - QVulkanInstance::Flags flags = instance->flags(); - m_enabledLayers = instance->layers(); - m_enabledExtensions = instance->extensions(); - - if (!m_vkInst) { - VkApplicationInfo appInfo; - memset(&appInfo, 0, sizeof(appInfo)); - appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; - QByteArray appName = QCoreApplication::applicationName().toUtf8(); - appInfo.pApplicationName = appName.constData(); - const QVersionNumber apiVersion = instance->apiVersion(); - if (!apiVersion.isNull()) { - appInfo.apiVersion = VK_MAKE_VERSION(apiVersion.majorVersion(), - apiVersion.minorVersion(), - apiVersion.microVersion()); - } - - if (!flags.testFlag(QVulkanInstance::NoDebugOutputRedirect)) - m_enabledExtensions.append("VK_EXT_debug_report"); - - m_enabledExtensions.append("VK_KHR_surface"); - - for (const QByteArray &ext : extraExts) - m_enabledExtensions.append(ext); - - // No clever stuff with QSet and friends: the order for layers matters - // and the user-provided order must be kept. - for (int i = 0; i < m_enabledLayers.count(); ++i) { - const QByteArray &layerName(m_enabledLayers[i]); - if (!m_supportedLayers.contains(layerName)) - m_enabledLayers.removeAt(i--); - } - qDebug(lcPlatVk) << "Enabling Vulkan instance layers:" << m_enabledLayers; - for (int i = 0; i < m_enabledExtensions.count(); ++i) { - const QByteArray &extName(m_enabledExtensions[i]); - if (!m_supportedExtensions.contains(extName)) - m_enabledExtensions.removeAt(i--); - } - qDebug(lcPlatVk) << "Enabling Vulkan instance extensions:" << m_enabledExtensions; - - VkInstanceCreateInfo instInfo; - memset(&instInfo, 0, sizeof(instInfo)); - instInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; - instInfo.pApplicationInfo = &appInfo; - - QVector<const char *> layerNameVec; - for (const QByteArray &ba : qAsConst(m_enabledLayers)) - layerNameVec.append(ba.constData()); - if (!layerNameVec.isEmpty()) { - instInfo.enabledLayerCount = layerNameVec.count(); - instInfo.ppEnabledLayerNames = layerNameVec.constData(); - } - - QVector<const char *> extNameVec; - for (const QByteArray &ba : qAsConst(m_enabledExtensions)) - extNameVec.append(ba.constData()); - if (!extNameVec.isEmpty()) { - instInfo.enabledExtensionCount = extNameVec.count(); - instInfo.ppEnabledExtensionNames = extNameVec.constData(); - } - - m_errorCode = m_vkCreateInstance(&instInfo, nullptr, &m_vkInst); - if (m_errorCode != VK_SUCCESS || !m_vkInst) { - qWarning("Failed to create Vulkan instance: %d", m_errorCode); - return; - } - - m_vkDestroyInstance = reinterpret_cast<PFN_vkDestroyInstance>(m_vkGetInstanceProcAddr(m_vkInst, "vkDestroyInstance")); - if (!m_vkDestroyInstance) { - qWarning("Failed to find vkDestroyInstance"); - m_vkInst = VK_NULL_HANDLE; - return; - } - - m_ownsVkInst = true; - } - - m_getPhysDevSurfaceSupport = reinterpret_cast<PFN_vkGetPhysicalDeviceSurfaceSupportKHR>( - m_vkGetInstanceProcAddr(m_vkInst, "vkGetPhysicalDeviceSurfaceSupportKHR")); - if (!m_getPhysDevSurfaceSupport) - qWarning("Failed to find vkGetPhysicalDeviceSurfaceSupportKHR"); - - m_destroySurface = reinterpret_cast<PFN_vkDestroySurfaceKHR>( - m_vkGetInstanceProcAddr(m_vkInst, "vkDestroySurfaceKHR")); - if (!m_destroySurface) - qWarning("Failed to find vkDestroySurfaceKHR"); - - if (!flags.testFlag(QVulkanInstance::NoDebugOutputRedirect)) - setupDebugOutput(); -} - -bool QBasicPlatformVulkanInstance::isValid() const -{ - return m_vkInst != VK_NULL_HANDLE; -} - -VkResult QBasicPlatformVulkanInstance::errorCode() const -{ - return m_errorCode; -} - -VkInstance QBasicPlatformVulkanInstance::vkInstance() const -{ - return m_vkInst; -} - -QByteArrayList QBasicPlatformVulkanInstance::enabledLayers() const -{ - return m_enabledLayers; -} - -QByteArrayList QBasicPlatformVulkanInstance::enabledExtensions() const -{ - return m_enabledExtensions; -} - -PFN_vkVoidFunction QBasicPlatformVulkanInstance::getInstanceProcAddr(const char *name) -{ - if (!name) - return nullptr; - - const bool needsNullInstance = !strcmp(name, "vkEnumerateInstanceLayerProperties") - || !strcmp(name, "vkEnumerateInstanceExtensionProperties"); - - return m_vkGetInstanceProcAddr(needsNullInstance ? 0 : m_vkInst, name); -} - -bool QBasicPlatformVulkanInstance::supportsPresent(VkPhysicalDevice physicalDevice, - uint32_t queueFamilyIndex, - QWindow *window) -{ - if (!m_getPhysDevSurfaceSupport) - return true; - - VkSurfaceKHR surface = QVulkanInstance::surfaceForWindow(window); - VkBool32 supported = false; - m_getPhysDevSurfaceSupport(physicalDevice, queueFamilyIndex, surface, &supported); - - return supported; -} - -void QBasicPlatformVulkanInstance::destroySurface(VkSurfaceKHR surface) const -{ - if (m_destroySurface && surface) - m_destroySurface(m_vkInst, surface, nullptr); -} - -static VKAPI_ATTR VkBool32 VKAPI_CALL defaultDebugCallbackFunc(VkDebugReportFlagsEXT flags, - VkDebugReportObjectTypeEXT objectType, - uint64_t object, - size_t location, - int32_t messageCode, - const char *pLayerPrefix, - const char *pMessage, - void *pUserData) -{ - Q_UNUSED(flags); - Q_UNUSED(objectType); - Q_UNUSED(object); - Q_UNUSED(location); - Q_UNUSED(pUserData); - - // not categorized, just route to plain old qDebug - qDebug("vkDebug: %s: %d: %s", pLayerPrefix, messageCode, pMessage); - - return VK_FALSE; -} - -void QBasicPlatformVulkanInstance::setupDebugOutput() -{ - if (!m_enabledExtensions.contains("VK_EXT_debug_report")) - return; - - PFN_vkCreateDebugReportCallbackEXT createDebugReportCallback = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>( - m_vkGetInstanceProcAddr(m_vkInst, "vkCreateDebugReportCallbackEXT")); - m_vkDestroyDebugReportCallbackEXT = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>( - m_vkGetInstanceProcAddr(m_vkInst, "vkDestroyDebugReportCallbackEXT")); - - VkDebugReportCallbackCreateInfoEXT dbgCallbackInfo; - memset(&dbgCallbackInfo, 0, sizeof(dbgCallbackInfo)); - dbgCallbackInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; - dbgCallbackInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT - | VK_DEBUG_REPORT_WARNING_BIT_EXT - | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; - dbgCallbackInfo.pfnCallback = defaultDebugCallbackFunc; - - VkResult err = createDebugReportCallback(m_vkInst, &dbgCallbackInfo, nullptr, &m_debugCallback); - if (err != VK_SUCCESS) - qWarning("Failed to create debug report callback: %d", err); -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/vkconvenience/qbasicvulkanplatforminstance_p.h b/src/platformsupport/vkconvenience/qbasicvulkanplatforminstance_p.h deleted file mode 100644 index 566140b032..0000000000 --- a/src/platformsupport/vkconvenience/qbasicvulkanplatforminstance_p.h +++ /dev/null @@ -1,112 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QBASICVULKANPLATFORMINSTANCE_P_H -#define QBASICVULKANPLATFORMINSTANCE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/QLibrary> -#include <qpa/qplatformvulkaninstance.h> - -QT_BEGIN_NAMESPACE - -class QLibrary; - -class QBasicPlatformVulkanInstance : public QPlatformVulkanInstance -{ -public: - QBasicPlatformVulkanInstance(); - ~QBasicPlatformVulkanInstance(); - - QVulkanInfoVector<QVulkanLayer> supportedLayers() const override; - QVulkanInfoVector<QVulkanExtension> supportedExtensions() const override; - bool isValid() const override; - VkResult errorCode() const override; - VkInstance vkInstance() const override; - QByteArrayList enabledLayers() const override; - QByteArrayList enabledExtensions() const override; - PFN_vkVoidFunction getInstanceProcAddr(const char *name) override; - bool supportsPresent(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, QWindow *window) override; - void destroySurface(VkSurfaceKHR surface) const; - -protected: - void loadVulkanLibrary(const QString &defaultLibraryName); - void init(QLibrary *lib); - void initInstance(QVulkanInstance *instance, const QByteArrayList &extraExts); - - VkInstance m_vkInst; - PFN_vkGetInstanceProcAddr m_vkGetInstanceProcAddr; - PFN_vkGetPhysicalDeviceSurfaceSupportKHR m_getPhysDevSurfaceSupport; - PFN_vkDestroySurfaceKHR m_destroySurface; - -private: - void setupDebugOutput(); - - QLibrary m_vulkanLib; - - bool m_ownsVkInst; - VkResult m_errorCode; - QVulkanInfoVector<QVulkanLayer> m_supportedLayers; - QVulkanInfoVector<QVulkanExtension> m_supportedExtensions; - QByteArrayList m_enabledLayers; - QByteArrayList m_enabledExtensions; - - PFN_vkCreateInstance m_vkCreateInstance; - PFN_vkEnumerateInstanceLayerProperties m_vkEnumerateInstanceLayerProperties; - PFN_vkEnumerateInstanceExtensionProperties m_vkEnumerateInstanceExtensionProperties; - - PFN_vkDestroyInstance m_vkDestroyInstance; - - VkDebugReportCallbackEXT m_debugCallback; - PFN_vkDestroyDebugReportCallbackEXT m_vkDestroyDebugReportCallbackEXT; -}; - -QT_END_NAMESPACE - -#endif // QBASICVULKANPLATFORMINSTANCE_P_H diff --git a/src/platformsupport/vkconvenience/qvkconvenience.cpp b/src/platformsupport/vkconvenience/qvkconvenience.cpp deleted file mode 100644 index 462cdc9e0d..0000000000 --- a/src/platformsupport/vkconvenience/qvkconvenience.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qvkconvenience_p.h" - -#include <QOpenGLTexture> - -QT_BEGIN_NAMESPACE - -/*! - \class QVkConvenience - \brief A collection of static helper functions for Vulkan support - \since 5.14 - \internal - \ingroup qpa - */ - -VkFormat QVkConvenience::vkFormatFromGlFormat(uint glFormat) -{ - using GlFormat = QOpenGLTexture::TextureFormat; - switch (glFormat) { - case GlFormat::NoFormat: return VK_FORMAT_UNDEFINED; // GL_NONE - - // Unsigned normalized formats - case GlFormat::R8_UNorm: return VK_FORMAT_R8_UNORM; // GL_R8 - case GlFormat::RG8_UNorm: return VK_FORMAT_R8G8_UNORM; // GL_RG8 - case GlFormat::RGB8_UNorm: return VK_FORMAT_R8G8B8_UNORM; // GL_RGB8 - case GlFormat::RGBA8_UNorm: return VK_FORMAT_R8G8B8A8_UNORM; // GL_RGBA8 - - case GlFormat::R16_UNorm: return VK_FORMAT_R16_UNORM; // GL_R16 - case GlFormat::RG16_UNorm: return VK_FORMAT_R16G16_UNORM; // GL_RG16 - case GlFormat::RGB16_UNorm: return VK_FORMAT_R16G16B16_UNORM; // GL_RGB16 - case GlFormat::RGBA16_UNorm: return VK_FORMAT_R16G16B16A16_UNORM; // GL_RGBA16 - - // Signed normalized formats - case GlFormat::R8_SNorm: return VK_FORMAT_R8_SNORM; // GL_R8_SNORM - case GlFormat::RG8_SNorm: return VK_FORMAT_R8G8_SNORM; // GL_RG8_SNORM - case GlFormat::RGB8_SNorm: return VK_FORMAT_R8G8B8_SNORM; // GL_RGB8_SNORM - case GlFormat::RGBA8_SNorm: return VK_FORMAT_R8G8B8A8_SNORM; // GL_RGBA8_SNORM - - case GlFormat::R16_SNorm: return VK_FORMAT_R16_SNORM; // GL_R16_SNORM - case GlFormat::RG16_SNorm: return VK_FORMAT_R16G16_SNORM; // GL_RG16_SNORM - case GlFormat::RGB16_SNorm: return VK_FORMAT_R16G16B16_SNORM; // GL_RGB16_SNORM - case GlFormat::RGBA16_SNorm: return VK_FORMAT_R16G16B16A16_SNORM; // GL_RGBA16_SNORM - - // Unsigned integer formats - case GlFormat::R8U: return VK_FORMAT_R8_UINT; // GL_R8UI - case GlFormat::RG8U: return VK_FORMAT_R8G8_UINT; // GL_RG8UI - case GlFormat::RGB8U: return VK_FORMAT_R8G8B8_UINT; // GL_RGB8UI - case GlFormat::RGBA8U: return VK_FORMAT_R8G8B8A8_UINT; // GL_RGBA8UI - - case GlFormat::R16U: return VK_FORMAT_R16_UINT; // GL_R16UI - case GlFormat::RG16U: return VK_FORMAT_R16G16_UINT; // GL_RG16UI - case GlFormat::RGB16U: return VK_FORMAT_R16G16B16_UINT; // GL_RGB16UI - case GlFormat::RGBA16U: return VK_FORMAT_R16G16B16A16_UINT; // GL_RGBA16UI - - case GlFormat::R32U: return VK_FORMAT_R32_UINT; // GL_R32UI - case GlFormat::RG32U: return VK_FORMAT_R32G32_UINT; // GL_RG32UI - case GlFormat::RGB32U: return VK_FORMAT_R32G32B32_UINT; // GL_RGB32UI - case GlFormat::RGBA32U: return VK_FORMAT_R32G32B32A32_UINT; // GL_RGBA32UI - - // Signed integer formats - case GlFormat::R8I: return VK_FORMAT_R8_SINT; // GL_R8I - case GlFormat::RG8I: return VK_FORMAT_R8G8_SINT; // GL_RG8I - case GlFormat::RGB8I: return VK_FORMAT_R8G8B8_SINT; // GL_RGB8I - case GlFormat::RGBA8I: return VK_FORMAT_R8G8B8A8_SINT; // GL_RGBA8I - - case GlFormat::R16I: return VK_FORMAT_R16_SINT; // GL_R16I - case GlFormat::RG16I: return VK_FORMAT_R16G16_SINT; // GL_RG16I - case GlFormat::RGB16I: return VK_FORMAT_R16G16B16_SINT; // GL_RGB16I - case GlFormat::RGBA16I: return VK_FORMAT_R16G16B16A16_SINT; // GL_RGBA16I - - case GlFormat::R32I: return VK_FORMAT_R32_SINT; // GL_R32I - case GlFormat::RG32I: return VK_FORMAT_R32G32_SINT; // GL_RG32I - case GlFormat::RGB32I: return VK_FORMAT_R32G32B32_SINT; // GL_RGB32I - case GlFormat::RGBA32I: return VK_FORMAT_R32G32B32A32_SINT; // GL_RGBA32I - - // Floating point formats - case GlFormat::R16F: return VK_FORMAT_R16_SFLOAT; // GL_R16F - case GlFormat::RG16F: return VK_FORMAT_R16G16_SFLOAT; // GL_RG16F - case GlFormat::RGB16F: return VK_FORMAT_R16G16B16_SFLOAT; // GL_RGB16F - case GlFormat::RGBA16F: return VK_FORMAT_R16G16B16A16_SFLOAT; // GL_RGBA16F - - case GlFormat::R32F: return VK_FORMAT_R32_SFLOAT; // GL_R32F - case GlFormat::RG32F: return VK_FORMAT_R32G32_SFLOAT; // GL_RG32F - case GlFormat::RGB32F: return VK_FORMAT_R32G32B32_SFLOAT; // GL_RGB32F - case GlFormat::RGBA32F: return VK_FORMAT_R32G32B32A32_SFLOAT; // GL_RGBA32F - - // Packed formats - case GlFormat::RGB9E5: return VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; // GL_RGB9_E5 - case GlFormat::RG11B10F: return VK_FORMAT_B10G11R11_UFLOAT_PACK32; // GL_R11F_G11F_B10F -// case GlFormat::RG3B2: return VK_FORMAT_R3_G3_B2; // GL_R3_G3_B2 - case GlFormat::R5G6B5: return VK_FORMAT_R5G6B5_UNORM_PACK16; // GL_RGB565 - case GlFormat::RGB5A1: return VK_FORMAT_R5G5B5A1_UNORM_PACK16; // GL_RGB5_A1 - case GlFormat::RGBA4: return VK_FORMAT_R4G4B4A4_UNORM_PACK16; // GL_RGBA4 - case GlFormat::RGB10A2: return VK_FORMAT_A2R10G10B10_UINT_PACK32; // GL_RGB10_A2UI - - // Depth formats -// case Format::D16: return VK_FORMAT_DEPTH_COMPONENT16; // GL_DEPTH_COMPONENT16 -// case Format::D24: return VK_FORMAT_DEPTH_COMPONENT24; // GL_DEPTH_COMPONENT24 -// case Format::D24S8: return VK_FORMAT_DEPTH24_STENCIL8; // GL_DEPTH24_STENCIL8 -// case Format::D32: return VK_FORMAT_DEPTH_COMPONENT32; // GL_DEPTH_COMPONENT32 -// case Format::D32F: return VK_FORMAT_DEPTH_COMPONENT32F; // GL_DEPTH_COMPONENT32F -// case Format::D32FS8X24: return VK_FORMAT_DEPTH32F_STENCIL8; // GL_DEPTH32F_STENCIL8 -// case Format::S8: return VK_FORMAT_STENCIL_INDEX8; // GL_STENCIL_INDEX8 - - // Compressed formats - case GlFormat::RGB_DXT1: return VK_FORMAT_BC1_RGB_UNORM_BLOCK; // GL_COMPRESSED_RGB_S3TC_DXT1_EXT - case GlFormat::RGBA_DXT1: return VK_FORMAT_BC1_RGBA_UNORM_BLOCK; // GL_COMPRESSED_RGBA_S3TC_DXT1_EXT - case GlFormat::RGBA_DXT3: return VK_FORMAT_BC2_UNORM_BLOCK; // GL_COMPRESSED_RGBA_S3TC_DXT3_EXT - case GlFormat::RGBA_DXT5: return VK_FORMAT_BC3_UNORM_BLOCK; // GL_COMPRESSED_RGBA_S3TC_DXT5_EXT - case GlFormat::R_ATI1N_UNorm: return VK_FORMAT_BC4_UNORM_BLOCK; // GL_COMPRESSED_RED_RGTC1 - case GlFormat::R_ATI1N_SNorm: return VK_FORMAT_BC4_SNORM_BLOCK; // GL_COMPRESSED_SIGNED_RED_RGTC1 - case GlFormat::RG_ATI2N_UNorm: return VK_FORMAT_BC5_UNORM_BLOCK; // GL_COMPRESSED_RG_RGTC2 - case GlFormat::RG_ATI2N_SNorm: return VK_FORMAT_BC5_SNORM_BLOCK; // GL_COMPRESSED_SIGNED_RG_RGTC2 - case GlFormat::RGB_BP_UNSIGNED_FLOAT: return VK_FORMAT_BC6H_UFLOAT_BLOCK; // GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB - case GlFormat::RGB_BP_SIGNED_FLOAT: return VK_FORMAT_BC6H_SFLOAT_BLOCK; // GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB - case GlFormat::RGB_BP_UNorm: return VK_FORMAT_BC7_UNORM_BLOCK; // GL_COMPRESSED_RGBA_BPTC_UNORM_ARB - case GlFormat::R11_EAC_UNorm: return VK_FORMAT_EAC_R11_UNORM_BLOCK; // GL_COMPRESSED_R11_EAC - case GlFormat::R11_EAC_SNorm: return VK_FORMAT_EAC_R11_SNORM_BLOCK; // GL_COMPRESSED_SIGNED_R11_EAC - case GlFormat::RG11_EAC_UNorm: return VK_FORMAT_EAC_R11G11_UNORM_BLOCK; // GL_COMPRESSED_RG11_EAC - case GlFormat::RG11_EAC_SNorm: return VK_FORMAT_EAC_R11G11_SNORM_BLOCK; // GL_COMPRESSED_SIGNED_RG11_EAC - case GlFormat::RGB8_ETC2: return VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK; // GL_COMPRESSED_RGB8_ETC2 - case GlFormat::SRGB8_ETC2: return VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ETC2 - case GlFormat::RGB8_PunchThrough_Alpha1_ETC2: return VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK; // GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 - case GlFormat::SRGB8_PunchThrough_Alpha1_ETC2: return VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 - case GlFormat::RGBA8_ETC2_EAC: return VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK; // GL_COMPRESSED_RGBA8_ETC2_EAC - case GlFormat::SRGB8_Alpha8_ETC2_EAC: return VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC -// case GlFormat::RGB8_ETC1: return VK_FORMAT_ETC1_RGB8_OES; // GL_ETC1_RGB8_OES - case GlFormat::RGBA_ASTC_4x4: return VK_FORMAT_ASTC_4x4_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_4x4_KHR - case GlFormat::RGBA_ASTC_5x4: return VK_FORMAT_ASTC_5x4_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_5x4_KHR - case GlFormat::RGBA_ASTC_5x5: return VK_FORMAT_ASTC_5x5_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_5x5_KHR - case GlFormat::RGBA_ASTC_6x5: return VK_FORMAT_ASTC_6x5_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_6x5_KHR - case GlFormat::RGBA_ASTC_6x6: return VK_FORMAT_ASTC_6x6_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_6x6_KHR - case GlFormat::RGBA_ASTC_8x5: return VK_FORMAT_ASTC_8x5_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_8x5_KHR - case GlFormat::RGBA_ASTC_8x6: return VK_FORMAT_ASTC_8x6_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_8x6_KHR - case GlFormat::RGBA_ASTC_8x8: return VK_FORMAT_ASTC_8x8_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_8x8_KHR - case GlFormat::RGBA_ASTC_10x5: return VK_FORMAT_ASTC_10x5_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_10x5_KHR - case GlFormat::RGBA_ASTC_10x6: return VK_FORMAT_ASTC_10x6_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_10x6_KHR - case GlFormat::RGBA_ASTC_10x8: return VK_FORMAT_ASTC_10x8_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_10x8_KHR - case GlFormat::RGBA_ASTC_10x10: return VK_FORMAT_ASTC_10x10_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_10x10_KHR - case GlFormat::RGBA_ASTC_12x10: return VK_FORMAT_ASTC_12x10_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_12x10_KHR - case GlFormat::RGBA_ASTC_12x12: return VK_FORMAT_ASTC_12x12_UNORM_BLOCK; // GL_COMPRESSED_RGBA_ASTC_12x12_KHR - case GlFormat::SRGB8_Alpha8_ASTC_4x4: return VK_FORMAT_ASTC_4x4_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR - case GlFormat::SRGB8_Alpha8_ASTC_5x4: return VK_FORMAT_ASTC_5x4_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR - case GlFormat::SRGB8_Alpha8_ASTC_5x5: return VK_FORMAT_ASTC_5x5_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR - case GlFormat::SRGB8_Alpha8_ASTC_6x5: return VK_FORMAT_ASTC_6x5_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR - case GlFormat::SRGB8_Alpha8_ASTC_6x6: return VK_FORMAT_ASTC_6x6_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR - case GlFormat::SRGB8_Alpha8_ASTC_8x5: return VK_FORMAT_ASTC_8x5_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR - case GlFormat::SRGB8_Alpha8_ASTC_8x6: return VK_FORMAT_ASTC_8x6_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR - case GlFormat::SRGB8_Alpha8_ASTC_8x8: return VK_FORMAT_ASTC_8x8_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR - case GlFormat::SRGB8_Alpha8_ASTC_10x5: return VK_FORMAT_ASTC_10x5_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR - case GlFormat::SRGB8_Alpha8_ASTC_10x6: return VK_FORMAT_ASTC_10x6_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR - case GlFormat::SRGB8_Alpha8_ASTC_10x8: return VK_FORMAT_ASTC_10x8_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR - case GlFormat::SRGB8_Alpha8_ASTC_10x10: return VK_FORMAT_ASTC_10x10_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR - case GlFormat::SRGB8_Alpha8_ASTC_12x10: return VK_FORMAT_ASTC_12x10_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR - case GlFormat::SRGB8_Alpha8_ASTC_12x12: return VK_FORMAT_ASTC_12x12_SRGB_BLOCK; // GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR - - // sRGB formats - case GlFormat::SRGB8: return VK_FORMAT_R8G8B8_SRGB; // GL_SRGB8 - case GlFormat::SRGB8_Alpha8: return VK_FORMAT_R8G8B8A8_SRGB; // GL_SRGB8_ALPHA8 - case GlFormat::SRGB_DXT1: return VK_FORMAT_BC1_RGB_SRGB_BLOCK; // GL_COMPRESSED_SRGB_S3TC_DXT1_EXT - case GlFormat::SRGB_Alpha_DXT1: return VK_FORMAT_BC1_RGBA_SRGB_BLOCK; // GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT - case GlFormat::SRGB_Alpha_DXT3: return VK_FORMAT_BC2_SRGB_BLOCK; // GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT - case GlFormat::SRGB_Alpha_DXT5: return VK_FORMAT_BC3_SRGB_BLOCK; // GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT - case GlFormat::SRGB_BP_UNorm: return VK_FORMAT_BC7_SRGB_BLOCK; // GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB - - // ES 2 formats -// case GlFormat::DepthFormat: return VK_FORMAT_DEPTH_COMPONENT; // GL_DEPTH_COMPONENT -// case GlFormat::AlphaFormat: return VK_FORMAT_ALPHA; // GL_ALPHA -// case GlFormat::RGBFormat: return VK_FORMAT_RGB; // GL_RGB -// case GlFormat::RGBAFormat: return VK_FORMAT_RGBA; // GL_RGBA -// case GlFormat::LuminanceFormat: return VK_FORMAT_LUMINANCE; // GL_LUMINANCE -// case GlFormat::LuminanceAlphaFormat: return VK_FORMAT; - default: return VK_FORMAT_UNDEFINED; - } -} - -QT_END_NAMESPACE diff --git a/src/platformsupport/vkconvenience/qvkconvenience_p.h b/src/platformsupport/vkconvenience/qvkconvenience_p.h deleted file mode 100644 index 1dd1dfc4a7..0000000000 --- a/src/platformsupport/vkconvenience/qvkconvenience_p.h +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2019 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the plugins of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QVKCONVENIENCE_P_H -#define QVKCONVENIENCE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/qglobal.h> -#include <qvulkaninstance.h> - -QT_BEGIN_NAMESPACE - -class QVkConvenience -{ -public: - static VkFormat vkFormatFromGlFormat(uint glFormat); -}; - -QT_END_NAMESPACE - -#endif // QVKCONVENIENCE_P_H diff --git a/src/platformsupport/vkconvenience/vkconvenience.pro b/src/platformsupport/vkconvenience/vkconvenience.pro deleted file mode 100644 index ee540024cf..0000000000 --- a/src/platformsupport/vkconvenience/vkconvenience.pro +++ /dev/null @@ -1,18 +0,0 @@ -TARGET = QtVulkanSupport -MODULE = vulkan_support - -QT = core-private gui-private -CONFIG += static internal_module - -DEFINES += QT_NO_CAST_FROM_ASCII -PRECOMPILED_HEADER = ../../corelib/global/qt_pch.h - -SOURCES += \ - qvkconvenience.cpp \ - qbasicvulkanplatforminstance.cpp - -HEADERS += \ - qvkconvenience_p.h \ - qbasicvulkanplatforminstance_p.h - -load(qt_module) diff --git a/src/platformsupport/windowsuiautomation/qwindowsuiawrapper.cpp b/src/platformsupport/windowsuiautomation/qwindowsuiawrapper.cpp deleted file mode 100644 index 79541fe636..0000000000 --- a/src/platformsupport/windowsuiautomation/qwindowsuiawrapper.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <initguid.h> - -#include "qwindowsuiawrapper_p.h" -#include <QtCore/private/qsystemlibrary_p.h> - -QT_BEGIN_NAMESPACE - -// private constructor -QWindowsUiaWrapper::QWindowsUiaWrapper() -{ - QSystemLibrary uiaLib(QStringLiteral("UIAutomationCore")); - if (uiaLib.load()) { - m_pUiaReturnRawElementProvider = reinterpret_cast<PtrUiaReturnRawElementProvider>(uiaLib.resolve("UiaReturnRawElementProvider")); - m_pUiaHostProviderFromHwnd = reinterpret_cast<PtrUiaHostProviderFromHwnd>(uiaLib.resolve("UiaHostProviderFromHwnd")); - m_pUiaRaiseAutomationPropertyChangedEvent = reinterpret_cast<PtrUiaRaiseAutomationPropertyChangedEvent>(uiaLib.resolve("UiaRaiseAutomationPropertyChangedEvent")); - m_pUiaRaiseAutomationEvent = reinterpret_cast<PtrUiaRaiseAutomationEvent>(uiaLib.resolve("UiaRaiseAutomationEvent")); - m_pUiaClientsAreListening = reinterpret_cast<PtrUiaClientsAreListening>(uiaLib.resolve("UiaClientsAreListening")); - } -} - -QWindowsUiaWrapper::~QWindowsUiaWrapper() -{ -} - -// shared instance -QWindowsUiaWrapper *QWindowsUiaWrapper::instance() -{ - static QWindowsUiaWrapper wrapper; - return &wrapper; -} - -// True if all symbols resolved. -BOOL QWindowsUiaWrapper::ready() -{ - return m_pUiaReturnRawElementProvider - && m_pUiaHostProviderFromHwnd - && m_pUiaRaiseAutomationPropertyChangedEvent - && m_pUiaRaiseAutomationEvent - && m_pUiaClientsAreListening; -} - -BOOL QWindowsUiaWrapper::clientsAreListening() -{ - if (!m_pUiaClientsAreListening) - return FALSE; - return m_pUiaClientsAreListening(); -} - -LRESULT QWindowsUiaWrapper::returnRawElementProvider(HWND hwnd, WPARAM wParam, LPARAM lParam, IRawElementProviderSimple *el) -{ - if (!m_pUiaReturnRawElementProvider) - return static_cast<LRESULT>(NULL); - return m_pUiaReturnRawElementProvider(hwnd, wParam, lParam, el); -} - -HRESULT QWindowsUiaWrapper::hostProviderFromHwnd(HWND hwnd, IRawElementProviderSimple **ppProvider) -{ - if (!m_pUiaHostProviderFromHwnd) - return UIA_E_NOTSUPPORTED; - return m_pUiaHostProviderFromHwnd(hwnd, ppProvider); -} - -HRESULT QWindowsUiaWrapper::raiseAutomationPropertyChangedEvent(IRawElementProviderSimple *pProvider, PROPERTYID id, VARIANT oldValue, VARIANT newValue) -{ - if (!m_pUiaRaiseAutomationPropertyChangedEvent) - return UIA_E_NOTSUPPORTED; - return m_pUiaRaiseAutomationPropertyChangedEvent(pProvider, id, oldValue, newValue); -} - -HRESULT QWindowsUiaWrapper::raiseAutomationEvent(IRawElementProviderSimple *pProvider, EVENTID id) -{ - if (!m_pUiaRaiseAutomationEvent) - return UIA_E_NOTSUPPORTED; - return m_pUiaRaiseAutomationEvent(pProvider, id); -} - -QT_END_NAMESPACE - diff --git a/src/platformsupport/windowsuiautomation/qwindowsuiawrapper_p.h b/src/platformsupport/windowsuiautomation/qwindowsuiawrapper_p.h deleted file mode 100644 index 3ebc3008d3..0000000000 --- a/src/platformsupport/windowsuiautomation/qwindowsuiawrapper_p.h +++ /dev/null @@ -1,100 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QWINDOWSUIAWRAPPER_H -#define QWINDOWSUIAWRAPPER_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtGui/private/qtguiglobal_p.h> - -#include "uiatypes_p.h" -#include "uiaattributeids_p.h" -#include "uiacontroltypeids_p.h" -#include "uiaerrorids_p.h" -#include "uiaeventids_p.h" -#include "uiageneralids_p.h" -#include "uiapatternids_p.h" -#include "uiapropertyids_p.h" -#include "uiaserverinterfaces_p.h" -#include "uiaclientinterfaces_p.h" - -QT_REQUIRE_CONFIG(accessibility); - -QT_BEGIN_NAMESPACE - -class QWindowsUiaWrapper -{ - QWindowsUiaWrapper(); - virtual ~QWindowsUiaWrapper(); -public: - static QWindowsUiaWrapper *instance(); - BOOL ready(); - BOOL clientsAreListening(); - LRESULT returnRawElementProvider(HWND hwnd, WPARAM wParam, LPARAM lParam, IRawElementProviderSimple *el); - HRESULT hostProviderFromHwnd(HWND hwnd, IRawElementProviderSimple **ppProvider); - HRESULT raiseAutomationPropertyChangedEvent(IRawElementProviderSimple *pProvider, PROPERTYID id, VARIANT oldValue, VARIANT newValue); - HRESULT raiseAutomationEvent(IRawElementProviderSimple *pProvider, EVENTID id); - -private: - typedef LRESULT (WINAPI *PtrUiaReturnRawElementProvider)(HWND, WPARAM, LPARAM, IRawElementProviderSimple *); - typedef HRESULT (WINAPI *PtrUiaHostProviderFromHwnd)(HWND, IRawElementProviderSimple **); - typedef HRESULT (WINAPI *PtrUiaRaiseAutomationPropertyChangedEvent)(IRawElementProviderSimple *, PROPERTYID, VARIANT, VARIANT); - typedef HRESULT (WINAPI *PtrUiaRaiseAutomationEvent)(IRawElementProviderSimple *, EVENTID); - typedef BOOL (WINAPI *PtrUiaClientsAreListening)(); - PtrUiaReturnRawElementProvider m_pUiaReturnRawElementProvider = nullptr; - PtrUiaHostProviderFromHwnd m_pUiaHostProviderFromHwnd = nullptr; - PtrUiaRaiseAutomationPropertyChangedEvent m_pUiaRaiseAutomationPropertyChangedEvent = nullptr; - PtrUiaRaiseAutomationEvent m_pUiaRaiseAutomationEvent = nullptr; - PtrUiaClientsAreListening m_pUiaClientsAreListening = nullptr; -}; - -QT_END_NAMESPACE - -#endif //QWINDOWSUIAWRAPPER_H - diff --git a/src/platformsupport/windowsuiautomation/uiaattributeids_p.h b/src/platformsupport/windowsuiautomation/uiaattributeids_p.h deleted file mode 100644 index 795cb9e551..0000000000 --- a/src/platformsupport/windowsuiautomation/uiaattributeids_p.h +++ /dev/null @@ -1,99 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef UIAATTRIBUTEIDS_H -#define UIAATTRIBUTEIDS_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#define UIA_AnimationStyleAttributeId 40000 -#define UIA_BackgroundColorAttributeId 40001 -#define UIA_BulletStyleAttributeId 40002 -#define UIA_CapStyleAttributeId 40003 -#define UIA_CultureAttributeId 40004 -#define UIA_FontNameAttributeId 40005 -#define UIA_FontSizeAttributeId 40006 -#define UIA_FontWeightAttributeId 40007 -#define UIA_ForegroundColorAttributeId 40008 -#define UIA_HorizontalTextAlignmentAttributeId 40009 -#define UIA_IndentationFirstLineAttributeId 40010 -#define UIA_IndentationLeadingAttributeId 40011 -#define UIA_IndentationTrailingAttributeId 40012 -#define UIA_IsHiddenAttributeId 40013 -#define UIA_IsItalicAttributeId 40014 -#define UIA_IsReadOnlyAttributeId 40015 -#define UIA_IsSubscriptAttributeId 40016 -#define UIA_IsSuperscriptAttributeId 40017 -#define UIA_MarginBottomAttributeId 40018 -#define UIA_MarginLeadingAttributeId 40019 -#define UIA_MarginTopAttributeId 40020 -#define UIA_MarginTrailingAttributeId 40021 -#define UIA_OutlineStylesAttributeId 40022 -#define UIA_OverlineColorAttributeId 40023 -#define UIA_OverlineStyleAttributeId 40024 -#define UIA_StrikethroughColorAttributeId 40025 -#define UIA_StrikethroughStyleAttributeId 40026 -#define UIA_TabsAttributeId 40027 -#define UIA_TextFlowDirectionsAttributeId 40028 -#define UIA_UnderlineColorAttributeId 40029 -#define UIA_UnderlineStyleAttributeId 40030 -#define UIA_AnnotationTypesAttributeId 40031 -#define UIA_AnnotationObjectsAttributeId 40032 -#define UIA_StyleNameAttributeId 40033 -#define UIA_StyleIdAttributeId 40034 -#define UIA_LinkAttributeId 40035 -#define UIA_IsActiveAttributeId 40036 -#define UIA_SelectionActiveEndAttributeId 40037 -#define UIA_CaretPositionAttributeId 40038 -#define UIA_CaretBidiModeAttributeId 40039 -#define UIA_LineSpacingAttributeId 40040 -#define UIA_BeforeParagraphSpacingAttributeId 40041 -#define UIA_AfterParagraphSpacingAttributeId 40042 -#define UIA_SayAsInterpretAsAttributeId 40043 - -#endif diff --git a/src/platformsupport/windowsuiautomation/uiaclientinterfaces_p.h b/src/platformsupport/windowsuiautomation/uiaclientinterfaces_p.h deleted file mode 100644 index a4f3e15baa..0000000000 --- a/src/platformsupport/windowsuiautomation/uiaclientinterfaces_p.h +++ /dev/null @@ -1,266 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef UIACLIENTINTERFACES_H -#define UIACLIENTINTERFACES_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <unknwn.h> - -#ifndef __IUIAutomationElement_INTERFACE_DEFINED__ - -struct IUIAutomationCondition; -struct IUIAutomationCacheRequest; -struct IUIAutomationElementArray; -struct IUIAutomationTreeWalker; -struct IUIAutomationEventHandler; -struct IUIAutomationPropertyChangedEventHandler; -struct IUIAutomationStructureChangedEventHandler; -struct IUIAutomationFocusChangedEventHandler; -struct IUIAutomationProxyFactory; -struct IUIAutomationProxyFactoryEntry; -struct IUIAutomationProxyFactoryMapping; -#ifndef __IAccessible_FWD_DEFINED__ -#define __IAccessible_FWD_DEFINED__ -struct IAccessible; -#endif /* __IAccessible_FWD_DEFINED__ */ - -#define __IUIAutomationElement_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IUIAutomationElement, 0xd22108aa, 0x8ac5, 0x49a5, 0x83,0x7b, 0x37,0xbb,0xb3,0xd7,0x59,0x1e); -MIDL_INTERFACE("d22108aa-8ac5-49a5-837b-37bbb3d7591e") -IUIAutomationElement : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE SetFocus() = 0; - virtual HRESULT STDMETHODCALLTYPE GetRuntimeId(__RPC__deref_out_opt SAFEARRAY **runtimeId) = 0; - virtual HRESULT STDMETHODCALLTYPE FindFirst(enum TreeScope scope, __RPC__in_opt IUIAutomationCondition *condition, __RPC__deref_out_opt IUIAutomationElement **found) = 0; - virtual HRESULT STDMETHODCALLTYPE FindAll(enum TreeScope scope, __RPC__in_opt IUIAutomationCondition *condition, __RPC__deref_out_opt IUIAutomationElementArray **found) = 0; - virtual HRESULT STDMETHODCALLTYPE FindFirstBuildCache(enum TreeScope scope, __RPC__in_opt IUIAutomationCondition *condition, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **found) = 0; - virtual HRESULT STDMETHODCALLTYPE FindAllBuildCache(enum TreeScope scope, __RPC__in_opt IUIAutomationCondition *condition, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElementArray **found) = 0; - virtual HRESULT STDMETHODCALLTYPE BuildUpdatedCache(__RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **updatedElement) = 0; - virtual HRESULT STDMETHODCALLTYPE GetCurrentPropertyValue(PROPERTYID propertyId, __RPC__out VARIANT *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetCurrentPropertyValueEx(PROPERTYID propertyId, BOOL ignoreDefaultValue, __RPC__out VARIANT *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetCachedPropertyValue(PROPERTYID propertyId, __RPC__out VARIANT *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetCachedPropertyValueEx(PROPERTYID propertyId, BOOL ignoreDefaultValue, __RPC__out VARIANT *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetCurrentPatternAs(PATTERNID patternId, __RPC__in REFIID riid, __RPC__deref_out_opt void **patternObject) = 0; - virtual HRESULT STDMETHODCALLTYPE GetCachedPatternAs(PATTERNID patternId, __RPC__in REFIID riid, __RPC__deref_out_opt void **patternObject) = 0; - virtual HRESULT STDMETHODCALLTYPE GetCurrentPattern(PATTERNID patternId, __RPC__deref_out_opt IUnknown **patternObject) = 0; - virtual HRESULT STDMETHODCALLTYPE GetCachedPattern(PATTERNID patternId, __RPC__deref_out_opt IUnknown **patternObject) = 0; - virtual HRESULT STDMETHODCALLTYPE GetCachedParent(__RPC__deref_out_opt IUIAutomationElement **parent) = 0; - virtual HRESULT STDMETHODCALLTYPE GetCachedChildren(__RPC__deref_out_opt IUIAutomationElementArray **children) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentProcessId(__RPC__out int *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentControlType(__RPC__out CONTROLTYPEID *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentLocalizedControlType(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentName(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentAcceleratorKey(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentAccessKey(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentHasKeyboardFocus(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentIsKeyboardFocusable(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentIsEnabled(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentAutomationId(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentClassName(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentHelpText(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentCulture(__RPC__out int *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentIsControlElement(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentIsContentElement(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentIsPassword(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentNativeWindowHandle(__RPC__deref_out_opt UIA_HWND *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentItemType(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentIsOffscreen(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentOrientation(__RPC__out enum OrientationType *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentFrameworkId(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentIsRequiredForForm(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentItemStatus(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentBoundingRectangle(__RPC__out RECT *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentLabeledBy(__RPC__deref_out_opt IUIAutomationElement **retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentAriaRole(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentAriaProperties(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentIsDataValidForForm(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentControllerFor(__RPC__deref_out_opt IUIAutomationElementArray **retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentDescribedBy(__RPC__deref_out_opt IUIAutomationElementArray **retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentFlowsTo(__RPC__deref_out_opt IUIAutomationElementArray **retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CurrentProviderDescription(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedProcessId(__RPC__out int *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedControlType(__RPC__out CONTROLTYPEID *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedLocalizedControlType(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedName(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedAcceleratorKey(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedAccessKey(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedHasKeyboardFocus(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedIsKeyboardFocusable(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedIsEnabled(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedAutomationId(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedClassName(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedHelpText(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedCulture(__RPC__out int *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedIsControlElement(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedIsContentElement(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedIsPassword(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedNativeWindowHandle(__RPC__deref_out_opt UIA_HWND *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedItemType(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedIsOffscreen(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedOrientation(__RPC__out enum OrientationType *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedFrameworkId(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedIsRequiredForForm(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedItemStatus(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedBoundingRectangle(__RPC__out RECT *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedLabeledBy(__RPC__deref_out_opt IUIAutomationElement **retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedAriaRole(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedAriaProperties(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedIsDataValidForForm(__RPC__out BOOL *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedControllerFor(__RPC__deref_out_opt IUIAutomationElementArray **retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedDescribedBy(__RPC__deref_out_opt IUIAutomationElementArray **retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedFlowsTo(__RPC__deref_out_opt IUIAutomationElementArray **retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CachedProviderDescription(__RPC__deref_out_opt BSTR *retVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetClickablePoint(__RPC__out POINT *clickable, __RPC__out BOOL *gotClickable) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IUIAutomationElement, 0xd22108aa, 0x8ac5, 0x49a5, 0x83,0x7b, 0x37,0xbb,0xb3,0xd7,0x59,0x1e) -#endif -#endif - - -#ifndef __IUIAutomation_INTERFACE_DEFINED__ -#define __IUIAutomation_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IUIAutomation, 0x30cbe57d, 0xd9d0, 0x452a, 0xab,0x13, 0x7a,0xc5,0xac,0x48,0x25,0xee); -MIDL_INTERFACE("30cbe57d-d9d0-452a-ab13-7ac5ac4825ee") -IUIAutomation : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE CompareElements(__RPC__in_opt IUIAutomationElement *el1, __RPC__in_opt IUIAutomationElement *el2, __RPC__out BOOL *areSame) = 0; - virtual HRESULT STDMETHODCALLTYPE CompareRuntimeIds(__RPC__in SAFEARRAY * runtimeId1, __RPC__in SAFEARRAY * runtimeId2, __RPC__out BOOL *areSame) = 0; - virtual HRESULT STDMETHODCALLTYPE GetRootElement(__RPC__deref_out_opt IUIAutomationElement **root) = 0; - virtual HRESULT STDMETHODCALLTYPE ElementFromHandle(__RPC__in UIA_HWND hwnd, __RPC__deref_out_opt IUIAutomationElement **element) = 0; - virtual HRESULT STDMETHODCALLTYPE ElementFromPoint(POINT pt, __RPC__deref_out_opt IUIAutomationElement **element) = 0; - virtual HRESULT STDMETHODCALLTYPE GetFocusedElement(__RPC__deref_out_opt IUIAutomationElement **element) = 0; - virtual HRESULT STDMETHODCALLTYPE GetRootElementBuildCache(__RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **root) = 0; - virtual HRESULT STDMETHODCALLTYPE ElementFromHandleBuildCache(__RPC__in UIA_HWND hwnd, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **element) = 0; - virtual HRESULT STDMETHODCALLTYPE ElementFromPointBuildCache(POINT pt, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **element) = 0; - virtual HRESULT STDMETHODCALLTYPE GetFocusedElementBuildCache(__RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **element) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateTreeWalker(__RPC__in_opt IUIAutomationCondition *pCondition, __RPC__deref_out_opt IUIAutomationTreeWalker **walker) = 0; - virtual HRESULT STDMETHODCALLTYPE get_ControlViewWalker(__RPC__deref_out_opt IUIAutomationTreeWalker **walker) = 0; - virtual HRESULT STDMETHODCALLTYPE get_ContentViewWalker(__RPC__deref_out_opt IUIAutomationTreeWalker **walker) = 0; - virtual HRESULT STDMETHODCALLTYPE get_RawViewWalker(__RPC__deref_out_opt IUIAutomationTreeWalker **walker) = 0; - virtual HRESULT STDMETHODCALLTYPE get_RawViewCondition(__RPC__deref_out_opt IUIAutomationCondition **condition) = 0; - virtual HRESULT STDMETHODCALLTYPE get_ControlViewCondition(__RPC__deref_out_opt IUIAutomationCondition **condition) = 0; - virtual HRESULT STDMETHODCALLTYPE get_ContentViewCondition(__RPC__deref_out_opt IUIAutomationCondition **condition) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateCacheRequest(__RPC__deref_out_opt IUIAutomationCacheRequest **cacheRequest) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateTrueCondition(__RPC__deref_out_opt IUIAutomationCondition **newCondition) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateFalseCondition(__RPC__deref_out_opt IUIAutomationCondition **newCondition) = 0; - virtual HRESULT STDMETHODCALLTYPE CreatePropertyCondition(PROPERTYID propertyId, VARIANT value, __RPC__deref_out_opt IUIAutomationCondition **newCondition) = 0; - virtual HRESULT STDMETHODCALLTYPE CreatePropertyConditionEx(PROPERTYID propertyId, VARIANT value, enum PropertyConditionFlags flags, __RPC__deref_out_opt IUIAutomationCondition **newCondition) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateAndCondition(__RPC__in_opt IUIAutomationCondition *condition1, __RPC__in_opt IUIAutomationCondition *condition2, __RPC__deref_out_opt IUIAutomationCondition **newCondition) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateAndConditionFromArray(__RPC__in_opt SAFEARRAY * conditions, __RPC__deref_out_opt IUIAutomationCondition **newCondition) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateAndConditionFromNativeArray(__RPC__in_ecount_full(conditionCount) IUIAutomationCondition **conditions, int conditionCount, __RPC__deref_out_opt IUIAutomationCondition **newCondition) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateOrCondition(__RPC__in_opt IUIAutomationCondition *condition1, __RPC__in_opt IUIAutomationCondition *condition2, __RPC__deref_out_opt IUIAutomationCondition **newCondition) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateOrConditionFromArray(__RPC__in_opt SAFEARRAY * conditions, __RPC__deref_out_opt IUIAutomationCondition **newCondition) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateOrConditionFromNativeArray(__RPC__in_ecount_full(conditionCount) IUIAutomationCondition **conditions, int conditionCount, __RPC__deref_out_opt IUIAutomationCondition **newCondition) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateNotCondition(__RPC__in_opt IUIAutomationCondition *condition, __RPC__deref_out_opt IUIAutomationCondition **newCondition) = 0; - virtual HRESULT STDMETHODCALLTYPE AddAutomationEventHandler(EVENTID eventId, __RPC__in_opt IUIAutomationElement *element, enum TreeScope scope, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__in_opt IUIAutomationEventHandler *handler) = 0; - virtual HRESULT STDMETHODCALLTYPE RemoveAutomationEventHandler(EVENTID eventId, __RPC__in_opt IUIAutomationElement *element, __RPC__in_opt IUIAutomationEventHandler *handler) = 0; - virtual HRESULT STDMETHODCALLTYPE AddPropertyChangedEventHandlerNativeArray(__RPC__in_opt IUIAutomationElement *element, enum TreeScope scope, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__in_opt IUIAutomationPropertyChangedEventHandler *handler, __RPC__in_ecount_full(propertyCount) PROPERTYID *propertyArray, int propertyCount) = 0; - virtual HRESULT STDMETHODCALLTYPE AddPropertyChangedEventHandler(__RPC__in_opt IUIAutomationElement *element, enum TreeScope scope, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__in_opt IUIAutomationPropertyChangedEventHandler *handler, __RPC__in SAFEARRAY * propertyArray) = 0; - virtual HRESULT STDMETHODCALLTYPE RemovePropertyChangedEventHandler(__RPC__in_opt IUIAutomationElement *element, __RPC__in_opt IUIAutomationPropertyChangedEventHandler *handler) = 0; - virtual HRESULT STDMETHODCALLTYPE AddStructureChangedEventHandler(__RPC__in_opt IUIAutomationElement *element, enum TreeScope scope, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__in_opt IUIAutomationStructureChangedEventHandler *handler) = 0; - virtual HRESULT STDMETHODCALLTYPE RemoveStructureChangedEventHandler(__RPC__in_opt IUIAutomationElement *element, __RPC__in_opt IUIAutomationStructureChangedEventHandler *handler) = 0; - virtual HRESULT STDMETHODCALLTYPE AddFocusChangedEventHandler(__RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__in_opt IUIAutomationFocusChangedEventHandler *handler) = 0; - virtual HRESULT STDMETHODCALLTYPE RemoveFocusChangedEventHandler(__RPC__in_opt IUIAutomationFocusChangedEventHandler *handler) = 0; - virtual HRESULT STDMETHODCALLTYPE RemoveAllEventHandlers() = 0; - virtual HRESULT STDMETHODCALLTYPE IntNativeArrayToSafeArray(__RPC__in_ecount_full(arrayCount) int *array, int arrayCount, __RPC__deref_out_opt SAFEARRAY **safeArray) = 0; - virtual HRESULT STDMETHODCALLTYPE IntSafeArrayToNativeArray(__RPC__in SAFEARRAY * intArray, __RPC__deref_out_ecount_full_opt(*arrayCount) int **array, __RPC__out int *arrayCount) = 0; - virtual HRESULT STDMETHODCALLTYPE RectToVariant(RECT rc, __RPC__out VARIANT *var) = 0; - virtual HRESULT STDMETHODCALLTYPE VariantToRect(VARIANT var, __RPC__out RECT *rc) = 0; - virtual HRESULT STDMETHODCALLTYPE SafeArrayToRectNativeArray(__RPC__in SAFEARRAY * rects, __RPC__deref_out_ecount_full_opt(*rectArrayCount) RECT **rectArray, __RPC__out int *rectArrayCount) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateProxyFactoryEntry(__RPC__in_opt IUIAutomationProxyFactory *factory, __RPC__deref_out_opt IUIAutomationProxyFactoryEntry **factoryEntry) = 0; - virtual HRESULT STDMETHODCALLTYPE get_ProxyFactoryMapping(__RPC__deref_out_opt IUIAutomationProxyFactoryMapping **factoryMapping) = 0; - virtual HRESULT STDMETHODCALLTYPE GetPropertyProgrammaticName(PROPERTYID property, __RPC__deref_out_opt BSTR *name) = 0; - virtual HRESULT STDMETHODCALLTYPE GetPatternProgrammaticName(PATTERNID pattern, __RPC__deref_out_opt BSTR *name) = 0; - virtual HRESULT STDMETHODCALLTYPE PollForPotentialSupportedPatterns(__RPC__in_opt IUIAutomationElement *pElement, __RPC__deref_out_opt SAFEARRAY **patternIds, __RPC__deref_out_opt SAFEARRAY **patternNames) = 0; - virtual HRESULT STDMETHODCALLTYPE PollForPotentialSupportedProperties(__RPC__in_opt IUIAutomationElement *pElement, __RPC__deref_out_opt SAFEARRAY **propertyIds, __RPC__deref_out_opt SAFEARRAY **propertyNames) = 0; - virtual HRESULT STDMETHODCALLTYPE CheckNotSupported(VARIANT value, __RPC__out BOOL *isNotSupported) = 0; - virtual HRESULT STDMETHODCALLTYPE get_ReservedNotSupportedValue(__RPC__deref_out_opt IUnknown **notSupportedValue) = 0; - virtual HRESULT STDMETHODCALLTYPE get_ReservedMixedAttributeValue(__RPC__deref_out_opt IUnknown **mixedAttributeValue) = 0; - virtual HRESULT STDMETHODCALLTYPE ElementFromIAccessible(__RPC__in_opt IAccessible *accessible, int childId, __RPC__deref_out_opt IUIAutomationElement **element) = 0; - virtual HRESULT STDMETHODCALLTYPE ElementFromIAccessibleBuildCache(__RPC__in_opt IAccessible *accessible, int childId, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **element) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IUIAutomation, 0x30cbe57d, 0xd9d0, 0x452a, 0xab,0x13, 0x7a,0xc5,0xac,0x48,0x25,0xee) -#endif -#endif - - -#ifndef __IUIAutomationTreeWalker_INTERFACE_DEFINED__ -#define __IUIAutomationTreeWalker_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IUIAutomationTreeWalker, 0x4042c624, 0x389c, 0x4afc, 0xa6,0x30, 0x9d,0xf8,0x54,0xa5,0x41,0xfc); -MIDL_INTERFACE("4042c624-389c-4afc-a630-9df854a541fc") -IUIAutomationTreeWalker : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE GetParentElement(__RPC__in_opt IUIAutomationElement *element, __RPC__deref_out_opt IUIAutomationElement **parent) = 0; - virtual HRESULT STDMETHODCALLTYPE GetFirstChildElement(__RPC__in_opt IUIAutomationElement *element, __RPC__deref_out_opt IUIAutomationElement **first) = 0; - virtual HRESULT STDMETHODCALLTYPE GetLastChildElement(__RPC__in_opt IUIAutomationElement *element, __RPC__deref_out_opt IUIAutomationElement **last) = 0; - virtual HRESULT STDMETHODCALLTYPE GetNextSiblingElement(__RPC__in_opt IUIAutomationElement *element, __RPC__deref_out_opt IUIAutomationElement **next) = 0; - virtual HRESULT STDMETHODCALLTYPE GetPreviousSiblingElement(__RPC__in_opt IUIAutomationElement *element, __RPC__deref_out_opt IUIAutomationElement **previous) = 0; - virtual HRESULT STDMETHODCALLTYPE NormalizeElement(__RPC__in_opt IUIAutomationElement *element, __RPC__deref_out_opt IUIAutomationElement **normalized) = 0; - virtual HRESULT STDMETHODCALLTYPE GetParentElementBuildCache(__RPC__in_opt IUIAutomationElement *element, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **parent) = 0; - virtual HRESULT STDMETHODCALLTYPE GetFirstChildElementBuildCache(__RPC__in_opt IUIAutomationElement *element, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **first) = 0; - virtual HRESULT STDMETHODCALLTYPE GetLastChildElementBuildCache(__RPC__in_opt IUIAutomationElement *element, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **last) = 0; - virtual HRESULT STDMETHODCALLTYPE GetNextSiblingElementBuildCache(__RPC__in_opt IUIAutomationElement *element, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **next) = 0; - virtual HRESULT STDMETHODCALLTYPE GetPreviousSiblingElementBuildCache(__RPC__in_opt IUIAutomationElement *element, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **previous) = 0; - virtual HRESULT STDMETHODCALLTYPE NormalizeElementBuildCache(__RPC__in_opt IUIAutomationElement *element, __RPC__in_opt IUIAutomationCacheRequest *cacheRequest, __RPC__deref_out_opt IUIAutomationElement **normalized) = 0; - virtual HRESULT STDMETHODCALLTYPE get_Condition(__RPC__deref_out_opt IUIAutomationCondition **condition) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IUIAutomationTreeWalker, 0x4042c624, 0x389c, 0x4afc, 0xa6,0x30, 0x9d,0xf8,0x54,0xa5,0x41,0xfc) -#endif -#endif - -DEFINE_GUID(CLSID_CUIAutomation, 0xff48dba4, 0x60ef, 0x4201, 0xaa,0x87, 0x54,0x10,0x3e,0xef,0x59,0x4e); - -#endif diff --git a/src/platformsupport/windowsuiautomation/uiacontroltypeids_p.h b/src/platformsupport/windowsuiautomation/uiacontroltypeids_p.h deleted file mode 100644 index b5c5a0a4ff..0000000000 --- a/src/platformsupport/windowsuiautomation/uiacontroltypeids_p.h +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef UIACONTROLTYPEIDS_H -#define UIACONTROLTYPEIDS_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#define UIA_ButtonControlTypeId 50000 -#define UIA_CalendarControlTypeId 50001 -#define UIA_CheckBoxControlTypeId 50002 -#define UIA_ComboBoxControlTypeId 50003 -#define UIA_EditControlTypeId 50004 -#define UIA_HyperlinkControlTypeId 50005 -#define UIA_ImageControlTypeId 50006 -#define UIA_ListItemControlTypeId 50007 -#define UIA_ListControlTypeId 50008 -#define UIA_MenuControlTypeId 50009 -#define UIA_MenuBarControlTypeId 50010 -#define UIA_MenuItemControlTypeId 50011 -#define UIA_ProgressBarControlTypeId 50012 -#define UIA_RadioButtonControlTypeId 50013 -#define UIA_ScrollBarControlTypeId 50014 -#define UIA_SliderControlTypeId 50015 -#define UIA_SpinnerControlTypeId 50016 -#define UIA_StatusBarControlTypeId 50017 -#define UIA_TabControlTypeId 50018 -#define UIA_TabItemControlTypeId 50019 -#define UIA_TextControlTypeId 50020 -#define UIA_ToolBarControlTypeId 50021 -#define UIA_ToolTipControlTypeId 50022 -#define UIA_TreeControlTypeId 50023 -#define UIA_TreeItemControlTypeId 50024 -#define UIA_CustomControlTypeId 50025 -#define UIA_GroupControlTypeId 50026 -#define UIA_ThumbControlTypeId 50027 -#define UIA_DataGridControlTypeId 50028 -#define UIA_DataItemControlTypeId 50029 -#define UIA_DocumentControlTypeId 50030 -#define UIA_SplitButtonControlTypeId 50031 -#define UIA_WindowControlTypeId 50032 -#define UIA_PaneControlTypeId 50033 -#define UIA_HeaderControlTypeId 50034 -#define UIA_HeaderItemControlTypeId 50035 -#define UIA_TableControlTypeId 50036 -#define UIA_TitleBarControlTypeId 50037 -#define UIA_SeparatorControlTypeId 50038 -#define UIA_SemanticZoomControlTypeId 50039 -#define UIA_AppBarControlTypeId 50040 - -#endif diff --git a/src/platformsupport/windowsuiautomation/uiaerrorids_p.h b/src/platformsupport/windowsuiautomation/uiaerrorids_p.h deleted file mode 100644 index 8c2a24dbc7..0000000000 --- a/src/platformsupport/windowsuiautomation/uiaerrorids_p.h +++ /dev/null @@ -1,62 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef UIAERRORIDS_H -#define UIAERRORIDS_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#define UIA_E_ELEMENTNOTENABLED 0x80040200 -#define UIA_E_ELEMENTNOTAVAILABLE 0x80040201 -#define UIA_E_NOCLICKABLEPOINT 0x80040202 -#define UIA_E_PROXYASSEMBLYNOTLOADED 0x80040203 -#define UIA_E_NOTSUPPORTED 0x80040204 -#define UIA_E_INVALIDOPERATION 0x80131509 -#define UIA_E_TIMEOUT 0x80131505 - -#endif diff --git a/src/platformsupport/windowsuiautomation/uiaeventids_p.h b/src/platformsupport/windowsuiautomation/uiaeventids_p.h deleted file mode 100644 index ed6c36834e..0000000000 --- a/src/platformsupport/windowsuiautomation/uiaeventids_p.h +++ /dev/null @@ -1,90 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef UIAEVENTIDS_H -#define UIAEVENTIDS_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#define UIA_ToolTipOpenedEventId 20000 -#define UIA_ToolTipClosedEventId 20001 -#define UIA_StructureChangedEventId 20002 -#define UIA_MenuOpenedEventId 20003 -#define UIA_AutomationPropertyChangedEventId 20004 -#define UIA_AutomationFocusChangedEventId 20005 -#define UIA_AsyncContentLoadedEventId 20006 -#define UIA_MenuClosedEventId 20007 -#define UIA_LayoutInvalidatedEventId 20008 -#define UIA_Invoke_InvokedEventId 20009 -#define UIA_SelectionItem_ElementAddedToSelectionEventId 20010 -#define UIA_SelectionItem_ElementRemovedFromSelectionEventId 20011 -#define UIA_SelectionItem_ElementSelectedEventId 20012 -#define UIA_Selection_InvalidatedEventId 20013 -#define UIA_Text_TextSelectionChangedEventId 20014 -#define UIA_Text_TextChangedEventId 20015 -#define UIA_Window_WindowOpenedEventId 20016 -#define UIA_Window_WindowClosedEventId 20017 -#define UIA_MenuModeStartEventId 20018 -#define UIA_MenuModeEndEventId 20019 -#define UIA_InputReachedTargetEventId 20020 -#define UIA_InputReachedOtherElementEventId 20021 -#define UIA_InputDiscardedEventId 20022 -#define UIA_SystemAlertEventId 20023 -#define UIA_LiveRegionChangedEventId 20024 -#define UIA_HostedFragmentRootsInvalidatedEventId 20025 -#define UIA_Drag_DragStartEventId 20026 -#define UIA_Drag_DragCancelEventId 20027 -#define UIA_Drag_DragCompleteEventId 20028 -#define UIA_DropTarget_DragEnterEventId 20029 -#define UIA_DropTarget_DragLeaveEventId 20030 -#define UIA_DropTarget_DroppedEventId 20031 -#define UIA_TextEdit_TextChangedEventId 20032 -#define UIA_TextEdit_ConversionTargetChangedEventId 20033 -#define UIA_ChangesEventId 20034 - -#endif diff --git a/src/platformsupport/windowsuiautomation/uiageneralids_p.h b/src/platformsupport/windowsuiautomation/uiageneralids_p.h deleted file mode 100644 index 220554f885..0000000000 --- a/src/platformsupport/windowsuiautomation/uiageneralids_p.h +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef UIAGENERALIDS_H -#define UIAGENERALIDS_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#define UiaAppendRuntimeId 3 -#define UiaRootObjectId -25 - -#endif diff --git a/src/platformsupport/windowsuiautomation/uiapatternids_p.h b/src/platformsupport/windowsuiautomation/uiapatternids_p.h deleted file mode 100644 index d3f4c9bd7a..0000000000 --- a/src/platformsupport/windowsuiautomation/uiapatternids_p.h +++ /dev/null @@ -1,89 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef UIAPATTERNIDS_H -#define UIAPATTERNIDS_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#define UIA_InvokePatternId 10000 -#define UIA_SelectionPatternId 10001 -#define UIA_ValuePatternId 10002 -#define UIA_RangeValuePatternId 10003 -#define UIA_ScrollPatternId 10004 -#define UIA_ExpandCollapsePatternId 10005 -#define UIA_GridPatternId 10006 -#define UIA_GridItemPatternId 10007 -#define UIA_MultipleViewPatternId 10008 -#define UIA_WindowPatternId 10009 -#define UIA_SelectionItemPatternId 10010 -#define UIA_DockPatternId 10011 -#define UIA_TablePatternId 10012 -#define UIA_TableItemPatternId 10013 -#define UIA_TextPatternId 10014 -#define UIA_TogglePatternId 10015 -#define UIA_TransformPatternId 10016 -#define UIA_ScrollItemPatternId 10017 -#define UIA_LegacyIAccessiblePatternId 10018 -#define UIA_ItemContainerPatternId 10019 -#define UIA_VirtualizedItemPatternId 10020 -#define UIA_SynchronizedInputPatternId 10021 -#define UIA_ObjectModelPatternId 10022 -#define UIA_AnnotationPatternId 10023 -#define UIA_TextPattern2Id 10024 -#define UIA_StylesPatternId 10025 -#define UIA_SpreadsheetPatternId 10026 -#define UIA_SpreadsheetItemPatternId 10027 -#define UIA_TransformPattern2Id 10028 -#define UIA_TextChildPatternId 10029 -#define UIA_DragPatternId 10030 -#define UIA_DropTargetPatternId 10031 -#define UIA_TextEditPatternId 10032 -#define UIA_CustomNavigationPatternId 10033 - -#endif diff --git a/src/platformsupport/windowsuiautomation/uiapropertyids_p.h b/src/platformsupport/windowsuiautomation/uiapropertyids_p.h deleted file mode 100644 index 74e84147f6..0000000000 --- a/src/platformsupport/windowsuiautomation/uiapropertyids_p.h +++ /dev/null @@ -1,223 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef UIAPROPERTYIDS_H -#define UIAPROPERTYIDS_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#define UIA_RuntimeIdPropertyId 30000 -#define UIA_BoundingRectanglePropertyId 30001 -#define UIA_ProcessIdPropertyId 30002 -#define UIA_ControlTypePropertyId 30003 -#define UIA_LocalizedControlTypePropertyId 30004 -#define UIA_NamePropertyId 30005 -#define UIA_AcceleratorKeyPropertyId 30006 -#define UIA_AccessKeyPropertyId 30007 -#define UIA_HasKeyboardFocusPropertyId 30008 -#define UIA_IsKeyboardFocusablePropertyId 30009 -#define UIA_IsEnabledPropertyId 30010 -#define UIA_AutomationIdPropertyId 30011 -#define UIA_ClassNamePropertyId 30012 -#define UIA_HelpTextPropertyId 30013 -#define UIA_ClickablePointPropertyId 30014 -#define UIA_CulturePropertyId 30015 -#define UIA_IsControlElementPropertyId 30016 -#define UIA_IsContentElementPropertyId 30017 -#define UIA_LabeledByPropertyId 30018 -#define UIA_IsPasswordPropertyId 30019 -#define UIA_NativeWindowHandlePropertyId 30020 -#define UIA_ItemTypePropertyId 30021 -#define UIA_IsOffscreenPropertyId 30022 -#define UIA_OrientationPropertyId 30023 -#define UIA_FrameworkIdPropertyId 30024 -#define UIA_IsRequiredForFormPropertyId 30025 -#define UIA_ItemStatusPropertyId 30026 -#define UIA_IsDockPatternAvailablePropertyId 30027 -#define UIA_IsExpandCollapsePatternAvailablePropertyId 30028 -#define UIA_IsGridItemPatternAvailablePropertyId 30029 -#define UIA_IsGridPatternAvailablePropertyId 30030 -#define UIA_IsInvokePatternAvailablePropertyId 30031 -#define UIA_IsMultipleViewPatternAvailablePropertyId 30032 -#define UIA_IsRangeValuePatternAvailablePropertyId 30033 -#define UIA_IsScrollPatternAvailablePropertyId 30034 -#define UIA_IsScrollItemPatternAvailablePropertyId 30035 -#define UIA_IsSelectionItemPatternAvailablePropertyId 30036 -#define UIA_IsSelectionPatternAvailablePropertyId 30037 -#define UIA_IsTablePatternAvailablePropertyId 30038 -#define UIA_IsTableItemPatternAvailablePropertyId 30039 -#define UIA_IsTextPatternAvailablePropertyId 30040 -#define UIA_IsTogglePatternAvailablePropertyId 30041 -#define UIA_IsTransformPatternAvailablePropertyId 30042 -#define UIA_IsValuePatternAvailablePropertyId 30043 -#define UIA_IsWindowPatternAvailablePropertyId 30044 -#define UIA_ValueValuePropertyId 30045 -#define UIA_ValueIsReadOnlyPropertyId 30046 -#define UIA_RangeValueValuePropertyId 30047 -#define UIA_RangeValueIsReadOnlyPropertyId 30048 -#define UIA_RangeValueMinimumPropertyId 30049 -#define UIA_RangeValueMaximumPropertyId 30050 -#define UIA_RangeValueLargeChangePropertyId 30051 -#define UIA_RangeValueSmallChangePropertyId 30052 -#define UIA_ScrollHorizontalScrollPercentPropertyId 30053 -#define UIA_ScrollHorizontalViewSizePropertyId 30054 -#define UIA_ScrollVerticalScrollPercentPropertyId 30055 -#define UIA_ScrollVerticalViewSizePropertyId 30056 -#define UIA_ScrollHorizontallyScrollablePropertyId 30057 -#define UIA_ScrollVerticallyScrollablePropertyId 30058 -#define UIA_SelectionSelectionPropertyId 30059 -#define UIA_SelectionCanSelectMultiplePropertyId 30060 -#define UIA_SelectionIsSelectionRequiredPropertyId 30061 -#define UIA_GridRowCountPropertyId 30062 -#define UIA_GridColumnCountPropertyId 30063 -#define UIA_GridItemRowPropertyId 30064 -#define UIA_GridItemColumnPropertyId 30065 -#define UIA_GridItemRowSpanPropertyId 30066 -#define UIA_GridItemColumnSpanPropertyId 30067 -#define UIA_GridItemContainingGridPropertyId 30068 -#define UIA_DockDockPositionPropertyId 30069 -#define UIA_ExpandCollapseExpandCollapseStatePropertyId 30070 -#define UIA_MultipleViewCurrentViewPropertyId 30071 -#define UIA_MultipleViewSupportedViewsPropertyId 30072 -#define UIA_WindowCanMaximizePropertyId 30073 -#define UIA_WindowCanMinimizePropertyId 30074 -#define UIA_WindowWindowVisualStatePropertyId 30075 -#define UIA_WindowWindowInteractionStatePropertyId 30076 -#define UIA_WindowIsModalPropertyId 30077 -#define UIA_WindowIsTopmostPropertyId 30078 -#define UIA_SelectionItemIsSelectedPropertyId 30079 -#define UIA_SelectionItemSelectionContainerPropertyId 30080 -#define UIA_TableRowHeadersPropertyId 30081 -#define UIA_TableColumnHeadersPropertyId 30082 -#define UIA_TableRowOrColumnMajorPropertyId 30083 -#define UIA_TableItemRowHeaderItemsPropertyId 30084 -#define UIA_TableItemColumnHeaderItemsPropertyId 30085 -#define UIA_ToggleToggleStatePropertyId 30086 -#define UIA_TransformCanMovePropertyId 30087 -#define UIA_TransformCanResizePropertyId 30088 -#define UIA_TransformCanRotatePropertyId 30089 -#define UIA_IsLegacyIAccessiblePatternAvailablePropertyId 30090 -#define UIA_LegacyIAccessibleChildIdPropertyId 30091 -#define UIA_LegacyIAccessibleNamePropertyId 30092 -#define UIA_LegacyIAccessibleValuePropertyId 30093 -#define UIA_LegacyIAccessibleDescriptionPropertyId 30094 -#define UIA_LegacyIAccessibleRolePropertyId 30095 -#define UIA_LegacyIAccessibleStatePropertyId 30096 -#define UIA_LegacyIAccessibleHelpPropertyId 30097 -#define UIA_LegacyIAccessibleKeyboardShortcutPropertyId 30098 -#define UIA_LegacyIAccessibleSelectionPropertyId 30099 -#define UIA_LegacyIAccessibleDefaultActionPropertyId 30100 -#define UIA_AriaRolePropertyId 30101 -#define UIA_AriaPropertiesPropertyId 30102 -#define UIA_IsDataValidForFormPropertyId 30103 -#define UIA_ControllerForPropertyId 30104 -#define UIA_DescribedByPropertyId 30105 -#define UIA_FlowsToPropertyId 30106 -#define UIA_ProviderDescriptionPropertyId 30107 -#define UIA_IsItemContainerPatternAvailablePropertyId 30108 -#define UIA_IsVirtualizedItemPatternAvailablePropertyId 30109 -#define UIA_IsSynchronizedInputPatternAvailablePropertyId 30110 -#define UIA_OptimizeForVisualContentPropertyId 30111 -#define UIA_IsObjectModelPatternAvailablePropertyId 30112 -#define UIA_AnnotationAnnotationTypeIdPropertyId 30113 -#define UIA_AnnotationAnnotationTypeNamePropertyId 30114 -#define UIA_AnnotationAuthorPropertyId 30115 -#define UIA_AnnotationDateTimePropertyId 30116 -#define UIA_AnnotationTargetPropertyId 30117 -#define UIA_IsAnnotationPatternAvailablePropertyId 30118 -#define UIA_IsTextPattern2AvailablePropertyId 30119 -#define UIA_StylesStyleIdPropertyId 30120 -#define UIA_StylesStyleNamePropertyId 30121 -#define UIA_StylesFillColorPropertyId 30122 -#define UIA_StylesFillPatternStylePropertyId 30123 -#define UIA_StylesShapePropertyId 30124 -#define UIA_StylesFillPatternColorPropertyId 30125 -#define UIA_StylesExtendedPropertiesPropertyId 30126 -#define UIA_IsStylesPatternAvailablePropertyId 30127 -#define UIA_IsSpreadsheetPatternAvailablePropertyId 30128 -#define UIA_SpreadsheetItemFormulaPropertyId 30129 -#define UIA_SpreadsheetItemAnnotationObjectsPropertyId 30130 -#define UIA_SpreadsheetItemAnnotationTypesPropertyId 30131 -#define UIA_IsSpreadsheetItemPatternAvailablePropertyId 30132 -#define UIA_Transform2CanZoomPropertyId 30133 -#define UIA_IsTransformPattern2AvailablePropertyId 30134 -#define UIA_LiveSettingPropertyId 30135 -#define UIA_IsTextChildPatternAvailablePropertyId 30136 -#define UIA_IsDragPatternAvailablePropertyId 30137 -#define UIA_DragIsGrabbedPropertyId 30138 -#define UIA_DragDropEffectPropertyId 30139 -#define UIA_DragDropEffectsPropertyId 30140 -#define UIA_IsDropTargetPatternAvailablePropertyId 30141 -#define UIA_DropTargetDropTargetEffectPropertyId 30142 -#define UIA_DropTargetDropTargetEffectsPropertyId 30143 -#define UIA_DragGrabbedItemsPropertyId 30144 -#define UIA_Transform2ZoomLevelPropertyId 30145 -#define UIA_Transform2ZoomMinimumPropertyId 30146 -#define UIA_Transform2ZoomMaximumPropertyId 30147 -#define UIA_FlowsFromPropertyId 30148 -#define UIA_IsTextEditPatternAvailablePropertyId 30149 -#define UIA_IsPeripheralPropertyId 30150 -#define UIA_IsCustomNavigationPatternAvailablePropertyId 30151 -#define UIA_PositionInSetPropertyId 30152 -#define UIA_SizeOfSetPropertyId 30153 -#define UIA_LevelPropertyId 30154 -#define UIA_AnnotationTypesPropertyId 30155 -#define UIA_AnnotationObjectsPropertyId 30156 -#define UIA_LandmarkTypePropertyId 30157 -#define UIA_LocalizedLandmarkTypePropertyId 30158 -#define UIA_FullDescriptionPropertyId 30159 -#define UIA_FillColorPropertyId 30160 -#define UIA_OutlineColorPropertyId 30161 -#define UIA_FillTypePropertyId 30162 -#define UIA_VisualEffectsPropertyId 30163 -#define UIA_OutlineThicknessPropertyId 30164 -#define UIA_CenterPointPropertyId 30165 -#define UIA_RotationPropertyId 30166 -#define UIA_SizePropertyId 30167 - -#endif diff --git a/src/platformsupport/windowsuiautomation/uiaserverinterfaces_p.h b/src/platformsupport/windowsuiautomation/uiaserverinterfaces_p.h deleted file mode 100644 index fd39b6ee33..0000000000 --- a/src/platformsupport/windowsuiautomation/uiaserverinterfaces_p.h +++ /dev/null @@ -1,386 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef UIASERVERINTERFACES_H -#define UIASERVERINTERFACES_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <unknwn.h> - -#ifndef __IRawElementProviderSimple_INTERFACE_DEFINED__ -#define __IRawElementProviderSimple_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IRawElementProviderSimple, 0xd6dd68d1, 0x86fd, 0x4332, 0x86,0x66, 0x9a,0xbe,0xde,0xa2,0xd2,0x4c); -MIDL_INTERFACE("d6dd68d1-86fd-4332-8666-9abedea2d24c") -IRawElementProviderSimple : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE get_ProviderOptions(__RPC__out enum ProviderOptions *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetPatternProvider(PATTERNID patternId, __RPC__deref_out_opt IUnknown **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetPropertyValue(PROPERTYID propertyId, __RPC__out VARIANT *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_HostRawElementProvider(__RPC__deref_out_opt IRawElementProviderSimple **pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IRawElementProviderSimple, 0xd6dd68d1, 0x86fd, 0x4332, 0x86,0x66, 0x9a,0xbe,0xde,0xa2,0xd2,0x4c) -#endif -#endif - - -#ifndef __IRawElementProviderFragmentRoot_FWD_DEFINED__ -#define __IRawElementProviderFragmentRoot_FWD_DEFINED__ -typedef interface IRawElementProviderFragmentRoot IRawElementProviderFragmentRoot; -#endif - - -#ifndef __IRawElementProviderFragment_FWD_DEFINED__ -#define __IRawElementProviderFragment_FWD_DEFINED__ -typedef interface IRawElementProviderFragment IRawElementProviderFragment; -#endif - - -#ifndef __IRawElementProviderFragment_INTERFACE_DEFINED__ -#define __IRawElementProviderFragment_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IRawElementProviderFragment, 0xf7063da8, 0x8359, 0x439c, 0x92,0x97, 0xbb,0xc5,0x29,0x9a,0x7d,0x87); -MIDL_INTERFACE("f7063da8-8359-439c-9297-bbc5299a7d87") -IRawElementProviderFragment : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE Navigate(enum NavigateDirection direction, __RPC__deref_out_opt IRawElementProviderFragment **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetRuntimeId(__RPC__deref_out_opt SAFEARRAY **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_BoundingRectangle(__RPC__out struct UiaRect *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetEmbeddedFragmentRoots(__RPC__deref_out_opt SAFEARRAY **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE SetFocus() = 0; - virtual HRESULT STDMETHODCALLTYPE get_FragmentRoot(__RPC__deref_out_opt IRawElementProviderFragmentRoot **pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IRawElementProviderFragment, 0xf7063da8, 0x8359, 0x439c, 0x92,0x97, 0xbb,0xc5,0x29,0x9a,0x7d,0x87) -#endif -#endif - - -#ifndef __IRawElementProviderFragmentRoot_INTERFACE_DEFINED__ -#define __IRawElementProviderFragmentRoot_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IRawElementProviderFragmentRoot, 0x620ce2a5, 0xab8f, 0x40a9, 0x86,0xcb, 0xde,0x3c,0x75,0x59,0x9b,0x58); -MIDL_INTERFACE("620ce2a5-ab8f-40a9-86cb-de3c75599b58") -IRawElementProviderFragmentRoot : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE ElementProviderFromPoint(double x, double y, __RPC__deref_out_opt IRawElementProviderFragment **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetFocus(__RPC__deref_out_opt IRawElementProviderFragment **pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IRawElementProviderFragmentRoot, 0x620ce2a5, 0xab8f, 0x40a9, 0x86,0xcb, 0xde,0x3c,0x75,0x59,0x9b,0x58) -#endif -#endif - - -#ifndef __IValueProvider_INTERFACE_DEFINED__ -#define __IValueProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IValueProvider, 0xc7935180, 0x6fb3, 0x4201, 0xb1,0x74, 0x7d,0xf7,0x3a,0xdb,0xf6,0x4a); -MIDL_INTERFACE("c7935180-6fb3-4201-b174-7df73adbf64a") -IValueProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE SetValue(__RPC__in LPCWSTR val) = 0; - virtual HRESULT STDMETHODCALLTYPE get_Value(__RPC__deref_out_opt BSTR *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_IsReadOnly(__RPC__out BOOL *pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IValueProvider, 0xc7935180, 0x6fb3, 0x4201, 0xb1,0x74, 0x7d,0xf7,0x3a,0xdb,0xf6,0x4a) -#endif -#endif - - -#ifndef __IRangeValueProvider_INTERFACE_DEFINED__ -#define __IRangeValueProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IRangeValueProvider, 0x36dc7aef, 0x33e6, 0x4691, 0xaf,0xe1, 0x2b,0xe7,0x27,0x4b,0x3d,0x33); -MIDL_INTERFACE("36dc7aef-33e6-4691-afe1-2be7274b3d33") -IRangeValueProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE SetValue(double val) = 0; - virtual HRESULT STDMETHODCALLTYPE get_Value(__RPC__out double *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_IsReadOnly(__RPC__out BOOL *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_Maximum(__RPC__out double *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_Minimum(__RPC__out double *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_LargeChange(__RPC__out double *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_SmallChange(__RPC__out double *pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IRangeValueProvider, 0x36dc7aef, 0x33e6, 0x4691, 0xaf,0xe1, 0x2b,0xe7,0x27,0x4b,0x3d,0x33) -#endif -#endif - - -#ifndef __ITextRangeProvider_INTERFACE_DEFINED__ -#define __ITextRangeProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_ITextRangeProvider, 0x5347ad7b, 0xc355, 0x46f8, 0xaf,0xf5, 0x90,0x90,0x33,0x58,0x2f,0x63); -MIDL_INTERFACE("5347ad7b-c355-46f8-aff5-909033582f63") -ITextRangeProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE Clone(__RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE Compare(__RPC__in_opt ITextRangeProvider *range, __RPC__out BOOL *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE CompareEndpoints(enum TextPatternRangeEndpoint endpoint, __RPC__in_opt ITextRangeProvider *targetRange, enum TextPatternRangeEndpoint targetEndpoint, __RPC__out int *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE ExpandToEnclosingUnit(enum TextUnit unit) = 0; - virtual HRESULT STDMETHODCALLTYPE FindAttribute(TEXTATTRIBUTEID attributeId, VARIANT val, BOOL backward, __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE FindText(__RPC__in BSTR text, BOOL backward, BOOL ignoreCase, __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetAttributeValue(TEXTATTRIBUTEID attributeId, __RPC__out VARIANT *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetBoundingRectangles(__RPC__deref_out_opt SAFEARRAY **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetEnclosingElement(__RPC__deref_out_opt IRawElementProviderSimple **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetText(int maxLength, __RPC__deref_out_opt BSTR *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE Move(enum TextUnit unit, int count, __RPC__out int *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE MoveEndpointByUnit(enum TextPatternRangeEndpoint endpoint, enum TextUnit unit, int count, __RPC__out int *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE MoveEndpointByRange(enum TextPatternRangeEndpoint endpoint, __RPC__in_opt ITextRangeProvider *targetRange, enum TextPatternRangeEndpoint targetEndpoint) = 0; - virtual HRESULT STDMETHODCALLTYPE Select() = 0; - virtual HRESULT STDMETHODCALLTYPE AddToSelection() = 0; - virtual HRESULT STDMETHODCALLTYPE RemoveFromSelection() = 0; - virtual HRESULT STDMETHODCALLTYPE ScrollIntoView(BOOL alignToTop) = 0; - virtual HRESULT STDMETHODCALLTYPE GetChildren(__RPC__deref_out_opt SAFEARRAY **pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(ITextRangeProvider, 0x5347ad7b, 0xc355, 0x46f8, 0xaf,0xf5, 0x90,0x90,0x33,0x58,0x2f,0x63) -#endif -#endif - - -#ifndef __ITextProvider_INTERFACE_DEFINED__ -#define __ITextProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_ITextProvider, 0x3589c92c, 0x63f3, 0x4367, 0x99,0xbb, 0xad,0xa6,0x53,0xb7,0x7c,0xf2); -MIDL_INTERFACE("3589c92c-63f3-4367-99bb-ada653b77cf2") -ITextProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE GetSelection(__RPC__deref_out_opt SAFEARRAY **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetVisibleRanges(__RPC__deref_out_opt SAFEARRAY **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE RangeFromChild(__RPC__in_opt IRawElementProviderSimple *childElement, __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE RangeFromPoint(struct UiaPoint point, __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_DocumentRange(__RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_SupportedTextSelection(__RPC__out enum SupportedTextSelection *pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(ITextProvider, 0x3589c92c, 0x63f3, 0x4367, 0x99,0xbb, 0xad,0xa6,0x53,0xb7,0x7c,0xf2) -#endif -#endif - - -#ifndef __ITextProvider2_INTERFACE_DEFINED__ -#define __ITextProvider2_INTERFACE_DEFINED__ -DEFINE_GUID(IID_ITextProvider2, 0x0dc5e6ed, 0x3e16, 0x4bf1, 0x8f,0x9a, 0xa9,0x79,0x87,0x8b,0xc1,0x95); -MIDL_INTERFACE("0dc5e6ed-3e16-4bf1-8f9a-a979878bc195") -ITextProvider2 : public ITextProvider -{ -public: - virtual HRESULT STDMETHODCALLTYPE RangeFromAnnotation(__RPC__in_opt IRawElementProviderSimple *annotationElement, __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetCaretRange(__RPC__out BOOL *isActive, __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(ITextProvider2, 0x0dc5e6ed, 0x3e16, 0x4bf1, 0x8f,0x9a, 0xa9,0x79,0x87,0x8b,0xc1,0x95) -#endif -#endif - - -#ifndef __IToggleProvider_INTERFACE_DEFINED__ -#define __IToggleProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IToggleProvider, 0x56d00bd0, 0xc4f4, 0x433c, 0xa8,0x36, 0x1a,0x52,0xa5,0x7e,0x08,0x92); -MIDL_INTERFACE("56d00bd0-c4f4-433c-a836-1a52a57e0892") -IToggleProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE Toggle() = 0; - virtual HRESULT STDMETHODCALLTYPE get_ToggleState(__RPC__out enum ToggleState *pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IToggleProvider, 0x56d00bd0, 0xc4f4, 0x433c, 0xa8,0x36, 0x1a,0x52,0xa5,0x7e,0x08,0x92) -#endif -#endif - - -#ifndef __IInvokeProvider_INTERFACE_DEFINED__ -#define __IInvokeProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IInvokeProvider, 0x54fcb24b, 0xe18e, 0x47a2, 0xb4,0xd3, 0xec,0xcb,0xe7,0x75,0x99,0xa2); -MIDL_INTERFACE("54fcb24b-e18e-47a2-b4d3-eccbe77599a2") -IInvokeProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE Invoke() = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IInvokeProvider, 0x54fcb24b, 0xe18e, 0x47a2, 0xb4,0xd3, 0xec,0xcb,0xe7,0x75,0x99,0xa2) -#endif -#endif - - -#ifndef __ISelectionProvider_INTERFACE_DEFINED__ -#define __ISelectionProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_ISelectionProvider, 0xfb8b03af, 0x3bdf, 0x48d4, 0xbd,0x36, 0x1a,0x65,0x79,0x3b,0xe1,0x68); -MIDL_INTERFACE("fb8b03af-3bdf-48d4-bd36-1a65793be168") -ISelectionProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE GetSelection(__RPC__deref_out_opt SAFEARRAY **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CanSelectMultiple(__RPC__out BOOL *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_IsSelectionRequired(__RPC__out BOOL *pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(ISelectionProvider, 0xfb8b03af, 0x3bdf, 0x48d4, 0xbd,0x36, 0x1a,0x65,0x79,0x3b,0xe1,0x68) -#endif -#endif - - -#ifndef __ISelectionItemProvider_INTERFACE_DEFINED__ -#define __ISelectionItemProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_ISelectionItemProvider, 0x2acad808, 0xb2d4, 0x452d, 0xa4,0x07, 0x91,0xff,0x1a,0xd1,0x67,0xb2); -MIDL_INTERFACE("2acad808-b2d4-452d-a407-91ff1ad167b2") -ISelectionItemProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE Select() = 0; - virtual HRESULT STDMETHODCALLTYPE AddToSelection() = 0; - virtual HRESULT STDMETHODCALLTYPE RemoveFromSelection() = 0; - virtual HRESULT STDMETHODCALLTYPE get_IsSelected(__RPC__out BOOL *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_SelectionContainer(__RPC__deref_out_opt IRawElementProviderSimple **pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(ISelectionItemProvider, 0x2acad808, 0xb2d4, 0x452d, 0xa4,0x07, 0x91,0xff,0x1a,0xd1,0x67,0xb2) -#endif -#endif - - -#ifndef __ITableProvider_INTERFACE_DEFINED__ -#define __ITableProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_ITableProvider, 0x9c860395, 0x97b3, 0x490a, 0xb5,0x2a, 0x85,0x8c,0xc2,0x2a,0xf1,0x66); -MIDL_INTERFACE("9c860395-97b3-490a-b52a-858cc22af166") -ITableProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE GetRowHeaders(__RPC__deref_out_opt SAFEARRAY **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetColumnHeaders(__RPC__deref_out_opt SAFEARRAY **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_RowOrColumnMajor(__RPC__out enum RowOrColumnMajor *pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(ITableProvider, 0x9c860395, 0x97b3, 0x490a, 0xb5,0x2a, 0x85,0x8c,0xc2,0x2a,0xf1,0x66) -#endif -#endif - - -#ifndef __ITableItemProvider_INTERFACE_DEFINED__ -#define __ITableItemProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_ITableItemProvider, 0xb9734fa6, 0x771f, 0x4d78, 0x9c,0x90, 0x25,0x17,0x99,0x93,0x49,0xcd); -MIDL_INTERFACE("b9734fa6-771f-4d78-9c90-2517999349cd") -ITableItemProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE GetRowHeaderItems(__RPC__deref_out_opt SAFEARRAY **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE GetColumnHeaderItems(__RPC__deref_out_opt SAFEARRAY **pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(ITableItemProvider, 0xb9734fa6, 0x771f, 0x4d78, 0x9c,0x90, 0x25,0x17,0x99,0x93,0x49,0xcd) -#endif -#endif - - -#ifndef __IGridProvider_INTERFACE_DEFINED__ -#define __IGridProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IGridProvider, 0xb17d6187, 0x0907, 0x464b, 0xa1,0x68, 0x0e,0xf1,0x7a,0x15,0x72,0xb1); -MIDL_INTERFACE("b17d6187-0907-464b-a168-0ef17a1572b1") -IGridProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE GetItem(int row, int column, __RPC__deref_out_opt IRawElementProviderSimple **pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_RowCount(__RPC__out int *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_ColumnCount(__RPC__out int *pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IGridProvider, 0xb17d6187, 0x0907, 0x464b, 0xa1,0x68, 0x0e,0xf1,0x7a,0x15,0x72,0xb1) -#endif -#endif - - -#ifndef __IGridItemProvider_INTERFACE_DEFINED__ -#define __IGridItemProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IGridItemProvider, 0xd02541f1, 0xfb81, 0x4d64, 0xae,0x32, 0xf5,0x20,0xf8,0xa6,0xdb,0xd1); -MIDL_INTERFACE("d02541f1-fb81-4d64-ae32-f520f8a6dbd1") -IGridItemProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE get_Row(__RPC__out int *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_Column(__RPC__out int *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_RowSpan(__RPC__out int *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_ColumnSpan(__RPC__out int *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_ContainingGrid(__RPC__deref_out_opt IRawElementProviderSimple **pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IGridItemProvider, 0xd02541f1, 0xfb81, 0x4d64, 0xae,0x32, 0xf5,0x20,0xf8,0xa6,0xdb,0xd1) -#endif -#endif - - -#ifndef __IWindowProvider_INTERFACE_DEFINED__ -#define __IWindowProvider_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IWindowProvider, 0x987df77b, 0xdb06, 0x4d77, 0x8f,0x8a, 0x86,0xa9,0xc3,0xbb,0x90,0xb9); -MIDL_INTERFACE("987df77b-db06-4d77-8f8a-86a9c3bb90b9") -IWindowProvider : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE SetVisualState(enum WindowVisualState state) = 0; - virtual HRESULT STDMETHODCALLTYPE Close( void) = 0; - virtual HRESULT STDMETHODCALLTYPE WaitForInputIdle(int milliseconds, __RPC__out BOOL *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CanMaximize(__RPC__out BOOL *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_CanMinimize(__RPC__out BOOL *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_IsModal(__RPC__out BOOL *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_WindowVisualState(__RPC__out enum WindowVisualState *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_WindowInteractionState(__RPC__out enum WindowInteractionState *pRetVal) = 0; - virtual HRESULT STDMETHODCALLTYPE get_IsTopmost(__RPC__out BOOL *pRetVal) = 0; -}; -#ifdef __CRT_UUID_DECL -__CRT_UUID_DECL(IWindowProvider, 0x987df77b, 0xdb06, 0x4d77, 0x8f,0x8a, 0x86,0xa9,0xc3,0xbb,0x90,0xb9) -#endif -#endif - -#endif diff --git a/src/platformsupport/windowsuiautomation/uiatypes_p.h b/src/platformsupport/windowsuiautomation/uiatypes_p.h deleted file mode 100644 index 8ef71843a3..0000000000 --- a/src/platformsupport/windowsuiautomation/uiatypes_p.h +++ /dev/null @@ -1,170 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef UIATYPES_H -#define UIATYPES_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -typedef int PROPERTYID; -typedef int PATTERNID; -typedef int EVENTID; -typedef int TEXTATTRIBUTEID; -typedef int CONTROLTYPEID; -typedef int LANDMARKTYPEID; -typedef int METADATAID; - -typedef void *UIA_HWND; - -enum NavigateDirection { - NavigateDirection_Parent = 0, - NavigateDirection_NextSibling = 1, - NavigateDirection_PreviousSibling = 2, - NavigateDirection_FirstChild = 3, - NavigateDirection_LastChild = 4 -}; - -enum ProviderOptions { - ProviderOptions_ClientSideProvider = 0x1, - ProviderOptions_ServerSideProvider = 0x2, - ProviderOptions_NonClientAreaProvider = 0x4, - ProviderOptions_OverrideProvider = 0x8, - ProviderOptions_ProviderOwnsSetFocus = 0x10, - ProviderOptions_UseComThreading = 0x20, - ProviderOptions_RefuseNonClientSupport = 0x40, - ProviderOptions_HasNativeIAccessible = 0x80, - ProviderOptions_UseClientCoordinates = 0x100 -}; - -enum SupportedTextSelection { - SupportedTextSelection_None = 0, - SupportedTextSelection_Single = 1, - SupportedTextSelection_Multiple = 2 -}; - -enum TextUnit { - TextUnit_Character = 0, - TextUnit_Format = 1, - TextUnit_Word = 2, - TextUnit_Line = 3, - TextUnit_Paragraph = 4, - TextUnit_Page = 5, - TextUnit_Document = 6 -}; - -enum TextPatternRangeEndpoint { - TextPatternRangeEndpoint_Start = 0, - TextPatternRangeEndpoint_End = 1 -}; - -enum CaretPosition { - CaretPosition_Unknown = 0, - CaretPosition_EndOfLine = 1, - CaretPosition_BeginningOfLine = 2 -}; - -enum ToggleState { - ToggleState_Off = 0, - ToggleState_On = 1, - ToggleState_Indeterminate = 2 -}; - -enum RowOrColumnMajor { - RowOrColumnMajor_RowMajor = 0, - RowOrColumnMajor_ColumnMajor = 1, - RowOrColumnMajor_Indeterminate = 2 -}; - -enum TreeScope { - TreeScope_None = 0, - TreeScope_Element = 0x1, - TreeScope_Children = 0x2, - TreeScope_Descendants = 0x4, - TreeScope_Parent = 0x8, - TreeScope_Ancestors = 0x10, - TreeScope_Subtree = TreeScope_Element | TreeScope_Children | TreeScope_Descendants -}; - -enum OrientationType { - OrientationType_None = 0, - OrientationType_Horizontal = 1, - OrientationType_Vertical = 2 -}; - -enum PropertyConditionFlags { - PropertyConditionFlags_None = 0, - PropertyConditionFlags_IgnoreCase = 1 -}; - -enum WindowVisualState { - WindowVisualState_Normal = 0, - WindowVisualState_Maximized = 1, - WindowVisualState_Minimized = 2 -}; - -enum WindowInteractionState { - WindowInteractionState_Running = 0, - WindowInteractionState_Closing = 1, - WindowInteractionState_ReadyForUserInteraction = 2, - WindowInteractionState_BlockedByModalWindow = 3, - WindowInteractionState_NotResponding = 4 -}; - -struct UiaRect { - double left; - double top; - double width; - double height; -}; - -struct UiaPoint { - double x; - double y; -}; - -#endif diff --git a/src/platformsupport/windowsuiautomation/windowsuiautomation.pro b/src/platformsupport/windowsuiautomation/windowsuiautomation.pro deleted file mode 100644 index 97cdb60ef9..0000000000 --- a/src/platformsupport/windowsuiautomation/windowsuiautomation.pro +++ /dev/null @@ -1,23 +0,0 @@ -TARGET = QtWindowsUIAutomationSupport -MODULE = windowsuiautomation_support - -QT = core-private gui-private -CONFIG += static internal_module - -HEADERS += \ - qwindowsuiawrapper_p.h \ - uiaattributeids_p.h \ - uiacontroltypeids_p.h \ - uiaerrorids_p.h \ - uiaeventids_p.h \ - uiageneralids_p.h \ - uiaserverinterfaces_p.h \ - uiaclientinterfaces_p.h \ - uiapatternids_p.h \ - uiapropertyids_p.h \ - uiatypes_p.h - -SOURCES += \ - qwindowsuiawrapper.cpp - -load(qt_module) |